@journey-to-code/rooms 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/dist/client.d.ts +62 -0
- package/dist/client.js +134 -0
- package/dist/client.js.map +1 -0
- package/dist/server.d.ts +303 -0
- package/dist/server.js +875 -0
- package/dist/server.js.map +1 -0
- package/package.json +43 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
// Rooms: turn-based games (or anything with private per-person state) over @zubra/sync.
|
|
2
|
+
//
|
|
3
|
+
// The server is the only writer. A page never writes a document; it sends a move to
|
|
4
|
+
// `POST <mount>/<id>/act`, the room's `act` decides it, and the server writes every seat's view.
|
|
5
|
+
// `authorize` lets a player read only their own seat's view, so a hand stays in one browser.
|
|
6
|
+
//
|
|
7
|
+
// Collections:
|
|
8
|
+
// rooms/<id> public: seats (names, bots), whether it started, a summary,
|
|
9
|
+
// and the deadline that's running, if any (everyone reads)
|
|
10
|
+
// views/<id>/<seat> one seat's view of the game (that seat only)
|
|
11
|
+
// views/<id>/watch what someone watching may see: nobody's hand (everyone, if watching is allowed)
|
|
12
|
+
// games/<id> options, seed, when it was dealt, and seat holders (server only)
|
|
13
|
+
// moves/<id> every move and its time, one field per move, for replays (server only)
|
|
14
|
+
// chat/<id> the table's chat, one field per message (everyone)
|
|
15
|
+
import { createSyncServer, memoryLog } from "@zubra/sync/server";
|
|
16
|
+
export class RefusedMove extends Error {
|
|
17
|
+
name = "RefusedMove";
|
|
18
|
+
}
|
|
19
|
+
/** What a removed chat message says instead. */
|
|
20
|
+
export const REMOVED_TEXT = "(removed by a moderator)";
|
|
21
|
+
/** How long a message may be, and how often one player may send. */
|
|
22
|
+
export const CHAT_LIMIT = 280;
|
|
23
|
+
const CHAT_GAP_MS = 400;
|
|
24
|
+
/** setTimeout can't wait longer than this (about 24.8 days): a longer deadline wakes and waits again. */
|
|
25
|
+
const LONGEST_TIMEOUT = 2 ** 31 - 1;
|
|
26
|
+
const COOKIE = "rooms_player";
|
|
27
|
+
const ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
|
|
28
|
+
const randomId = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => ALPHABET[b % ALPHABET.length]).join("");
|
|
29
|
+
/** A new player id: the secret a browser's cookie holds. */
|
|
30
|
+
export const newPlayerId = () => randomId(24);
|
|
31
|
+
/** Whether the browser reached us over HTTPS: directly, or through a proxy that says so (Railway). */
|
|
32
|
+
export function overHttps(request) {
|
|
33
|
+
if (!request)
|
|
34
|
+
return false;
|
|
35
|
+
const forwarded = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
|
|
36
|
+
if (forwarded)
|
|
37
|
+
return forwarded === "https";
|
|
38
|
+
try {
|
|
39
|
+
return new URL(request.url).protocol === "https:";
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The Set-Cookie value that makes a browser this player, for a year. Over HTTPS it's also Secure, so
|
|
47
|
+
* the browser never sends it over plain http; plain-http development (localhost) still works.
|
|
48
|
+
*/
|
|
49
|
+
export const playerCookie = (player, request) => `${COOKIE}=${player}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000${overHttps(request) ? "; Secure" : ""}`;
|
|
50
|
+
export function playerOf(request) {
|
|
51
|
+
const cookie = request.headers.get("cookie") ?? "";
|
|
52
|
+
const match = cookie.match(new RegExp(`(?:^|;\\s*)${COOKIE}=([a-z0-9]+)`));
|
|
53
|
+
return match?.[1] ?? null;
|
|
54
|
+
}
|
|
55
|
+
const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
|
|
56
|
+
export function createRooms(def, options = {}) {
|
|
57
|
+
const mount = (options.mount ?? "/rooms").replace(/\/$/, "");
|
|
58
|
+
const fixedDelay = options.botDelay;
|
|
59
|
+
const grace = options.deadlineGrace ?? 5000;
|
|
60
|
+
const seatsFor = (o) => (typeof def.seats === "function" ? def.seats(o) : def.seats);
|
|
61
|
+
/** Run an app's hook without letting it break the room. */
|
|
62
|
+
const safely = (fn) => {
|
|
63
|
+
try {
|
|
64
|
+
fn();
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
console.error("rooms: a hook threw", e);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const newSeed = options.seed ?? (() => crypto.getRandomValues(new Uint32Array(1))[0]);
|
|
71
|
+
const newId = options.id ?? (() => randomId(6));
|
|
72
|
+
const live = new Map();
|
|
73
|
+
const sync = createSyncServer({
|
|
74
|
+
mount: options.syncMount ?? "/_zb/sync",
|
|
75
|
+
log: options.log ?? memoryLog({ keep: "latest" }),
|
|
76
|
+
authorize: async ({ request, collection, key, kind }) => {
|
|
77
|
+
if (kind === "change")
|
|
78
|
+
return false; // the server is the only writer
|
|
79
|
+
if (collection === "rooms")
|
|
80
|
+
return true; // reading, and presence (who's at the table)
|
|
81
|
+
if (collection === "chat" && kind === "read")
|
|
82
|
+
return true;
|
|
83
|
+
if (collection === "views" && kind === "read") {
|
|
84
|
+
// The watch view holds only what every seat can already see.
|
|
85
|
+
if (key.endsWith("/watch"))
|
|
86
|
+
return (await options.spectators?.()) ?? true;
|
|
87
|
+
const [id, seat] = splitViewKey(key);
|
|
88
|
+
// A table of computer players has no hands to keep secret.
|
|
89
|
+
if ((await room(id))?.watchable)
|
|
90
|
+
return true;
|
|
91
|
+
const player = playerOf(request);
|
|
92
|
+
return player !== null && (await game(id))?.holders[seat] === player;
|
|
93
|
+
}
|
|
94
|
+
return false; // games and moves are the server's alone
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
const docs = sync.documents();
|
|
98
|
+
const splitViewKey = (key) => {
|
|
99
|
+
const at = key.lastIndexOf("/");
|
|
100
|
+
return [key.slice(0, at), Number(key.slice(at + 1))];
|
|
101
|
+
};
|
|
102
|
+
const game = async (id) => (await docs).get("games", id);
|
|
103
|
+
const room = async (id) => (await docs).get("rooms", id);
|
|
104
|
+
/** The live state of a room, replaying its move log after a restart. */
|
|
105
|
+
async function stateOf(id) {
|
|
106
|
+
const entry = live.get(id);
|
|
107
|
+
if (entry)
|
|
108
|
+
return entry;
|
|
109
|
+
// Two requests for a room that isn't in memory share one restore: a second copy of the room
|
|
110
|
+
// would mean a second deadline, and a timeout applied twice.
|
|
111
|
+
let pending = restoring.get(id);
|
|
112
|
+
if (!pending) {
|
|
113
|
+
pending = restore(id).finally(() => restoring.delete(id));
|
|
114
|
+
restoring.set(id, pending);
|
|
115
|
+
}
|
|
116
|
+
return pending;
|
|
117
|
+
}
|
|
118
|
+
const restoring = new Map();
|
|
119
|
+
async function restore(id) {
|
|
120
|
+
const r = await room(id);
|
|
121
|
+
const g = await game(id);
|
|
122
|
+
const entry = { state: null, moves: 0, version: r?.version ?? 0, bot: null, timer: null, last: Date.now(), table: tableOf(r, g), deadline: null };
|
|
123
|
+
if (g?.seed != null) {
|
|
124
|
+
// A game dealt before moves had times starts its clock now, for good: writing it down means
|
|
125
|
+
// every later replay counts from the same moment.
|
|
126
|
+
const startedAt = g.startedAt ?? Date.now();
|
|
127
|
+
if (g.startedAt == null)
|
|
128
|
+
void sync.write("games", id, { startedAt });
|
|
129
|
+
let state = def.setup(g.options, g.seed);
|
|
130
|
+
const log = (await docs).get("moves", id) ?? {};
|
|
131
|
+
const count = Object.keys(log).filter((k) => /^\d+$/.test(k)).length;
|
|
132
|
+
// Each move gets the time it was first decided at, so a game with clocks replays to the same
|
|
133
|
+
// state. A move from before times were kept took no time at all.
|
|
134
|
+
let last = startedAt;
|
|
135
|
+
for (let n = 0; n < count; n++) {
|
|
136
|
+
const { seat, move, at } = log[String(n)];
|
|
137
|
+
const when = Math.max(at ?? last, last);
|
|
138
|
+
state = def.act(state, seat, move, { at: when, elapsed: when - last });
|
|
139
|
+
last = when;
|
|
140
|
+
}
|
|
141
|
+
entry.state = state;
|
|
142
|
+
entry.moves = count;
|
|
143
|
+
entry.last = last;
|
|
144
|
+
}
|
|
145
|
+
live.set(id, entry);
|
|
146
|
+
// The clock kept running while the server was away: the deadline is where it was, measured from
|
|
147
|
+
// the last move's own time. If that has already passed, the seat gets a moment's grace first.
|
|
148
|
+
arm(id, entry, true);
|
|
149
|
+
const now = deadlineDoc(entry);
|
|
150
|
+
if (now?.at !== r?.deadline?.at || now?.seat !== r?.deadline?.seat)
|
|
151
|
+
void sync.write("rooms", id, { deadline: now });
|
|
152
|
+
return entry;
|
|
153
|
+
}
|
|
154
|
+
const tableOf = (r, g) => ({
|
|
155
|
+
// A room from before it had settings plays with the defaults.
|
|
156
|
+
settings: g?.settings ?? def.settings?.(undefined) ?? null,
|
|
157
|
+
seats: r?.seats ?? [],
|
|
158
|
+
});
|
|
159
|
+
const deadlineDoc = (entry) => (entry.deadline ? { at: entry.deadline.at, seat: entry.deadline.seat } : null);
|
|
160
|
+
function disarm(entry) {
|
|
161
|
+
if (entry.deadline?.timer)
|
|
162
|
+
clearTimeout(entry.deadline.timer);
|
|
163
|
+
entry.deadline = null;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Ask the game for its deadline in this state and set the one timer that keeps it. `sudden` is for a
|
|
167
|
+
* deadline nobody at the table saw coming (a restart, a changed setting): it's never closer than the
|
|
168
|
+
* grace period, unless the one it replaces already was. Returns whether there is one now.
|
|
169
|
+
*/
|
|
170
|
+
function arm(id, entry, sudden = false) {
|
|
171
|
+
const before = entry.deadline?.at ?? null;
|
|
172
|
+
disarm(entry);
|
|
173
|
+
if (!def.deadline || entry.state === null || def.finished?.(entry.state))
|
|
174
|
+
return false;
|
|
175
|
+
let due = null;
|
|
176
|
+
try {
|
|
177
|
+
due = def.deadline(entry.state, entry.table);
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
console.error(`rooms: the deadline of ${id} threw`, e);
|
|
181
|
+
}
|
|
182
|
+
const asked = due ? (due.at ?? (due.after === undefined ? NaN : entry.last + due.after)) : NaN;
|
|
183
|
+
if (!due || !Number.isFinite(asked))
|
|
184
|
+
return false;
|
|
185
|
+
let at = Math.round(asked);
|
|
186
|
+
// The grace never puts off a deadline that was already armed, or asking twice would be a way to stall.
|
|
187
|
+
if (sudden)
|
|
188
|
+
at = Math.max(at, Math.min(Date.now() + grace, before ?? Infinity));
|
|
189
|
+
const armed = { at, fire: at + Math.max(0, due.grace ?? 0), seat: due.seat, timer: null };
|
|
190
|
+
const wait = () => {
|
|
191
|
+
armed.timer = setTimeout(() => {
|
|
192
|
+
armed.timer = null;
|
|
193
|
+
if (entry.deadline !== armed)
|
|
194
|
+
return; // a move got in first
|
|
195
|
+
if (Date.now() < armed.fire)
|
|
196
|
+
return wait(); // longer than one timer can sleep, or the timer woke early
|
|
197
|
+
timeUp(id, entry, armed);
|
|
198
|
+
}, Math.min(Math.max(armed.fire - Date.now(), 0), LONGEST_TIMEOUT));
|
|
199
|
+
};
|
|
200
|
+
entry.deadline = armed;
|
|
201
|
+
wait();
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Time ran out: make the game's timeout move, exactly as if the seat had sent it. Everything up to
|
|
206
|
+
* recording the move happens with no await, and a move that got in first has already put this
|
|
207
|
+
* deadline away (see apply), so a move and a timeout can never both land on the same state.
|
|
208
|
+
*/
|
|
209
|
+
function timeUp(id, entry, armed) {
|
|
210
|
+
entry.deadline = null;
|
|
211
|
+
let applied = null;
|
|
212
|
+
try {
|
|
213
|
+
const due = entry.state === null ? null : def.deadline(entry.state, entry.table);
|
|
214
|
+
const move = due && due.seat === armed.seat ? due.move() : null;
|
|
215
|
+
if (move !== null)
|
|
216
|
+
applied = { before: apply(id, entry, armed.seat, move), move };
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
console.error(`rooms: the timeout move in ${id} for seat ${armed.seat} was refused`, e);
|
|
220
|
+
}
|
|
221
|
+
// Nothing to do for that seat: the game waits, and pages stop counting down.
|
|
222
|
+
if (!applied)
|
|
223
|
+
return void sync.write("rooms", id, { deadline: null });
|
|
224
|
+
void settle(id, entry, applied.before, armed.seat, applied.move, true);
|
|
225
|
+
}
|
|
226
|
+
/** After any move: tell everyone, then let the bots and the clock carry on (or put the game away). */
|
|
227
|
+
async function settle(id, entry, before, seat, move, timeout = false) {
|
|
228
|
+
const after = entry.state;
|
|
229
|
+
await publish(id, entry);
|
|
230
|
+
void moved(id, before, after, seat, move, timeout);
|
|
231
|
+
if (!forgetIfFinished(id, entry))
|
|
232
|
+
void driveBots(id);
|
|
233
|
+
}
|
|
234
|
+
/** Messages per room, counted once from the log and then kept here. */
|
|
235
|
+
const chatCount = new Map();
|
|
236
|
+
const lastSaid = new Map();
|
|
237
|
+
/** Add a message to a room's chat, as a seat. Bots speak through this too. */
|
|
238
|
+
async function say(id, seat, text) {
|
|
239
|
+
const clean = text.replace(/\s+/g, " ").trim().slice(0, CHAT_LIMIT);
|
|
240
|
+
if (!clean)
|
|
241
|
+
return "Say something first.";
|
|
242
|
+
const r = await room(id);
|
|
243
|
+
const who = r?.seats[seat];
|
|
244
|
+
if (!r || !who)
|
|
245
|
+
return "No such seat.";
|
|
246
|
+
if (!chatCount.has(id)) {
|
|
247
|
+
const existing = (await docs).get("chat", id) ?? {};
|
|
248
|
+
chatCount.set(id, Object.keys(existing).filter((k) => /^m\d+$/.test(k)).length);
|
|
249
|
+
}
|
|
250
|
+
const n = chatCount.get(id);
|
|
251
|
+
chatCount.set(id, n + 1);
|
|
252
|
+
const message = { seat, name: who.name ?? `Seat ${seat + 1}`, text: clean, at: Date.now(), bot: who.bot };
|
|
253
|
+
await sync.write("chat", id, { [`m${String(n).padStart(6, "0")}`]: message });
|
|
254
|
+
return message;
|
|
255
|
+
}
|
|
256
|
+
/** Open a new room with these options. Resolves to its id. */
|
|
257
|
+
async function create(roomOptions, given) {
|
|
258
|
+
const id = newId();
|
|
259
|
+
const n = seatsFor(roomOptions);
|
|
260
|
+
const settings = def.settings ? def.settings(given) : null;
|
|
261
|
+
await sync.write("games", id, { options: roomOptions, settings, seed: null, holders: Array(n).fill(null) });
|
|
262
|
+
await sync.write("rooms", id, { seats: Array.from({ length: n }, () => ({ name: null, bot: false })), info: def.info?.(roomOptions) ?? null, settings, started: false, summary: null, version: 0 });
|
|
263
|
+
return id;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Seat a player (by their player id) or a bot, from server code, before the game starts. An app
|
|
267
|
+
* that sets up a table itself (a challenge, say) uses these instead of the HTTP endpoints.
|
|
268
|
+
*/
|
|
269
|
+
async function seatPlayer(id, seat, player, name) {
|
|
270
|
+
const g = await game(id);
|
|
271
|
+
const r = await room(id);
|
|
272
|
+
if (!g || !r || r.started)
|
|
273
|
+
throw new Error("That table isn't open.");
|
|
274
|
+
const holders = g.holders.map((h) => (h === player ? null : h));
|
|
275
|
+
holders[seat] = player;
|
|
276
|
+
const seats = r.seats.map((s, i) => (holders[i] === null && !s.bot ? { name: null, bot: false } : s));
|
|
277
|
+
seats[seat] = { name: name.trim().slice(0, 20) || "Player", bot: false };
|
|
278
|
+
await sync.write("games", id, { holders });
|
|
279
|
+
await sync.write("rooms", id, { seats });
|
|
280
|
+
await seatsChanged(id);
|
|
281
|
+
}
|
|
282
|
+
async function seatBot(id, seat, name) {
|
|
283
|
+
const r = await room(id);
|
|
284
|
+
if (!r || r.started)
|
|
285
|
+
throw new Error("That table isn't open.");
|
|
286
|
+
const seats = [...r.seats];
|
|
287
|
+
seats[seat] = { name, bot: true };
|
|
288
|
+
await sync.write("rooms", id, { seats });
|
|
289
|
+
await seatsChanged(id);
|
|
290
|
+
}
|
|
291
|
+
/** Free a person's seat before the game starts (they left, say). Resolves to whether anyone was there. */
|
|
292
|
+
async function unseat(id, seat) {
|
|
293
|
+
const g = await game(id);
|
|
294
|
+
const r = await room(id);
|
|
295
|
+
if (!g || !r || r.started || !g.holders[seat])
|
|
296
|
+
return false;
|
|
297
|
+
const holders = [...g.holders];
|
|
298
|
+
holders[seat] = null;
|
|
299
|
+
const seats = [...r.seats];
|
|
300
|
+
seats[seat] = { name: null, bot: false };
|
|
301
|
+
await sync.write("games", id, { holders });
|
|
302
|
+
await sync.write("rooms", id, { seats });
|
|
303
|
+
await seatsChanged(id);
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Take a person's seat away and sit a bot there, at any point. In a game that's been dealt, the bot
|
|
308
|
+
* plays on from where they were. Resolves to whether anyone was there.
|
|
309
|
+
*/
|
|
310
|
+
async function replaceWithBot(id, seat, name) {
|
|
311
|
+
const g = await game(id);
|
|
312
|
+
const r = await room(id);
|
|
313
|
+
if (!g || !r || !g.holders[seat])
|
|
314
|
+
return false;
|
|
315
|
+
const holders = [...g.holders];
|
|
316
|
+
holders[seat] = null;
|
|
317
|
+
const seats = [...r.seats];
|
|
318
|
+
seats[seat] = { name, bot: true };
|
|
319
|
+
await sync.write("games", id, { holders });
|
|
320
|
+
await sync.write("rooms", id, { seats });
|
|
321
|
+
if (!r.started)
|
|
322
|
+
return await seatsChanged(id), true;
|
|
323
|
+
if (r.closed)
|
|
324
|
+
return true; // nothing plays on at a closed table
|
|
325
|
+
const entry = await stateOf(id);
|
|
326
|
+
entry.table = { ...entry.table, seats };
|
|
327
|
+
stopBot(entry);
|
|
328
|
+
// A clock that was running on the person isn't the bot's: work it out again.
|
|
329
|
+
if (def.deadline && entry.state !== null) {
|
|
330
|
+
const before = deadlineDoc(entry);
|
|
331
|
+
arm(id, entry, true);
|
|
332
|
+
const now = deadlineDoc(entry);
|
|
333
|
+
if (before?.at !== now?.at || before?.seat !== now?.seat)
|
|
334
|
+
void sync.write("rooms", id, { deadline: now });
|
|
335
|
+
}
|
|
336
|
+
void driveBots(id);
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
/** Tell the app the seats changed. */
|
|
340
|
+
async function seatsChanged(id) {
|
|
341
|
+
if (!options.onSeats)
|
|
342
|
+
return;
|
|
343
|
+
const r = await room(id);
|
|
344
|
+
if (r)
|
|
345
|
+
safely(() => options.onSeats({ id, room: r }));
|
|
346
|
+
}
|
|
347
|
+
/** Deal: from a seated player's request, or from server code. Resolves to a problem, or null. */
|
|
348
|
+
async function start(id) {
|
|
349
|
+
const g = await game(id);
|
|
350
|
+
const r = await room(id);
|
|
351
|
+
if (!g || !r)
|
|
352
|
+
return "No such table.";
|
|
353
|
+
if (r.started)
|
|
354
|
+
return null;
|
|
355
|
+
if (r.seats.some((s, i) => !s.bot && !g.holders[i]))
|
|
356
|
+
return "Every seat needs a player or a bot.";
|
|
357
|
+
const seed = newSeed();
|
|
358
|
+
const entry = await stateOf(id);
|
|
359
|
+
if (entry.state !== null)
|
|
360
|
+
return null; // two people pressed Deal at once
|
|
361
|
+
const startedAt = Date.now();
|
|
362
|
+
entry.state = def.setup(g.options, seed);
|
|
363
|
+
entry.moves = 0;
|
|
364
|
+
entry.last = startedAt;
|
|
365
|
+
entry.table = tableOf(r, g);
|
|
366
|
+
await sync.write("games", id, { seed, startedAt });
|
|
367
|
+
await publish(id, entry);
|
|
368
|
+
if (options.onStart) {
|
|
369
|
+
const started = await room(id);
|
|
370
|
+
if (started)
|
|
371
|
+
safely(() => options.onStart({ id, state: entry.state, room: started }));
|
|
372
|
+
}
|
|
373
|
+
void driveBots(id);
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
/** Set the seats for good (after seating everyone from server code), and name the table. */
|
|
377
|
+
async function lock(id, label) {
|
|
378
|
+
await sync.write("rooms", id, { locked: true, ...(label ? { label: label.slice(0, 60) } : {}) });
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Make a table one to watch: its seats are set (all computer players, seated from server code)
|
|
382
|
+
* and anyone may read every seat's view. Refuses a table with a person at it.
|
|
383
|
+
*/
|
|
384
|
+
async function exhibit(id, label) {
|
|
385
|
+
const g = await game(id);
|
|
386
|
+
const r = await room(id);
|
|
387
|
+
if (!g || !r || g.holders.some(Boolean) || r.seats.some((s) => !s.bot))
|
|
388
|
+
throw new Error("Only a table of computer players can be watched this way.");
|
|
389
|
+
await sync.write("rooms", id, { locked: true, watchable: true, ...(label ? { label: label.slice(0, 60) } : {}) });
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Close a table for good (moderation): bots stop, and every later seat, move or message is
|
|
393
|
+
* refused with `reason`. Pages see `closed` on the room. Resolves false when there's no such table.
|
|
394
|
+
*/
|
|
395
|
+
async function closeTable(id, reason) {
|
|
396
|
+
if (!(await room(id)))
|
|
397
|
+
return false;
|
|
398
|
+
await sync.write("rooms", id, { closed: reason.replace(/\s+/g, " ").trim().slice(0, 200) || "This table was closed." });
|
|
399
|
+
const entry = live.get(id);
|
|
400
|
+
if (entry)
|
|
401
|
+
stopBot(entry);
|
|
402
|
+
live.delete(id);
|
|
403
|
+
return true;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Take a person out of a seat (moderation). Before the game starts the seat is simply free again;
|
|
407
|
+
* once it has, a bot called `bot` plays the seat on, so the others can finish. Resolves to a
|
|
408
|
+
* problem, or null.
|
|
409
|
+
*/
|
|
410
|
+
async function removePlayer(id, seat, bot = "Bot") {
|
|
411
|
+
const g = await game(id);
|
|
412
|
+
const r = await room(id);
|
|
413
|
+
if (!g || !r)
|
|
414
|
+
return "No such table.";
|
|
415
|
+
if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length || !g.holders[seat])
|
|
416
|
+
return "Nobody's sitting there.";
|
|
417
|
+
const gone = r.started ? await replaceWithBot(id, seat, bot.trim().slice(0, 20) || "Bot") : await unseat(id, seat);
|
|
418
|
+
return gone ? null : "Nobody's sitting there.";
|
|
419
|
+
}
|
|
420
|
+
/** Take the words out of a chat message (moderation). `key` is the message's field in `chat/<id>`. */
|
|
421
|
+
async function redact(id, key) {
|
|
422
|
+
const message = ((await docs).get("chat", id) ?? {})[key];
|
|
423
|
+
if (!/^m\d+$/.test(key) || !message)
|
|
424
|
+
return false;
|
|
425
|
+
await sync.write("chat", id, { [key]: { ...message, text: REMOVED_TEXT, removed: true } });
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
/** Who holds each seat (player ids), for server code. Never send these to a page. */
|
|
429
|
+
async function holders(id) {
|
|
430
|
+
return (await game(id))?.holders ?? [];
|
|
431
|
+
}
|
|
432
|
+
/** A finished game no longer needs its state in memory: a later request replays it from the log. */
|
|
433
|
+
function forgetIfFinished(id, entry) {
|
|
434
|
+
if (entry.state === null || !def.finished?.(entry.state))
|
|
435
|
+
return false;
|
|
436
|
+
stopBot(entry);
|
|
437
|
+
disarm(entry);
|
|
438
|
+
live.delete(id);
|
|
439
|
+
return true;
|
|
440
|
+
}
|
|
441
|
+
/** Write every seat's view and the public room doc. */
|
|
442
|
+
async function publish(id, entry) {
|
|
443
|
+
entry.version += 1;
|
|
444
|
+
// The state changed, so its deadline did: arm it before anything is awaited, and publish it with the rest.
|
|
445
|
+
arm(id, entry);
|
|
446
|
+
const deadline = deadlineDoc(entry);
|
|
447
|
+
const writes = [];
|
|
448
|
+
if (entry.state !== null) {
|
|
449
|
+
const n = (await game(id))?.holders.length ?? 0;
|
|
450
|
+
const views = Array.from({ length: n }, (_, seat) => def.view(entry.state, seat));
|
|
451
|
+
for (const [seat, view] of views.entries())
|
|
452
|
+
writes.push(sync.write("views", `${id}/${seat}`, { view, version: entry.version }));
|
|
453
|
+
if (def.watch)
|
|
454
|
+
writes.push(sync.write("views", `${id}/watch`, { view: def.watch(entry.state, views), version: entry.version }));
|
|
455
|
+
}
|
|
456
|
+
writes.push(sync.write("rooms", id, {
|
|
457
|
+
started: entry.state !== null,
|
|
458
|
+
summary: entry.state !== null && def.summary ? def.summary(entry.state) : null,
|
|
459
|
+
...(def.deadline ? { deadline, moved: entry.last } : {}),
|
|
460
|
+
version: entry.version,
|
|
461
|
+
}));
|
|
462
|
+
await Promise.all(writes);
|
|
463
|
+
}
|
|
464
|
+
/** Apply a move. No await between deciding and recording it, so two moves can't interleave. */
|
|
465
|
+
function apply(id, entry, seat, move) {
|
|
466
|
+
const before = entry.state;
|
|
467
|
+
const at = Math.max(Date.now(), entry.last); // a clock set back never makes a move take less than no time
|
|
468
|
+
const next = def.act(before, seat, move, { at, elapsed: at - entry.last }); // throws to refuse
|
|
469
|
+
entry.state = next;
|
|
470
|
+
entry.last = at;
|
|
471
|
+
// The deadline was for the state before this move: put it away now, so it can't fire on this one.
|
|
472
|
+
disarm(entry);
|
|
473
|
+
const n = entry.moves++;
|
|
474
|
+
void sync.write("moves", id, { [String(n)]: { seat, move, at } });
|
|
475
|
+
return before;
|
|
476
|
+
}
|
|
477
|
+
async function moved(id, before, after, seat, move, timeout = false) {
|
|
478
|
+
if (!options.onMove)
|
|
479
|
+
return;
|
|
480
|
+
const r = await room(id);
|
|
481
|
+
if (r)
|
|
482
|
+
safely(() => options.onMove({ id, before, after, seat, move, room: r, ...(timeout ? { timeout } : {}) }));
|
|
483
|
+
}
|
|
484
|
+
/** Stop the bot that's about to move, whatever it was doing: its pause ends and its answer, if one is still coming, is dropped. */
|
|
485
|
+
function stopBot(entry) {
|
|
486
|
+
if (entry.timer)
|
|
487
|
+
clearTimeout(entry.timer);
|
|
488
|
+
entry.timer = null;
|
|
489
|
+
entry.bot?.stop.abort();
|
|
490
|
+
entry.bot = null;
|
|
491
|
+
}
|
|
492
|
+
/** Ask for a bot's move: from `think` when the room has one (it may answer later), else from `bot`. */
|
|
493
|
+
const ask = (id, state, seat, name, settings, stop) => def.think ? def.think(state, seat, name, settings, { signal: stop.signal, table: id }) : def.bot(state, seat, name, settings);
|
|
494
|
+
const later = (answer) => typeof answer?.then === "function";
|
|
495
|
+
/**
|
|
496
|
+
* If it's a bot's move, make it after a pause. The think starts as the pause does, so a think
|
|
497
|
+
* that takes a while (see RoomDefinition.think) hides inside the pause instead of adding to it.
|
|
498
|
+
*/
|
|
499
|
+
async function driveBots(id) {
|
|
500
|
+
const entry = await stateOf(id);
|
|
501
|
+
if ((!def.bot && !def.think) || entry.state === null || entry.bot)
|
|
502
|
+
return;
|
|
503
|
+
const current = await room(id);
|
|
504
|
+
if (current?.closed)
|
|
505
|
+
return;
|
|
506
|
+
const seats = current?.seats ?? [];
|
|
507
|
+
// A room from before it had settings plays with the defaults.
|
|
508
|
+
const settings = (await game(id))?.settings ?? def.settings?.(undefined);
|
|
509
|
+
if (entry.bot)
|
|
510
|
+
return; // set while this was reading
|
|
511
|
+
for (let seat = 0; seat < seats.length; seat++) {
|
|
512
|
+
if (!seats[seat]?.bot)
|
|
513
|
+
continue;
|
|
514
|
+
const name = seats[seat].name ?? "";
|
|
515
|
+
const stop = new AbortController();
|
|
516
|
+
const answer = ask(id, entry.state, seat, name, settings, stop);
|
|
517
|
+
if (answer === null)
|
|
518
|
+
continue;
|
|
519
|
+
const delay = fixedDelay ?? def.botDelay?.(entry.state, seat, name, settings) ?? 700;
|
|
520
|
+
const turn = { seat, name, settings, state: entry.state, answer, stop };
|
|
521
|
+
// An answer that fails is reported when the pause ends; until then it mustn't count as unhandled.
|
|
522
|
+
if (later(answer))
|
|
523
|
+
answer.catch(() => { });
|
|
524
|
+
entry.bot = turn;
|
|
525
|
+
entry.timer = setTimeout(() => {
|
|
526
|
+
entry.timer = null;
|
|
527
|
+
void play(id, entry, turn);
|
|
528
|
+
}, delay);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* A bot's pause is over: play its move, on the state it was worked out for and no other. A pause
|
|
534
|
+
* isn't restarted because someone else moved meanwhile (in a race, a quick person mustn't keep
|
|
535
|
+
* resetting the computer's clock): the move is worked out again from the table as it is now, and
|
|
536
|
+
* played as soon as it's known.
|
|
537
|
+
*/
|
|
538
|
+
async function play(id, entry, turn) {
|
|
539
|
+
for (;;) {
|
|
540
|
+
if (entry.bot !== turn || entry.state === null)
|
|
541
|
+
return; // stopped: nobody wants this move any more
|
|
542
|
+
if (entry.state !== turn.state) {
|
|
543
|
+
turn.stop.abort();
|
|
544
|
+
turn.stop = new AbortController();
|
|
545
|
+
turn.state = entry.state;
|
|
546
|
+
try {
|
|
547
|
+
const answer = ask(id, turn.state, turn.seat, turn.name, turn.settings, turn.stop);
|
|
548
|
+
// Not this seat's move any more: see whose it is now.
|
|
549
|
+
if (answer === null)
|
|
550
|
+
return void ((entry.bot = null), live.get(id) === entry && driveBots(id));
|
|
551
|
+
turn.answer = answer;
|
|
552
|
+
}
|
|
553
|
+
catch (e) {
|
|
554
|
+
console.error(`rooms: the bot in ${id} seat ${turn.seat} couldn't think`, e);
|
|
555
|
+
return void (entry.bot = null);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
const state = turn.state;
|
|
559
|
+
let move = turn.answer;
|
|
560
|
+
if (later(turn.answer)) {
|
|
561
|
+
try {
|
|
562
|
+
move = await turn.answer;
|
|
563
|
+
}
|
|
564
|
+
catch (e) {
|
|
565
|
+
if (entry.bot !== turn)
|
|
566
|
+
return;
|
|
567
|
+
console.error(`rooms: the bot in ${id} seat ${turn.seat} couldn't think`, e);
|
|
568
|
+
return void (entry.bot = null);
|
|
569
|
+
}
|
|
570
|
+
if (entry.bot !== turn)
|
|
571
|
+
return; // stopped while it was thinking: the answer is dropped
|
|
572
|
+
// The game moved on while it was thinking (a person moved, a deadline's move): the answer
|
|
573
|
+
// was for a table that's gone. Drop it and ask again.
|
|
574
|
+
if (entry.state !== state)
|
|
575
|
+
continue;
|
|
576
|
+
if (move === null) {
|
|
577
|
+
console.error(`rooms: the bot in ${id} seat ${turn.seat} had a move to make and then made none`);
|
|
578
|
+
return void (entry.bot = null);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
entry.bot = null;
|
|
582
|
+
let before;
|
|
583
|
+
try {
|
|
584
|
+
before = apply(id, entry, turn.seat, move);
|
|
585
|
+
}
|
|
586
|
+
catch (e) {
|
|
587
|
+
console.error(`rooms: bot in ${id} seat ${turn.seat} made a refused move`, e);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
await settle(id, entry, before, turn.seat, move);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
async function body(request) {
|
|
595
|
+
try {
|
|
596
|
+
const value = await request.json();
|
|
597
|
+
return value && typeof value === "object" ? value : {};
|
|
598
|
+
}
|
|
599
|
+
catch {
|
|
600
|
+
return {};
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async function handleRooms(request, path) {
|
|
604
|
+
const parts = path.split("/").filter(Boolean);
|
|
605
|
+
const method = request.method;
|
|
606
|
+
// POST /rooms { options, settings? } → { id }
|
|
607
|
+
if (parts.length === 0 && method === "POST") {
|
|
608
|
+
const { options: given, settings } = await body(request);
|
|
609
|
+
const refused = await options.allow?.(given ?? {});
|
|
610
|
+
if (refused)
|
|
611
|
+
return json({ error: refused }, 403);
|
|
612
|
+
return json({ id: await create((given ?? {}), settings) }, 201);
|
|
613
|
+
}
|
|
614
|
+
const id = parts[0];
|
|
615
|
+
const action = parts[1] ?? "";
|
|
616
|
+
const g = await game(id);
|
|
617
|
+
const r = await room(id);
|
|
618
|
+
if (!g || !r)
|
|
619
|
+
return json({ error: "There's no table with that code." }, 404);
|
|
620
|
+
const player = playerOf(request);
|
|
621
|
+
const mySeat = player ? g.holders.indexOf(player) : -1;
|
|
622
|
+
// GET /rooms/:id → the public room and which seat (if any) this browser holds
|
|
623
|
+
// `now` is the server's clock, so a page can count down to a deadline by it and not its own.
|
|
624
|
+
if (action === "" && method === "GET")
|
|
625
|
+
return json({ id, ...r, seat: mySeat >= 0 ? mySeat : null, now: Date.now() });
|
|
626
|
+
if (method !== "POST")
|
|
627
|
+
return json({ error: "Not found" }, 404);
|
|
628
|
+
if (r.closed)
|
|
629
|
+
return json({ error: r.closed }, 410);
|
|
630
|
+
const input = await body(request);
|
|
631
|
+
if (action === "sit") {
|
|
632
|
+
if (r.locked)
|
|
633
|
+
return json({ error: "The seats at this table are already set." }, 409);
|
|
634
|
+
const seat = Number(input.seat);
|
|
635
|
+
const name = String(input.name ?? "").trim().slice(0, 20) || "Player";
|
|
636
|
+
if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length)
|
|
637
|
+
return json({ error: "No such seat." }, 400);
|
|
638
|
+
if (r.started && mySeat !== seat)
|
|
639
|
+
return json({ error: "This game has started." }, 409);
|
|
640
|
+
const holder = g.holders[seat];
|
|
641
|
+
if ((holder && holder !== player) || r.seats[seat]?.bot)
|
|
642
|
+
return json({ error: "Someone's already sitting there." }, 409);
|
|
643
|
+
const me = player ?? newPlayerId();
|
|
644
|
+
const holders = g.holders.map((h) => (h === me ? null : h));
|
|
645
|
+
holders[seat] = me;
|
|
646
|
+
const seats = r.seats.map((s, i) => (holders[i] === null && !s.bot ? { name: null, bot: false } : s));
|
|
647
|
+
seats[seat] = { name, bot: false };
|
|
648
|
+
await sync.write("games", id, { holders });
|
|
649
|
+
await sync.write("rooms", id, { seats });
|
|
650
|
+
const entry = live.get(id);
|
|
651
|
+
if (entry)
|
|
652
|
+
entry.table = { ...entry.table, seats };
|
|
653
|
+
await seatsChanged(id);
|
|
654
|
+
return json({ seat }, 200, player ? {} : { "set-cookie": playerCookie(me, request) });
|
|
655
|
+
}
|
|
656
|
+
if (mySeat < 0)
|
|
657
|
+
return json({ error: "Take a seat first." }, 403);
|
|
658
|
+
// POST /rooms/:id/stand → give up your seat, before the game starts
|
|
659
|
+
if (action === "stand") {
|
|
660
|
+
if (r.started)
|
|
661
|
+
return json({ error: "This game has started." }, 409);
|
|
662
|
+
if (r.locked)
|
|
663
|
+
return json({ error: "The seats at this table are already set." }, 409);
|
|
664
|
+
await unseat(id, mySeat);
|
|
665
|
+
return json({ ok: true });
|
|
666
|
+
}
|
|
667
|
+
// POST /rooms/:id/settings { settings } → anyone seated changes the table's settings, mid-game too.
|
|
668
|
+
// A bot already waiting to move starts over at the new pace.
|
|
669
|
+
if (action === "settings") {
|
|
670
|
+
if (!def.settings)
|
|
671
|
+
return json({ error: "This table has no settings." }, 404);
|
|
672
|
+
const settings = def.settings(input.settings);
|
|
673
|
+
await sync.write("games", id, { settings });
|
|
674
|
+
await sync.write("rooms", id, { settings });
|
|
675
|
+
const entry = live.get(id);
|
|
676
|
+
if (entry)
|
|
677
|
+
stopBot(entry);
|
|
678
|
+
// A deadline may depend on the settings (a turn timer): work it out again. The clock isn't
|
|
679
|
+
// restarted, or changing a setting would be a way to stall.
|
|
680
|
+
if (entry && def.deadline && entry.state !== null) {
|
|
681
|
+
const before = deadlineDoc(entry);
|
|
682
|
+
entry.table = { ...entry.table, settings };
|
|
683
|
+
arm(id, entry, true);
|
|
684
|
+
const now = deadlineDoc(entry);
|
|
685
|
+
if (before?.at !== now?.at || before?.seat !== now?.seat)
|
|
686
|
+
void sync.write("rooms", id, { deadline: now });
|
|
687
|
+
}
|
|
688
|
+
void driveBots(id);
|
|
689
|
+
return json({ settings });
|
|
690
|
+
}
|
|
691
|
+
if (action === "bot") {
|
|
692
|
+
const seat = Number(input.seat);
|
|
693
|
+
const add = input.add !== false;
|
|
694
|
+
if (r.started)
|
|
695
|
+
return json({ error: "This game has started." }, 409);
|
|
696
|
+
if (r.locked)
|
|
697
|
+
return json({ error: "The seats at this table are already set." }, 409);
|
|
698
|
+
if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length || g.holders[seat])
|
|
699
|
+
return json({ error: "That seat isn't free." }, 409);
|
|
700
|
+
const seats = [...r.seats];
|
|
701
|
+
seats[seat] = add ? { name: String(input.name ?? `Bot ${seat + 1}`), bot: true } : { name: null, bot: false };
|
|
702
|
+
await sync.write("rooms", id, { seats });
|
|
703
|
+
await seatsChanged(id);
|
|
704
|
+
return json({ ok: true });
|
|
705
|
+
}
|
|
706
|
+
if (action === "start") {
|
|
707
|
+
const problem = await start(id);
|
|
708
|
+
return problem ? json({ error: problem }, 409) : json({ ok: true });
|
|
709
|
+
}
|
|
710
|
+
// POST /rooms/:id/say { text }
|
|
711
|
+
if (action === "say") {
|
|
712
|
+
const key = `${id}/${mySeat}`;
|
|
713
|
+
const now = Date.now();
|
|
714
|
+
if (now - (lastSaid.get(key) ?? 0) < CHAT_GAP_MS)
|
|
715
|
+
return json({ error: "Slow down a little." }, 429);
|
|
716
|
+
const checked = options.beforeSay ? await options.beforeSay({ id, seat: mySeat, text: String(input.text ?? ""), room: r }) : String(input.text ?? "");
|
|
717
|
+
if (typeof checked !== "string")
|
|
718
|
+
return json({ error: checked.error }, 403);
|
|
719
|
+
const result = await say(id, mySeat, checked);
|
|
720
|
+
if (typeof result === "string")
|
|
721
|
+
return json({ error: result }, 400);
|
|
722
|
+
lastSaid.set(key, now); // only a message that was sent counts toward the pace
|
|
723
|
+
if (options.onSay) {
|
|
724
|
+
const said = await room(id);
|
|
725
|
+
if (said)
|
|
726
|
+
safely(() => options.onSay({ id, message: result, room: said }));
|
|
727
|
+
}
|
|
728
|
+
return json(result);
|
|
729
|
+
}
|
|
730
|
+
if (action === "act") {
|
|
731
|
+
const entry = await stateOf(id);
|
|
732
|
+
if (entry.state === null)
|
|
733
|
+
return json({ error: "The game hasn't started." }, 409);
|
|
734
|
+
let before;
|
|
735
|
+
try {
|
|
736
|
+
before = apply(id, entry, mySeat, input.move);
|
|
737
|
+
}
|
|
738
|
+
catch (e) {
|
|
739
|
+
return json({ error: e instanceof Error ? e.message : "That move isn't allowed." }, 400);
|
|
740
|
+
}
|
|
741
|
+
await settle(id, entry, before, mySeat, input.move);
|
|
742
|
+
return json({ ok: true });
|
|
743
|
+
}
|
|
744
|
+
return json({ error: "Not found" }, 404);
|
|
745
|
+
}
|
|
746
|
+
// Deadlines have to be kept even if nobody opens the table again after a restart (a day a move):
|
|
747
|
+
// bring back every room that had a clock running. Rooms without one wait for their next request.
|
|
748
|
+
const restored = def.deadline
|
|
749
|
+
? docs.then(async (d) => {
|
|
750
|
+
for (const r of d.all("rooms"))
|
|
751
|
+
if (r.started && r.deadline)
|
|
752
|
+
await stateOf(r.key).catch((e) => console.error(`rooms: couldn't restore ${r.key}`, e));
|
|
753
|
+
}, (e) => console.error("rooms: couldn't read the rooms to restore their deadlines", e))
|
|
754
|
+
: Promise.resolve();
|
|
755
|
+
return {
|
|
756
|
+
sync,
|
|
757
|
+
/** Resolves once the rooms that had a deadline running before a restart have theirs again. */
|
|
758
|
+
restored,
|
|
759
|
+
create,
|
|
760
|
+
say,
|
|
761
|
+
seatPlayer,
|
|
762
|
+
seatBot,
|
|
763
|
+
unseat,
|
|
764
|
+
replaceWithBot,
|
|
765
|
+
start,
|
|
766
|
+
lock,
|
|
767
|
+
exhibit,
|
|
768
|
+
/** Set what the cards look like at a table (anything the app's pages understand), or null for the app's own. */
|
|
769
|
+
setDeck: async (id, deck) => void (await sync.write("rooms", id, { deck: deck ?? null })),
|
|
770
|
+
/** Get a table's computer players moving again (after a restart, nothing else would wake a table with no people). */
|
|
771
|
+
nudge: (id) => void driveBots(id),
|
|
772
|
+
holders,
|
|
773
|
+
closeTable,
|
|
774
|
+
removePlayer,
|
|
775
|
+
redact,
|
|
776
|
+
/** The public room doc, or undefined. */
|
|
777
|
+
room,
|
|
778
|
+
/** How many rooms have their state in memory (finished ones are dropped). */
|
|
779
|
+
get inMemory() {
|
|
780
|
+
return live.size;
|
|
781
|
+
},
|
|
782
|
+
/** Answers rooms and sync requests; null for anything else. */
|
|
783
|
+
async fetch(request) {
|
|
784
|
+
const { pathname } = new URL(request.url);
|
|
785
|
+
if (pathname === mount || pathname.startsWith(`${mount}/`))
|
|
786
|
+
return handleRooms(request, pathname.slice(mount.length));
|
|
787
|
+
return sync.fetch(request);
|
|
788
|
+
},
|
|
789
|
+
/** For Node's http: answers rooms and sync requests and resolves true, else false. */
|
|
790
|
+
async handle(req, res) {
|
|
791
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
792
|
+
if (url.pathname === mount || url.pathname.startsWith(`${mount}/`)) {
|
|
793
|
+
const chunks = [];
|
|
794
|
+
for await (const chunk of req)
|
|
795
|
+
chunks.push(chunk);
|
|
796
|
+
const request = new Request(url, {
|
|
797
|
+
method: req.method,
|
|
798
|
+
headers: req.headers,
|
|
799
|
+
body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks),
|
|
800
|
+
});
|
|
801
|
+
const response = await handleRooms(request, url.pathname.slice(mount.length));
|
|
802
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
803
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
804
|
+
return true;
|
|
805
|
+
}
|
|
806
|
+
return sync.handle(req, res);
|
|
807
|
+
},
|
|
808
|
+
/** Stop bot timers and deadlines (for tests and shutdown). */
|
|
809
|
+
close() {
|
|
810
|
+
for (const entry of live.values()) {
|
|
811
|
+
stopBot(entry);
|
|
812
|
+
disarm(entry);
|
|
813
|
+
}
|
|
814
|
+
},
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
const same = (a, b) => {
|
|
818
|
+
if (a === b)
|
|
819
|
+
return true;
|
|
820
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
|
|
821
|
+
return false;
|
|
822
|
+
if (Array.isArray(a) !== Array.isArray(b))
|
|
823
|
+
return false;
|
|
824
|
+
const ka = Object.keys(a);
|
|
825
|
+
const kb = Object.keys(b);
|
|
826
|
+
return ka.length === kb.length && ka.every((k) => same(a[k], b[k]));
|
|
827
|
+
};
|
|
828
|
+
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
829
|
+
/** What a list of values have in common: the value where they all agree; where they don't, nothing (see sharedView). */
|
|
830
|
+
function common(values) {
|
|
831
|
+
const first = values[0];
|
|
832
|
+
if (values.every((v) => same(v, first)))
|
|
833
|
+
return first;
|
|
834
|
+
// Lists of the same length are compared place by place: a list of seats, a grid of cards.
|
|
835
|
+
if (values.every(Array.isArray)) {
|
|
836
|
+
const lists = values;
|
|
837
|
+
return lists.every((l) => l.length === lists[0].length) ? lists[0].map((_, i) => common(lists.map((l) => l[i]))) : [];
|
|
838
|
+
}
|
|
839
|
+
// Records with the same keys are compared key by key. Anything else that differs is simply not shown.
|
|
840
|
+
if (values.every(isRecord)) {
|
|
841
|
+
const records = values;
|
|
842
|
+
const keys = Object.keys(records[0]);
|
|
843
|
+
if (records.every((r) => Object.keys(r).length === keys.length && keys.every((k) => k in r)))
|
|
844
|
+
return Object.fromEntries(keys.map((k) => [k, common(records.map((r) => r[k]))]));
|
|
845
|
+
}
|
|
846
|
+
return null;
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* A view for someone watching, made from every seat's view: whatever all the seats see alike is
|
|
850
|
+
* kept, and whatever differs between them (a hand, the moves on offer, a card only one player has
|
|
851
|
+
* peeked at) becomes null, or an empty list. A watcher so learns nothing that every player at the
|
|
852
|
+
* table doesn't already know, in any game, without the game saying which parts are private.
|
|
853
|
+
*
|
|
854
|
+
* Name a game's private parts in `blank` anyway (their values replace the seats' own before
|
|
855
|
+
* comparing): two hands that happened to match in some detail would otherwise show it. `from`
|
|
856
|
+
* takes the named keys from one seat's view as they are, for the parts that say where the viewer
|
|
857
|
+
* sits rather than what they know.
|
|
858
|
+
*/
|
|
859
|
+
export function sharedView(views, { blank = {}, from } = {}) {
|
|
860
|
+
if (!views.length)
|
|
861
|
+
throw new Error("A table has at least one seat.");
|
|
862
|
+
const placed = from ? views[from.seat] ?? views[0] : null;
|
|
863
|
+
const comparable = views.map((v) => {
|
|
864
|
+
const copy = { ...v, ...blank };
|
|
865
|
+
// Where the viewer sits differs by definition; it's set from one seat below.
|
|
866
|
+
for (const key of from?.keys ?? [])
|
|
867
|
+
delete copy[key];
|
|
868
|
+
return copy;
|
|
869
|
+
});
|
|
870
|
+
const shared = common(comparable);
|
|
871
|
+
for (const key of from?.keys ?? [])
|
|
872
|
+
shared[key] = placed[key];
|
|
873
|
+
return shared;
|
|
874
|
+
}
|
|
875
|
+
//# sourceMappingURL=server.js.map
|