/** * The game session as seen by one browser: the live connection plus the * derived Svelte stores the UI reads from. * * The server is the single source of truth (PLAN.md section 3.1): this * client holds only the last full state snapshot, the seat table, its own * session identity, and connection status. Every mutation is a command sent * to the server; the resulting `update` replaces the local snapshot. */ import { derived, writable, get, type Readable, type Writable } from 'svelte/store'; import { GameConnection, type ConnectionOptions, type ConnectionStatus } from '../protocol/connection'; import type { GameState, Role, ServerMessage, SettingsPayload } from '../protocol/types'; import { serverSettings } from '../settings'; export interface SessionInfo { id: string; role: Role; } export interface ProtocolError { code: string; message: string; } export class GameSession { readonly state: Writable = writable(null); readonly seats: Writable> = writable({}); readonly session: Writable = writable(null); readonly status: Writable = writable('connecting'); readonly index: Writable = writable(-1); readonly description: Writable = writable(null); /** The number of undoable actions in the history. */ readonly historyLength: Writable = writable(0); /** The action an undo would roll back (null at the baseline). */ readonly undoDescription: Writable = writable(null); /** The action a redo would re-execute (null when exhausted). */ readonly redoDescription: Writable = writable(null); readonly lastError: Writable = writable(null); /** * Reactive player/spectator flag derived from the live seat table (see * `isSpectator()`). The UI reads this as a store — it flips the moment * a claim is granted, without waiting for a new `welcome`. */ readonly player: Readable = derived( [this.session, this.seats], ([session, seats]) => { if (!session) return false; return Object.values(seats).some((owner) => owner === session.id); } ); private readonly connection: GameConnection; constructor(options: ConnectionOptions = {}) { this.connection = new GameConnection(options); this.connection.onStatus = (s) => this.status.set(s); this.connection.onMessage = (m) => this.handle(m); this.connection.onError = (e) => this.lastError.set({ code: e.code, message: e.message }); } /** The underlying connection (for advanced control / resync). */ get conn(): GameConnection { return this.connection; } private handle(message: ServerMessage): void { switch (message.t) { case 'welcome': this.session.set({ id: message.session, role: message.role }); this.state.set(message.state); this.seats.set(message.seats); this.index.set(message.index); this.description.set(message.description); this.historyLength.set(message.historyLength); this.undoDescription.set(message.undoDescription); this.redoDescription.set(message.redoDescription); serverSettings.set(message.settings); break; case 'update': this.state.set(message.state); this.index.set(message.index); this.description.set(message.description); this.historyLength.set(message.historyLength); this.undoDescription.set(message.undoDescription); this.redoDescription.set(message.redoDescription); break; case 'seats': this.seats.set(message.seats); break; case 'settings': serverSettings.set(message.settings); break; case 'error': this.lastError.set({ code: message.code, message: message.message }); break; case 'pong': // keepalive ack — nothing to surface break; } } connect(): void { this.connection.connect(); } disconnect(): void { this.connection.disconnect(); } // --- ownership ------------------------------------------------------------ /** True when [characterId] is owned by this session. */ owns(characterId: string): boolean { const s = get(this.session); const seats = get(this.seats); return !!s && seats[characterId] === s.id; } /** This session's role (null before the first welcome). */ role(): Role | null { return get(this.session)?.role ?? null; } /** The character ids this session owns. */ ownedCharacterIds(): string[] { const s = get(this.session); if (!s) return []; const seats = get(this.seats); return Object.keys(seats).filter((id) => seats[id] === s.id); } /** * A spectator has claimed no character. Derived from the live seat table * (not the `welcome` role, which is only computed at handshake) so that * the moment a claim is granted the UI switches to player controls — * the `seats` broadcast carries the truth. */ isSpectator(): boolean { return this.ownedCharacterIds().length === 0; } // --- commands ------------------------------------------------------------- command(name: string, args: Record = {}): void { this.connection.sendCmd(name, args); } claim(characterId: string): void { this.connection.claim(characterId); } undo(): void { this.connection.undo(); } redo(): void { this.connection.redo(); } // --- Phase 6: settings + saves (players only on the server side) -------- /** Set a server-side (game-relevant) setting (the server broadcasts it). */ setSetting(name: string, value: boolean | number | string): void { this.connection.setSetting(name, value); } /** Save the current game state to a named slot. */ save(name: string): void { this.connection.save(name); } /** Load a named save (an undoable action on the server). */ loadSave(name: string): void { this.connection.loadSave(name); } /** Delete a named save. */ deleteSave(name: string): void { this.connection.deleteSave(name); } /** Save one character's state under [name]. */ saveCharacter(name: string, characterId: string): void { this.connection.saveCharacter(name, characterId); } /** Load a character save ([saveId] = `"$name\n$characterId"`). */ loadCharacterSave(saveId: string): void { this.connection.loadCharacterSave(saveId); } /** Delete a character save. */ deleteCharacterSave(saveId: string): void { this.connection.deleteCharacterSave(saveId); } /** Clear a surfaced protocol error (call after toasting it). */ clearError(): void { this.lastError.set(null); } } /** * Convenience: the set of character ids owned by a given session within a * seat table. Exported for unit testing. */ export function ownedIds( sessionId: string | null, seats: Record ): string[] { if (!sessionId) return []; return Object.keys(seats).filter((id) => seats[id] === sessionId); }