@hadoku/rooms-server 0.45.59 → 0.45.61

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,68 @@
1
+ import type { Server as SocketIOServer, Socket } from 'socket.io';
2
+ /**
3
+ * Pushes a `RoomBook`'s (or any `watchRoomSource`-driven) change events down
4
+ * one socket.io server, instead of a browser reading a room list on a timer.
5
+ *
6
+ * ## The wire contract is INJECTED, not imported
7
+ *
8
+ * `@wolffm/rooms-protocol`'s `feed.ts` is the canonical channel names and
9
+ * parser (`ROOM_FEED_CHANNEL`, `parseRoomWatch`) — every consumer should use
10
+ * THOSE, never a second copy. This file does not import that module directly;
11
+ * it takes a `RoomFeedWire` the caller builds from it. Same posture as
12
+ * `claimAvatar`'s pool or `RoomRegistry`'s seat-table factory: a shared name
13
+ * or policy that is genuinely app-agnostic still does not belong hardcoded
14
+ * into a generic package when the package can just as well take it as a
15
+ * parameter — and here it buys something concrete: this file, and its tests,
16
+ * build and run with zero dependency on which version of the wire module a
17
+ * given workspace happens to have wired into its exports yet.
18
+ *
19
+ * ## No membership gating by default
20
+ *
21
+ * cardtable's `attachRoomFeed` only pings a watcher of a specific room while
22
+ * `lobby.isMember(room, participantId)` — rooms there are private. A generic
23
+ * `RoomBook` has no opinion on privacy, so `deps.isMember` is OPTIONAL: when
24
+ * omitted, every watcher of a room id gets pushed, which is correct for an
25
+ * app (watchparty's lobby, publicly listed) where there is nothing to hide. A
26
+ * privacy-sensitive consumer supplies `isMember` and gets cardtable's
27
+ * behaviour back.
28
+ *
29
+ * ## One ping per room per turn
30
+ *
31
+ * Changes are collected and flushed once per `setImmediate` tick, so a run of
32
+ * writes inside one request is said once, not once per write — same reasoning
33
+ * as cardtable's `apps/server/src/room/feed.ts`.
34
+ */
35
+ export interface RoomFeedWatch {
36
+ rooms: readonly string[];
37
+ list: boolean;
38
+ }
39
+ export type RoomFeedChanged = {
40
+ room: string;
41
+ } | {
42
+ list: true;
43
+ };
44
+ export interface RoomFeedWire {
45
+ channel: {
46
+ watch: string;
47
+ changed: string;
48
+ };
49
+ /** Parse an inbound `watch` payload off the wire. `null` for anything malformed. */
50
+ parseWatch(raw: unknown): RoomFeedWatch | null;
51
+ }
52
+ export interface RoomFeedDeps {
53
+ wire: RoomFeedWire;
54
+ /** Be told a room (or the list) changed. Usually `RoomBook.onChange` / `RoomSourceWatcher.onChange`. */
55
+ onChange(listener: (roomId: string) => void): () => void;
56
+ /** Gate a per-room push. Omit for a public room list — see this file's header. */
57
+ isMember?(roomId: string, participantId: string): boolean;
58
+ /** Identify the connecting socket's caller. Defaults to the socket id (ephemeral, fine for an app with no durable identity on this channel). */
59
+ participantId?(socket: Socket): string;
60
+ log?(line: Record<string, unknown>): void;
61
+ }
62
+ export interface RoomFeedHandle {
63
+ /** Push a room's ping on THIS tick, bypassing the batching window. Rarely needed: `onChange` already drives every push. */
64
+ changed(roomId: string): void;
65
+ close(): void;
66
+ }
67
+ export declare function attachRoomBookFeed(io: SocketIOServer, deps: RoomFeedDeps): RoomFeedHandle;
68
+ //# sourceMappingURL=feed.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feed.d.ts","sourceRoot":"","sources":["../../src/book/feed.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,cAAc,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,IAAI,CAAA;CAAE,CAAC;AAEhE,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAC5C,oFAAoF;IACpF,UAAU,CAAC,GAAG,EAAE,OAAO,GAAG,aAAa,GAAG,IAAI,CAAC;CAChD;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,YAAY,CAAC;IACnB,wGAAwG;IACxG,QAAQ,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACzD,kFAAkF;IAClF,QAAQ,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC;IAC1D,gJAAgJ;IAChJ,aAAa,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACvC,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC3C;AAED,MAAM,WAAW,cAAc;IAC7B,2HAA2H;IAC3H,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,KAAK,IAAI,IAAI,CAAC;CACf;AASD,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,YAAY,GAAG,cAAc,CA4DzF"}
@@ -0,0 +1,62 @@
1
+ export function attachRoomBookFeed(io, deps) {
2
+ const log = deps.log ?? (() => { });
3
+ const watchers = new Map();
4
+ const changedRooms = new Set();
5
+ let flushing = false;
6
+ const send = (socket, message) => {
7
+ socket.emit(deps.wire.channel.changed, message);
8
+ };
9
+ const flush = () => {
10
+ flushing = false;
11
+ const rooms = [...changedRooms];
12
+ changedRooms.clear();
13
+ for (const watcher of watchers.values()) {
14
+ for (const room of rooms) {
15
+ if (!watcher.rooms.has(room))
16
+ continue;
17
+ if (deps.isMember && !deps.isMember(room, watcher.participantId))
18
+ continue;
19
+ send(watcher.socket, { room });
20
+ }
21
+ if (watcher.list)
22
+ send(watcher.socket, { list: true });
23
+ }
24
+ };
25
+ const note = (roomId) => {
26
+ changedRooms.add(roomId);
27
+ if (flushing)
28
+ return;
29
+ flushing = true;
30
+ setImmediate(flush);
31
+ };
32
+ const stopListening = deps.onChange(note);
33
+ io.on('connection', (socket) => {
34
+ const participantId = deps.participantId ? deps.participantId(socket) : socket.id;
35
+ socket.on(deps.wire.channel.watch, (raw, ack) => {
36
+ const parsed = deps.wire.parseWatch(raw);
37
+ if (!parsed) {
38
+ log({ evt: 'watch-malformed', participantId });
39
+ return;
40
+ }
41
+ if (parsed.rooms.length === 0 && !parsed.list) {
42
+ watchers.delete(socket.id);
43
+ }
44
+ else {
45
+ watchers.set(socket.id, { socket, participantId, rooms: new Set(parsed.rooms), list: parsed.list });
46
+ }
47
+ if (typeof ack === 'function')
48
+ ack();
49
+ });
50
+ socket.on('disconnect', () => {
51
+ watchers.delete(socket.id);
52
+ });
53
+ });
54
+ return {
55
+ changed: note,
56
+ close() {
57
+ stopListening();
58
+ watchers.clear();
59
+ changedRooms.clear();
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,3 @@
1
+ export { RoomBook, watchRoomSource, type RoomBookDeps, type RoomBookOptions, type RoomChangeListener, type RoomSourceWatcher, type RoomStamp, type WatchRoomSourceOptions, } from './roomBook.js';
2
+ export { attachRoomBookFeed, type RoomFeedChanged, type RoomFeedDeps, type RoomFeedHandle, type RoomFeedWatch, type RoomFeedWire, } from './feed.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/book/index.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,QAAQ,EACR,eAAe,EACf,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,sBAAsB,GAC5B,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,kBAAkB,EAClB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,YAAY,GAClB,MAAM,WAAW,CAAC"}
@@ -0,0 +1,11 @@
1
+ /*
2
+ * @wolffm/rooms-server's room book: `list`, `get`, `open`, `close` and change
3
+ * events over a `RoomRegistry`, plus the socket.io push that lets a feed
4
+ * (`feed.ts`) replace a browser's periodic re-read. See `roomBook.ts`'s
5
+ * header for why change detection is a cheap `updatedAt` sweep rather than an
6
+ * instrumented call site in every mutation, and `feed.ts`'s for why the wire
7
+ * contract (`@wolffm/rooms-protocol`'s `feed.ts`) is injected rather than
8
+ * imported directly.
9
+ */
10
+ export { RoomBook, watchRoomSource, } from './roomBook.js';
11
+ export { attachRoomBookFeed, } from './feed.js';
@@ -0,0 +1,94 @@
1
+ import type { CoreRoomState, SeatTableFactory } from '../state.js';
2
+ import { RoomRegistry } from '../state.js';
3
+ /**
4
+ * The set of an app's rooms — list, get, open, close — plus change events, so
5
+ * a feed (`./feed.ts`) can push "the list moved" instead of a browser polling
6
+ * for it (platform plan v2, line 371).
7
+ *
8
+ * A thin layer over `RoomRegistry`: everything about ONE room (membership,
9
+ * seating, avatars) is already `RoomRegistry`'s job (`../state.ts`). What
10
+ * `RoomRegistry` does not have is a way to be TOLD "something changed" — it is
11
+ * mutated directly, from many call sites across a hosting app (joins, leaves,
12
+ * ready state, playback control…), and most of those sites will never import
13
+ * this package's feed machinery. Instrumenting every one of them is a
14
+ * per-app decision outside this package's reach, so `RoomBook` does not try:
15
+ * it detects change the one way available to ANY `CoreRoomState` without
16
+ * reading app-specific fields — `updatedAt` — on a cheap in-memory sweep
17
+ * (`watchRoomSource`, below). `gc.ts`'s `evaluateRoom` already leans on the
18
+ * same field for the same reason, with the same acknowledged coarseness: any
19
+ * write at all pushes the signal out, which is conservative, not exact.
20
+ *
21
+ * `open`/`close` additionally fire the moment they happen, with no need to
22
+ * wait out the sweep interval — a room appearing or disappearing is this
23
+ * class's own doing, so it can always say so immediately.
24
+ */
25
+ export type RoomChangeListener = (roomId: string) => void;
26
+ /** One room summary a sweep needs — just enough to detect change. */
27
+ export interface RoomStamp {
28
+ roomId: string;
29
+ updatedAt: number;
30
+ }
31
+ export interface RoomSourceWatcher {
32
+ onChange(listener: RoomChangeListener): () => void;
33
+ /** Check right now, instead of waiting for the next tick — call after a write you know just happened. */
34
+ poke(): void;
35
+ close(): void;
36
+ }
37
+ export interface WatchRoomSourceOptions {
38
+ /** How often to re-check. Default 500ms. */
39
+ sweepMs?: number;
40
+ /** Repeating timer. Defaults to `setInterval`; injectable for tests and non-Node hosts. */
41
+ setTimer?: (fn: () => void, ms: number) => unknown;
42
+ /** Cancels a `setTimer` handle. Defaults to `clearInterval`. */
43
+ clearTimer?: (handle: unknown) => void;
44
+ }
45
+ /**
46
+ * Watches a plain list of `{roomId, updatedAt}` and fires a listener for any
47
+ * id whose `updatedAt` advanced since the last check, any id that appeared, or
48
+ * any id that disappeared. Exported on its own (not only as `RoomBook`
49
+ * internals) because a hosting app that already has its own room source
50
+ * (watchparty's `allRooms()`, say) can drive this mechanism without
51
+ * constructing a `RoomBook` or holding a `RoomRegistry` at all.
52
+ *
53
+ * Pure diffing, no transport: nothing here knows about sockets.
54
+ */
55
+ export declare function watchRoomSource(source: () => readonly RoomStamp[], opts?: WatchRoomSourceOptions): RoomSourceWatcher;
56
+ export type RoomBookOptions = WatchRoomSourceOptions;
57
+ export interface RoomBookDeps<TApp, TClient = unknown> {
58
+ registry: RoomRegistry<TApp, TClient>;
59
+ }
60
+ /**
61
+ * `list`, `get`, `open`, `close`, and change events, over one `RoomRegistry`.
62
+ *
63
+ * A fresh consumer that has no binding layer of its own constructs one of
64
+ * these directly. A host that already wraps `RoomRegistry` in its own module
65
+ * (watchparty's `apps/server/src/rooms/store.ts`) is not obliged to adopt
66
+ * `RoomBook` itself — it can drive `watchRoomSource` straight off whatever
67
+ * function it already exports (`allRooms()`), and get the same change events
68
+ * with no new class in the mix. `RoomBook` exists for the case where nothing
69
+ * like that exists yet.
70
+ */
71
+ export declare class RoomBook<TApp, TClient = unknown> {
72
+ #private;
73
+ constructor(deps: RoomBookDeps<TApp, TClient>, opts?: RoomBookOptions);
74
+ list(): CoreRoomState<TApp, TClient>[];
75
+ get(roomId: string): CoreRoomState<TApp, TClient> | undefined;
76
+ /** Create the room if it does not exist yet. Returns the existing one otherwise — idempotent, like `RoomRegistry.seed`. */
77
+ open(roomId: string, roomKey: string, createSeats?: SeatTableFactory): CoreRoomState<TApp, TClient>;
78
+ /** False when there was no such room. */
79
+ close(roomId: string): boolean;
80
+ /**
81
+ * Tell the book a room changed, without waiting out the sweep interval. For
82
+ * a caller that just wrote something the sweep's `updatedAt` check would
83
+ * catch anyway, but wants the push to go out on THIS tick rather than the
84
+ * next one — mirrors cardtable's `RoomFeedHandle.changed()`. `_roomId` is
85
+ * kept in the signature for that symmetry even though the sweep itself
86
+ * re-reads every room regardless of which one is named.
87
+ */
88
+ changed(_roomId: string): void;
89
+ /** Be told whenever a room opens, closes, or (on the sweep) looks written-to. Returns the unsubscribe. */
90
+ onChange(listener: RoomChangeListener): () => void;
91
+ /** Stops the sweep. A book that is no longer used must be stopped, or its timer (unref'd, but still live) outlives it. */
92
+ stop(): void;
93
+ }
94
+ //# sourceMappingURL=roomBook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roomBook.d.ts","sourceRoot":"","sources":["../../src/book/roomBook.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,MAAM,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;AAE1D,qEAAqE;AACrE,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI,CAAC;IACnD,yGAAyG;IACzG,IAAI,IAAI,IAAI,CAAC;IACb,KAAK,IAAI,IAAI,CAAC;CACf;AAED,MAAM,WAAW,sBAAsB;IACrC,4CAA4C;IAC5C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2FAA2F;IAC3F,QAAQ,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,EAAE,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;IACnD,gEAAgE;IAChE,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CACxC;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,SAAS,SAAS,EAAE,EAAE,IAAI,GAAE,sBAA2B,GAAG,iBAAiB,CAoDxH;AAED,MAAM,MAAM,eAAe,GAAG,sBAAsB,CAAC;AAErD,MAAM,WAAW,YAAY,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO;IACnD,QAAQ,EAAE,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;CACvC;AAED;;;;;;;;;;GAUG;AACH,qBAAa,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO;;gBAI/B,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,GAAE,eAAoB;IASzE,IAAI,IAAI,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE;IAItC,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,SAAS;IAI7D,2HAA2H;IAC3H,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,gBAAgB,GAAG,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC;IAOnG,yCAAyC;IACzC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAO9B;;;;;;;OAOG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAI9B,0GAA0G;IAC1G,QAAQ,CAAC,QAAQ,EAAE,kBAAkB,GAAG,MAAM,IAAI;IAIlD,0HAA0H;IAC1H,IAAI,IAAI,IAAI;CAGb"}
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Watches a plain list of `{roomId, updatedAt}` and fires a listener for any
3
+ * id whose `updatedAt` advanced since the last check, any id that appeared, or
4
+ * any id that disappeared. Exported on its own (not only as `RoomBook`
5
+ * internals) because a hosting app that already has its own room source
6
+ * (watchparty's `allRooms()`, say) can drive this mechanism without
7
+ * constructing a `RoomBook` or holding a `RoomRegistry` at all.
8
+ *
9
+ * Pure diffing, no transport: nothing here knows about sockets.
10
+ */
11
+ export function watchRoomSource(source, opts = {}) {
12
+ const sweepMs = opts.sweepMs ?? 500;
13
+ const setTimer = opts.setTimer ?? ((fn, ms) => {
14
+ const handle = setInterval(fn, ms);
15
+ // Never the reason a process stays alive — same posture as rooms-server's
16
+ // other background timers (`session-claims.ts`, `presence.ts`).
17
+ handle.unref?.();
18
+ return handle;
19
+ });
20
+ const clearTimer = opts.clearTimer ?? ((h) => clearInterval(h));
21
+ const listeners = new Set();
22
+ const known = new Map();
23
+ const fire = (roomId) => {
24
+ for (const listener of [...listeners])
25
+ listener(roomId);
26
+ };
27
+ const check = () => {
28
+ const seen = new Set();
29
+ for (const { roomId, updatedAt } of source()) {
30
+ seen.add(roomId);
31
+ const prev = known.get(roomId);
32
+ if (prev === undefined || prev !== updatedAt) {
33
+ known.set(roomId, updatedAt);
34
+ fire(roomId);
35
+ }
36
+ }
37
+ for (const roomId of known.keys()) {
38
+ if (!seen.has(roomId)) {
39
+ known.delete(roomId);
40
+ fire(roomId);
41
+ }
42
+ }
43
+ };
44
+ // Baseline without a firing storm on the very first tick.
45
+ for (const { roomId, updatedAt } of source())
46
+ known.set(roomId, updatedAt);
47
+ const timer = setTimer(check, sweepMs);
48
+ return {
49
+ onChange(listener) {
50
+ listeners.add(listener);
51
+ return () => listeners.delete(listener);
52
+ },
53
+ poke: check,
54
+ close() {
55
+ clearTimer(timer);
56
+ listeners.clear();
57
+ known.clear();
58
+ },
59
+ };
60
+ }
61
+ /**
62
+ * `list`, `get`, `open`, `close`, and change events, over one `RoomRegistry`.
63
+ *
64
+ * A fresh consumer that has no binding layer of its own constructs one of
65
+ * these directly. A host that already wraps `RoomRegistry` in its own module
66
+ * (watchparty's `apps/server/src/rooms/store.ts`) is not obliged to adopt
67
+ * `RoomBook` itself — it can drive `watchRoomSource` straight off whatever
68
+ * function it already exports (`allRooms()`), and get the same change events
69
+ * with no new class in the mix. `RoomBook` exists for the case where nothing
70
+ * like that exists yet.
71
+ */
72
+ export class RoomBook {
73
+ #registry;
74
+ #watcher;
75
+ constructor(deps, opts = {}) {
76
+ this.#registry = deps.registry;
77
+ this.#watcher = watchRoomSource(() => this.#stamps(), opts);
78
+ }
79
+ #stamps() {
80
+ return this.#registry.all().map((r) => ({ roomId: r.roomId, updatedAt: r.updatedAt }));
81
+ }
82
+ list() {
83
+ return this.#registry.all();
84
+ }
85
+ get(roomId) {
86
+ return this.#registry.get(roomId);
87
+ }
88
+ /** Create the room if it does not exist yet. Returns the existing one otherwise — idempotent, like `RoomRegistry.seed`. */
89
+ open(roomId, roomKey, createSeats) {
90
+ const isNew = this.#registry.get(roomId) === undefined;
91
+ const room = this.#registry.seed(roomId, roomKey, createSeats);
92
+ if (isNew)
93
+ this.#watcher.poke();
94
+ return room;
95
+ }
96
+ /** False when there was no such room. */
97
+ close(roomId) {
98
+ if (this.#registry.get(roomId) === undefined)
99
+ return false;
100
+ this.#registry.delete(roomId);
101
+ this.#watcher.poke();
102
+ return true;
103
+ }
104
+ /**
105
+ * Tell the book a room changed, without waiting out the sweep interval. For
106
+ * a caller that just wrote something the sweep's `updatedAt` check would
107
+ * catch anyway, but wants the push to go out on THIS tick rather than the
108
+ * next one — mirrors cardtable's `RoomFeedHandle.changed()`. `_roomId` is
109
+ * kept in the signature for that symmetry even though the sweep itself
110
+ * re-reads every room regardless of which one is named.
111
+ */
112
+ changed(_roomId) {
113
+ this.#watcher.poke();
114
+ }
115
+ /** Be told whenever a room opens, closes, or (on the sweep) looks written-to. Returns the unsubscribe. */
116
+ onChange(listener) {
117
+ return this.#watcher.onChange(listener);
118
+ }
119
+ /** Stops the sweep. A book that is no longer used must be stopped, or its timer (unref'd, but still live) outlives it. */
120
+ stop() {
121
+ this.#watcher.close();
122
+ }
123
+ }
@@ -0,0 +1,52 @@
1
+ export interface ChatHistoryRecord {
2
+ id: string;
3
+ ts: number;
4
+ }
5
+ export interface PagedChatResult<M> {
6
+ messages: M[];
7
+ hasMore: boolean;
8
+ }
9
+ export type ChatLogLevel = 'info' | 'warn';
10
+ export interface ChatHistoryConfig<M extends ChatHistoryRecord> {
11
+ /** Directory per-room JSONL files live under. A thunk so a host can read it
12
+ * from its own (possibly test-overridden) config lazily, on every call. */
13
+ stateDir: () => string;
14
+ /** In-memory + on-disk cap per room. */
15
+ maxMessages: number;
16
+ /** Default / max page size for `pagedMessages`. */
17
+ pageLimit: number;
18
+ pageLimitMax: number;
19
+ /**
20
+ * How long a room's chat outlives a delete notification with no further
21
+ * activity. A thunk so it can be overridden per-test without rebuilding the
22
+ * store. See the module doc for why this defers rather than deletes.
23
+ */
24
+ roomLifeMs: () => number;
25
+ /** Room ids safe to use as a filename; anything else is never persisted. */
26
+ safeRoomId?: RegExp;
27
+ /** Structured logging, routed to the host's own logger. Never thrown. */
28
+ onEvent?: (level: ChatLogLevel, event: string, roomId: string, fields?: Record<string, unknown>) => void;
29
+ }
30
+ export interface ChatHistoryStore<M extends ChatHistoryRecord> {
31
+ appendMessage(roomId: string, msg: M): Promise<void>;
32
+ recentMessages(roomId: string, limit?: number): Promise<M[]>;
33
+ pagedMessages(roomId: string, opts?: {
34
+ beforeTs?: number;
35
+ limit?: number;
36
+ }): Promise<PagedChatResult<M>>;
37
+ /** Register as the room registry's delete hook. Never deletes inline — see
38
+ * the module doc. */
39
+ clearRoomChat(roomId: string): Promise<void>;
40
+ /**
41
+ * Read every per-room file back into memory (startup). A file whose mtime
42
+ * is older than `retentionMs` is deleted in the same pass. `migrate` can
43
+ * drop (return null) or rewrite a loaded record for a host's own privacy
44
+ * rules; omit it to load records as-is.
45
+ */
46
+ loadFromDisk(retentionMs: number, migrate?: (raw: unknown) => M | null): Promise<void>;
47
+ /** Test-only: cancels every pending deferred wipe and forgets all in-memory
48
+ * rooms. Never called in production. */
49
+ resetForTests(): void;
50
+ }
51
+ export declare function createChatHistoryStore<M extends ChatHistoryRecord>(config: ChatHistoryConfig<M>): ChatHistoryStore<M>;
52
+ //# sourceMappingURL=history.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../../src/chat/history.ts"],"names":[],"mappings":"AA+BA,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,QAAQ,EAAE,CAAC,EAAE,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,MAAM,CAAC;AAE3C,MAAM,WAAW,iBAAiB,CAAC,CAAC,SAAS,iBAAiB;IAC5D;gFAC4E;IAC5E,QAAQ,EAAE,MAAM,MAAM,CAAC;IACvB,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,UAAU,EAAE,MAAM,MAAM,CAAC;IACzB,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,yEAAyE;IACzE,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CAC1G;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC,SAAS,iBAAiB;IAC3D,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;IAC7D,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;IACzG;0BACsB;IACtB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7C;;;;;OAKG;IACH,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvF;6CACyC;IACzC,aAAa,IAAI,IAAI,CAAC;CACvB;AAID,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,iBAAiB,EAChE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAC3B,gBAAgB,CAAC,CAAC,CAAC,CAgKrB"}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Generic, per-room chat history: append, read back (recent or paged), and
3
+ * forget. App-agnostic — no socket.io, no hosting-app vocabulary, and no
4
+ * opinion about what a message LOOKS like beyond `{ id, ts }`; the host's own
5
+ * message shape rides through as the type parameter `M`.
6
+ *
7
+ * Extracted from watchparty's `apps/server/src/chat/history.ts` (platform plan
8
+ * v2, line 372): "Chat moves into the room core... each app serves its own
9
+ * rooms' chat to that room's members."
10
+ *
11
+ * WHY `clearRoomChat` DEFERS INSTEAD OF DELETING
12
+ * The intended caller is a host's room-registry delete hook — fired both when
13
+ * a room empties and its GC grace elapses, AND when a room is explicitly,
14
+ * genuinely removed. Nothing in that hook's signature says which happened
15
+ * (the registry itself doesn't keep the two apart; see rooms-server
16
+ * `RoomRegistry.delete`). Deleting history inline on every call meant a
17
+ * room's chat vanished within minutes of its last tab closing even though the
18
+ * room's OWN state (a resumable playback position, a seat table) survives a
19
+ * GC reap for the room's real life — the platform plan (lines 372, 394)
20
+ * names this directly: "a room's chat is deleted two minutes after its last
21
+ * tab closes, while the room itself lives 8 to 12 hours."
22
+ *
23
+ * So `clearRoomChat` here schedules the wipe `roomLifeMs()` out instead of
24
+ * running it, and `appendMessage` cancels any pending wipe for that room —
25
+ * new activity is proof the room is not actually gone. A room that stays
26
+ * quiet for the whole window is forgotten exactly as before; one that comes
27
+ * back inside it keeps every line.
28
+ */
29
+ import { mkdir, appendFile, writeFile, rename, readdir, readFile, stat, unlink } from 'node:fs/promises';
30
+ import { dirname, join, resolve } from 'node:path';
31
+ const DEFAULT_SAFE_ROOMID_RE = /^[a-z0-9_-]+$/i;
32
+ export function createChatHistoryStore(config) {
33
+ const memory = new Map();
34
+ const fileLineCount = new Map();
35
+ const pendingClears = new Map();
36
+ const safeRoomId = config.safeRoomId ?? DEFAULT_SAFE_ROOMID_RE;
37
+ function emit(level, event, roomId, fields) {
38
+ config.onEvent?.(level, event, roomId, fields);
39
+ }
40
+ function filePath(roomId) {
41
+ if (!safeRoomId.test(roomId))
42
+ return null;
43
+ return join(resolve(config.stateDir()), `${roomId}.jsonl`);
44
+ }
45
+ function cancelPendingClear(roomId) {
46
+ const timer = pendingClears.get(roomId);
47
+ if (!timer)
48
+ return;
49
+ clearTimeout(timer);
50
+ pendingClears.delete(roomId);
51
+ }
52
+ async function wipe(roomId) {
53
+ memory.delete(roomId);
54
+ fileLineCount.delete(roomId);
55
+ const fp = filePath(roomId);
56
+ if (!fp)
57
+ return;
58
+ try {
59
+ await unlink(fp);
60
+ }
61
+ catch (err) {
62
+ if (err?.code === 'ENOENT')
63
+ return;
64
+ emit('warn', 'chat.persist_unlink_failed', roomId, { err_message: String(err) });
65
+ }
66
+ }
67
+ async function persistAppend(roomId, msg, list) {
68
+ const fp = filePath(roomId);
69
+ if (!fp)
70
+ return;
71
+ try {
72
+ await mkdir(dirname(fp), { recursive: true });
73
+ const lineCount = fileLineCount.get(roomId) ?? 0;
74
+ if (lineCount >= config.maxMessages * 2) {
75
+ const tmp = `${fp}.tmp`;
76
+ const body = `${list.map((m) => JSON.stringify(m)).join('\n')}\n`;
77
+ await writeFile(tmp, body);
78
+ await rename(tmp, fp);
79
+ fileLineCount.set(roomId, list.length);
80
+ }
81
+ else {
82
+ await appendFile(fp, `${JSON.stringify(msg)}\n`);
83
+ fileLineCount.set(roomId, lineCount + 1);
84
+ }
85
+ }
86
+ catch (err) {
87
+ emit('warn', 'chat.persist_failed', roomId, { err_message: String(err) });
88
+ }
89
+ }
90
+ async function appendMessage(roomId, msg) {
91
+ // New activity is proof the room is alive — a wipe scheduled for it (by
92
+ // an earlier GC reap, or a since-reverted explicit delete) no longer
93
+ // applies.
94
+ cancelPendingClear(roomId);
95
+ let list = memory.get(roomId);
96
+ if (!list) {
97
+ list = [];
98
+ memory.set(roomId, list);
99
+ }
100
+ list.push(msg);
101
+ if (list.length > config.maxMessages)
102
+ list.splice(0, list.length - config.maxMessages);
103
+ await persistAppend(roomId, msg, list);
104
+ }
105
+ async function recentMessages(roomId, limit = config.maxMessages) {
106
+ const list = memory.get(roomId) || [];
107
+ return list.slice(-limit);
108
+ }
109
+ async function pagedMessages(roomId, opts = {}) {
110
+ const limit = Math.min(Math.max(opts.limit || config.pageLimit, 1), config.pageLimitMax);
111
+ const all = await recentMessages(roomId, config.maxMessages);
112
+ const filtered = typeof opts.beforeTs === 'number' ? all.filter((m) => m.ts < opts.beforeTs) : all;
113
+ const slice = filtered.slice(-limit);
114
+ const hasMore = filtered.length > limit;
115
+ return { messages: slice, hasMore };
116
+ }
117
+ async function clearRoomChat(roomId) {
118
+ cancelPendingClear(roomId);
119
+ const life = config.roomLifeMs();
120
+ const timer = setTimeout(() => {
121
+ pendingClears.delete(roomId);
122
+ void wipe(roomId);
123
+ }, life);
124
+ timer.unref?.();
125
+ pendingClears.set(roomId, timer);
126
+ }
127
+ async function loadFromDisk(retentionMs, migrate) {
128
+ const dir = resolve(config.stateDir());
129
+ let files = [];
130
+ try {
131
+ files = await readdir(dir);
132
+ }
133
+ catch {
134
+ return;
135
+ }
136
+ const cutoff = Date.now() - retentionMs;
137
+ for (const f of files) {
138
+ if (!f.endsWith('.jsonl'))
139
+ continue;
140
+ const roomId = f.replace(/\.jsonl$/, '');
141
+ if (!safeRoomId.test(roomId))
142
+ continue;
143
+ const fp = join(dir, f);
144
+ try {
145
+ const st = await stat(fp);
146
+ if (st.mtimeMs < cutoff) {
147
+ await unlink(fp);
148
+ emit('info', 'chat.persist_swept', roomId, { age_ms: Date.now() - st.mtimeMs });
149
+ continue;
150
+ }
151
+ const content = await readFile(fp, 'utf-8');
152
+ const lines = content.split('\n').filter(Boolean);
153
+ const tail = lines.slice(-config.maxMessages);
154
+ const messages = [];
155
+ let rewritten = false;
156
+ for (const line of tail) {
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(line);
160
+ }
161
+ catch {
162
+ continue; // skip corrupt line
163
+ }
164
+ const kept = migrate ? migrate(parsed) : parsed;
165
+ if (kept !== parsed)
166
+ rewritten = true;
167
+ if (kept)
168
+ messages.push(kept);
169
+ }
170
+ if (messages.length > 0)
171
+ memory.set(roomId, messages);
172
+ fileLineCount.set(roomId, lines.length);
173
+ if (rewritten || lines.length > tail.length) {
174
+ const tmp = `${fp}.tmp`;
175
+ await writeFile(tmp, `${messages.map((m) => JSON.stringify(m)).join('\n')}${messages.length ? '\n' : ''}`);
176
+ await rename(tmp, fp);
177
+ fileLineCount.set(roomId, messages.length);
178
+ if (rewritten)
179
+ emit('info', 'chat.persist_cleaned', roomId);
180
+ }
181
+ emit('info', 'chat.persist_loaded', roomId, { count: messages.length });
182
+ }
183
+ catch (err) {
184
+ emit('warn', 'chat.persist_load_failed', roomId, { err_message: String(err) });
185
+ }
186
+ }
187
+ }
188
+ function resetForTests() {
189
+ for (const timer of pendingClears.values())
190
+ clearTimeout(timer);
191
+ pendingClears.clear();
192
+ memory.clear();
193
+ fileLineCount.clear();
194
+ }
195
+ return { appendMessage, recentMessages, pagedMessages, clearRoomChat, loadFromDisk, resetForTests };
196
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @wolffm/rooms-server/chat — generic, per-room chat history.
3
+ *
4
+ * Kept off the main entry (`../index.ts`), same as `../store`: it reaches
5
+ * `node:fs`, and the main entry stays usable from a browser-safe context.
6
+ */
7
+ export * from './history.js';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/chat/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,cAAc,cAAc,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @wolffm/rooms-server/chat — generic, per-room chat history.
3
+ *
4
+ * Kept off the main entry (`../index.ts`), same as `../store`: it reaches
5
+ * `node:fs`, and the main entry stays usable from a browser-safe context.
6
+ */
7
+ export * from './history.js';
package/dist/index.d.ts CHANGED
@@ -16,10 +16,12 @@
16
16
  * would have been a wrong answer for the second consumer.
17
17
  */
18
18
  export * from './state.js';
19
+ export * from './seats.js';
19
20
  export * from './identity.js';
20
21
  export * from './emit.js';
21
22
  export * from './gc.js';
22
23
  export * from './rateLimiter.js';
23
24
  export * from './presence.js';
24
25
  export * from './session-claims.js';
26
+ export * from './book/index.js';
25
27
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -16,12 +16,14 @@
16
16
  * would have been a wrong answer for the second consumer.
17
17
  */
18
18
  export * from './state.js';
19
+ export * from './seats.js';
19
20
  export * from './identity.js';
20
21
  export * from './emit.js';
21
22
  export * from './gc.js';
22
23
  export * from './rateLimiter.js';
23
24
  export * from './presence.js';
24
25
  export * from './session-claims.js';
26
+ export * from './book/index.js';
25
27
  // NOT `export * from '@wolffm/rooms-protocol'`. Re-exporting it would give
26
28
  // every symbol two import paths, and the first thing that drifts is which one
27
29
  // a file happens to use. Consumers depend on both packages explicitly.
@@ -0,0 +1,126 @@
1
+ import type { ParticipantId } from '@wolffm/rooms-protocol';
2
+ /**
3
+ * Generic room membership — people, not sockets — plus the two things the
4
+ * operator's rulings hang off it: readiness and leader succession (room step
5
+ * 6 of the platform plan, 2026-11-06).
6
+ *
7
+ * ## Why this is not `CoreRoomState.clients`
8
+ *
9
+ * `clients` (`state.ts`) is keyed by the EPHEMERAL connection id and holds one
10
+ * entry per TAB — two tabs of one person are two entries, and the entry for a
11
+ * tab disappears the instant that connection closes (see `leaveRoom`'s header
12
+ * in `state.ts`). Two rulings need the opposite:
13
+ *
14
+ * - **Ready is "per unique userid."** A refresh must never drop a tick, and
15
+ * a second tab must never count twice.
16
+ * - **Leadership never moves on a disconnect** — it must survive every
17
+ * connection dropping at once, the same way a server restart drops every
18
+ * socket simultaneously without anybody's role changing.
19
+ *
20
+ * Both need a ledger keyed by the PARTICIPANT, independent of which
21
+ * connections happen to be open right now. `MembershipLedger` is that ledger.
22
+ * It is pure data plus pure functions — no socket, no timer, no I/O — so a
23
+ * hosting app embeds it in its own `TApp` (the same place watchparty today
24
+ * keeps its ready-check's `active` flag) exactly as it already does for
25
+ * `PresenceTracker` and `SessionClaims`.
26
+ *
27
+ * ## Membership is explicit, not implied by a live connection
28
+ *
29
+ * A participant is added once, on `addMember` (their first join), and stays
30
+ * on the ledger until an explicit `memberLeft` call — never as a side effect
31
+ * of their last socket closing. That is deliberate: `leaderId` in
32
+ * `state.ts` already behaves this way in production ("never moves on a
33
+ * disconnect"), and this module gives the same rule to a ledger that also
34
+ * knows how to move it — on a genuine departure, to whoever has been a
35
+ * member longest (R16, cardtable `lobby.ts`'s `leave()`:
36
+ * `room.members.reduce((earliest, m) => m.joinedAt < earliest.joinedAt ? m : earliest)`).
37
+ * A disconnect handler must call neither `memberLeft` nor anything that
38
+ * reaches it — only an explicit "this person is leaving the room" action may.
39
+ *
40
+ * ## `min`/`max` is `SeatTable.capacity`, one level up
41
+ *
42
+ * `SeatTable` (`rooms-protocol`) bounds how many SEATS a table has, and
43
+ * already guarantees the seating half of the operator's ruling — a spectator
44
+ * can never take an active player's seat, because `seatParticipant` only ever
45
+ * evicts a BOT, never a human, and nothing unseats a participant except that
46
+ * participant's own departure (`leaveRoom`'s header, `state.ts`). A room's
47
+ * MEMBERSHIP can want its own bound independent of any one table — a lobby
48
+ * that should not start until enough people have shown up (`min`), or that
49
+ * should stop admitting new members once it is full even before any table
50
+ * exists (`max`). Both default to unbounded, so a host that never asks for
51
+ * this (watchparty, today) sees no behaviour change.
52
+ */
53
+ export interface MemberCapacity {
54
+ /** Fewest members before the room is "enough to start". Default 0 (no floor). */
55
+ min?: number;
56
+ /** Most members the room admits. Default unbounded. */
57
+ max?: number;
58
+ }
59
+ export interface Member {
60
+ participantId: ParticipantId;
61
+ /** When this participant FIRST joined — survives a reconnect or a second tab. */
62
+ joinedAt: number;
63
+ }
64
+ export interface MembershipLedger {
65
+ /** Members, in JOIN order (array order === join order; see `addMember`). */
66
+ members: Member[];
67
+ /** Ready participants — see this module's header. */
68
+ ready: Set<ParticipantId>;
69
+ /** The durable leader, by participant identity, or null. See this module's header. */
70
+ leaderId: ParticipantId | null;
71
+ }
72
+ export declare function createMembershipLedger(): MembershipLedger;
73
+ export declare function memberCount(ledger: MembershipLedger): number;
74
+ export declare function isMember(ledger: MembershipLedger, participantId: ParticipantId): boolean;
75
+ /** At or above `min`? `capacity.min` undefined is always satisfied (0 is the default floor). */
76
+ export declare function hasQuorum(ledger: MembershipLedger, capacity: MemberCapacity): boolean;
77
+ /**
78
+ * Room has space for one more under `max`? `capacity.max` undefined is
79
+ * unbounded. A participant already on the ledger always has "room" — this
80
+ * answers whether a NEW admission fits, not whether an existing member may
81
+ * stay.
82
+ */
83
+ export declare function hasRoomFor(ledger: MembershipLedger, capacity: MemberCapacity, participantId: ParticipantId): boolean;
84
+ /**
85
+ * Add a member. Idempotent across reconnects and extra tabs: a participant
86
+ * already on the ledger keeps their ORIGINAL `joinedAt` — a second tab, or a
87
+ * reconnect, must never look like a new, later join for leader-succession
88
+ * purposes. The first member ever added becomes leader; every later arrival
89
+ * leaves the current leader in place.
90
+ *
91
+ * Returns false (no-op) when `capacity.max` is reached and this participant
92
+ * is not already a member — the caller decides what that means (refuse the
93
+ * join, seat them as a spectator via `SeatTable`, etc). Returns true
94
+ * otherwise, including when they were already a member.
95
+ */
96
+ export declare function addMember(ledger: MembershipLedger, participantId: ParticipantId, now?: number, capacity?: MemberCapacity): boolean;
97
+ /** Ready, keyed by participant — two tabs of one person count once (operator ruling). */
98
+ export declare function setReady(ledger: MembershipLedger, participantId: ParticipantId, ready: boolean): void;
99
+ export declare function isReady(ledger: MembershipLedger, participantId: ParticipantId): boolean;
100
+ /** Every ready participant. A snapshot array, like `seatRows` — never a live view. */
101
+ export declare function readyParticipants(ledger: MembershipLedger): ParticipantId[];
102
+ /** Drop everyone's ready flag — the start of a fresh round. */
103
+ export declare function clearReady(ledger: MembershipLedger): void;
104
+ /**
105
+ * The member who has been here longest, or null if there are none. Ties
106
+ * (equal `joinedAt`) resolve to whichever is first in `members` — the only
107
+ * way `joinedAt` can tie is two adds in the same millisecond, and array order
108
+ * is still join order in that case.
109
+ */
110
+ export declare function earliestMember(ledger: MembershipLedger): ParticipantId | null;
111
+ /**
112
+ * A member explicitly LEAVES the room — a deliberate departure, never a mere
113
+ * disconnect (see this module's header: leadership must not react to a
114
+ * dropped connection, only to this call). Drops them from the ledger and from
115
+ * `ready`. If they were leader, hands leadership to `earliestMember` of
116
+ * whoever remains (R16); otherwise the leader is untouched, even though the
117
+ * leaving member might currently be offline-but-still-a-member before this
118
+ * call.
119
+ *
120
+ * Returns the ledger's leader AFTER the departure (possibly unchanged, or
121
+ * null if the room is now empty). No-op on the membership/ready data if
122
+ * `participantId` was never a member — callers do not need to check
123
+ * `isMember` first — but the current leader is still returned.
124
+ */
125
+ export declare function memberLeft(ledger: MembershipLedger, participantId: ParticipantId): ParticipantId | null;
126
+ //# sourceMappingURL=seats.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seats.d.ts","sourceRoot":"","sources":["../src/seats.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AAEH,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,MAAM;IACrB,aAAa,EAAE,aAAa,CAAC;IAC7B,iFAAiF;IACjF,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC/B,4EAA4E;IAC5E,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,qDAAqD;IACrD,KAAK,EAAE,GAAG,CAAC,aAAa,CAAC,CAAC;IAC1B,sFAAsF;IACtF,QAAQ,EAAE,aAAa,GAAG,IAAI,CAAC;CAChC;AAED,wBAAgB,sBAAsB,IAAI,gBAAgB,CAEzD;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM,CAE5D;AAED,wBAAgB,QAAQ,CAAC,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,GAAG,OAAO,CAExF;AAED,gGAAgG;AAChG,wBAAgB,SAAS,CAAC,MAAM,EAAE,gBAAgB,EAAE,QAAQ,EAAE,cAAc,GAAG,OAAO,CAErF;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CACxB,MAAM,EAAE,gBAAgB,EACxB,QAAQ,EAAE,cAAc,EACxB,aAAa,EAAE,aAAa,GAC3B,OAAO,CAIT;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,gBAAgB,EACxB,aAAa,EAAE,aAAa,EAC5B,GAAG,GAAE,MAAmB,EACxB,QAAQ,GAAE,cAAmB,GAC5B,OAAO,CAMT;AAED,yFAAyF;AACzF,wBAAgB,QAAQ,CAAC,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAGrG;AAED,wBAAgB,OAAO,CAAC,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,GAAG,OAAO,CAEvF;AAED,sFAAsF;AACtF,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,gBAAgB,GAAG,aAAa,EAAE,CAE3E;AAED,+DAA+D;AAC/D,wBAAgB,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAEzD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,gBAAgB,GAAG,aAAa,GAAG,IAAI,CAG7E;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,GAAG,aAAa,GAAG,IAAI,CASvG"}
package/dist/seats.js ADDED
@@ -0,0 +1,102 @@
1
+ export function createMembershipLedger() {
2
+ return { members: [], ready: new Set(), leaderId: null };
3
+ }
4
+ export function memberCount(ledger) {
5
+ return ledger.members.length;
6
+ }
7
+ export function isMember(ledger, participantId) {
8
+ return ledger.members.some((m) => m.participantId === participantId);
9
+ }
10
+ /** At or above `min`? `capacity.min` undefined is always satisfied (0 is the default floor). */
11
+ export function hasQuorum(ledger, capacity) {
12
+ return ledger.members.length >= (capacity.min ?? 0);
13
+ }
14
+ /**
15
+ * Room has space for one more under `max`? `capacity.max` undefined is
16
+ * unbounded. A participant already on the ledger always has "room" — this
17
+ * answers whether a NEW admission fits, not whether an existing member may
18
+ * stay.
19
+ */
20
+ export function hasRoomFor(ledger, capacity, participantId) {
21
+ if (capacity.max === undefined)
22
+ return true;
23
+ if (isMember(ledger, participantId))
24
+ return true;
25
+ return ledger.members.length < capacity.max;
26
+ }
27
+ /**
28
+ * Add a member. Idempotent across reconnects and extra tabs: a participant
29
+ * already on the ledger keeps their ORIGINAL `joinedAt` — a second tab, or a
30
+ * reconnect, must never look like a new, later join for leader-succession
31
+ * purposes. The first member ever added becomes leader; every later arrival
32
+ * leaves the current leader in place.
33
+ *
34
+ * Returns false (no-op) when `capacity.max` is reached and this participant
35
+ * is not already a member — the caller decides what that means (refuse the
36
+ * join, seat them as a spectator via `SeatTable`, etc). Returns true
37
+ * otherwise, including when they were already a member.
38
+ */
39
+ export function addMember(ledger, participantId, now = Date.now(), capacity = {}) {
40
+ if (isMember(ledger, participantId))
41
+ return true;
42
+ if (!hasRoomFor(ledger, capacity, participantId))
43
+ return false;
44
+ ledger.members.push({ participantId, joinedAt: now });
45
+ if (ledger.leaderId === null)
46
+ ledger.leaderId = participantId;
47
+ return true;
48
+ }
49
+ /** Ready, keyed by participant — two tabs of one person count once (operator ruling). */
50
+ export function setReady(ledger, participantId, ready) {
51
+ if (ready)
52
+ ledger.ready.add(participantId);
53
+ else
54
+ ledger.ready.delete(participantId);
55
+ }
56
+ export function isReady(ledger, participantId) {
57
+ return ledger.ready.has(participantId);
58
+ }
59
+ /** Every ready participant. A snapshot array, like `seatRows` — never a live view. */
60
+ export function readyParticipants(ledger) {
61
+ return Array.from(ledger.ready);
62
+ }
63
+ /** Drop everyone's ready flag — the start of a fresh round. */
64
+ export function clearReady(ledger) {
65
+ ledger.ready.clear();
66
+ }
67
+ /**
68
+ * The member who has been here longest, or null if there are none. Ties
69
+ * (equal `joinedAt`) resolve to whichever is first in `members` — the only
70
+ * way `joinedAt` can tie is two adds in the same millisecond, and array order
71
+ * is still join order in that case.
72
+ */
73
+ export function earliestMember(ledger) {
74
+ if (ledger.members.length === 0)
75
+ return null;
76
+ return ledger.members.reduce((earliest, m) => (m.joinedAt < earliest.joinedAt ? m : earliest)).participantId;
77
+ }
78
+ /**
79
+ * A member explicitly LEAVES the room — a deliberate departure, never a mere
80
+ * disconnect (see this module's header: leadership must not react to a
81
+ * dropped connection, only to this call). Drops them from the ledger and from
82
+ * `ready`. If they were leader, hands leadership to `earliestMember` of
83
+ * whoever remains (R16); otherwise the leader is untouched, even though the
84
+ * leaving member might currently be offline-but-still-a-member before this
85
+ * call.
86
+ *
87
+ * Returns the ledger's leader AFTER the departure (possibly unchanged, or
88
+ * null if the room is now empty). No-op on the membership/ready data if
89
+ * `participantId` was never a member — callers do not need to check
90
+ * `isMember` first — but the current leader is still returned.
91
+ */
92
+ export function memberLeft(ledger, participantId) {
93
+ const index = ledger.members.findIndex((m) => m.participantId === participantId);
94
+ if (index === -1)
95
+ return ledger.leaderId;
96
+ ledger.members.splice(index, 1);
97
+ ledger.ready.delete(participantId);
98
+ if (ledger.leaderId === participantId) {
99
+ ledger.leaderId = earliestMember(ledger);
100
+ }
101
+ return ledger.leaderId;
102
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/rooms-server",
3
- "version": "0.45.59",
4
- "gitHead": "9ec23c882cb2508804727b568b486ba101a946cf",
3
+ "version": "0.45.61",
4
+ "gitHead": "0e98044983dd1855d944daa8dcafc17e5c0b450b",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Room lifecycle, membership, seating, identity, presence, backpressure-aware emit and durable room storage for a socket.io server.",
@@ -15,6 +15,10 @@
15
15
  "./store": {
16
16
  "types": "./dist/store/index.d.ts",
17
17
  "import": "./dist/store/index.js"
18
+ },
19
+ "./chat": {
20
+ "types": "./dist/chat/index.d.ts",
21
+ "import": "./dist/chat/index.js"
18
22
  }
19
23
  },
20
24
  "files": [
@@ -27,7 +31,7 @@
27
31
  "directory": "packages/rooms-server"
28
32
  },
29
33
  "dependencies": {
30
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.59"
34
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.61"
31
35
  },
32
36
  "peerDependencies": {
33
37
  "socket.io": "^4.8.3"