1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
|
/**
* 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<GameState | null> = writable<GameState | null>(null);
readonly seats: Writable<Record<string, string | null>> = writable({});
readonly session: Writable<SessionInfo | null> = writable<SessionInfo | null>(null);
readonly status: Writable<ConnectionStatus> = writable('connecting');
readonly index: Writable<number> = writable(-1);
readonly description: Writable<string | null> = writable<string | null>(null);
/** The number of undoable actions in the history. */
readonly historyLength: Writable<number> = writable(0);
/** The action an undo would roll back (null at the baseline). */
readonly undoDescription: Writable<string | null> =
writable<string | null>(null);
/** The action a redo would re-execute (null when exhausted). */
readonly redoDescription: Writable<string | null> =
writable<string | null>(null);
readonly lastError: Writable<ProtocolError | null> =
writable<ProtocolError | null>(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<boolean> = 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<string, unknown> = {}): 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, string | null>
): string[] {
if (!sessionId) return [];
return Object.keys(seats).filter((id) => seats[id] === sessionId);
}
|