@hadoku/game-server 0.1.113 → 0.1.115

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.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Account erase in the per-person store (`users/store.ts`): the person's document is deleted,
3
+ * whole. It holds nothing anyone else needs (their favourites, when they last played each deck,
4
+ * the decks they built, their art picks), so nothing is anonymised and kept.
5
+ *
6
+ * An account merge folds the merged-away account's document into the kept one, by the game's own
7
+ * merge (the kept account wins each conflict), and deletes it.
8
+ */
9
+ import type { UserStore } from '../users/store.js';
10
+ import type { EraseStep } from './index.js';
11
+ export declare function usersEraseStep(store: Pick<UserStore<unknown>, 'remove' | 'move'>): EraseStep;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Account erase in the per-person store (`users/store.ts`): the person's document is deleted,
3
+ * whole. It holds nothing anyone else needs (their favourites, when they last played each deck,
4
+ * the decks they built, their art picks), so nothing is anonymised and kept.
5
+ *
6
+ * An account merge folds the merged-away account's document into the kept one, by the game's own
7
+ * merge (the kept account wins each conflict), and deletes it.
8
+ */
9
+ export function usersEraseStep(store) {
10
+ return {
11
+ what: 'users',
12
+ erase: ({ userId }) => store.remove(userId),
13
+ merge: ({ from, into }) => store.move(from.userId, into.userId),
14
+ };
15
+ }
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * `/api/rooms`'s GENERIC surface: list, create, join, ready, leave, close, an
3
3
  * admin's testing-room reset, the watchparty bind, "the room that started this
4
- * match", and the `{ gameType }` arm of `PATCH /:id`. `rooms.ts` stays Magic:
5
- * formats, pods, drafts, tournaments, and the `{ format }`/`{ settings }`/
6
- * `{ mode }` arms of the same PATCH, mounted on this file's OWN router after it.
4
+ * match", and the `{ gameType }` and `{ settings }` arms of `PATCH /:id`. `rooms.ts`
5
+ * stays Magic: formats, pods, drafts, tournaments, and the `{ format }`/`{ mode }`
6
+ * arms of the same PATCH, mounted on this file's OWN router after it.
7
7
  *
8
8
  * This file imports no `Lobby`, no `RoomView`, no `@hadoku/shared` (the ratchet
9
9
  * resolves `@hadoku/shared` as one package, magic even through `/platform`) —
@@ -17,7 +17,7 @@
17
17
  *
18
18
  * ONE registration of `PATCH /:id` (the frozen `route-table.json` admits each
19
19
  * method+path once): this file parses the body with `deps.wire.patchRoomBody`
20
- * and answers `{ gameType }` itself; anything else goes to `opts.onPatch`, a
20
+ * and answers `{ gameType }` (and, opted in, `{ settings }`) itself; anything else goes to `opts.onPatch`, a
21
21
  * hook `rooms.ts` passes in — never a second route, never `res.locals`.
22
22
  */
23
23
  import { Router, type NextFunction, type Request, type Response } from 'express';
@@ -128,7 +128,29 @@ export interface LobbyCore<V extends RoomViewCore, C> {
128
128
  ok: false;
129
129
  reason: string;
130
130
  };
131
+ /** The leader changes some of the room's settings (`room/lobby.ts`'s `setSettings`); called only when `RoomCoreDeps.settings` is set. */
132
+ setSettings?(roomId: string, callerId: string, patch: Record<string, unknown>): {
133
+ ok: true;
134
+ room: V;
135
+ } | {
136
+ ok: false;
137
+ reason: string;
138
+ };
131
139
  }
140
+ /** A settings refusal as it is answered: its status and its JSON body. */
141
+ export interface SettingsRefusal {
142
+ status: number;
143
+ body: {
144
+ error: string;
145
+ reason?: string;
146
+ };
147
+ }
148
+ /**
149
+ * `{ settings }`' refusals, by the lobby's reason: the leader's alone to change (403), and a lock
150
+ * that holds (409, with the lock's reason so a page can tell which). A game whose locks have
151
+ * reasons of their own names them in `RoomCoreDeps.settings.refusal`.
152
+ */
153
+ export declare function settingsRefusal(reason: string): SettingsRefusal;
132
154
  /** Every one of the leader's three seat ops, per caller: a burst of 10, then one every 10 s — the same shape as a join attempt, spent only by a leader who is actually a member of the room (checked before this is asked). */
133
155
  export declare const SEAT_OP_RATE_LIMIT: RateLimitConfig;
134
156
  /** The request-body schemas and the room-id shape, injected rather than imported: the real values live in a Magic-resolved package. */
@@ -221,6 +243,15 @@ export interface RoomCoreDeps<V extends RoomViewCore, C, P extends object, G = n
221
243
  joinRateLimit?: RateLimitConfig;
222
244
  createRateLimit?: RateLimitConfig | null;
223
245
  now?: () => number;
246
+ /**
247
+ * Answer `PATCH /:id { settings }` here, through `lobby.setSettings`; `wire.patchRoomBody` has
248
+ * already checked the patch against the game's declaration. `refusal` maps a reason the lobby
249
+ * gave to its answer (default {@link settingsRefusal}). Absent: `{ settings }` goes to `onPatch`
250
+ * like any other variant.
251
+ */
252
+ settings?: {
253
+ refusal?(reason: string): SettingsRefusal;
254
+ };
224
255
  }
