Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0141G6xqLeNRYEtviLWSB5Up
721 lines
34 KiB
TypeScript
721 lines
34 KiB
TypeScript
// Rooms: who sits where, whose move it is, and the duel itself. Every change
|
|
// goes to the ledger first and is then applied, so a restart replays to the
|
|
// same place. Inputs wait in memory until every seat that must move has moved;
|
|
// then the turn resolves at once, bots included.
|
|
|
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
import { chooseBotTurn } from '../../src/lib/game/bot';
|
|
import { resolveTurn } from '../../src/lib/game/resolve';
|
|
import { GESTURES, type Gesture } from '../../src/lib/game/spells';
|
|
import { CURRENT_RULES, createGame, inDuel, SPECTATOR, type GameState, type TurnInput, type WizardId } from '../../src/lib/game/state';
|
|
import { viewFor, type ChatLine, type RoomView } from '../../src/lib/game/view';
|
|
import type { LedgerLine, Store } from './store';
|
|
import { botLine, botsNamed, turnTalk } from './voices';
|
|
|
|
/** A dozen seats at most: a turn resolves only when every seat has moved, and the slowest sets the pace. */
|
|
const SEAT_IDS: WizardId[] = 'ABCDEFGHJKLM'.split('');
|
|
const BOT_NAMES = ['Aldric', 'Morwenna', 'Thessaly', 'Gandric', 'Ysolde', 'Ormund', 'Corwin', 'Isaura', 'Bellamy', 'Hesper', 'Lucan', 'Wynne'];
|
|
export const MAX_SEATS = SEAT_IDS.length;
|
|
export { SPECTATOR };
|
|
const CHAT_MAX_LENGTH = 300;
|
|
/** Lines of talk kept and sent; the ledger keeps them all. */
|
|
const CHAT_KEEP = 200;
|
|
/** Turns the bots play on among themselves in one go; a duel still running past this many waits where it stands. */
|
|
const BOTS_ALONE_LIMIT = 300;
|
|
|
|
export interface Seat {
|
|
id: WizardId;
|
|
name: string;
|
|
/** SHA-256 of the seat's token, hex; empty for a bot. A seat a bot stands in for keeps the wizard's, which opens nothing while it does. */
|
|
tokenHash: string;
|
|
/** A bot plays this seat: one seated as a bot, or one standing in for a wizard. */
|
|
bot: boolean;
|
|
/** The host gave this wizard's seat to a bot; a phrase from the host, or the keeper, gives it back. */
|
|
standIn?: true;
|
|
/** The address this person's seat was last used from, as a salted hash; a seat their browser lost goes back to the same address. */
|
|
addr?: string;
|
|
}
|
|
|
|
/** A table whose ledger has not been written in this long is not looked through for a lost seat. */
|
|
const LOST_SEAT_LOOKBACK_MS = 90 * 24 * 60 * 60 * 1000;
|
|
/** A seat's address is noted at most this often: one seat open on two networks at once must not write a line per request. */
|
|
const SEEN_EVERY_MS = 10 * 60 * 1000;
|
|
|
|
export function hashToken(token: string): string {
|
|
return createHash('sha256').update(token).digest('hex');
|
|
}
|
|
|
|
export interface Room {
|
|
id: string;
|
|
size: number;
|
|
createdAt: number;
|
|
seats: Seat[];
|
|
/** The host lets the Peanut Gallery talk at this table. */
|
|
galleryTalk: boolean;
|
|
/** The keeper of the site was called to a seat, and by whom. */
|
|
challenge: { by: WizardId; at: number } | null;
|
|
/** Names with a seat held for them: the wizards of the last table, or the keeper. */
|
|
expected: string[];
|
|
/** A finished table that called for a rematch: where it went, and who called. */
|
|
rematch: { to: string; by: WizardId } | null;
|
|
/** The table this one is the rematch of. */
|
|
rematchOf: string | null;
|
|
state: GameState | null;
|
|
/** Inputs received for the turn in progress, by seat. */
|
|
pending: Record<WizardId, TurnInput>;
|
|
chat: ChatLine[];
|
|
/** Turns played so far, time stops included; a move names the count it was made against. */
|
|
resolved: number;
|
|
/** Bumped on every change a client might want to see. */
|
|
seq: number;
|
|
updatedAt: number;
|
|
}
|
|
|
|
export class RoomError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public status = 400
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
function newId(bytes: number): string {
|
|
return randomBytes(bytes).toString('base64url');
|
|
}
|
|
|
|
/** Room codes: four letters or digits, none that read alike, easy to say aloud. */
|
|
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
function newCode(): string {
|
|
const bytes = randomBytes(4);
|
|
return [...bytes].map((b) => CODE_ALPHABET[b % CODE_ALPHABET.length]).join('');
|
|
}
|
|
|
|
function newSeed(): number {
|
|
return (Date.now() ^ (Math.random() * 0xffffffff)) >>> 0;
|
|
}
|
|
|
|
/** Phrases that carry a seat between devices: four plain words, ten minutes, one use. */
|
|
const TRANSFER_WORDS = [
|
|
'ember', 'raven', 'flagon', 'wand', 'rune', 'moss', 'torch', 'frost', 'amber', 'wisp', 'cellar', 'gable',
|
|
'onyx', 'briar', 'tome', 'cinder', 'gloom', 'spiral', 'mirror', 'lantern', 'thistle', 'harbor', 'quill', 'saddle',
|
|
'willow', 'copper', 'meadow', 'anvil', 'beacon', 'orchard', 'pebble', 'cloister', 'walnut', 'tallow', 'heron', 'marble',
|
|
'ivy', 'kestrel', 'fennel', 'velvet', 'canyon', 'lattice', 'ledger', 'bramble', 'sable', 'tundra', 'juniper', 'compass'
|
|
];
|
|
const TRANSFER_TTL_MS = 10 * 60 * 1000;
|
|
const TRANSFER_FAIL_LIMIT = 20;
|
|
|
|
/** A table with nobody seated yet. */
|
|
function blank(id: string, size: number, createdAt: number, rematchOf: string | null, expected: string[], seq = 0): Room {
|
|
return { id, size, createdAt, seats: [], galleryTalk: false, challenge: null, expected, rematch: null, rematchOf, state: null, pending: {}, chat: [], resolved: 0, seq, updatedAt: createdAt };
|
|
}
|
|
|
|
export function normalizeCode(raw: string): string {
|
|
return raw.trim().toUpperCase();
|
|
}
|
|
|
|
export class Rooms {
|
|
private rooms = new Map<string, Room>();
|
|
private listeners = new Map<string, Set<(room: Room) => void>>();
|
|
/** Sockets watching from the gallery, by room. */
|
|
private gallery = new Map<string, number>();
|
|
|
|
constructor(
|
|
private store: Store,
|
|
/** The keeper of the site: the name a table may call to a seat, and where they live. */
|
|
private keeper: { name: string; zone: string } = { name: 'the keeper', zone: 'UTC' }
|
|
) {
|
|
for (const id of store.roomIds()) {
|
|
const room = replay(id, store.read(id));
|
|
if (room) this.rooms.set(id, room);
|
|
}
|
|
}
|
|
|
|
get(id: string): Room {
|
|
const room = this.rooms.get(id) ?? this.rooms.get(normalizeCode(id)) ?? this.load(normalizeCode(id));
|
|
if (!room) throw new RoomError('No duel answers to that code.', 404);
|
|
return room;
|
|
}
|
|
|
|
/** A room evicted from memory comes back from its ledger on the next visit. */
|
|
private load(id: string): Room | undefined {
|
|
if (!/^[A-Z0-9]{4}$/.test(id)) return undefined;
|
|
const room = replay(id, this.store.read(id));
|
|
if (room) this.rooms.set(id, room);
|
|
return room ?? undefined;
|
|
}
|
|
|
|
/** Forget rooms nobody has touched or watched for a while; their ledgers stay on disk. */
|
|
evictIdle(olderThanMs: number, now = Date.now()): number {
|
|
let n = 0;
|
|
for (const [id, room] of this.rooms) {
|
|
if (now - room.updatedAt < olderThanMs) continue;
|
|
if ((this.listeners.get(id)?.size ?? 0) > 0) continue;
|
|
this.rooms.delete(id);
|
|
n += 1;
|
|
}
|
|
return n;
|
|
}
|
|
|
|
/** How many rooms are held in memory. */
|
|
get loaded(): number {
|
|
return this.rooms.size;
|
|
}
|
|
|
|
/** The seat a token unlocks, compared by hash in constant time. */
|
|
seatOf(room: Room, token: string | undefined): Seat {
|
|
if (!token) throw new RoomError('That token opens no seat at this duel.', 403);
|
|
const given = Buffer.from(hashToken(token), 'hex');
|
|
const seat = room.seats.find((s) => s.tokenHash.length === given.length * 2 && timingSafeEqual(Buffer.from(s.tokenHash, 'hex'), given));
|
|
if (seat?.standIn) throw new RoomError('The host gave your seat to a bot, which duels on in your place. Ask them for a transfer phrase to take it back.', 403);
|
|
if (!seat) throw new RoomError('That token opens no seat at this duel.', 403);
|
|
return seat;
|
|
}
|
|
|
|
create(name: string, size: number): { room: Room; seat: Seat; token: string } {
|
|
if (!Number.isInteger(size) || size < 2 || size > MAX_SEATS) throw new RoomError(`A table seats 2 to ${MAX_SEATS} wizards.`);
|
|
return this.open(name, size);
|
|
}
|
|
|
|
/** Open a table with its first seat taken; a rematch names the table it follows and holds seats for its wizards. */
|
|
private open(name: string, size: number, follows?: { rematchOf: string; expected: string[] }): { room: Room; seat: Seat; token: string } {
|
|
let id = newCode();
|
|
while (this.rooms.has(id) || this.store.exists(id)) id = newCode();
|
|
const room = blank(id, size, Date.now(), follows?.rematchOf ?? null, follows?.expected ?? []);
|
|
this.rooms.set(id, room);
|
|
this.commit(room, { t: 'room', id, seats: size, createdAt: room.createdAt, ...(follows ? { rematchOf: follows.rematchOf, expected: follows.expected } : {}) });
|
|
return { room, ...this.sit(room, name, false) };
|
|
}
|
|
|
|
join(room: Room, name: string): { seat: Seat; token: string } {
|
|
if (room.state) throw new RoomError('The duel has begun; no more seats are taken.', 409);
|
|
return this.sit(room, name, false);
|
|
}
|
|
|
|
/** Names with a seat held who have not yet sat. */
|
|
private awaited(room: Room): string[] {
|
|
return room.expected.filter((n) => !room.seats.some((s) => s.name.toLowerCase() === n.toLowerCase()));
|
|
}
|
|
|
|
/** Host only: let the Peanut Gallery talk at this table, or hush it. Written to the ledger. */
|
|
setGalleryTalk(room: Room, token: string | undefined, on: boolean): void {
|
|
const seat = this.seatOf(room, token);
|
|
if (seat.id !== room.seats[0]?.id) throw new RoomError('Only the wizard who opened the table decides whether the gallery may talk.', 403);
|
|
if (room.galleryTalk === on) return;
|
|
this.commit(room, { t: 'galleryTalk', at: Date.now(), on, by: seat.id });
|
|
}
|
|
|
|
/** A word from the Peanut Gallery, when the host allows it: signed with a name no seat holds. */
|
|
sayFromGallery(room: Room, rawName: unknown, raw: unknown): void {
|
|
if (!room.galleryTalk) throw new RoomError('The gallery listens at this table; the host has not let it talk.', 403);
|
|
const name = cleanName(rawName);
|
|
if (room.seats.some((s) => s.name.toLowerCase() === name.toLowerCase())) throw new RoomError('A wizard at the table has that name.', 409);
|
|
const text = cleanTalk(raw);
|
|
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name, text });
|
|
this.answer(room, name, text);
|
|
}
|
|
|
|
/** The keeper of the site says a word at a table from the keeper's door, whether or not the gallery may talk: the answer to a call they could not take up. */
|
|
keeperSays(room: Room, keeper: string, raw: unknown): void {
|
|
const text = cleanTalk(raw);
|
|
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name: keeper, text, keeper: true });
|
|
this.answer(room, keeper, text);
|
|
}
|
|
|
|
/**
|
|
* A seated wizard calls the keeper of the site to the table: a seat is
|
|
* held under the keeper's name and the call goes on the ledger. Once per
|
|
* table, before the duel begins. The caller rings the keeper's bell.
|
|
*/
|
|
callKeeper(room: Room, token: string | undefined, keeper: string): void {
|
|
const seat = this.seatOf(room, token);
|
|
if (room.state) throw new RoomError('The duel has begun.', 409);
|
|
if (room.challenge) throw new RoomError(`${keeper} has already been called to this table.`, 409);
|
|
if (room.seats.some((s) => s.name.toLowerCase() === keeper.toLowerCase())) throw new RoomError(`${keeper} is already here.`, 409);
|
|
if (room.seats.length + this.awaited(room).length >= room.size) throw new RoomError('Every seat at this table is taken or held.', 409);
|
|
this.commit(room, { t: 'challenge', at: Date.now(), by: seat.id, keeper });
|
|
}
|
|
|
|
/**
|
|
* A finished table calls for a rematch: a new table of the same size with
|
|
* the same bots, seats held for the same people, the caller seated as its
|
|
* host. Anyone at the old table may call; a second call finds the table
|
|
* already open.
|
|
*/
|
|
rematch(room: Room, token: string | undefined): { roomId: string; seat: Seat | null; token: string | null; created: boolean } {
|
|
const caller = this.seatOf(room, token);
|
|
if (!room.state?.over) throw new RoomError('The duel is not over yet.', 409);
|
|
if (room.rematch) return { roomId: room.rematch.to, seat: null, token: null, created: false };
|
|
// A wizard a bot stood in for is still one of the company; the stand-in does not follow.
|
|
const others = room.seats.filter((s) => (!s.bot || s.standIn) && s.id !== caller.id).map((s) => s.name);
|
|
const next = this.open(caller.name, room.size, { rematchOf: room.id, expected: others });
|
|
for (const bot of room.seats.filter((s) => s.bot && !s.standIn)) this.sit(next.room, bot.name, true);
|
|
this.commit(room, { t: 'rematch', at: Date.now(), to: next.room.id, by: caller.id });
|
|
return { roomId: next.room.id, seat: next.seat, token: next.token, created: true };
|
|
}
|
|
|
|
/** Phrases waiting to be claimed, with the seat and the token they carry; the host's carry none, and re-seat on claim. */
|
|
private transfers = new Map<string, { roomId: string; seatId: WizardId; token: string | null; expiresAt: number }>();
|
|
private failedClaims = 0;
|
|
private failWindowStart = 0;
|
|
|
|
/** Mint a phrase that brings this seat to another device: four words, ten minutes, one use. */
|
|
transfer(room: Room, token: string | undefined): { phrase: string; expiresAt: number } {
|
|
const seat = this.seatOf(room, token);
|
|
return this.mint(room.id, seat.id, token!);
|
|
}
|
|
|
|
/**
|
|
* The host mints a phrase for another wizard's seat: for a player whose browser lost it, or to take it back
|
|
* from a bot standing in. Claimed, it gives the seat a new token, so the old one opens nothing after.
|
|
*/
|
|
hostPhrase(room: Room, token: string | undefined, seatId: unknown): { phrase: string; expiresAt: number } {
|
|
const host = this.seatOf(room, token);
|
|
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the wizard who opened the table may make a phrase for another seat.', 403);
|
|
const seat = room.seats.find((s) => s.id === seatId && s.id !== host.id && (!s.bot || s.standIn));
|
|
if (!seat) throw new RoomError('No other wizard sits in that seat.', 404);
|
|
return this.mint(room.id, seat.id, null);
|
|
}
|
|
|
|
private mint(roomId: string, seatId: WizardId, token: string | null): { phrase: string; expiresAt: number } {
|
|
const now = Date.now();
|
|
for (const [phrase, t] of this.transfers) if (t.expiresAt < now) this.transfers.delete(phrase);
|
|
if (this.transfers.size >= 200) throw new RoomError('Too many transfers are pending; try again in a few minutes.', 429);
|
|
let phrase: string;
|
|
do {
|
|
phrase = Array.from({ length: 4 }, () => TRANSFER_WORDS[randomBytes(1)[0] % TRANSFER_WORDS.length]).join('-');
|
|
} while (this.transfers.has(phrase));
|
|
const expiresAt = now + TRANSFER_TTL_MS;
|
|
this.transfers.set(phrase, { roomId, seatId, token, expiresAt });
|
|
return { phrase, expiresAt };
|
|
}
|
|
|
|
/** When each seat's address was last noted, by room and seat. */
|
|
private seenAt = new Map<string, number>();
|
|
|
|
/** The address a seat is used from, noted when it changes, and not more often than SEEN_EVERY_MS. Not a change the table need hear of: nothing wakes for it. */
|
|
seen(room: Room, token: string | undefined, addr: string): void {
|
|
let seat: Seat;
|
|
try {
|
|
seat = this.seatOf(room, token);
|
|
} catch {
|
|
return;
|
|
}
|
|
if (seat.addr === addr) return;
|
|
// Keyed by the token too: a seat given a new token is noted afresh at once, whoever held it before.
|
|
const key = `${room.id}/${seat.id}/${seat.tokenHash}`;
|
|
const now = Date.now();
|
|
if ((this.seenAt.get(key) ?? 0) > now - SEEN_EVERY_MS) return;
|
|
this.seenAt.set(key, now);
|
|
const line: LedgerLine = { t: 'seen', at: now, id: seat.id, addr };
|
|
this.store.append(room.id, line);
|
|
apply(room, line);
|
|
}
|
|
|
|
/** The tables not yet over, written to lately, where a person of this name sits; one table alone when it is named. */
|
|
private tablesOf(name: string, only?: string): { room: Room; seat: Seat }[] {
|
|
const wanted = cleanName(name).toLowerCase();
|
|
const since = Date.now() - LOST_SEAT_LOOKBACK_MS;
|
|
const ids = only ? [normalizeCode(String(only))] : this.store.roomIds().filter((id) => this.store.updatedAt(id) > since);
|
|
const found: { room: Room; seat: Seat }[] = [];
|
|
for (const id of ids) {
|
|
let room: Room;
|
|
try {
|
|
room = this.get(id);
|
|
} catch {
|
|
continue;
|
|
}
|
|
if (room.state?.over) continue;
|
|
const seat = room.seats.find((s) => (!s.bot || s.standIn) && s.name.toLowerCase() === wanted);
|
|
if (seat) found.push({ room, seat });
|
|
}
|
|
return found;
|
|
}
|
|
|
|
/**
|
|
* The seats a name holds at tables not yet over, for a browser that lost them. A seat last used from the
|
|
* asker's own address, at a table where no other person shares that address, is theirs again with a new
|
|
* token, the old one dead. The rest are only counted: a name proves nothing, so neither the tables nor the
|
|
* company at them are told to the asker, who can get a phrase from the host, or a link from the keeper. A
|
|
* seat the host gave to a bot is the host's to give back, by a phrase, never taken back by name.
|
|
*/
|
|
findSeats(rawName: string, addr: string, only?: string): { seated: { roomId: string; seat: WizardId; token: string }[]; elsewhere: number } {
|
|
const seated: { roomId: string; seat: WizardId; token: string }[] = [];
|
|
let elsewhere = 0;
|
|
for (const { room, seat } of this.tablesOf(rawName, only)) {
|
|
const shared = room.seats.some((s) => s !== seat && (!s.bot || s.standIn) && s.addr === addr);
|
|
if (seat.addr === addr && !shared && !seat.standIn) {
|
|
const { token } = this.reseat(room, seat.id);
|
|
seated.push({ roomId: room.id, seat: seat.id, token });
|
|
} else elsewhere += 1;
|
|
}
|
|
return { seated, elsewhere };
|
|
}
|
|
|
|
/** For the keeper: every table not yet over where a person of this name sits, with the company there, to re-seat them by. */
|
|
tablesForKeeper(name: string): { roomId: string; seat: WizardId; standIn: boolean; players: string[]; updatedAt: number }[] {
|
|
return this.tablesOf(name).map(({ room, seat }) => ({ roomId: room.id, seat: seat.id, standIn: !!seat.standIn, players: room.seats.filter((s) => s !== seat).map((s) => s.name), updatedAt: room.updatedAt }));
|
|
}
|
|
|
|
/** Claim a phrase: the seat and its token, once. Too many misses void every pending phrase. */
|
|
claim(raw: unknown): { roomId: string; seat: WizardId; token: string } {
|
|
const now = Date.now();
|
|
if (now - this.failWindowStart > TRANSFER_TTL_MS) {
|
|
this.failWindowStart = now;
|
|
this.failedClaims = 0;
|
|
}
|
|
if (this.failedClaims >= TRANSFER_FAIL_LIMIT) throw new RoomError('Too many failed claims; transfers are cooling off. Mint a fresh phrase.', 429);
|
|
const phrase = String(raw ?? '').trim().toLowerCase().replace(/\s+/g, '-');
|
|
const t = this.transfers.get(phrase);
|
|
if (!t || t.expiresAt < now) {
|
|
this.failedClaims += 1;
|
|
if (this.failedClaims >= TRANSFER_FAIL_LIMIT) this.transfers.clear();
|
|
throw new RoomError('That phrase is unknown or has expired.', 404);
|
|
}
|
|
this.transfers.delete(phrase);
|
|
const room = this.get(t.roomId);
|
|
if (t.token === null) {
|
|
const { seat, token } = this.reseat(room, t.seatId);
|
|
return { roomId: room.id, seat: seat.id, token };
|
|
}
|
|
const seat = this.seatOf(room, t.token);
|
|
return { roomId: room.id, seat: seat.id, token: t.token };
|
|
}
|
|
|
|
/** The host, who opened the table, begins the duel once at least two are seated, however full the table. */
|
|
begin(room: Room, token: string | undefined): void {
|
|
const seat = this.seatOf(room, token);
|
|
if (seat.id !== room.seats[0]?.id) throw new RoomError('Only the wizard who opened the table may begin the duel.', 403);
|
|
if (room.state) throw new RoomError('The duel has already begun.', 409);
|
|
if (room.seats.length < 2) throw new RoomError('A duel needs at least two wizards.', 409);
|
|
this.commit(room, { t: 'start', seed: newSeed(), rules: CURRENT_RULES });
|
|
const bots = this.voiced(room);
|
|
const bot = bots[Math.floor(Math.random() * bots.length)];
|
|
if (bot) this.commit(room, { t: 'chat', at: Date.now(), id: bot.id, text: botLine(bot.name, 'begin') });
|
|
}
|
|
|
|
/** The host seats a bot in an empty chair. */
|
|
addBot(room: Room, token: string | undefined): Seat {
|
|
const host = this.seatOf(room, token);
|
|
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the wizard who opened the table may seat a bot.', 403);
|
|
if (room.state) throw new RoomError('The duel has begun; no more seats are taken.', 409);
|
|
const taken = new Set(room.seats.map((s) => s.name.toLowerCase()));
|
|
const pool = BOT_NAMES.filter((n) => !taken.has(n.toLowerCase()));
|
|
const name = pool[Math.floor(Math.random() * pool.length)] ?? 'The Construct';
|
|
const seat = this.sit(room, name, true).seat;
|
|
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text: botLine(name, 'sit') });
|
|
return seat;
|
|
}
|
|
|
|
/** Take the next free seat. The token is returned once and never stored; the ledger keeps its hash. */
|
|
private sit(room: Room, rawName: string, bot: boolean): { seat: Seat; token: string } {
|
|
if (room.seats.length >= room.size) throw new RoomError('Every seat at this duel is taken.', 409);
|
|
const name = cleanName(rawName);
|
|
const awaited = this.awaited(room);
|
|
if (!awaited.some((n) => n.toLowerCase() === name.toLowerCase()) && room.seats.length + awaited.length >= room.size) {
|
|
throw new RoomError('The seats left are held for wizards expected at this table.', 409);
|
|
}
|
|
if (room.seats.some((s) => s.name.toLowerCase() === name.toLowerCase())) throw new RoomError('Another wizard here already has that name.', 409);
|
|
const id = SEAT_IDS.find((s) => !room.seats.some((taken) => taken.id === s))!;
|
|
const token = bot ? '' : newId(18);
|
|
const seat: Seat = { id, name, tokenHash: bot ? '' : hashToken(token), bot };
|
|
this.commit(room, { t: 'seat', id: seat.id, name, tokenHash: seat.tokenHash, bot });
|
|
return { seat, token };
|
|
}
|
|
|
|
/**
|
|
* A wizard's seat gets a new token, for a player whose browser lost the old one, or one taking it back from a
|
|
* bot standing in. Whether the one asking holds the seat is the keeper's judgment, or the host's in the phrase
|
|
* they made; this carries it out. The old token opens nothing after.
|
|
*/
|
|
reseat(room: Room, seatId: unknown): { seat: Seat; token: string } {
|
|
const seat = room.seats.find((s) => s.id === seatId && (!s.bot || s.standIn));
|
|
if (!seat) throw new RoomError('No wizard sits in that seat.', 404);
|
|
const token = newId(18);
|
|
this.commit(room, { t: 'reseat', at: Date.now(), id: seat.id, tokenHash: hashToken(token) });
|
|
this.voidPhrases(room, seat.id);
|
|
return { seat, token };
|
|
}
|
|
|
|
/**
|
|
* The host gives a wizard's seat to a bot, for a player who cannot go on: the bot plays it from the gestures the
|
|
* seat owes, and the wizard's token opens nothing until a phrase from the host gives it back.
|
|
*/
|
|
standIn(room: Room, token: string | undefined, seatId: unknown): void {
|
|
const host = this.seatOf(room, token);
|
|
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the wizard who opened the table may give a seat to a bot.', 403);
|
|
if (!room.state || room.state.over) throw new RoomError('Only a duel under way needs a stand-in.', 409);
|
|
if (seatId === host.id) throw new RoomError('The host keeps their own seat.', 409);
|
|
const seat = room.seats.find((s) => s.id === seatId && !s.bot);
|
|
if (!seat) throw new RoomError('No wizard sits in that seat.', 404);
|
|
this.commit(room, { t: 'standIn', at: Date.now(), id: seat.id, by: host.id });
|
|
this.voidPhrases(room, seat.id);
|
|
// The turn may have been waiting on this seat alone.
|
|
if (waitingOn(room).length === 0) this.resolve(room);
|
|
}
|
|
|
|
/** A phrase minted for a seat whose token has changed hands would carry a seat that no longer answers to it. */
|
|
private voidPhrases(room: Room, seatId: WizardId): void {
|
|
for (const [phrase, t] of this.transfers) if (t.roomId === room.id && t.seatId === seatId) this.transfers.delete(phrase);
|
|
}
|
|
|
|
/** The table as the keeper sees it before re-seating: who sits where, and when each wizard last moved or spoke. */
|
|
seatsForKeeper(room: Room): { id: WizardId; name: string; bot: boolean; standIn: boolean; lastActed: number | null }[] {
|
|
const last = new Map<WizardId, number>();
|
|
for (const line of this.store.read(room.id)) {
|
|
if (line.t === 'input' || line.t === 'chat') last.set(line.id, line.at);
|
|
else if (line.t === 'turn') for (const id of Object.keys(line.inputs)) last.set(id, line.at);
|
|
}
|
|
return room.seats.map((s) => ({ id: s.id, name: s.name, bot: s.bot && !s.standIn, standIn: !!s.standIn, lastActed: s.bot && !s.standIn ? null : (last.get(s.id) ?? null) }));
|
|
}
|
|
|
|
/** The host sends a bot away before the duel begins. People leave by not coming back. */
|
|
unseat(room: Room, token: string | undefined, seatId: unknown): void {
|
|
const host = this.seatOf(room, token);
|
|
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the wizard who opened the table may send a bot away.', 403);
|
|
if (room.state) throw new RoomError('The duel has begun; the table is set.', 409);
|
|
const seat = room.seats.find((s) => s.id === seatId);
|
|
if (!seat || !seat.bot) throw new RoomError('Only a bot can be sent away.', 400);
|
|
this.commit(room, { t: 'unseat', id: seat.id });
|
|
}
|
|
|
|
/**
|
|
* Record a seat's move on the ledger, so a restart keeps it; resolve the turn once nobody else is awaited.
|
|
* `resolved` is how many turns the page had seen played when the gestures were made: gestures that
|
|
* arrive after their turn was played (a slow connection, a second click, a stale tab) are refused
|
|
* rather than taken as the next turn's.
|
|
*/
|
|
submit(room: Room, token: string | undefined, raw: unknown, resolved?: unknown): void {
|
|
const seat = this.seatOf(room, token);
|
|
if (!room.state) throw new RoomError('The duel has not begun: seats are still empty.', 409);
|
|
if (room.state.over) throw new RoomError('The duel is over.', 409);
|
|
if (typeof resolved !== 'number') throw new RoomError('This page is out of date. Reload it to see the duel as it stands.', 409);
|
|
if (resolved !== room.resolved) throw new RoomError('Those gestures were made for a turn that has already been played. Your page will catch up.', 409);
|
|
if (!waitingOn(room).includes(seat.id)) throw new RoomError('It is not your move.', 409);
|
|
this.commit(room, { t: 'input', at: Date.now(), id: seat.id, input: cleanInput(raw) });
|
|
if (waitingOn(room).length === 0) this.resolve(room);
|
|
}
|
|
|
|
private resolve(room: Room): void {
|
|
const state = room.state!;
|
|
const inputs: Record<WizardId, TurnInput> = { ...room.pending };
|
|
// Gestures a wizard made before a bot stood in for them stand.
|
|
for (const seat of room.seats) {
|
|
if (seat.bot && needsInput(state, seat.id) && !(seat.id in inputs)) inputs[seat.id] = chooseBotTurn(state, seat.id);
|
|
}
|
|
this.commit(room, { t: 'turn', at: Date.now(), inputs });
|
|
// A turn nobody at the table is awaited for is the bots' alone, whether a time stop owed to
|
|
// one of them or the rest of a duel every wizard has left; it resolves at once, to the end.
|
|
for (let played = 0; room.state && !room.state.over && waitingOn(room).length === 0 && played < BOTS_ALONE_LIMIT; played++) {
|
|
const theirs: Record<WizardId, TurnInput> = {};
|
|
for (const seat of room.seats) if (seat.bot && needsInput(room.state, seat.id)) theirs[seat.id] = chooseBotTurn(room.state, seat.id);
|
|
this.commit(room, { t: 'turn', at: Date.now(), inputs: theirs });
|
|
}
|
|
if (room.state?.over) this.commit(room, { t: 'over', at: Date.now(), winner: room.state.over.winner, reason: room.state.over.reason });
|
|
for (const line of turnTalk(this.voiced(room), state, room.state!)) this.commit(room, { t: 'chat', at: Date.now(), id: line.id, text: line.text });
|
|
}
|
|
|
|
/** Table talk, from a seat to everyone at the table and in the gallery. */
|
|
say(room: Room, token: string | undefined, raw: unknown): void {
|
|
const seat = this.seatOf(room, token);
|
|
const text = cleanTalk(raw);
|
|
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text });
|
|
this.answer(room, seat.name, text);
|
|
}
|
|
|
|
/** The bots at the table, speaking for themselves; one standing in for a wizard keeps that wizard's silence. */
|
|
private voiced(room: Room): { id: WizardId; name: string }[] {
|
|
return room.seats.filter((s) => s.bot && !s.standIn).map((s) => ({ id: s.id, name: s.name }));
|
|
}
|
|
|
|
/** A bot named in a line of talk answers it. */
|
|
private answer(room: Room, speaker: string, text: string): void {
|
|
for (const bot of botsNamed(text, this.voiced(room))) this.commit(room, { t: 'chat', at: Date.now(), id: bot.id, text: botLine(bot.name, bot.moment, { who: speaker }) });
|
|
}
|
|
|
|
/** The view for a seat, or for the gallery when the seat is SPECTATOR. */
|
|
view(room: Room, seatId: WizardId): RoomView {
|
|
return {
|
|
roomId: room.id,
|
|
seq: room.seq,
|
|
size: room.size,
|
|
me: seatId,
|
|
host: room.seats[0]?.id ?? seatId,
|
|
seats: room.seats.map((s) => ({ id: s.id, name: s.name, bot: s.bot, ...(s.standIn ? { standIn: true as const } : {}) })),
|
|
waitingOn: waitingOn(room),
|
|
resolved: room.resolved,
|
|
state: room.state ? viewFor(room.state, seatId) : null,
|
|
chat: room.chat,
|
|
audience: this.gallery.get(room.id) ?? 0,
|
|
galleryTalk: room.galleryTalk,
|
|
challenge: room.challenge,
|
|
expected: this.awaited(room),
|
|
rematch: room.rematch,
|
|
rematchOf: room.rematchOf,
|
|
keeper: this.keeper.name,
|
|
keeperZone: this.keeper.zone
|
|
};
|
|
}
|
|
|
|
subscribe(roomId: string, fn: (room: Room) => void): () => void {
|
|
if (!this.listeners.has(roomId)) this.listeners.set(roomId, new Set());
|
|
this.listeners.get(roomId)!.add(fn);
|
|
return () => this.listeners.get(roomId)?.delete(fn);
|
|
}
|
|
|
|
/** Subscribe from the gallery; the table is told when its audience changes. */
|
|
watch(room: Room, fn: (room: Room) => void): () => void {
|
|
const unsubscribe = this.subscribe(room.id, fn);
|
|
this.gallery.set(room.id, (this.gallery.get(room.id) ?? 0) + 1);
|
|
room.seq += 1;
|
|
this.notify(room);
|
|
return () => {
|
|
unsubscribe();
|
|
this.gallery.set(room.id, Math.max(0, (this.gallery.get(room.id) ?? 1) - 1));
|
|
room.seq += 1;
|
|
this.notify(room);
|
|
};
|
|
}
|
|
|
|
audience(room: Room): number {
|
|
return this.gallery.get(room.id) ?? 0;
|
|
}
|
|
|
|
/** Write to the ledger, then apply; the file is the truth a restart returns to. */
|
|
private commit(room: Room, line: LedgerLine): void {
|
|
this.store.append(room.id, line);
|
|
apply(room, line);
|
|
room.seq += 1;
|
|
room.updatedAt = Date.now();
|
|
this.notify(room);
|
|
}
|
|
|
|
private notify(room: Room): void {
|
|
for (const fn of this.listeners.get(room.id) ?? []) fn(room);
|
|
}
|
|
}
|
|
|
|
/** Seats whose input the next resolution needs and has not yet received. */
|
|
export function waitingOn(room: Room): WizardId[] {
|
|
if (!room.state || room.state.over) return [];
|
|
return room.seats
|
|
.filter((s) => !s.bot && needsInput(room.state!, s.id) && !(s.id in room.pending))
|
|
.map((s) => s.id);
|
|
}
|
|
|
|
function needsInput(state: GameState, id: WizardId): boolean {
|
|
if (state.timeStops.length > 0) return state.timeStops[0] === id;
|
|
return inDuel(state.wizards[id]);
|
|
}
|
|
|
|
function apply(room: Room, line: LedgerLine): void {
|
|
switch (line.t) {
|
|
case 'room':
|
|
break;
|
|
case 'seat':
|
|
room.seats.push({ id: line.id, name: line.name, tokenHash: line.tokenHash ?? (line.token ? hashToken(line.token) : ''), bot: line.bot });
|
|
break;
|
|
case 'seen': {
|
|
const seat = room.seats.find((s) => s.id === line.id);
|
|
if (seat) seat.addr = line.addr;
|
|
break;
|
|
}
|
|
case 'reseat': {
|
|
const seat = room.seats.find((s) => s.id === line.id);
|
|
if (!seat) break;
|
|
seat.tokenHash = line.tokenHash;
|
|
// Whoever used the seat before has no claim on it by address now: the next use from the new device is noted afresh.
|
|
delete seat.addr;
|
|
seat.bot = false;
|
|
delete seat.standIn;
|
|
break;
|
|
}
|
|
case 'standIn': {
|
|
const seat = room.seats.find((s) => s.id === line.id);
|
|
if (!seat) break;
|
|
seat.bot = true;
|
|
seat.standIn = true;
|
|
break;
|
|
}
|
|
case 'input':
|
|
room.pending[line.id] = line.input;
|
|
break;
|
|
case 'galleryTalk':
|
|
room.galleryTalk = line.on;
|
|
break;
|
|
case 'challenge':
|
|
room.challenge = { by: line.by, at: line.at };
|
|
if (!room.expected.some((n) => n.toLowerCase() === line.keeper.toLowerCase())) room.expected = [...room.expected, line.keeper];
|
|
break;
|
|
case 'rematch':
|
|
room.rematch = { to: line.to, by: line.by };
|
|
break;
|
|
case 'unseat':
|
|
room.seats = room.seats.filter((s) => s.id !== line.id);
|
|
break;
|
|
case 'start':
|
|
room.state = createGame(Object.fromEntries(room.seats.map((s) => [s.id, s.name])), line.seed, line.rules ?? 1);
|
|
break;
|
|
case 'turn':
|
|
if (!room.state) return;
|
|
room.state = resolveTurn(room.state, line.inputs);
|
|
room.pending = {};
|
|
room.resolved += 1;
|
|
break;
|
|
case 'over':
|
|
break;
|
|
case 'chat':
|
|
room.chat.push({ id: line.id, text: line.text, at: line.at, ...(line.name ? { name: line.name } : {}), ...(line.keeper ? { keeper: true as const } : {}) });
|
|
if (room.chat.length > CHAT_KEEP) room.chat.splice(0, room.chat.length - CHAT_KEEP);
|
|
break;
|
|
}
|
|
}
|
|
|
|
function replay(id: string, lines: LedgerLine[]): Room | null {
|
|
const first = lines[0];
|
|
if (!first || first.t !== 'room') return null;
|
|
const room = blank(id, first.seats, first.createdAt, first.rematchOf ?? null, first.expected ?? [], lines.length);
|
|
for (const line of lines) {
|
|
apply(room, line);
|
|
if (line.t === 'turn' || line.t === 'input') room.updatedAt = line.at;
|
|
}
|
|
return room;
|
|
}
|
|
|
|
function cleanTalk(raw: unknown): string {
|
|
const text = String(raw ?? '')
|
|
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
.replace(/\s+/g, ' ')
|
|
.trim()
|
|
.slice(0, CHAT_MAX_LENGTH);
|
|
if (!text) throw new RoomError('Nothing to say.');
|
|
return text;
|
|
}
|
|
|
|
export function cleanName(raw: unknown): string {
|
|
const name = String(raw ?? '')
|
|
.replace(/\s+/g, ' ')
|
|
.trim()
|
|
.slice(0, 24);
|
|
if (!name) throw new RoomError('A wizard needs a name.');
|
|
return name;
|
|
}
|
|
|
|
/** Only the shapes the engine understands get through; the engine validates the rest. */
|
|
function cleanInput(raw: unknown): TurnInput {
|
|
const r = (raw ?? {}) as Record<string, unknown>;
|
|
const gesture = (g: unknown): Gesture => (GESTURES.includes(g as Gesture) ? (g as Gesture) : '-');
|
|
const casts = Array.isArray(r.casts) ? (r.casts as TurnInput['casts']).slice(0, 4) : [];
|
|
const input: TurnInput = { left: gesture(r.left), right: gesture(r.right), casts };
|
|
if (r.second && typeof r.second === 'object') {
|
|
const s = r.second as Record<string, unknown>;
|
|
input.second = { left: gesture(s.left), right: gesture(s.right), casts: Array.isArray(s.casts) ? (s.casts as TurnInput['casts']).slice(0, 4) : [] };
|
|
if (typeof s.stabTarget === 'string') input.second.stabTarget = s.stabTarget;
|
|
}
|
|
if (r.release && typeof r.release === 'object') input.release = r.release as TurnInput['release'];
|
|
if (typeof r.stabTarget === 'string') input.stabTarget = r.stabTarget;
|
|
if (r.monsterOrders && typeof r.monsterOrders === 'object') input.monsterOrders = r.monsterOrders as TurnInput['monsterOrders'];
|
|
if (typeof r.charmGesture === 'string') input.charmGesture = gesture(r.charmGesture);
|
|
return input;
|
|
}
|