@hadoku/rooms-protocol 0.45.56 → 0.45.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -12,4 +12,5 @@ export * from './seats.js';
12
12
  export * from './resync.js';
13
13
  export * from './game-bundle.js';
14
14
  export * from './avatars.js';
15
+ export * from './session.js';
15
16
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,cAAc,oBAAoB,CAAC;AACnC,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,cAAc,oBAAoB,CAAC;AACnC,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -12,3 +12,4 @@ export * from './seats.js';
12
12
  export * from './resync.js';
13
13
  export * from './game-bundle.js';
14
14
  export * from './avatars.js';
15
+ export * from './session.js';
@@ -0,0 +1,113 @@
1
+ /**
2
+ * One live tab per player per room: the wire contract, and how a browser tab
3
+ * names itself.
4
+ *
5
+ * A player of a room (a seat, a place in a pod or draft, a seat in one of the
6
+ * room's matches) plays it from ONE browser tab at a time. A second tab of the
7
+ * same account asks before it takes over; the tab it took from is told, and
8
+ * offers to take it back the same way. Watchers keep as many tabs as they like.
9
+ * The server's half is `@wolffm/rooms-server`'s `SessionClaims`; this file is
10
+ * what both ends agree on.
11
+ *
12
+ * ## The flow
13
+ *
14
+ * 1. A tab settles its id (`settleTabId`), then sends `claim` for the room.
15
+ * 2. The server answers:
16
+ * - `granted`: nobody else holds it, or this tab already does (a reload, a
17
+ * reconnect), or the holder had gone silent (`SessionClaims`' idle window)
18
+ * and was retired without asking;
19
+ * - `held`: another tab of this account is live in the room. The tab asks
20
+ * its player, and on yes sends `claim` again with `take: true`;
21
+ * - `watcher`: the account plays nothing here; no claim is held;
22
+ * - `refused`: the request did not parse, or names no room it may join.
23
+ * 3. On a take, every connection of the old tab for that room is told `taken`
24
+ * and closed by the server. A server-side close does not auto-reconnect, so
25
+ * the old tab cannot loop back into stealing the session; it offers to take
26
+ * it back, which is step 2's `take: true` again.
27
+ * 4. While it holds a claim a connection is sent `beat`, and answers its ack.
28
+ * A beat arrives as a message, so a hidden tab, whose timers the browser
29
+ * throttles, still answers it at once. A holder that stops answering is
30
+ * stale, and a new tab takes from it without asking.
31
+ *
32
+ * ## A tab's id
33
+ *
34
+ * Kept in `sessionStorage`, so a reload keeps it and never asks. A duplicated
35
+ * tab starts with a COPY of the original's `sessionStorage`, so the stored id
36
+ * alone would make two live tabs one; `settleTabId` asks every other tab of
37
+ * the origin on a `BroadcastChannel` whether the id is in use, and mints a
38
+ * fresh one if it is. Another device is just another tab.
39
+ */
40
+ /** Socket event names. */
41
+ export declare const SESSION_EVENTS: {
42
+ /** client → server, with an ack carrying `SessionClaimAnswer`. Payload `SessionClaimRequest`. */
43
+ readonly claim: "session:claim";
44
+ /** server → client: this tab's session in `room` was taken by another tab. Payload `SessionTaken`. */
45
+ readonly taken: "session:taken";
46
+ /** server → client, with an ack the client calls at once: the holder is alive. No payload. */
47
+ readonly beat: "session:beat";
48
+ };
49
+ /** A tab id: what `mintTabId` makes, and what a server accepts. */
50
+ export declare const TAB_ID_PATTERN: RegExp;
51
+ export declare function isTabId(value: unknown): value is string;
52
+ export interface SessionClaimRequest {
53
+ /** The room's id, as the app names it. */
54
+ room: string;
55
+ tabId: string;
56
+ /** Take the session from the tab that holds it. Only after the player said yes. */
57
+ take?: boolean;
58
+ }
59
+ export declare const SESSION_CLAIM_STATUSES: readonly ["granted", "held", "watcher", "refused"];
60
+ export type SessionClaimStatus = (typeof SESSION_CLAIM_STATUSES)[number];
61
+ export interface SessionClaimAnswer {
62
+ room: string;
63
+ status: SessionClaimStatus;
64
+ }
65
+ export interface SessionTaken {
66
+ room: string;
67
+ }
68
+ /** The longest room id a claim may name. */
69
+ export declare const SESSION_ROOM_MAX = 128;
70
+ /** Parse a `claim` off the wire: null for anything that is not exactly a request. */
71
+ export declare function parseSessionClaim(raw: unknown): SessionClaimRequest | null;
72
+ /** Parse a `claim`'s answer: null for anything that is not one. */
73
+ export declare function parseSessionAnswer(raw: unknown): SessionClaimAnswer | null;
74
+ /** Parse a `taken`: null for anything that is not one. */
75
+ export declare function parseSessionTaken(raw: unknown): SessionTaken | null;
76
+ /** The `BroadcastChannel` name tabs probe each other's ids on. */
77
+ export declare const TAB_ID_CHANNEL = "hadoku:tab-id";
78
+ /** How long a tab waits for another to say its id is in use. Same-origin delivery takes a few ms. */
79
+ export declare const TAB_PROBE_MS = 150;
80
+ /**
81
+ * The part of a `BroadcastChannel` this file uses, so a test (or a host
82
+ * without one) can stand in. `browserTabChannel` adapts the real one.
83
+ */
84
+ export interface TabIdChannel {
85
+ post(message: unknown): void;
86
+ /** Returns the unsubscribe. */
87
+ listen(handler: (message: unknown) => void): () => void;
88
+ }
89
+ /** 128 random bits as hex. `getRandomValues`, not `randomUUID`, which an insecure origin lacks. */
90
+ export declare function mintTabId(): string;
91
+ /**
92
+ * Answer other tabs' probes for the id this tab holds (`current`, read at each
93
+ * probe). Install it once per tab, before or while settling. Returns the stop.
94
+ */
95
+ export declare function answerTabProbes(channel: TabIdChannel, current: () => string | null): () => void;
96
+ export interface SettleTabIdOptions {
97
+ /** The id this tab would like: the stored one. null or malformed: mint one, no probe. */
98
+ candidate: string | null;
99
+ /** null where there is no `BroadcastChannel`: the candidate is taken as it is. */
100
+ channel: TabIdChannel | null;
101
+ mint?: () => string;
102
+ waitMs?: number;
103
+ setTimer?: (fn: () => void, ms: number) => unknown;
104
+ }
105
+ /**
106
+ * The id this tab goes by: the candidate, unless another live tab of the
107
+ * origin answers that it is using it (a duplicated tab), in which case a fresh
108
+ * one. Resolves after at most `waitMs`.
109
+ */
110
+ export declare function settleTabId(opts: SettleTabIdOptions): Promise<string>;
111
+ /** A real `BroadcastChannel` as a `TabIdChannel`, or null where the host has none. */
112
+ export declare function browserTabChannel(name?: string): TabIdChannel | null;
113
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,0BAA0B;AAC1B,eAAO,MAAM,cAAc;IACzB,iGAAiG;;IAEjG,sGAAsG;;IAEtG,8FAA8F;;CAEtF,CAAC;AAEX,mEAAmE;AACnE,eAAO,MAAM,cAAc,QAA0B,CAAC;AAEtD,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEvD;AAED,MAAM,WAAW,mBAAmB;IAClC,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,mFAAmF;IACnF,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,eAAO,MAAM,sBAAsB,oDAAqD,CAAC;AACzF,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,sBAAsB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEzE,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,kBAAkB,CAAC;CAC5B;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,4CAA4C;AAC5C,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,qFAAqF;AACrF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,mBAAmB,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 /**
2
+ * One live tab per player per room: the wire contract, and how a browser tab
3
+ * names itself.
4
+ *
5
+ * A player of a room (a seat, a place in a pod or draft, a seat in one of the
6
+ * room's matches) plays it from ONE browser tab at a time. A second tab of the
7
+ * same account asks before it takes over; the tab it took from is told, and
8
+ * offers to take it back the same way. Watchers keep as many tabs as they like.
9
+ * The server's half is `@wolffm/rooms-server`'s `SessionClaims`; this file is
10
+ * what both ends agree on.
11
+ *
12
+ * ## The flow
13
+ *
14
+ * 1. A tab settles its id (`settleTabId`), then sends `claim` for the room.
15
+ * 2. The server answers:
16
+ * - `granted`: nobody else holds it, or this tab already does (a reload, a
17
+ * reconnect), or the holder had gone silent (`SessionClaims`' idle window)
18
+ * and was retired without asking;
19
+ * - `held`: another tab of this account is live in the room. The tab asks
20
+ * its player, and on yes sends `claim` again with `take: true`;
21
+ * - `watcher`: the account plays nothing here; no claim is held;
22
+ * - `refused`: the request did not parse, or names no room it may join.
23
+ * 3. On a take, every connection of the old tab for that room is told `taken`
24
+ * and closed by the server. A server-side close does not auto-reconnect, so
25
+ * the old tab cannot loop back into stealing the session; it offers to take
26
+ * it back, which is step 2's `take: true` again.
27
+ * 4. While it holds a claim a connection is sent `beat`, and answers its ack.
28
+ * A beat arrives as a message, so a hidden tab, whose timers the browser
29
+ * throttles, still answers it at once. A holder that stops answering is
30
+ * stale, and a new tab takes from it without asking.
31
+ *
32
+ * ## A tab's id
33
+ *
34
+ * Kept in `sessionStorage`, so a reload keeps it and never asks. A duplicated
35
+ * tab starts with a COPY of the original's `sessionStorage`, so the stored id
36
+ * alone would make two live tabs one; `settleTabId` asks every other tab of
37
+ * the origin on a `BroadcastChannel` whether the id is in use, and mints a
38
+ * fresh one if it is. Another device is just another tab.
39
+ */
40
+ /** Socket event names. */
41
+ export const SESSION_EVENTS = {
42
+ /** client → server, with an ack carrying `SessionClaimAnswer`. Payload `SessionClaimRequest`. */
43
+ claim: 'session:claim',
44
+ /** server → client: this tab's session in `room` was taken by another tab. Payload `SessionTaken`. */
45
+ taken: 'session:taken',
46
+ /** server → client, with an ack the client calls at once: the holder is alive. No payload. */
47
+ beat: 'session:beat',
48
+ };
49
+ /** A tab id: what `mintTabId` makes, and what a server accepts. */
50
+ export const TAB_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/;
51
+ export function isTabId(value) {
52
+ return typeof value === 'string' && TAB_ID_PATTERN.test(value);
53
+ }
54
+ export const SESSION_CLAIM_STATUSES = ['granted', 'held', 'watcher', 'refused'];
55
+ /** The longest room id a claim may name. */
56
+ export const SESSION_ROOM_MAX = 128;
57
+ /** Parse a `claim` off the wire: null for anything that is not exactly a request. */
58
+ export function parseSessionClaim(raw) {
59
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
60
+ return null;
61
+ const { room, tabId, take, ...rest } = raw;
62
+ if (Object.keys(rest).length > 0)
63
+ return null;
64
+ if (typeof room !== 'string' || room.length === 0 || room.length > SESSION_ROOM_MAX)
65
+ return null;
66
+ if (!isTabId(tabId))
67
+ return null;
68
+ if (take !== undefined && typeof take !== 'boolean')
69
+ return null;
70
+ return take === true ? { room, tabId, take } : { room, tabId };
71
+ }
72
+ /** Parse a `claim`'s answer: null for anything that is not one. */
73
+ export function parseSessionAnswer(raw) {
74
+ if (typeof raw !== 'object' || raw === null)
75
+ return null;
76
+ const { room, status } = raw;
77
+ if (typeof room !== 'string')
78
+ return null;
79
+ if (!SESSION_CLAIM_STATUSES.includes(status))
80
+ return null;
81
+ return { room, status: status };
82
+ }
83
+ /** Parse a `taken`: null for anything that is not one. */
84
+ export function parseSessionTaken(raw) {
85
+ if (typeof raw !== 'object' || raw === null)
86
+ return null;
87
+ const { room } = raw;
88
+ return typeof room === 'string' && room.length > 0 ? { room } : null;
89
+ }
90
+ // ── A tab's id ─────────────────────────────────────────────────────────────
91
+ /** The `BroadcastChannel` name tabs probe each other's ids on. */
92
+ export const TAB_ID_CHANNEL = 'hadoku:tab-id';
93
+ /** How long a tab waits for another to say its id is in use. Same-origin delivery takes a few ms. */
94
+ export const TAB_PROBE_MS = 150;
95
+ /** 128 random bits as hex. `getRandomValues`, not `randomUUID`, which an insecure origin lacks. */
96
+ export function mintTabId() {
97
+ return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join('');
98
+ }
99
+ /**
100
+ * Answer other tabs' probes for the id this tab holds (`current`, read at each
101
+ * probe). Install it once per tab, before or while settling. Returns the stop.
102
+ */
103
+ export function answerTabProbes(channel, current) {
104
+ return channel.listen((message) => {
105
+ const m = message;
106
+ if (m?.type !== 'tab-id:probe' || typeof m.nonce !== 'string')
107
+ return;
108
+ const id = current();
109
+ if (id === null || m.id !== id)
110
+ return;
111
+ channel.post({ type: 'tab-id:in-use', id, nonce: m.nonce });
112
+ });
113
+ }
114
+ /**
115
+ * The id this tab goes by: the candidate, unless another live tab of the
116
+ * origin answers that it is using it (a duplicated tab), in which case a fresh
117
+ * one. Resolves after at most `waitMs`.
118
+ */
119
+ export function settleTabId(opts) {
120
+ const mint = opts.mint ?? mintTabId;
121
+ const candidate = opts.candidate;
122
+ if (!isTabId(candidate))
123
+ return Promise.resolve(mint());
124
+ const channel = opts.channel;
125
+ if (channel === null)
126
+ return Promise.resolve(candidate);
127
+ const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
128
+ const nonce = mint();
129
+ return new Promise((resolve) => {
130
+ let done = false;
131
+ const finish = (id) => {
132
+ if (done)
133
+ return;
134
+ done = true;
135
+ stop();
136
+ resolve(id);
137
+ };
138
+ const stop = channel.listen((message) => {
139
+ const m = message;
140
+ if (m?.type === 'tab-id:in-use' && m.nonce === nonce && m.id === candidate)
141
+ finish(mint());
142
+ });
143
+ channel.post({ type: 'tab-id:probe', id: candidate, nonce });
144
+ setTimer(() => finish(candidate), opts.waitMs ?? TAB_PROBE_MS);
145
+ });
146
+ }
147
+ /** A real `BroadcastChannel` as a `TabIdChannel`, or null where the host has none. */
148
+ export function browserTabChannel(name = TAB_ID_CHANNEL) {
149
+ if (typeof globalThis.BroadcastChannel !== 'function')
150
+ return null;
151
+ const bc = new globalThis.BroadcastChannel(name);
152
+ return {
153
+ post: (message) => bc.postMessage(message),
154
+ listen: (handler) => {
155
+ const onMessage = (event) => handler(event.data);
156
+ bc.addEventListener('message', onMessage);
157
+ return () => bc.removeEventListener('message', onMessage);
158
+ },
159
+ };
160
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/rooms-protocol",
3
- "version": "0.45.56",
4
- "gitHead": "69d5ce6b957f1e1b8eb3b16448367d5f3b4714eb",
3
+ "version": "0.45.58",
4
+ "gitHead": "f29f3a0ffaf16ad7785bced1f0032096b061ab2d",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Room, identity and seating protocol — the wire contract shared by rooms-server and rooms-client.",