225
256
  /** The room, as this caller is told it: `V` untouched plus their own row. */
226
257
  export type RoomBody<V extends RoomViewCore, G = never> = V & {
@@ -253,7 +284,7 @@ export interface RoomCoreHandle<V extends RoomViewCore, G = never> {
253
284
  }
254
285
  export declare function attachRoomCore<V extends RoomViewCore, C, P extends object, G = never>(api: Router, deps: RoomCoreDeps<V, C, P, G>, opts?: {
255
286
  beforeWildcard?(router: Router): void;
256
- /** `{ format }`/`{ settings }`/`{ mode }` (Magic's three other PATCH variants) — method syntax for bivariance, like `LobbyCore`. */
287
+ /** Every other PATCH variant (Magic's `{ format }`/`{ mode }`) — method syntax for bivariance, like `LobbyCore`. */
257
288
  onPatch?(req: Request, res: Response, body: P, caller: CallerLike, roomId: string): void;
258
289
  }): RoomCoreHandle<V, G>;
259
290
  export { bodyErrors };
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * `/api/rooms`'s GENERIC surface: list, create, join, ready, leave, close, an
3
3
  * admin's testing-room reset, the watchparty bind, "the room that started this
4
- * match", and the `{ gameType }` arm of `PATCH /:id`. `rooms.ts` stays Magic:
5
- * formats, pods, drafts, tournaments, and the `{ format }`/`{ settings }`/
6
- * `{ mode }` arms of the same PATCH, mounted on this file's OWN router after it.
4
+ * match", and the `{ gameType }` and `{ settings }` arms of `PATCH /:id`. `rooms.ts`
5
+ * stays Magic: formats, pods, drafts, tournaments, and the `{ format }`/`{ mode }`
6
+ * arms of the same PATCH, mounted on this file's OWN router after it.
7
7
  *
8
8
  * This file imports no `Lobby`, no `RoomView`, no `@hadoku/shared` (the ratchet
9
9
  * resolves `@hadoku/shared` as one package, magic even through `/platform`) —
@@ -17,7 +17,7 @@
17
17
  *
18
18
  * ONE registration of `PATCH /:id` (the frozen `route-table.json` admits each
19
19
  * method+path once): this file parses the body with `deps.wire.patchRoomBody`
20
- * and answers `{ gameType }` itself; anything else goes to `opts.onPatch`, a
20
+ * and answers `{ gameType }` (and, opted in, `{ settings }`) itself; anything else goes to `opts.onPatch`, a
21
21
  * hook `rooms.ts` passes in — never a second route, never `res.locals`.
22
22
  */
23
23
  import { Router } from 'express';
@@ -28,6 +28,20 @@ import { tierAdmits } from '../room/tier-floor.js';
28
28
  import { bodyErrors, callerOf, parseBody, perCallerLimit } from './request.js';
29
29
  import { isWatchpartyRoomId, watchpartyRoomId } from '../room/watchparty-link.js';
30
30
  import { jsonLogger } from '../log.js';
31
+ /**
32
+ * `{ settings }`' refusals, by the lobby's reason: the leader's alone to change (403), and a lock
33
+ * that holds (409, with the lock's reason so a page can tell which). A game whose locks have
34
+ * reasons of their own names them in `RoomCoreDeps.settings.refusal`.
35
+ */
36
+ export function settingsRefusal(reason) {
37
+ if (reason === 'not-leader')
38
+ return { status: 403, body: { error: 'only the room leader can change the settings' } };
39
+ if (reason === 'no-settings')
40
+ return { status: 409, body: { error: 'this room has no settings', reason } };
41
+ if (reason === 'match-live')
42
+ return { status: 409, body: { error: 'a match is under way; the settings cannot change until it is over', reason } };
43
+ return { status: 409, body: { error: 'the settings cannot change now', reason } };
44
+ }
31
45
  /** A `BodySchema<T>` with no dependency the way `RoomCoreWire`'s injected ones have — this file imports no zod, no `@hadoku/shared`. */
32
46
  function field(check, message) {
33
47
  return {
@@ -119,6 +133,9 @@ export function notDurable(res, verb = 'create or join') {
119
133
  function hasGameType(v) {
120
134
  return 'gameType' in v && typeof v.gameType === 'string';
121
135
  }
136
+ function hasSettings(v) {
137
+ return 'settings' in v && typeof v.settings === 'object' && v.settings !== null;
138
+ }
122
139
  /**
123
140
  * Whether `req`'s caller may know `room` exists at all: a testing room is an admin's, and a room
124
141
  * with a tier floor (`room/tier-floor.ts`) is for that tier and above, by the edge's own name for it.
@@ -419,9 +436,10 @@ export function attachRoomCore(api, deps, opts = {}) {
419
436
  res.json(roomBody(result.room, caller.id));
420
437
  });
421
438
  /**
422
- * `{ gameType }` is this file's own: the game-type registry is platform.
423
- * Everything else `P` can be (Magic's `{ format }`/`{ settings }`/`{ mode }`)
424
- * goes to `opts.onPatch`. ONE registration either way — `route-table.json`
439
+ * `{ gameType }` is this file's own: the game-type registry is platform. So is
440
+ * `{ settings }` when `deps.settings` is set: the fields are the game's
441
+ * declaration, the route and its refusals are everyone's. Everything else `P`
442
+ * can be (Magic's `{ format }`/`{ mode }`) goes to `opts.onPatch`. ONE registration either way — `route-table.json`
425
443
  * admits `PATCH /:id` once.
426
444
  */
427
445
  rooms.patch('/:id', (req, res, next) => {
@@ -431,6 +449,17 @@ export function attachRoomCore(api, deps, opts = {}) {
431
449
  const id = String(req.params.id);
432
450
  if (!wire.roomIdRe.test(id))
433
451
  return noMatch(res);
452
+ const settings = deps.settings;
453
+ if (settings !== undefined && lobby.setSettings !== undefined && hasSettings(v)) {
454
+ const me = callerOf(req).id;
455
+ const result = lobby.setSettings(id, me, v.settings);
456
+ if (result.ok)
457
+ return void res.json(roomBody(result.room, me));
458
+ if (result.reason === 'no-room')
459
+ return noMatch(res);
460
+ const refused = (settings.refusal ?? settingsRefusal)(result.reason);
461
+ return void res.status(refused.status).json(refused.body);
462
+ }
434
463
  if (!hasGameType(v)) {
435
464
  if (opts.onPatch === undefined)
436
465
  return next();
@@ -99,6 +99,8 @@ export declare class RelayMatch extends HostedMatch<RelayLine, RelayCommand> imp
99
99
  * Undefined for a room's first match, and once this one has started.
100
100
  */
101
101
  lastEnded(): RelayEnded | undefined;
102
+ /** Whether a round is being played: its first message relayed, and not yet over. A room's `LIVE` settings are locked while it is. */
103
+ get underWay(): boolean;
102
104
  /** `RelayRoster.seatCount`. */
103
105
  get seatCount(): number;
104
106
  /** Who started this round — see {@link hostSeatRef}'s own doc. Null until a seat has joined. */
@@ -81,6 +81,10 @@ export class RelayMatch extends HostedMatch {
81
81
  lastEnded() {
82
82
  return this.sessionRef?.started === true ? undefined : this.deps.previous;
83
83
  }
84
+ /** Whether a round is being played: its first message relayed, and not yet over. A room's `LIVE` settings are locked while it is. */
85
+ get underWay() {
86
+ return this.status === 'running' && this.sessionRef?.started === true && !this.sessionRef.isEnded;
87
+ }
84
88
  /** `RelayRoster.seatCount`. */
85
89
  get seatCount() {
86
90
  return this.seats.length;
@@ -15,6 +15,9 @@
15
15
  * people every member named and dressed from their account (`attachPeople`)
16
16
  * rooms `/api/rooms*` (room-core, with its seat routes) and `/:id/start`, the
17
17
  * countdown every page counts to (`room/starts.ts`)
18
+ * settings the game's declared settings (`RelayGameOptions.settings`): stored with the
19
+ * room, in every room body, the leader's to change by `PATCH /:id { settings }`,
20
+ * a `LIVE` field locked from a Start's countdown until its round is over
18
21
  * page the game's own static directories, then index.html for every client route
19
22
  * /room chat, roster and presence (`room/serve.ts`)
20
23
  * relay + feed the match socket, and the room list pushed to the front page
@@ -26,6 +29,7 @@ import { type GamePlugin, type GameServer, type GameServerConfig as KernelConfig
26
29
  import { type GameAuth } from './auth.js';
27
30
  import { type GameServerConfig } from './config.js';
28
31
  import { type People } from './people.js';
32
+ import { type AnyRoomSettings } from '@wolffm/platform-wire/room-settings';
29
33
  import { RoomLobby, type PlainRoomSize, type PlainRoomView, type PlatformRoomView, type RoomCreateInput } from './room/lobby.js';
30
34
  import { type Starts } from './room/starts.js';
31
35
  import { type ReportOutcome, type RoundContext } from './stats/relay-results.js';
@@ -101,6 +105,12 @@ export interface RelayGameOptions {
101
105
  /** The bundle's fixed-name embed entries; everything else it emits is hashed. */
102
106
  embedEntries?: readonly string[];
103
107
  statics?: readonly StaticDir[];
108
+ /**
109
+ * The game's room settings (`@hadoku/platform-wire/room-settings`'s `defineRoomSettings`). A
110
+ * field locked `LIVE` refuses a change (409, `reason: 'match-live'`) from a Start until the
111
+ * round it began is over. Absent: the rooms have none, and a `{ settings }` PATCH is refused.
112
+ */
113
+ settings?: AnyRoomSettings;
104
114
  /** The countdown a Start counts down (ms). Default `COUNTDOWN_MS`. */
105
115
  countdownMs?: number;
106
116
  /**
@@ -15,6 +15,9 @@
15
15
  * people every member named and dressed from their account (`attachPeople`)
16
16
  * rooms `/api/rooms*` (room-core, with its seat routes) and `/:id/start`, the
17
17
  * countdown every page counts to (`room/starts.ts`)
18
+ * settings the game's declared settings (`RelayGameOptions.settings`): stored with the
19
+ * room, in every room body, the leader's to change by `PATCH /:id { settings }`,
20
+ * a `LIVE` field locked from a Start's countdown until its round is over
18
21
  * page the game's own static directories, then index.html for every client route
19
22
  * /room chat, roster and presence (`room/serve.ts`)
20
23
  * relay + feed the match socket, and the room list pushed to the front page
@@ -42,7 +45,8 @@ import { attachRelay } from './play/relay-socket.js';
42
45
  import { roomAdmits } from './room/tier-floor.js';
43
46
  import { relayMatches } from './play/runtimes/relay-match.js';
44
47
  import { configureParticipantIdDomain, identityFromHeaders } from './room/identity.js';
45
- import { RoomLobby, plainRoomType } from './room/lobby.js';
48
+ import { LIVE } from '@wolffm/platform-wire/room-settings';
49
+ import { MATCH_LIVE, RoomLobby, plainRoomType } from './room/lobby.js';
46
50
  import { attachServedRoom } from './room/serve.js';
47
51
  import { COUNTDOWN_MS, createStarts } from './room/starts.js';
48
52
  import { attachRoomFeed } from './room/watching.js';
@@ -90,7 +94,10 @@ export async function startRelayGame(options) {
90
94
  const relayLog = jsonLogger(`${id}-relay`);
91
95
  const statics = (options.statics ?? []).map((s) => ({ ...s, built: existsSync(join(s.dir, s.index ?? 'index.html')) }));
92
96
  const starts = createStarts({ countdownMs: options.countdownMs ?? COUNTDOWN_MS });
93
- const base = plainRoomType({ ...options.seats, markedSeats: true, keepOneOpen: true });
97
+ // A round is live from its Start's countdown until the round is over; a `LIVE` setting waits for the lobby.
98
+ const live = (roomId) => starts.view(roomId) !== null || relayMatches.get(roomId)?.underWay === true;
99
+ const settings = options.settings === undefined ? undefined : { spec: options.settings, locked: (room, lock) => (lock === LIVE && live(room.id) ? MATCH_LIVE : null) };
100
+ const base = plainRoomType({ ...options.seats, markedSeats: true, keepOneOpen: true, ...(settings === undefined ? {} : { settings }) });
94
101
  const roomType = {
95
102
  ...base,
96
103
  /** A pending start rides on every room body: every page counts down to it. */
@@ -171,8 +178,9 @@ export async function startRelayGame(options) {
171
178
  const lobby = ctx.state.lobby;
172
179
  const roomCore = attachRoomCore(ctx.api, {
173
180
  lobby,
174
- wire: relayWire(options.gameType, options.roomIdRe),
181
+ wire: relayWire(options.gameType, options.roomIdRe, options.settings),
175
182
  seatRoutes: lobby,
183
+ ...(options.settings === undefined ? {} : { settings: {} }),
176
184
  here: (roomId) => roomHere(roomId),
177
185
  arrived: (roomId, caller) => {
178
186
  if (caller.userId !== null)
@@ -344,8 +352,8 @@ export async function startRelayGame(options) {
344
352
  });
345
353
  return server;
346
354
  }
347
- /** The room routes' request bodies, for a game with one room type. */
348
- function relayWire(gameType, roomIdRe) {
355
+ /** The room routes' request bodies, for a game with one room type and, maybe, settings. */
356
+ function relayWire(gameType, roomIdRe, settings) {
349
357
  const object = (fields, required, message) => ({
350
358
  safeParse(body) {
351
359
  const ok = typeof body === 'object' &&
@@ -354,7 +362,7 @@ function relayWire(gameType, roomIdRe) {
354
362
  Object.keys(body).every((k) => k in fields) &&
355
363
  required.every((k) => k in body) &&
356
364
  Object.entries(body).every(([k, v]) => fields[k](v));
357
- return ok ? { success: true, data: body } : { success: false, error: { issues: [{ code: 'invalid_type', path: [], message }] } };
365
+ return ok ? { success: true, data: body } : refusal(message);
358
366
  },
359
367
  });
360
368
  const text = (max, min = 0) => (v) => typeof v === 'string' && v.trim().length >= min && v.length <= max;
@@ -366,6 +374,24 @@ function relayWire(gameType, roomIdRe) {
366
374
  readyBody: object({ ready: (v) => typeof v === 'boolean' }, ['ready'], 'expected { ready }'),
367
375
  emptyBody: object({}, [], 'expected an empty body'),
368
376
  watchpartyBindBody: object({ room: text(100, 1) }, ['room'], 'expected { room }'),
369
- patchRoomBody: object({ gameType: text(40, 1) }, ['gameType'], 'expected { gameType }'),
377
+ patchRoomBody: patchBody(object({ gameType: text(40, 1) }, ['gameType'], 'expected { gameType }'), settings),
370
378
  };
371
379
  }
380
+ /** `PATCH /:id`: `{ gameType }`, or, for a game that declares settings, `{ settings }` with the spec's own refusals. */
381
+ function patchBody(gameType, settings) {
382
+ if (settings === undefined)
383
+ return gameType;
384
+ return {
385
+ safeParse(body) {
386
+ if (typeof body !== 'object' || body === null || !('settings' in body))
387
+ return gameType.safeParse(body);
388
+ if (Object.keys(body).length > 1)
389
+ return refusal('patch one field at a time: gameType or settings');
390
+ const parsed = settings.parsePatch(body.settings);
391
+ return parsed.ok ? { success: true, data: { settings: parsed.patch } } : refusal(parsed.error);
392
+ },
393
+ };
394
+ }
395
+ function refusal(message) {
396
+ return { success: false, error: { issues: [{ code: 'invalid_type', path: [], message }] } };
397
+ }
@@ -34,6 +34,7 @@
34
34
  */
35
35
  import { FileRoomStore, type RoomCodec } from '@wolffm/rooms-server/store';
36
36
  import { type Look } from '@wolffm/platform-wire/look';
37
+ import type { AnyRoomSettings } from '@wolffm/platform-wire/room-settings';
37
38
  import { type IdMove } from '../erase/anonymise.js';
38
39
  import { type AiPersona } from './ai-faces.js';
39
40
  import type { Caller } from './caller.js';
@@ -217,7 +218,35 @@ export interface RoomTypeHooks<G, I extends RoomCreateInput = RoomCreateInput> {
217
218
  * `plainRoomType`'s).
218
219
  */
219
220
  subPlaceOf?(room: LobbyRoom<G>, rest: string): boolean;
221
+ /** The room's settings, which its leader changes (`RoomLobby.setSettings`). Absent: the type has none. */
222
+ settings?: RoomTypeSettings<G>;
220
223
  }
224
+ /**
225
+ * Where a room type keeps its settings and when they are locked. The fields themselves are the
226
+ * game's declaration (`@hadoku/platform-wire/room-settings`); the type only says where they live
227
+ * in its game part (it stores them, and its view shows them) and answers each lock by name.
228
+ */
229
+ export interface RoomTypeSettings<G> {
230
+ spec: AnyRoomSettings;
231
+ read(room: LobbyRoom<G>): Record<string, unknown>;
232
+ /** Called only with a change that passed every lock, before the room is saved. */
233
+ write(room: LobbyRoom<G>, next: Record<string, unknown>): void;
234
+ /** Why the fields under `lock` cannot change now (the refusal's reason), or null when they can. */
235
+ locked(room: LobbyRoom<G>, lock: string): string | null;
236
+ }
237
+ /**
238
+ * `setSettings`' answer. `no-settings`: the room's type declares none. Any other refusal is a lock's
239
+ * reason, as the type's `locked` named it (`match-live` for the kit's `LIVE` lock).
240
+ */
241
+ export type SetSettingsResult<V> = {
242
+ ok: true;
243
+ room: V;
244
+ } | {
245
+ ok: false;
246
+ reason: string;
247
+ };
248
+ /** The reason a relay room refuses a `LIVE` setting while its match is live or counting down. */
249
+ export declare const MATCH_LIVE = "match-live";
221
250
  /**
222
251
  * A generic seat lineup the leader's atomic ops can read and write — `room.seats` itself (every
223
252
  * room type that `usesSeats`), or, via `RoomTypeHooks.extraSeatTarget`, wherever ELSE a type that
@@ -459,6 +488,14 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
459
488
  * Made on first use with the caller as its creator and leader, joined after that.
460
489
  */
461
490
  bindWatchparty(caller: Caller, watchpartyRoom: string): JoinResult<V>;
491
+ /**
492
+ * The leader changes some of the room's settings; the rest stay as they are. `patch` is already
493
+ * valid (`RoomSettingsSpec.parsePatch`). A field whose value does not move is no change; one that
494
+ * does is checked against its lock, and the first lock that holds refuses the whole patch.
495
+ */
496
+ setSettings(roomId: string, callerId: string, patch: Record<string, unknown>): SetSettingsResult<V>;
497
+ /** `setSettings` on a room in hand. `write` stands in for the type's own (a game with more to move when a setting does). */
498
+ protected changeSettings(room: LobbyRoom, callerId: string, patch: Record<string, unknown>, write?: (room: LobbyRoom, next: Record<string, unknown>) => void): SetSettingsResult<V>;
462
499
  /** Idempotent for an existing member, who needs no password again. */
463
500
  join(roomId: string, caller: Caller, password?: string): JoinResult<V>;
464
501
  /**
@@ -596,11 +633,26 @@ export interface PlainRoomSize {
596
633
  * and a seat the leader closed is never reopened by it.
597
634
  */
598
635
  keepOneOpen?: boolean;
636
+ /**
637
+ * The game's settings (`@hadoku/platform-wire/room-settings`): kept in the room's game part
638
+ * (`app.game.settings`), shown as the view's `settings`, changed by the leader. `locked` answers
639
+ * each of the fields' locks by name; absent, nothing is ever locked.
640
+ */
641
+ settings?: {
642
+ spec: AnyRoomSettings;
643
+ locked?(room: LobbyRoom<PlainGame>, lock: string): string | null;
644
+ };
645
+ }
646
+ /** A plain room's game part: only its settings, when its game declares any. */
647
+ export interface PlainGame {
648
+ settings?: Record<string, unknown>;
599
649
  }
600
- /** What a plain room's view adds to the platform's: the AI at each seat, `seatPersonas`'s draw. */
650
+ /** What a plain room's view adds to the platform's: the AI at each seat, `seatPersonas`'s draw, and its settings. */
601
651
  export interface PlainRoomView {
602
652
  /** In seat order; null where no AI sits. */
603
653
  aiSeats: (AiPersona | null)[];
654
+ /** Present when the game declares settings: every field, at its value now. */
655
+ settings?: Record<string, unknown>;
604
656
  }
605
657
  /**
606
658
  * The room type of a game that keeps nothing of its own in the room (bomberman): no game part, its
@@ -610,5 +662,5 @@ export interface PlainRoomView {
610
662
  * A member who leaves the room gives up their seat (`leaving`): `RoomLobby.leave` drops only the
611
663
  * membership, so without it the departed id stayed in the seat for good.
612
664
  */
613
- export declare function plainRoomType<I extends RoomCreateInput>(size: PlainRoomSize): RoomTypeHooks<Record<string, never>, I>;
665
+ export declare function plainRoomType<I extends RoomCreateInput>(size: PlainRoomSize): RoomTypeHooks<PlainGame, I>;
614
666
  export {};
@@ -55,6 +55,8 @@ import { watchpartyRoomId } from "./watchparty-link.js";
55
55
  * the first person to join takes it over whole (`RoomLobby.join`).
56
56
  */
57
57
  export const TESTING_STAND_IN_ID = 'dev:testing-stand-in';
58
+ /** The reason a relay room refuses a `LIVE` setting while its match is live or counting down. */
59
+ export const MATCH_LIVE = 'match-live';
58
60
  /** The fewest seats a room is left with when its seats are closed: one player and one more. */
59
61
  export const MIN_OPEN_SEATS = 2;
60
62
  /** The room-level app blob's version. Additive fields never bump it: each reads with a default. */
@@ -492,6 +494,34 @@ export class RoomLobby {
492
494
  this.log({ event: 'room-created', roomId: id, gameType: room.gameType, ...said, locked: this.#secrets.has(id) });
493
495
  return this.view(room);
494
496
  }
497
+ /**
498
+ * The leader changes some of the room's settings; the rest stay as they are. `patch` is already
499
+ * valid (`RoomSettingsSpec.parsePatch`). A field whose value does not move is no change; one that
500
+ * does is checked against its lock, and the first lock that holds refuses the whole patch.
501
+ */
502
+ setSettings(roomId, callerId, patch) {
503
+ const room = this.#rooms.get(roomId);
504
+ if (room === undefined)
505
+ return { ok: false, reason: 'no-room' };
506
+ return this.changeSettings(room, callerId, patch);
507
+ }
508
+ /** `setSettings` on a room in hand. `write` stands in for the type's own (a game with more to move when a setting does). */
509
+ changeSettings(room, callerId, patch, write) {
510
+ const settings = this.hooksOf(room).settings;
511
+ if (settings === undefined)
512
+ return { ok: false, reason: 'no-settings' };
513
+ if (room.leader !== callerId)
514
+ return { ok: false, reason: 'not-leader' };
515
+ const result = settings.spec.apply(settings.read(room), patch, (lock) => settings.locked(room, lock));
516
+ if (!result.ok)
517
+ return { ok: false, reason: result.reason };
518
+ if (result.changed.length === 0)
519
+ return { ok: true, room: this.view(room) };
520
+ (write ?? settings.write)(room, result.next);
521
+ this.persist(room);
522
+ this.log({ event: 'room-settings', roomId: room.id, settings: result.next });
523
+ return { ok: true, room: this.view(room) };
524
+ }
495
525
  /** Idempotent for an existing member, who needs no password again. */
496
526
  join(roomId, caller, password) {
497
527
  if (!isDurableParticipantId(caller.id))
@@ -1120,6 +1150,10 @@ function isStoredSeats(v) {
1120
1150
  */
1121
1151
  export function plainRoomType(size) {
1122
1152
  const open = () => new Array(size.seats).fill(null);
1153
+ const declared = size.settings;
1154
+ /** A room's settings as the game part holds them; a room made before its game declared any reads the defaults. */
1155
+ const settingsOf = (room) => room.game.settings ?? declared.spec.defaults();
1156
+ const game = (settings) => (settings === undefined ? {} : { settings });
1123
1157
  const full = (seats) => !seats.some((s) => s === null || s === CLOSED_SEAT);
1124
1158
  const trim = (room) => {
1125
1159
  while (room.seats.length > size.seats && room.seats.at(-1) === null)
@@ -1128,15 +1162,20 @@ export function plainRoomType(size) {
1128
1162
  room.seats = [...room.seats, null];
1129
1163
  };
1130
1164
  return {
1131
- newGame: () => ({ seats: open(), game: {} }),
1132
- encode: () => ({}),
1165
+ newGame: () => ({ seats: open(), game: game(declared?.spec.defaults()) }),
1166
+ encode: (room) => game(room.game.settings),
1133
1167
  decode(app) {
1134
1168
  if (app.seats !== undefined && !isStoredSeats(app.seats))
1135
1169
  throw new Error('app.seats is invalid');
1136
- return { seats: app.seats === undefined ? open() : [...app.seats], game: {} };
1170
+ const raw = typeof app.game === 'object' && app.game !== null ? app.game.settings : undefined;
1171
+ // A game that declares no settings ignores whatever a file holds; one that does refuses settings it never declared.
1172
+ const settings = declared === undefined ? undefined : declared.spec.readStored(raw);
1173
+ if (settings === null)
1174
+ throw new Error('app.game.settings is invalid');
1175
+ return { seats: app.seats === undefined ? open() : [...app.seats], game: game(settings) };
1137
1176
  },
1138
- restore: () => ({ dropHolds: false, game: () => ({}) }),
1139
- view: (room) => ({ aiSeats: seatPersonas(room, AI_SEAT) }),
1177
+ restore: (app) => ({ dropHolds: false, game: () => game(app.game.settings) }),
1178
+ view: (room) => ({ aiSeats: seatPersonas(room, AI_SEAT), ...(declared === undefined ? {} : { settings: structuredClone(settingsOf(room)) }) }),
1140
1179
  busy: NO_BUSY_HOOK,
1141
1180
  liveMatches: () => [],
1142
1181
  usesSeats: () => true,
@@ -1155,6 +1194,18 @@ export function plainRoomType(size) {
1155
1194
  trim(room);
1156
1195
  },
1157
1196
  ...(size.markedSeats === true ? { seatsView: (room) => room.seats } : {}),
1197
+ ...(declared === undefined
1198
+ ? {}
1199
+ : {
1200
+ settings: {
1201
+ spec: declared.spec,
1202
+ read: settingsOf,
1203
+ write(room, next) {
1204
+ room.game = { ...room.game, settings: next };
1205
+ },
1206
+ locked: (room, lock) => declared.locked?.(room, lock) ?? null,
1207
+ },
1208
+ }),
1158
1209
  ...(size.relaySeats === undefined ? {} : { relaySeats: size.relaySeats }),
1159
1210
  };
1160
1211
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The per-person store: one JSON document per account, `<dir>/<userId>.json`, owned by this
3
+ * server and kept on its own disk (operator, 2026-11-23: "i would prefer if all the data was
4
+ * self-hosted so we don't rely on cloudflare for this").
5
+ *
6
+ * The store knows nothing of what a document holds. The game hands it the shape: an empty
7
+ * document, a parse of what is on disk, and a merge for an account merge. So Magic's favourites,
8
+ * last-played stamps, built decks and art picks live in Magic's own file, and this one stays MIT.
9
+ *
10
+ * Every write is a temp file renamed over the target, as `draftRooms.ts` writes a pod, so a
11
+ * reader never sees half a document and the nightly state backup (which carries the state dir
12
+ * whole) never copies one. Updates to one person are serialised in this process, so two requests
13
+ * that land together both keep their change.
14
+ *
15
+ * `get` and `update` are the whole interface the rest of the server uses, so moving the documents
16
+ * into dataplatform's store later (`docs/planning/telemetry-and-state-inventory.md` §4) replaces
17
+ * this file and nothing that reads it.
18
+ *
19
+ * A file that is not a document (truncated by a full disk, edited by hand) is moved aside to
20
+ * `<userId>.json.unreadable-<ms>`, logged, and the person starts from an empty document: their
21
+ * bytes are kept for the operator, and nothing they do afterwards is refused for it.
22
+ */
23
+ export declare function isStorableUserId(userId: string): boolean;
24
+ export interface UserDocShape<D> {
25
+ /** A person with no document yet. */
26
+ empty(): D;
27
+ /** What is on disk, as a document; throws when it is not one. */
28
+ parse(raw: unknown): D;
29
+ /** An account merge: `from`'s document folded into `into`'s, `into` winning every conflict. */
30
+ merge(from: D, into: D): D;
31
+ }
32
+ export interface UserStore<D> {
33
+ /** The person's document, or an empty one. */
34
+ get(userId: string): Promise<D>;
35
+ /** Change the person's document and write it. `fn` edits the document in place or returns a new one. Answers what was written. */
36
+ update(userId: string, fn: (doc: D) => D | void): Promise<D>;
37
+ /** Account erase: the person's document is deleted. Answers 1 when there was one. */
38
+ remove(userId: string): Promise<number>;
39
+ /** Account merge: `fromUserId`'s document folds into `intoUserId`'s and is deleted. Answers 1 when there was one to move. */
40
+ move(fromUserId: string, intoUserId: string): Promise<number>;
41
+ }
42
+ export interface UserStoreOptions<D> {
43
+ dir: string;
44
+ shape: UserDocShape<D>;
45
+ log?: (entry: Record<string, unknown>) => void;
46
+ now?: () => number;
47
+ }
48
+ export declare function createUserStore<D>(opts: UserStoreOptions<D>): UserStore<D>;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The per-person store: one JSON document per account, `<dir>/<userId>.json`, owned by this
3
+ * server and kept on its own disk (operator, 2026-11-23: "i would prefer if all the data was
4
+ * self-hosted so we don't rely on cloudflare for this").
5
+ *
6
+ * The store knows nothing of what a document holds. The game hands it the shape: an empty
7
+ * document, a parse of what is on disk, and a merge for an account merge. So Magic's favourites,
8
+ * last-played stamps, built decks and art picks live in Magic's own file, and this one stays MIT.
9
+ *
10
+ * Every write is a temp file renamed over the target, as `draftRooms.ts` writes a pod, so a
11
+ * reader never sees half a document and the nightly state backup (which carries the state dir
12
+ * whole) never copies one. Updates to one person are serialised in this process, so two requests
13
+ * that land together both keep their change.
14
+ *
15
+ * `get` and `update` are the whole interface the rest of the server uses, so moving the documents
16
+ * into dataplatform's store later (`docs/planning/telemetry-and-state-inventory.md` §4) replaces
17
+ * this file and nothing that reads it.
18
+ *
19
+ * A file that is not a document (truncated by a full disk, edited by hand) is moved aside to
20
+ * `<userId>.json.unreadable-<ms>`, logged, and the person starts from an empty document: their
21
+ * bytes are kept for the operator, and nothing they do afterwards is refused for it.
22
+ */
23
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
24
+ import { join } from 'node:path';
25
+ /** A registry userId: what the edge sends as `X-User-Id`. Anything else never becomes a file name. */
26
+ const USER_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
27
+ export function isStorableUserId(userId) {
28
+ return USER_ID.test(userId);
29
+ }
30
+ export function createUserStore(opts) {
31
+ const { dir, shape } = opts;
32
+ const log = opts.log ?? (() => undefined);
33
+ const now = opts.now ?? Date.now;
34
+ /** The tail of each person's queue of reads-then-writes. */
35
+ const queues = new Map();
36
+ const pathOf = (userId) => {
37
+ if (!isStorableUserId(userId))
38
+ throw new Error(`not a userId: ${JSON.stringify(userId)}`);
39
+ return join(dir, `${userId}.json`);
40
+ };
41
+ /** Run `job` after every earlier job for these people. */
42
+ function serial(userIds, job) {
43
+ const before = Promise.all(userIds.map((id) => queues.get(id)));
44
+ const run = before.then(job, job);
45
+ const tail = run.catch(() => undefined);
46
+ for (const id of userIds)
47
+ queues.set(id, tail);
48
+ void tail.then(() => {
49
+ for (const id of userIds)
50
+ if (queues.get(id) === tail)
51
+ queues.delete(id);
52
+ });
53
+ return run;
54
+ }
55
+ async function read(userId) {
56
+ const path = pathOf(userId);
57
+ let text;
58
+ try {
59
+ text = await readFile(path, 'utf8');
60
+ }
61
+ catch (err) {
62
+ if (err.code === 'ENOENT')
63
+ return null;
64
+ throw err;
65
+ }
66
+ try {
67
+ return shape.parse(JSON.parse(text));
68
+ }
69
+ catch (err) {
70
+ const aside = `${path}.unreadable-${now()}`;
71
+ await rename(path, aside);
72
+ log({ evt: 'user-doc-unreadable', userId, movedTo: aside, error: err.message });
73
+ return null;
74
+ }
75
+ }
76
+ async function write(userId, doc) {
77
+ const path = pathOf(userId);
78
+ await mkdir(dir, { recursive: true });
79
+ const tmp = `${path}.${process.pid}.${now()}.tmp`;
80
+ await writeFile(tmp, JSON.stringify(doc));
81
+ await rename(tmp, path);
82
+ }
83
+ async function drop(userId) {
84
+ try {
85
+ await rm(pathOf(userId));
86
+ return 1;
87
+ }
88
+ catch (err) {
89
+ if (err.code === 'ENOENT')
90
+ return 0;
91
+ throw err;
92
+ }
93
+ }
94
+ return {
95
+ get: (userId) => serial([userId], async () => (await read(userId)) ?? shape.empty()),
96
+ update: (userId, fn) => serial([userId], async () => {
97
+ const doc = (await read(userId)) ?? shape.empty();
98
+ const next = fn(doc) ?? doc;
99
+ await write(userId, next);
100
+ return next;
101
+ }),
102
+ // An id that cannot be a file name names no document: nothing to erase or move.
103
+ remove: (userId) => (isStorableUserId(userId) ? serial([userId], () => drop(userId)) : Promise.resolve(0)),
104
+ move: (fromUserId, intoUserId) => serial([fromUserId, intoUserId], async () => {
105
+ if (fromUserId === intoUserId || !isStorableUserId(fromUserId))
106
+ return 0;
107
+ const from = await read(fromUserId);
108
+ if (from === null)
109
+ return 0;
110
+ await write(intoUserId, shape.merge(from, (await read(intoUserId)) ?? shape.empty()));
111
+ await drop(fromUserId);
112
+ return 1;
113
+ }),
114
+ };
115
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.113",
4
- "gitHead": "c052ba27eccdd3f15c913c5604033d46b208a96e",
3
+ "version": "0.1.115",
4
+ "gitHead": "d9abd787456c0d6e2ca5a8fbd799bfa09948553c",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -17,9 +17,9 @@
17
17
  "play/remote/"
18
18
  ],
19
19
  "dependencies": {
20
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.113",
21
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.113",
22
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.146",
20
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.115",
21
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.115",
22
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.148",
23
23
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.1.32",
24
24
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.131",
25
25
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.131",