@hadoku/game-server 0.0.0-stage → 0.1.6

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.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base-path.d.ts +29 -0
  3. package/dist/base-path.js +30 -0
  4. package/dist/busy.d.ts +40 -0
  5. package/dist/busy.js +23 -0
  6. package/dist/capacity.d.ts +9 -0
  7. package/dist/capacity.js +6 -0
  8. package/dist/config.d.ts +247 -0
  9. package/dist/config.js +271 -0
  10. package/dist/edge-auth.d.ts +43 -0
  11. package/dist/edge-auth.js +47 -0
  12. package/dist/erase/anonymise.d.ts +7 -0
  13. package/dist/erase/anonymise.js +7 -0
  14. package/dist/erase/index.d.ts +18 -0
  15. package/dist/erase/index.js +20 -0
  16. package/dist/erase/legacy-ids.d.ts +7 -0
  17. package/dist/erase/legacy-ids.js +24 -0
  18. package/dist/erase/recordings.d.ts +26 -0
  19. package/dist/erase/recordings.js +128 -0
  20. package/dist/erase/rooms.d.ts +63 -0
  21. package/dist/erase/rooms.js +67 -0
  22. package/dist/gate.d.ts +27 -0
  23. package/dist/gate.js +15 -0
  24. package/dist/http/client-events.d.ts +25 -0
  25. package/dist/http/client-events.js +15 -0
  26. package/dist/http/page.d.ts +26 -0
  27. package/dist/http/page.js +35 -0
  28. package/dist/http/prepared.d.ts +14 -0
  29. package/dist/http/prepared.js +16 -0
  30. package/dist/http/request.d.ts +59 -0
  31. package/dist/http/request.js +37 -0
  32. package/dist/http/room-core.d.ts +160 -0
  33. package/dist/http/room-core.js +278 -0
  34. package/dist/http/trim.d.ts +23 -0
  35. package/dist/http/trim.js +76 -0
  36. package/dist/http/usage.d.ts +22 -0
  37. package/dist/http/usage.js +16 -0
  38. package/dist/kernel.d.ts +4 -0
  39. package/dist/kernel.js +26 -0
  40. package/dist/log.d.ts +9 -0
  41. package/dist/log.js +9 -0
  42. package/dist/people.d.ts +105 -0
  43. package/dist/people.js +145 -0
  44. package/dist/play/clock.d.ts +39 -0
  45. package/dist/play/clock.js +81 -0
  46. package/dist/play/diagnostics.d.ts +21 -0
  47. package/dist/play/diagnostics.js +35 -0
  48. package/dist/play/engine-runtime.d.ts +200 -0
  49. package/dist/play/engine-runtime.js +309 -0
  50. package/dist/play/game-adapter.d.ts +158 -0
  51. package/dist/play/game-adapter.js +1 -0
  52. package/dist/play/host.d.ts +482 -0
  53. package/dist/play/host.js +950 -0
  54. package/dist/play/jvm-transport.d.ts +25 -0
  55. package/dist/play/jvm-transport.js +1 -0
  56. package/dist/play/local-jvm.d.ts +325 -0
  57. package/dist/play/local-jvm.js +829 -0
  58. package/dist/play/match/hosted.d.ts +92 -0
  59. package/dist/play/match/hosted.js +151 -0
  60. package/dist/play/match/outcome.d.ts +26 -0
  61. package/dist/play/match/outcome.js +21 -0
  62. package/dist/play/match/shell.d.ts +378 -0
  63. package/dist/play/match/shell.js +613 -0
  64. package/dist/play/recording/retention.d.ts +36 -0
  65. package/dist/play/recording/retention.js +89 -0
  66. package/dist/play/recording/writer.d.ts +185 -0
  67. package/dist/play/recording/writer.js +90 -0
  68. package/dist/play/relay-socket.d.ts +128 -0
  69. package/dist/play/relay-socket.js +194 -0
  70. package/dist/play/runtimes/in-process.d.ts +47 -0
  71. package/dist/play/runtimes/in-process.js +43 -0
  72. package/dist/play/runtimes/relay-match.d.ts +166 -0
  73. package/dist/play/runtimes/relay-match.js +240 -0
  74. package/dist/play/runtimes/relay.d.ts +128 -0
  75. package/dist/play/runtimes/relay.js +183 -0
  76. package/dist/play/runtimes/streamed.d.ts +116 -0
  77. package/dist/play/runtimes/streamed.js +148 -0
  78. package/dist/play/start-queue.d.ts +65 -0
  79. package/dist/play/start-queue.js +187 -0
  80. package/dist/room/avatar.d.ts +1 -0
  81. package/dist/room/avatar.js +28 -0
  82. package/dist/room/caller.d.ts +21 -0
  83. package/dist/room/caller.js +1 -0
  84. package/dist/room/constants.d.ts +27 -0
  85. package/dist/room/constants.js +27 -0
  86. package/dist/room/events.d.ts +59 -0
  87. package/dist/room/events.js +174 -0
  88. package/dist/room/identity.d.ts +89 -0
  89. package/dist/room/identity.js +98 -0
  90. package/dist/room/lobby.d.ts +426 -0
  91. package/dist/room/lobby.js +880 -0
  92. package/dist/room/membership.d.ts +64 -0
  93. package/dist/room/membership.js +76 -0
  94. package/dist/room/provisioning.d.ts +22 -0
  95. package/dist/room/provisioning.js +46 -0
  96. package/dist/room/record.d.ts +63 -0
  97. package/dist/room/record.js +39 -0
  98. package/dist/room/room-list.d.ts +67 -0
  99. package/dist/room/room-list.js +66 -0
  100. package/dist/room/seats.d.ts +39 -0
  101. package/dist/room/seats.js +58 -0
  102. package/dist/room/session.d.ts +91 -0
  103. package/dist/room/session.js +156 -0
  104. package/dist/room/socket-auth.d.ts +2 -0
  105. package/dist/room/socket-auth.js +10 -0
  106. package/dist/room/watching.d.ts +35 -0
  107. package/dist/room/watching.js +72 -0
  108. package/dist/room/watchparty-link.d.ts +1 -0
  109. package/dist/room/watchparty-link.js +17 -0
  110. package/dist/stream/alloc.d.ts +115 -0
  111. package/dist/stream/alloc.js +368 -0
  112. package/dist/stream/index.d.ts +66 -0
  113. package/dist/stream/index.js +293 -0
  114. package/dist/telemetry.d.ts +46 -0
  115. package/dist/telemetry.js +25 -0
  116. package/dist/testPort.d.ts +1 -0
  117. package/dist/testPort.js +28 -0
  118. package/package.json +35 -4
  119. package/README.md +0 -3
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The generic room-membership core: who is in a room, who leads it, whether a
3
+ * member is ready, and whether a password opens it. Every mutator here works
4
+ * on a GENERIC member/room shape — no `gameType`, pod, draft, format or
5
+ * tournament field appears anywhere in this file — so it stays behind in
6
+ * `games/magic/server/src/room/` when stage 2b moves the rest of `lobby.ts`'s Magic
7
+ * content to `games/magic/server` (wave 110 §L, phase 2).
8
+ *
9
+ * Split out of `room/lobby.ts`'s `join`/`leave`/`setReady`/`viewOf`/`#persist`.
10
+ * These wrap `@wolffm/rooms-server`'s `MembershipLedger` functions, which
11
+ * already did the real work (leadership succession, readiness) — what moved
12
+ * here is the GLUE: adding a member also means maybe inheriting the room's
13
+ * leadership (an emptied room's new arrival leads it); removing one also
14
+ * means maybe passing it on (whoever remains joined EARLIEST, R16).
15
+ *
16
+ * Every mutator mutates in place and returns nothing but what the caller
17
+ * cannot otherwise observe — the same discipline `lobby.ts`'s own mutators
18
+ * keep. The caller still owns persisting the result and anything about the
19
+ * member's GAME state (a pod seat, a table, a series) — this file only ever
20
+ * touches `members`, `leader` and `ledger`.
21
+ */
22
+ import { type MembershipLedger } from '@wolffm/rooms-server';
23
+ import { type Secret } from './provisioning.js';
24
+ /** The minimal shape a member record needs to be one, whatever game it plays. */
25
+ export interface MemberRow {
26
+ id: string;
27
+ }
28
+ /** The minimal shape a room needs to carry generic membership. */
29
+ export interface MembershipRoom<M extends MemberRow> {
30
+ members: M[];
31
+ leader: string;
32
+ ledger: MembershipLedger;
33
+ }
34
+ /** Whether `id` already holds a seat at the table, so to speak — already a member of the room. */
35
+ export declare function isRoomMember<M extends MemberRow>(room: Pick<MembershipRoom<M>, 'members'>, id: string): boolean;
36
+ /**
37
+ * Add `member`, and give them the room's leadership exactly when the ledger
38
+ * says the room was empty before they joined (`ledger.leaderId`'s own rule —
39
+ * an emptied room's new arrival leads it). Mutates `room.members`,
40
+ * `room.leader` and `room.ledger`. The caller still owns auto-seating them
41
+ * and persisting the room.
42
+ */
43
+ export declare function addRoomMember<M extends MemberRow>(room: MembershipRoom<M>, member: M, joinedAt: number): void;
44
+ /**
45
+ * Remove the member `id` — answers the removed row, or `undefined` when they
46
+ * were never a member. If they held the room's leadership, it passes to
47
+ * whoever remains joined EARLIEST (`memberLeft`'s own rule, R16); the last
48
+ * member out leaves `room.leader` stale, for the caller's sweep to read.
49
+ * Mutates `room.members`, `room.leader` and `room.ledger`. The caller still
50
+ * owns anything about the leaving member's GAME state (a pod drop, a table
51
+ * seat, a series) and persisting the room.
52
+ */
53
+ export declare function removeRoomMember<M extends MemberRow>(room: MembershipRoom<M>, id: string): M | undefined;
54
+ /** `memberId`'s readiness for whatever the room is about to start. */
55
+ export declare function isMemberReady(room: Pick<MembershipRoom<MemberRow>, 'ledger'>, memberId: string): boolean;
56
+ /** Sets `memberId`'s readiness. The caller still owns every side effect a readiness change has on ITS game (a pod auto-seat, a tournament lock, …) and persisting the room. */
57
+ export declare function setMemberReady(room: Pick<MembershipRoom<MemberRow>, 'ledger'>, memberId: string, ready: boolean): void;
58
+ /**
59
+ * Whether `password` opens a room sealed with `secret` — no secret at all
60
+ * opens to anybody. The password is privacy between friends, not
61
+ * authentication (`room/lobby.ts`'s own header): this is the one place that
62
+ * reads as a refusal rather than a credential check.
63
+ */
64
+ export declare function passwordAdmits(secret: Secret | undefined, password: string | undefined): boolean;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The generic room-membership core: who is in a room, who leads it, whether a
3
+ * member is ready, and whether a password opens it. Every mutator here works
4
+ * on a GENERIC member/room shape — no `gameType`, pod, draft, format or
5
+ * tournament field appears anywhere in this file — so it stays behind in
6
+ * `games/magic/server/src/room/` when stage 2b moves the rest of `lobby.ts`'s Magic
7
+ * content to `games/magic/server` (wave 110 §L, phase 2).
8
+ *
9
+ * Split out of `room/lobby.ts`'s `join`/`leave`/`setReady`/`viewOf`/`#persist`.
10
+ * These wrap `@wolffm/rooms-server`'s `MembershipLedger` functions, which
11
+ * already did the real work (leadership succession, readiness) — what moved
12
+ * here is the GLUE: adding a member also means maybe inheriting the room's
13
+ * leadership (an emptied room's new arrival leads it); removing one also
14
+ * means maybe passing it on (whoever remains joined EARLIEST, R16).
15
+ *
16
+ * Every mutator mutates in place and returns nothing but what the caller
17
+ * cannot otherwise observe — the same discipline `lobby.ts`'s own mutators
18
+ * keep. The caller still owns persisting the result and anything about the
19
+ * member's GAME state (a pod seat, a table, a series) — this file only ever
20
+ * touches `members`, `leader` and `ledger`.
21
+ */
22
+ import { addMember, memberLeft, isReady, setReady as ledgerSetReady } from '@wolffm/rooms-server';
23
+ import { passwordMatches } from "./provisioning.js";
24
+ /** Whether `id` already holds a seat at the table, so to speak — already a member of the room. */
25
+ export function isRoomMember(room, id) {
26
+ return room.members.some((m) => m.id === id);
27
+ }
28
+ /**
29
+ * Add `member`, and give them the room's leadership exactly when the ledger
30
+ * says the room was empty before they joined (`ledger.leaderId`'s own rule —
31
+ * an emptied room's new arrival leads it). Mutates `room.members`,
32
+ * `room.leader` and `room.ledger`. The caller still owns auto-seating them
33
+ * and persisting the room.
34
+ */
35
+ export function addRoomMember(room, member, joinedAt) {
36
+ addMember(room.ledger, member.id, joinedAt);
37
+ room.leader = room.ledger.leaderId ?? room.leader;
38
+ room.members.push(member);
39
+ }
40
+ /**
41
+ * Remove the member `id` — answers the removed row, or `undefined` when they
42
+ * were never a member. If they held the room's leadership, it passes to
43
+ * whoever remains joined EARLIEST (`memberLeft`'s own rule, R16); the last
44
+ * member out leaves `room.leader` stale, for the caller's sweep to read.
45
+ * Mutates `room.members`, `room.leader` and `room.ledger`. The caller still
46
+ * owns anything about the leaving member's GAME state (a pod drop, a table
47
+ * seat, a series) and persisting the room.
48
+ */
49
+ export function removeRoomMember(room, id) {
50
+ const index = room.members.findIndex((m) => m.id === id);
51
+ if (index === -1)
52
+ return undefined;
53
+ const removed = room.members[index];
54
+ room.members.splice(index, 1);
55
+ const newLeader = memberLeft(room.ledger, id);
56
+ if (newLeader !== null)
57
+ room.leader = newLeader;
58
+ return removed;
59
+ }
60
+ /** `memberId`'s readiness for whatever the room is about to start. */
61
+ export function isMemberReady(room, memberId) {
62
+ return isReady(room.ledger, memberId);
63
+ }
64
+ /** Sets `memberId`'s readiness. The caller still owns every side effect a readiness change has on ITS game (a pod auto-seat, a tournament lock, …) and persisting the room. */
65
+ export function setMemberReady(room, memberId, ready) {
66
+ ledgerSetReady(room.ledger, memberId, ready);
67
+ }
68
+ /**
69
+ * Whether `password` opens a room sealed with `secret` — no secret at all
70
+ * opens to anybody. The password is privacy between friends, not
71
+ * authentication (`room/lobby.ts`'s own header): this is the one place that
72
+ * reads as a refusal rather than a credential check.
73
+ */
74
+ export function passwordAdmits(secret, password) {
75
+ return secret === undefined || passwordMatches(secret, password ?? '');
76
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A room's password (never stored in plaintext: scrypt with a per-room random
3
+ * salt, compared with `timingSafeEqual`) and the ids it mints for itself and
4
+ * its tables.
5
+ *
6
+ * Moved out of `room/lobby.ts` (split, wave 99 §L): generic room provisioning
7
+ * with no Magic content and no `FileLobby` state of its own.
8
+ */
9
+ export interface Secret {
10
+ salt: string;
11
+ hash: string;
12
+ }
13
+ export declare function makeSecret(password: string): Secret;
14
+ export declare function passwordMatches(secret: Secret, password: string): boolean;
15
+ /**
16
+ * `r-` plus 12 hex characters. The prefix means a room id can never equal a
17
+ * draft id or a match id; 48 random bits make a collision a non-event at this
18
+ * scale, and `create` re-rolls on one anyway.
19
+ */
20
+ export declare function mintRoomId(): string;
21
+ /** `t-` plus 8 hex characters, per the wire contract. Re-rolls on a collision against `existing`. */
22
+ export declare function mintTableId(existing: readonly string[]): string;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A room's password (never stored in plaintext: scrypt with a per-room random
3
+ * salt, compared with `timingSafeEqual`) and the ids it mints for itself and
4
+ * its tables.
5
+ *
6
+ * Moved out of `room/lobby.ts` (split, wave 99 §L): generic room provisioning
7
+ * with no Magic content and no `FileLobby` state of its own.
8
+ */
9
+ import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
10
+ // ── the password ─────────────────────────────────────────────────────────────
11
+ /**
12
+ * scrypt at node's defaults (N=2^14, r=8, p=1): tens of milliseconds, paid once
13
+ * at create and once per join attempt by a non-member, and join attempts are
14
+ * rate-limited per caller in `http/rooms.ts`. Sync, because the lobby is a
15
+ * synchronous in-memory structure and a friend group creates rooms by hand.
16
+ */
17
+ const SALT_BYTES = 16;
18
+ const KEY_BYTES = 32;
19
+ function hashPassword(password, salt) {
20
+ return scryptSync(password.normalize('NFC'), salt, KEY_BYTES);
21
+ }
22
+ export function makeSecret(password) {
23
+ const salt = randomBytes(SALT_BYTES);
24
+ return { salt: salt.toString('hex'), hash: hashPassword(password, salt).toString('hex') };
25
+ }
26
+ export function passwordMatches(secret, password) {
27
+ const expected = Buffer.from(secret.hash, 'hex');
28
+ const got = hashPassword(password, Buffer.from(secret.salt, 'hex'));
29
+ return got.length === expected.length && timingSafeEqual(got, expected);
30
+ }
31
+ /**
32
+ * `r-` plus 12 hex characters. The prefix means a room id can never equal a
33
+ * draft id or a match id; 48 random bits make a collision a non-event at this
34
+ * scale, and `create` re-rolls on one anyway.
35
+ */
36
+ export function mintRoomId() {
37
+ return `r-${randomBytes(6).toString('hex')}`;
38
+ }
39
+ /** `t-` plus 8 hex characters, per the wire contract. Re-rolls on a collision against `existing`. */
40
+ export function mintTableId(existing) {
41
+ const held = new Set(existing);
42
+ let id = `t-${randomBytes(4).toString('hex')}`;
43
+ while (held.has(id))
44
+ id = `t-${randomBytes(4).toString('hex')}`;
45
+ return id;
46
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * A room's record as every game's room has it: who is in it, who leads it, which game it plays, who
3
+ * holds each of that game's seats, and the game's own part, which this file never looks inside
4
+ * (`docs/planning/room-record-generic.md`).
5
+ *
6
+ * The password's salt and hash are not here: a lobby keeps them beside the record, so nothing that
7
+ * builds a view from a record can reach them. Ready is per member, in the membership ledger.
8
+ */
9
+ import type { MembershipLedger } from '@wolffm/rooms-server';
10
+ import type { MemberRow } from './membership.js';
11
+ /**
12
+ * The holder of each game seat, by seat number: a member id, a marker the game type owns for a seat
13
+ * no member holds (an AI's, a closed one), or null for an open seat. A member who holds no seat is
14
+ * watching.
15
+ */
16
+ export type GameSeats = (string | null)[];
17
+ /** The marker of a seat an AI holds. */
18
+ export declare const AI_SEAT = "ai";
19
+ /** The marker of a seat its room's leader closed: nobody sits there, and the game is a seat smaller. */
20
+ export declare const CLOSED_SEAT = "closed";
21
+ /** What every member record has, whatever the game. */
22
+ export interface PlatformMember extends MemberRow {
23
+ /** The registry userId. null for a member the edge named nobody. */
24
+ userId: string | null;
25
+ joinedAt: number;
26
+ /** The member's own per-room state, opaque here (a deck choice, say). */
27
+ state: unknown;
28
+ }
29
+ export interface PlatformRoomRecord<G, M extends PlatformMember = PlatformMember> {
30
+ id: string;
31
+ name: string;
32
+ creator: string;
33
+ /** Mirrors `ledger.leaderId`, kept non-null; it moves only when the leader leaves (`membership.ts`). */
34
+ leader: string;
35
+ gameType: string;
36
+ /** A seeded, admin-only room: never swept (`room-list.ts`). */
37
+ testing: boolean;
38
+ /** When its event starts (`events.ts`). Absent for a room no event made. */
39
+ scheduledFor?: number;
40
+ createdAt: number;
41
+ /** Last mutation, in ms. What the sweep ages a room out on. */
42
+ updatedAt: number;
43
+ members: M[];
44
+ /** Membership, ready and leader. In memory only, rebuilt from `members` and `leader` on restore. */
45
+ ledger: MembershipLedger;
46
+ /** The game seats (`GameSeats`). */
47
+ seats: GameSeats;
48
+ /** The game type's own part of the record. */
49
+ game: G;
50
+ }
51
+ /**
52
+ * The seat `memberId` holds in the room's game, or null when they hold none (they are watching, or
53
+ * not in the room). A seat whose holder is not a member counts as nobody's.
54
+ */
55
+ export declare function gameSeatOf(room: Pick<PlatformRoomRecord<unknown>, 'seats' | 'members'>, memberId: string): number | null;
56
+ /** The game seats by seat number with every seat no member holds read as open. */
57
+ export declare function memberSeats(room: Pick<PlatformRoomRecord<unknown>, 'seats' | 'members'>): GameSeats;
58
+ /** `memberId` takes `seat`, giving up any other game seat they held. The caller has checked the seat is theirs to take. */
59
+ export declare function takeGameSeat(room: Pick<PlatformRoomRecord<unknown>, 'seats'>, memberId: string, seat: number): void;
60
+ /** `memberId` gives their game seat back; it stays open. False when they held none. */
61
+ export declare function leaveGameSeat(room: Pick<PlatformRoomRecord<unknown>, 'seats'>, memberId: string): boolean;
62
+ /** `seat` holds `holder` now: a seat marker the game owns, or null to open it. */
63
+ export declare function setGameSeat(room: Pick<PlatformRoomRecord<unknown>, 'seats'>, seat: number, holder: string | null): void;
@@ -0,0 +1,39 @@
1
+ /** The marker of a seat an AI holds. */
2
+ export const AI_SEAT = 'ai';
3
+ /** The marker of a seat its room's leader closed: nobody sits there, and the game is a seat smaller. */
4
+ export const CLOSED_SEAT = 'closed';
5
+ /**
6
+ * The seat `memberId` holds in the room's game, or null when they hold none (they are watching, or
7
+ * not in the room). A seat whose holder is not a member counts as nobody's.
8
+ */
9
+ export function gameSeatOf(room, memberId) {
10
+ if (!room.members.some((m) => m.id === memberId))
11
+ return null;
12
+ const seat = room.seats.indexOf(memberId);
13
+ return seat === -1 ? null : seat;
14
+ }
15
+ /** The game seats by seat number with every seat no member holds read as open. */
16
+ export function memberSeats(room) {
17
+ return room.seats.map((s) => (s !== null && room.members.some((m) => m.id === s) ? s : null));
18
+ }
19
+ /** `memberId` takes `seat`, giving up any other game seat they held. The caller has checked the seat is theirs to take. */
20
+ export function takeGameSeat(room, memberId, seat) {
21
+ const seats = [...room.seats];
22
+ const held = seats.indexOf(memberId);
23
+ if (held !== -1)
24
+ seats[held] = null;
25
+ seats[seat] = memberId;
26
+ room.seats = seats;
27
+ }
28
+ /** `memberId` gives their game seat back; it stays open. False when they held none. */
29
+ export function leaveGameSeat(room, memberId) {
30
+ const held = room.seats.indexOf(memberId);
31
+ if (held === -1)
32
+ return false;
33
+ room.seats = room.seats.map((s, i) => (i === held ? null : s));
34
+ return true;
35
+ }
36
+ /** `seat` holds `holder` now: a seat marker the game owns, or null to open it. */
37
+ export function setGameSeat(room, seat, holder) {
38
+ room.seats = room.seats.map((s, i) => (i === seat ? holder : s));
39
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The room-list projection and the idle-sweep rule — generic to every room,
3
+ * whatever it plays: creation-order sorting, the front page's "worth
4
+ * advertising" rule, and "has this room sat idle long enough to forget."
5
+ *
6
+ * Each rule has exactly one Magic-specific exception (a draft room stays
7
+ * offered while dealing; a pod room's default idle window and its post-deal
8
+ * grace are a tournament's own), reached through `RoomBusyHook` rather than
9
+ * this file importing pods or drafts itself — the same hook pattern
10
+ * `useGameType`/`onRelayRoomOpened` already use. A non-Magic room (bomberman's)
11
+ * that wires no hook gets `NO_BUSY_HOOK`'s plain rule: no extra reason to stay
12
+ * offered past staleness, the casual idle window, never spared.
13
+ *
14
+ * Split out of `room/lobby.ts`'s `list`/`offered`/`sweep` (wave 110 §L, phase 3).
15
+ * Every function here is pure; the caller still owns persisting anything and
16
+ * iterating its own room map.
17
+ */
18
+ /** The minimal shape a room needs to be listed, offered or swept. */
19
+ export interface ListableRoom {
20
+ id: string;
21
+ createdAt: number;
22
+ updatedAt: number;
23
+ scheduledFor?: number;
24
+ testing: boolean;
25
+ members: {
26
+ length: number;
27
+ };
28
+ }
29
+ /**
30
+ * The one seam `isOfferedRoom`/`isSweepableRoom` read a game's own busy-ness
31
+ * through, rather than naming a game type's fields directly. `lobby.ts`
32
+ * wires Magic's own (`usesPod`, `draftStartedAt`, `POD_SPARED_MS`,
33
+ * `ROOM_IDLE_MS`, `CASUAL_ROOM_IDLE_MS`).
34
+ */
35
+ export interface RoomBusyHook<R> {
36
+ /** Whether a match is live in `room` (Magic: any of its tables plays one). A room with one is offered and never swept. */
37
+ liveMatch(room: R): boolean;
38
+ /** An extra reason — beyond a live match — `room` counts as busy enough to stay offered past `staleMs` (Magic: a draft under way). */
39
+ extraOffered(room: R): boolean;
40
+ /** The idle window `isSweepableRoom` uses when the caller gives none (Magic: a tournament's `ROOM_IDLE_MS`, else the casual one). */
41
+ defaultIdleMs(room: R): number;
42
+ /** Whether `room` is spared this sweep despite sitting past its idle window (Magic: a pod dealt within `POD_SPARED_MS`). */
43
+ sparedFromSweep(room: R, now: number): boolean;
44
+ }
45
+ /** The plain rule: no live match it can see, no extra reason to stay offered, an 8-hour idle window, never spared. What a room wires if its game has nothing extra to say. */
46
+ export declare const NO_BUSY_HOOK: RoomBusyHook<unknown>;
47
+ /** Creation order, with the (random) room id as a tie-break for two rooms made in the same millisecond — `list()`'s and `offered()`'s shared sort. */
48
+ export declare function sortRoomsByCreation<R extends {
49
+ id: string;
50
+ createdAt: number;
51
+ }>(rooms: readonly R[]): R[];
52
+ /**
53
+ * Whether `room` belongs on the front page right now: a seeded testing room
54
+ * always; an empty room never (R16 — hidden the instant its last member
55
+ * leaves, not after `staleMs`); otherwise a live match, the hook's own extra
56
+ * reason, or simply not yet stale since `touchedAt` (`updatedAt`, the last
57
+ * poll, or the event's own start, whichever is latest).
58
+ */
59
+ export declare function isOfferedRoom<R extends ListableRoom>(room: R, hook: RoomBusyHook<R>, now: number, staleMs: number, touchedAt: number | undefined): boolean;
60
+ /**
61
+ * Whether the idle sweep should forget `room` now: never a seeded testing
62
+ * room, never one with a live match (its own end is a different clock's
63
+ * job), never one the hook says is spared, and otherwise only once it has
64
+ * sat untouched — from its event's start if it has one — for longer than
65
+ * `idleMs` (or the hook's own default, absent an override).
66
+ */
67
+ export declare function isSweepableRoom<R extends ListableRoom>(room: R, hook: RoomBusyHook<R>, now: number, idleMs: number | undefined): boolean;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The room-list projection and the idle-sweep rule — generic to every room,
3
+ * whatever it plays: creation-order sorting, the front page's "worth
4
+ * advertising" rule, and "has this room sat idle long enough to forget."
5
+ *
6
+ * Each rule has exactly one Magic-specific exception (a draft room stays
7
+ * offered while dealing; a pod room's default idle window and its post-deal
8
+ * grace are a tournament's own), reached through `RoomBusyHook` rather than
9
+ * this file importing pods or drafts itself — the same hook pattern
10
+ * `useGameType`/`onRelayRoomOpened` already use. A non-Magic room (bomberman's)
11
+ * that wires no hook gets `NO_BUSY_HOOK`'s plain rule: no extra reason to stay
12
+ * offered past staleness, the casual idle window, never spared.
13
+ *
14
+ * Split out of `room/lobby.ts`'s `list`/`offered`/`sweep` (wave 110 §L, phase 3).
15
+ * Every function here is pure; the caller still owns persisting anything and
16
+ * iterating its own room map.
17
+ */
18
+ /** The plain rule: no live match it can see, no extra reason to stay offered, an 8-hour idle window, never spared. What a room wires if its game has nothing extra to say. */
19
+ export const NO_BUSY_HOOK = {
20
+ liveMatch: () => false,
21
+ extraOffered: () => false,
22
+ defaultIdleMs: () => 8 * 60 * 60_000,
23
+ sparedFromSweep: () => false,
24
+ };
25
+ /** Creation order, with the (random) room id as a tie-break for two rooms made in the same millisecond — `list()`'s and `offered()`'s shared sort. */
26
+ export function sortRoomsByCreation(rooms) {
27
+ return [...rooms].sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1));
28
+ }
29
+ /**
30
+ * Whether `room` belongs on the front page right now: a seeded testing room
31
+ * always; an empty room never (R16 — hidden the instant its last member
32
+ * leaves, not after `staleMs`); otherwise a live match, the hook's own extra
33
+ * reason, or simply not yet stale since `touchedAt` (`updatedAt`, the last
34
+ * poll, or the event's own start, whichever is latest).
35
+ */
36
+ export function isOfferedRoom(room, hook, now, staleMs, touchedAt) {
37
+ if (room.testing)
38
+ return true;
39
+ if (room.members.length === 0)
40
+ return false;
41
+ if (hook.liveMatch(room))
42
+ return true;
43
+ if (hook.extraOffered(room))
44
+ return true;
45
+ const cutoff = now - staleMs;
46
+ return Math.max(room.updatedAt, touchedAt ?? 0, room.scheduledFor ?? 0) > cutoff;
47
+ }
48
+ /**
49
+ * Whether the idle sweep should forget `room` now: never a seeded testing
50
+ * room, never one with a live match (its own end is a different clock's
51
+ * job), never one the hook says is spared, and otherwise only once it has
52
+ * sat untouched — from its event's start if it has one — for longer than
53
+ * `idleMs` (or the hook's own default, absent an override).
54
+ */
55
+ export function isSweepableRoom(room, hook, now, idleMs) {
56
+ if (room.testing)
57
+ return false;
58
+ if (hook.liveMatch(room))
59
+ return false;
60
+ const idle = idleMs ?? hook.defaultIdleMs(room);
61
+ if (Math.max(room.updatedAt, room.scheduledFor ?? 0) > now - idle)
62
+ return false;
63
+ if (hook.sparedFromSweep(room, now))
64
+ return false;
65
+ return true;
66
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A table's two seats and each seat's Ready: the one record of who sits where
3
+ * (`room/lobby.ts` keeps one per table). A seat is a place, as a pod's seats
4
+ * are: someone sits in the seat they pick (the first open one when they pick
5
+ * none), and a seat someone stands up from stays empty — nobody moves up into
6
+ * it. A Ready belongs to the player in the seat: it leaves with them.
7
+ *
8
+ * The game reads the seated players in seat order with the empty seat skipped
9
+ * (`seatList`, `seatOrder`): that order is a match's seat order, a series' and
10
+ * a Gauntlet's, so a player alone in the second seat is still the match's
11
+ * first seat against the AI.
12
+ */
13
+ export type SeatPair = [string | null, string | null];
14
+ export interface TableSeats {
15
+ seats: SeatPair;
16
+ ready: [boolean, boolean];
17
+ }
18
+ /** A seat's holder, their Ready, and which of the table's seats they sit in. */
19
+ export interface TableSeat {
20
+ memberId: string;
21
+ ready: boolean;
22
+ seat: number;
23
+ }
24
+ /** The seated players, in seat order. */
25
+ export declare function seatList(table: TableSeats): TableSeat[];
26
+ /** The seated players as a match, a series and a Gauntlet number them: seat order, the empty seat skipped. */
27
+ export declare function seatOrder(table: TableSeats): SeatPair;
28
+ /**
29
+ * `memberId` sits at `table` — in `seat` when it is given, else the first open
30
+ * one — giving up a seat held anywhere else in the room's `tables`, this table
31
+ * included (a move, as a pod's seats allow). True when they hold the seat
32
+ * afterwards (one already held is left as it is); false when it is someone
33
+ * else's, or no seat is open.
34
+ */
35
+ export declare function sitAt(tables: readonly TableSeats[], table: TableSeats, memberId: string, seat?: number): boolean;
36
+ /** Give a seat back, Ready and all; it stays empty. False when `memberId` held no seat here. */
37
+ export declare function leaveSeat(table: TableSeats, memberId: string): boolean;
38
+ /** A seated player's Ready. False when `memberId` holds no seat here. */
39
+ export declare function readySeat(table: TableSeats, memberId: string, ready: boolean): boolean;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * A table's two seats and each seat's Ready: the one record of who sits where
3
+ * (`room/lobby.ts` keeps one per table). A seat is a place, as a pod's seats
4
+ * are: someone sits in the seat they pick (the first open one when they pick
5
+ * none), and a seat someone stands up from stays empty — nobody moves up into
6
+ * it. A Ready belongs to the player in the seat: it leaves with them.
7
+ *
8
+ * The game reads the seated players in seat order with the empty seat skipped
9
+ * (`seatList`, `seatOrder`): that order is a match's seat order, a series' and
10
+ * a Gauntlet's, so a player alone in the second seat is still the match's
11
+ * first seat against the AI.
12
+ */
13
+ /** The seated players, in seat order. */
14
+ export function seatList(table) {
15
+ return table.seats.flatMap((memberId, seat) => (memberId === null ? [] : [{ memberId, ready: table.ready[seat], seat }]));
16
+ }
17
+ /** The seated players as a match, a series and a Gauntlet number them: seat order, the empty seat skipped. */
18
+ export function seatOrder(table) {
19
+ const [first, second] = seatList(table);
20
+ return [first?.memberId ?? null, second?.memberId ?? null];
21
+ }
22
+ /**
23
+ * `memberId` sits at `table` — in `seat` when it is given, else the first open
24
+ * one — giving up a seat held anywhere else in the room's `tables`, this table
25
+ * included (a move, as a pod's seats allow). True when they hold the seat
26
+ * afterwards (one already held is left as it is); false when it is someone
27
+ * else's, or no seat is open.
28
+ */
29
+ export function sitAt(tables, table, memberId, seat) {
30
+ const held = table.seats.indexOf(memberId);
31
+ if (seat === undefined ? held !== -1 : held === seat)
32
+ return true;
33
+ const target = seat ?? table.seats.indexOf(null);
34
+ if (target === -1 || table.seats[target] !== null)
35
+ return false;
36
+ for (const other of tables)
37
+ leaveSeat(other, memberId);
38
+ table.seats[target] = memberId;
39
+ table.ready[target] = false;
40
+ return true;
41
+ }
42
+ /** Give a seat back, Ready and all; it stays empty. False when `memberId` held no seat here. */
43
+ export function leaveSeat(table, memberId) {
44
+ const at = table.seats.indexOf(memberId);
45
+ if (at === -1)
46
+ return false;
47
+ table.seats[at] = null;
48
+ table.ready[at] = false;
49
+ return true;
50
+ }
51
+ /** A seated player's Ready. False when `memberId` holds no seat here. */
52
+ export function readySeat(table, memberId, ready) {
53
+ const at = table.seats.indexOf(memberId);
54
+ if (at === -1)
55
+ return false;
56
+ table.ready[at] = ready;
57
+ return true;
58
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * One live tab per player per room: `@wolffm/rooms-server`'s `SessionClaims`, on this server's sockets.
3
+ *
4
+ * The operator, 2026-11-07: *"whenever a player tried to join a game when they already have an active
5
+ * session we should … show a prompt in the middle of the screen … asking whether they want to take
6
+ * over in this session? if they click yes, then we terminate their previous session."* The rule is
7
+ * the shared room layer's (`SessionClaims`' header, and `@wolffm/rooms-protocol`'s `session.ts` for the
8
+ * wire); this file is where cardtable's sockets meet it.
9
+ *
10
+ * ## Which sockets
11
+ *
12
+ * A tab's screen gate (`packages/game-ui/src/room/session.ts`) opens one socket per room and sends
13
+ * `session:claim` on it: that is the claim the player is asked about. The tab's other sockets for the
14
+ * room join the same claim when they join as a player (`attach`): the pod's draft socket
15
+ * (`room/socket.ts`) and the match socket (`play/socket.ts`), each naming its tab. So a take retires
16
+ * every connection the old tab has in the room, its live match included, and a socket of a tab that
17
+ * does not hold the room is refused its player's join (`session-elsewhere`) instead of silently
18
+ * taking the seat.
19
+ *
20
+ * ## Who
21
+ *
22
+ * A player only (`isPlayer`): a seat at one of the room's tables, a place in its pod or draft, or a
23
+ * seat in its match. Watchers keep as many tabs as they like, and their claim answers `watcher`
24
+ * holding nothing. The screen claims again whenever its room changes, so a watcher who sits down is
25
+ * then a player with a claim, and a player who stands up lets go of it.
26
+ *
27
+ * ## The room's key
28
+ *
29
+ * The room id the screen is in, and for a match that no room holds (a scenario, a direct game against
30
+ * the AI) the match's own id: the same id `App.tsx`'s `roomIdFor` gives the screen.
31
+ *
32
+ * ## Liveness
33
+ *
34
+ * Every holding session socket is sent `session:beat` every `BEAT_MS`, and its ack is a heartbeat. A
35
+ * beat is a message, so a hidden tab whose timers the browser throttles still answers at once; an
36
+ * engine.io pong is one too, for every attached socket. A holder silent past `IDLE_MS` — a closed
37
+ * laptop, a dropped network, a socket whose ping has not timed out yet — is replaced without asking.
38
+ *
39
+ * ## A take
40
+ *
41
+ * The old tab's sockets are told `session:taken` and closed from here. A server-side close does not
42
+ * auto-reconnect, so the old tab cannot loop back into the room; it offers to take the session back,
43
+ * which is the same claim with `take`. Every take reports `session-takeover` with the room and whether
44
+ * the holder was live or stale.
45
+ */
46
+ import type { Server as SocketIOServer, Socket } from 'socket.io';
47
+ import { type JsonLog } from '../log.js';
48
+ /** How often a holding session socket is asked whether it is alive. */
49
+ export declare const BEAT_MS = 5000;
50
+ /** A holder that has answered nothing for this long is stale: two missed beats and change. */
51
+ export declare const IDLE_MS = 15000;
52
+ export interface SessionDeps {
53
+ /** Whether `participantId` plays in `room` (see the header's "Who"). */
54
+ isPlayer(room: string, participantId: string): boolean;
55
+ log?: JsonLog;
56
+ beatMs?: number;
57
+ idleMs?: number;
58
+ now?: () => number;
59
+ }
60
+ export interface SessionHandle {
61
+ /**
62
+ * A room socket of tab `tabId` joining `room` as `participantId`. False when another live tab of the
63
+ * account holds the room: refuse the player's join. True for a watcher, who holds nothing.
64
+ */
65
+ attach(room: string, participantId: string, tabId: string, socket: Socket): boolean;
66
+ close(): void;
67
+ }
68
+ export declare function attachSessions(io: SocketIOServer, deps: SessionDeps): SessionHandle;
69
+ /** The parts of a room view `playsIn` reads. */
70
+ export interface PlayedRoom {
71
+ /** A game part with tables (Magic's): absent for a room whose game has none. */
72
+ tables?: readonly {
73
+ players: readonly {
74
+ memberId: string;
75
+ }[];
76
+ }[];
77
+ /** The room's game seats (`RoomView.seats`), whatever game it plays. */
78
+ seats: readonly (string | null)[];
79
+ /** A game part with a pod (Magic's): absent for a room whose game has none. */
80
+ game?: {
81
+ pod: {
82
+ seats: readonly ({
83
+ memberId: string;
84
+ } | null)[];
85
+ drafters: readonly string[];
86
+ dropped?: readonly string[];
87
+ } | null;
88
+ };
89
+ }
90
+ /** Whether `participantId` plays in the room: a game seat, a table seat, a pod seat, or a place in its draft and rounds. */
91
+ export declare function playsIn(room: PlayedRoom, participantId: string): boolean;