@cardonjs/realtime-do 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Reconnecting browser client for a room. Zero dependencies and no Workers types: it runs in the
3
+ * browser. Import it from `@cardonjs/realtime-do/client`.
4
+ *
5
+ * The socket only signals "something changed": events are hints, and `onResync` reloads the
6
+ * state from the API after every reconnect and on each fallback poll while disconnected.
7
+ */
8
+ import { type RealtimeEvent } from "./validation.js";
9
+ export type { JsonValue, RealtimeEvent } from "./validation.js";
10
+ export type ConnectionStatus = "connecting" | "open" | "reconnecting" | "closed";
11
+ export interface RealtimeClientOptions {
12
+ /** `wss://…`, or a path resolved against `location` (`/v1/boards/1/live`). */
13
+ readonly url: string;
14
+ onEvent(event: RealtimeEvent): void;
15
+ /** Reload state: called on every reconnect and on each fallback poll while disconnected. */
16
+ onResync(): void | Promise<void>;
17
+ /** Called on every status change (not for the initial `"connecting"`). */
18
+ onStatus?(status: ConnectionStatus): void;
19
+ /**
20
+ * For a client without a same-site cookie: called before every connection attempt (the first
21
+ * and each reconnect), usually a `fetch` to the app's exchange route; the ticket it resolves
22
+ * with is offered with the upgrade (`new WebSocket(url, ["cardon.ticket.v1", ticket])`). A
23
+ * rejection, a value that is not a ticket, or no answer within 10 seconds counts as a failed
24
+ * attempt. Without it, the socket is opened with the URL alone. It is first called while
25
+ * `createRealtimeClient` runs: do not use the returned client before its first `await`.
26
+ */
27
+ readonly ticket?: () => string | Promise<string>;
28
+ /** Default 30 000; 0 disables fallback polling. */
29
+ readonly pollIntervalMs?: number;
30
+ /** Default 25 000. */
31
+ readonly pingIntervalMs?: number;
32
+ /** Default 10 000. */
33
+ readonly pongTimeoutMs?: number;
34
+ /** Default 1000. */
35
+ readonly minBackoffMs?: number;
36
+ /** Default 30 000. */
37
+ readonly maxBackoffMs?: number;
38
+ /** Injectable for tests. Default: the global `WebSocket`. */
39
+ readonly WebSocket?: typeof WebSocket;
40
+ /** Injectable for tests. Default: `Math.random`. */
41
+ readonly random?: () => number;
42
+ }
43
+ export interface RealtimeClient {
44
+ readonly status: ConnectionStatus;
45
+ /**
46
+ * Stops timers and the socket, then reports `"closed"`. Once it returns, no callback fires
47
+ * again, also when it is called from inside `onEvent`, `onResync` or `onStatus`.
48
+ */
49
+ close(): void;
50
+ }
51
+ /**
52
+ * Opens the socket and keeps it open: exponential backoff with full jitter between
53
+ * `minBackoffMs` and `maxBackoffMs` (reset once a connection stays open for 10 s), `"ping"`
54
+ * every `pingIntervalMs` with a `pongTimeoutMs` deadline, and fallback polling through
55
+ * `onResync` while disconnected.
56
+ *
57
+ * Close codes: 1008 stops for good (status `"closed"`); 4000 reconnects after a random delay
58
+ * below `minBackoffMs` (sockets that expire together do not come back together); anything
59
+ * else reconnects with backoff.
60
+ *
61
+ * Call `close()` when the API refuses the user (e.g. `onResync` gets a 401 or 403): the
62
+ * client cannot tell, and keeps retrying otherwise.
63
+ */
64
+ export declare function createRealtimeClient(options: RealtimeClientOptions): RealtimeClient;
65
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAGL,KAAK,aAAa,EAGnB,MAAM,iBAAiB,CAAC;AAEzB,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,MAAM,gBAAgB,GAAG,YAAY,GAAG,MAAM,GAAG,cAAc,GAAG,QAAQ,CAAC;AAEjF,MAAM,WAAW,qBAAqB;IACpC,8EAA8E;IAC9E,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;IACpC,4FAA4F;IAC5F,QAAQ,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,0EAA0E;IAC1E,QAAQ,CAAC,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC1C;;;;;;;OAOG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACjD,mDAAmD;IACnD,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,sBAAsB;IACtB,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,sBAAsB;IACtB,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,oBAAoB;IACpB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,sBAAsB;IACtB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;IACtC,oDAAoD;IACpD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC;IAClC;;;OAGG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AA8GD;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CAkOnF"}
package/dist/client.js ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Reconnecting browser client for a room. Zero dependencies and no Workers types: it runs in the
3
+ * browser. Import it from `@cardonjs/realtime-do/client`.
4
+ *
5
+ * The socket only signals "something changed": events are hints, and `onResync` reloads the
6
+ * state from the API after every reconnect and on each fallback poll while disconnected.
7
+ */
8
+ import { EVENT_TYPE_PATTERN, NAME_PATTERN, TICKET_PATTERN, TICKET_PROTOCOL, } from "./validation.js";
9
+ /** A connection that stays open this long resets the backoff. */
10
+ const STABLE_AFTER_MS = 10_000;
11
+ /** How long one attempt waits for the `ticket` function; past it the attempt failed. */
12
+ const TICKET_TIMEOUT_MS = 10_000;
13
+ const CLOSE_PROTOCOL = 1008;
14
+ const CLOSE_REAUTHENTICATE = 4000;
15
+ function isLocalHost(hostname) {
16
+ return (hostname === "localhost" ||
17
+ hostname.endsWith(".localhost") ||
18
+ hostname === "127.0.0.1" ||
19
+ hostname === "[::1]");
20
+ }
21
+ function resolveUrl(raw) {
22
+ const invalid = () => new TypeError("createRealtimeClient: url must be a wss: URL or a path (ws: only from an http: page on a local development host, to a local host).");
23
+ if (typeof raw !== "string" || raw === "")
24
+ throw invalid();
25
+ const location = globalThis.location;
26
+ let url;
27
+ try {
28
+ url = location === undefined ? new URL(raw) : new URL(raw, location.href);
29
+ }
30
+ catch {
31
+ throw invalid();
32
+ }
33
+ if (url.protocol === "https:")
34
+ url.protocol = "wss:";
35
+ else if (url.protocol === "http:")
36
+ url.protocol = "ws:";
37
+ if (url.username !== "" || url.password !== "")
38
+ throw invalid();
39
+ const localDevelopment = location !== undefined &&
40
+ location.protocol === "http:" &&
41
+ isLocalHost(location.hostname) &&
42
+ isLocalHost(url.hostname);
43
+ if (url.protocol !== "wss:" && !(url.protocol === "ws:" && localDevelopment))
44
+ throw invalid();
45
+ url.hash = "";
46
+ return url.href;
47
+ }
48
+ function integer(name, value, fallback, min) {
49
+ if (value === undefined)
50
+ return fallback;
51
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min) {
52
+ throw new TypeError(`createRealtimeClient: ${name} must be an integer of at least ${min}.`);
53
+ }
54
+ return value;
55
+ }
56
+ /** A frozen event, or `undefined` for anything that is not a well-formed event frame. */
57
+ function parseFrame(data) {
58
+ if (typeof data !== "string")
59
+ return undefined;
60
+ let value;
61
+ try {
62
+ value = JSON.parse(data);
63
+ }
64
+ catch {
65
+ return undefined;
66
+ }
67
+ if (typeof value !== "object" || value === null || Array.isArray(value))
68
+ return undefined;
69
+ const { channel, type, data: payload } = value;
70
+ if (typeof channel !== "string" || !NAME_PATTERN.test(channel))
71
+ return undefined;
72
+ if (typeof type !== "string" || !EVENT_TYPE_PATTERN.test(type))
73
+ return undefined;
74
+ return Object.freeze(payload === undefined
75
+ ? { channel, type }
76
+ : { channel, type, data: payload });
77
+ }
78
+ // Browsers and Workers type the clear functions differently for "no timer"; never pass one.
79
+ function stopTimeout(timer) {
80
+ if (timer !== undefined)
81
+ clearTimeout(timer);
82
+ }
83
+ function stopInterval(timer) {
84
+ if (timer !== undefined)
85
+ clearInterval(timer);
86
+ }
87
+ /** Runs a callback; neither a throw nor a rejection breaks the client. */
88
+ function safely(callback) {
89
+ try {
90
+ const result = callback();
91
+ if (result instanceof Promise)
92
+ result.catch(() => undefined);
93
+ }
94
+ catch {
95
+ // The app's callback failed; the client keeps going.
96
+ }
97
+ }
98
+ /**
99
+ * Opens the socket and keeps it open: exponential backoff with full jitter between
100
+ * `minBackoffMs` and `maxBackoffMs` (reset once a connection stays open for 10 s), `"ping"`
101
+ * every `pingIntervalMs` with a `pongTimeoutMs` deadline, and fallback polling through
102
+ * `onResync` while disconnected.
103
+ *
104
+ * Close codes: 1008 stops for good (status `"closed"`); 4000 reconnects after a random delay
105
+ * below `minBackoffMs` (sockets that expire together do not come back together); anything
106
+ * else reconnects with backoff.
107
+ *
108
+ * Call `close()` when the API refuses the user (e.g. `onResync` gets a 401 or 403): the
109
+ * client cannot tell, and keeps retrying otherwise.
110
+ */
111
+ export function createRealtimeClient(options) {
112
+ if (typeof options !== "object" || options === null) {
113
+ throw new TypeError("createRealtimeClient: options must be an object.");
114
+ }
115
+ if (typeof options.onEvent !== "function" || typeof options.onResync !== "function") {
116
+ throw new TypeError("createRealtimeClient: onEvent and onResync must be functions.");
117
+ }
118
+ if (options.onStatus !== undefined && typeof options.onStatus !== "function") {
119
+ throw new TypeError("createRealtimeClient: onStatus must be a function.");
120
+ }
121
+ if (options.ticket !== undefined && typeof options.ticket !== "function") {
122
+ throw new TypeError("createRealtimeClient: ticket must be a function.");
123
+ }
124
+ const ticketSource = options.ticket;
125
+ const url = resolveUrl(options.url);
126
+ const pollIntervalMs = integer("pollIntervalMs", options.pollIntervalMs, 30_000, 0);
127
+ const pingIntervalMs = integer("pingIntervalMs", options.pingIntervalMs, 25_000, 1);
128
+ const pongTimeoutMs = integer("pongTimeoutMs", options.pongTimeoutMs, 10_000, 1);
129
+ const minBackoffMs = integer("minBackoffMs", options.minBackoffMs, 1000, 1);
130
+ const maxBackoffMs = integer("maxBackoffMs", options.maxBackoffMs, 30_000, minBackoffMs);
131
+ const random = options.random ?? Math.random;
132
+ if (typeof random !== "function") {
133
+ throw new TypeError("createRealtimeClient: random must be a function.");
134
+ }
135
+ const candidate = options.WebSocket ?? globalThis.WebSocket;
136
+ if (typeof candidate !== "function") {
137
+ throw new TypeError("createRealtimeClient: no WebSocket implementation is available.");
138
+ }
139
+ const Socket = candidate;
140
+ let status = "connecting";
141
+ let stopped = false;
142
+ let socket;
143
+ let attempt = 0;
144
+ let opened = false;
145
+ let reconnectTimer;
146
+ let stableTimer;
147
+ let pongTimer;
148
+ let pingTimer;
149
+ let pollTimer;
150
+ let ticketTimer;
151
+ const setStatus = (next) => {
152
+ if (status === next)
153
+ return;
154
+ status = next;
155
+ safely(() => options.onStatus?.(next));
156
+ };
157
+ const resync = () => safely(() => options.onResync());
158
+ const stopPolling = () => {
159
+ stopInterval(pollTimer);
160
+ pollTimer = undefined;
161
+ };
162
+ const startPolling = () => {
163
+ if (pollIntervalMs > 0 && pollTimer === undefined) {
164
+ pollTimer = setInterval(() => {
165
+ if (!stopped)
166
+ resync();
167
+ }, pollIntervalMs);
168
+ }
169
+ };
170
+ /** Detaches the current socket so none of its late events are handled. */
171
+ const release = () => {
172
+ const current = socket;
173
+ socket = undefined;
174
+ stopInterval(pingTimer);
175
+ stopTimeout(pongTimer);
176
+ stopTimeout(stableTimer);
177
+ pingTimer = pongTimer = stableTimer = undefined;
178
+ if (current) {
179
+ current.onopen = current.onmessage = current.onclose = current.onerror = null;
180
+ }
181
+ return current;
182
+ };
183
+ const backoff = () => {
184
+ const cap = Math.min(maxBackoffMs, minBackoffMs * 2 ** (attempt + 1));
185
+ attempt++;
186
+ return Math.min(maxBackoffMs, minBackoffMs + Math.floor(random() * (cap - minBackoffMs)));
187
+ };
188
+ const scheduleReconnect = (reauthenticate) => {
189
+ if (stopped)
190
+ return;
191
+ setStatus("reconnecting");
192
+ if (stopped)
193
+ return; // `onStatus` called close().
194
+ startPolling();
195
+ stopTimeout(reconnectTimer);
196
+ // 4000: soon, but spread over [0, minBackoffMs) so expired sockets do not return as a herd.
197
+ const delay = reauthenticate ? Math.floor(random() * minBackoffMs) : backoff();
198
+ reconnectTimer = setTimeout(connect, Math.min(Math.max(delay, 0), maxBackoffMs));
199
+ };
200
+ function connect() {
201
+ reconnectTimer = undefined;
202
+ if (stopped)
203
+ return;
204
+ if (ticketSource === undefined) {
205
+ open(undefined);
206
+ return;
207
+ }
208
+ // A new ticket for every attempt: a ticket is single-use and short-lived.
209
+ let pending;
210
+ try {
211
+ pending = Promise.resolve(ticketSource());
212
+ }
213
+ catch {
214
+ scheduleReconnect(false);
215
+ return;
216
+ }
217
+ // Settled once: by the answer or by the timeout, whichever comes first. A late answer
218
+ // (after the timeout, or after close()) opens nothing.
219
+ let settled = false;
220
+ const settle = () => {
221
+ if (settled)
222
+ return false;
223
+ settled = true;
224
+ stopTimeout(ticketTimer);
225
+ ticketTimer = undefined;
226
+ return !stopped;
227
+ };
228
+ ticketTimer = setTimeout(() => {
229
+ if (settle())
230
+ scheduleReconnect(false);
231
+ }, TICKET_TIMEOUT_MS);
232
+ pending.then((ticket) => {
233
+ if (!settle())
234
+ return; // close() while the ticket was awaited, or too late: no socket.
235
+ if (typeof ticket !== "string" || !TICKET_PATTERN.test(ticket)) {
236
+ scheduleReconnect(false);
237
+ return;
238
+ }
239
+ open(ticket);
240
+ }, () => {
241
+ if (settle())
242
+ scheduleReconnect(false);
243
+ });
244
+ }
245
+ function open(ticket) {
246
+ let ws;
247
+ try {
248
+ // Without a ticket, exactly as before: the URL alone.
249
+ ws = ticket === undefined ? new Socket(url) : new Socket(url, [TICKET_PROTOCOL, ticket]);
250
+ }
251
+ catch {
252
+ scheduleReconnect(false);
253
+ return;
254
+ }
255
+ socket = ws;
256
+ ws.onopen = () => {
257
+ stopPolling();
258
+ const reconnected = opened;
259
+ opened = true;
260
+ setStatus("open");
261
+ if (stopped)
262
+ return; // `onStatus` called close().
263
+ stableTimer = setTimeout(() => {
264
+ attempt = 0;
265
+ }, STABLE_AFTER_MS);
266
+ pingTimer = setInterval(() => {
267
+ try {
268
+ ws.send("ping");
269
+ }
270
+ catch {
271
+ // The close event follows.
272
+ }
273
+ if (pongTimer === undefined) {
274
+ pongTimer = setTimeout(() => {
275
+ // No pong: the connection is dead even if the browser has not noticed.
276
+ const dead = release();
277
+ try {
278
+ dead?.close(1000, "No pong");
279
+ }
280
+ catch {
281
+ // Already closing.
282
+ }
283
+ scheduleReconnect(false);
284
+ }, pongTimeoutMs);
285
+ }
286
+ }, pingIntervalMs);
287
+ if (reconnected)
288
+ resync();
289
+ };
290
+ ws.onmessage = (event) => {
291
+ if (event.data === "pong") {
292
+ stopTimeout(pongTimer);
293
+ pongTimer = undefined;
294
+ return;
295
+ }
296
+ const parsed = parseFrame(event.data);
297
+ if (parsed !== undefined)
298
+ safely(() => options.onEvent(parsed));
299
+ };
300
+ ws.onclose = (event) => {
301
+ release();
302
+ if (event.code === CLOSE_PROTOCOL) {
303
+ stop();
304
+ return;
305
+ }
306
+ scheduleReconnect(event.code === CLOSE_REAUTHENTICATE);
307
+ };
308
+ // An error is always followed by a close event.
309
+ ws.onerror = () => undefined;
310
+ }
311
+ function stop() {
312
+ stopped = true;
313
+ stopTimeout(reconnectTimer);
314
+ reconnectTimer = undefined;
315
+ stopTimeout(ticketTimer);
316
+ ticketTimer = undefined;
317
+ stopPolling();
318
+ const current = release();
319
+ try {
320
+ current?.close(1000, "Closed");
321
+ }
322
+ catch {
323
+ // Already closing.
324
+ }
325
+ setStatus("closed");
326
+ }
327
+ connect();
328
+ return {
329
+ get status() {
330
+ return status;
331
+ },
332
+ close() {
333
+ if (!stopped)
334
+ stop();
335
+ },
336
+ };
337
+ }
338
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,kBAAkB,EAClB,YAAY,EAEZ,cAAc,EACd,eAAe,GAChB,MAAM,iBAAiB,CAAC;AAiEzB,iEAAiE;AACjE,MAAM,eAAe,GAAG,MAAM,CAAC;AAC/B,wFAAwF;AACxF,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,MAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC,SAAS,WAAW,CAAC,QAAgB;IACnC,OAAO,CACL,QAAQ,KAAK,WAAW;QACxB,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC/B,QAAQ,KAAK,WAAW;QACxB,QAAQ,KAAK,OAAO,CACrB,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,GAAY;IAC9B,MAAM,OAAO,GAAG,GAAG,EAAE,CACnB,IAAI,SAAS,CACX,oIAAoI,CACrI,CAAC;IACJ,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,EAAE;QAAE,MAAM,OAAO,EAAE,CAAC;IAC3D,MAAM,QAAQ,GAAI,UAA0C,CAAC,QAAQ,CAAC;IACtE,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,OAAO,EAAE,CAAC;IAClB,CAAC;IACD,IAAI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BAAoB,CAAC,CAAC;QACzD,CAAC,CAAC;QAEF,gDAAgD;QAChD,EAAE,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,SAAS,CAAC;IAC/B,CAAC;IAED,SAAS,IAAI;QACX,OAAO,GAAG,IAAI,CAAC;QACf,WAAW,CAAC,cAAc,CAAC,CAAC;QAC5B,cAAc,GAAG,SAAS,CAAC;QAC3B,WAAW,CAAC,WAAW,CAAC,CAAC;QACzB,WAAW,GAAG,SAAS,CAAC;QACxB,WAAW,EAAE,CAAC;QACd,MAAM,OAAO,GAAG,OAAO,EAAE,CAAC;QAC1B,IAAI,CAAC;YACH,OAAO,EAAE,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACP,mBAAmB;QACrB,CAAC;QACD,SAAS,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;IAED,OAAO,EAAE,CAAC;IAEV,OAAO;QACL,IAAI,MAAM;YACR,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,KAAK;YACH,IAAI,CAAC,OAAO;gBAAE,IAAI,EAAE,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { type RoomIdentity } from "./protocol.js";
2
+ export interface ConnectOptions {
3
+ readonly identity: RoomIdentity;
4
+ /** Chosen by the server; a client cannot subscribe to anything. 1 to 8, no repeats. */
5
+ readonly channels: readonly string[];
6
+ /** Exact origins allowed to open the socket, e.g. ["https://app.example.com"]. Required. */
7
+ readonly allowedOrigins: readonly string[];
8
+ }
9
+ /** `allowedOrigins`, checked; `caller` names the function in the `TypeError`. */
10
+ export declare function validOrigins(value: unknown, caller?: string): readonly string[];
11
+ /**
12
+ * Checks the upgrade and the `Origin`, then asks the room for a socket. Resolves with the 101
13
+ * response to return from the route.
14
+ *
15
+ * - Not a `GET` WebSocket upgrade: `ValidationError` (400).
16
+ * - `Origin` missing or not exactly in `allowedOrigins`: `ForbiddenError` (403). Browsers send
17
+ * the cookie on a cross-site upgrade, so this stops cross-site WebSocket hijacking.
18
+ * - The room is full, the identity has too many connections, or `disconnect` revoked it less
19
+ * than 60 seconds ago: `RateLimitedError` (429).
20
+ *
21
+ * Authorize the room in the route before calling this: the room's `onConnect` is not a gate.
22
+ * Never forward the client request to the room stub yourself; only this function and
23
+ * `realtime()` may call it.
24
+ *
25
+ * Invalid arguments (room, identity, channels, origins, binding) are programming errors and
26
+ * throw a `TypeError` before anything else.
27
+ */
28
+ export declare function connectToRoom(namespace: DurableObjectNamespace, room: string, request: Request, options: ConnectOptions): Promise<Response>;
29
+ //# sourceMappingURL=connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAKA,OAAO,EAML,KAAK,YAAY,EAGlB,MAAM,eAAe,CAAC;AAGvB,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC,uFAAuF;IACvF,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,4FAA4F;IAC5F,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5C;AAYD,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,SAAkB,GAAG,SAAS,MAAM,EAAE,CAgBxF;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE,sBAAsB,EACjC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,QAAQ,CAAC,CA4BnB"}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Opens a WebSocket on a room, from a route that has already authenticated the caller and
3
+ * authorized the room. Runs in the Worker; the socket is held by the room.
4
+ */
5
+ import { ForbiddenError, RateLimitedError, ValidationError } from "@cardonjs/core";
6
+ import { asciiJson, assertNamespace, CONNECT_HEADER, INTERNAL_ORIGIN, PATH, roomStub, validIdentity, } from "./protocol.js";
7
+ import { assertValidChannels, assertValidRoom } from "./validation.js";
8
+ /** Hosts where an `http:` origin is acceptable: local development only. */
9
+ function isLocalHost(hostname) {
10
+ return (hostname === "localhost" ||
11
+ hostname.endsWith(".localhost") ||
12
+ hostname === "127.0.0.1" ||
13
+ hostname === "[::1]");
14
+ }
15
+ /** `allowedOrigins`, checked; `caller` names the function in the `TypeError`. */
16
+ export function validOrigins(value, caller = "connectToRoom") {
17
+ const message = `${caller}: allowedOrigins must be a non-empty array of exact origins (https://host[:port]; http: only for localhost, *.localhost, 127.0.0.1 or [::1]), without wildcards.`;
18
+ if (!Array.isArray(value) || value.length === 0)
19
+ throw new TypeError(message);
20
+ for (const origin of value) {
21
+ if (typeof origin !== "string")
22
+ throw new TypeError(message);
23
+ let parsed;
24
+ try {
25
+ parsed = new URL(origin);
26
+ }
27
+ catch {
28
+ throw new TypeError(message);
29
+ }
30
+ const scheme = parsed.protocol === "https:" || (parsed.protocol === "http:" && isLocalHost(parsed.hostname));
31
+ if (!scheme || parsed.origin !== origin)
32
+ throw new TypeError(message);
33
+ }
34
+ return value;
35
+ }
36
+ /**
37
+ * Checks the upgrade and the `Origin`, then asks the room for a socket. Resolves with the 101
38
+ * response to return from the route.
39
+ *
40
+ * - Not a `GET` WebSocket upgrade: `ValidationError` (400).
41
+ * - `Origin` missing or not exactly in `allowedOrigins`: `ForbiddenError` (403). Browsers send
42
+ * the cookie on a cross-site upgrade, so this stops cross-site WebSocket hijacking.
43
+ * - The room is full, the identity has too many connections, or `disconnect` revoked it less
44
+ * than 60 seconds ago: `RateLimitedError` (429).
45
+ *
46
+ * Authorize the room in the route before calling this: the room's `onConnect` is not a gate.
47
+ * Never forward the client request to the room stub yourself; only this function and
48
+ * `realtime()` may call it.
49
+ *
50
+ * Invalid arguments (room, identity, channels, origins, binding) are programming errors and
51
+ * throw a `TypeError` before anything else.
52
+ */
53
+ export async function connectToRoom(namespace, room, request, options) {
54
+ assertNamespace(namespace, "connectToRoom");
55
+ assertValidRoom(room);
56
+ if (typeof options !== "object" || options === null) {
57
+ throw new TypeError("connectToRoom: options must be an object.");
58
+ }
59
+ const identity = validIdentity(options.identity);
60
+ assertValidChannels(options.channels);
61
+ const channels = [...options.channels];
62
+ const allowedOrigins = validOrigins(options.allowedOrigins);
63
+ if (request.method !== "GET" || request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
64
+ throw new ValidationError("A WebSocket upgrade is required.");
65
+ }
66
+ const origin = request.headers.get("origin");
67
+ if (origin === null || !allowedOrigins.includes(origin))
68
+ throw new ForbiddenError();
69
+ // A new request: no client header (cookies, authorization) reaches the room.
70
+ const response = await roomStub(namespace, room).fetch(`${INTERNAL_ORIGIN}${PATH.connect}`, {
71
+ headers: {
72
+ upgrade: "websocket",
73
+ // Cannot throw: ids are well-formed and everything outside printable ASCII is escaped.
74
+ [CONNECT_HEADER]: asciiJson({ room, identity, channels }),
75
+ },
76
+ });
77
+ if (response.status === 101 && response.webSocket)
78
+ return response;
79
+ if (response.status === 429)
80
+ throw new RateLimitedError();
81
+ throw new Error(`connectToRoom: the room refused the connection (status ${response.status}).`);
82
+ }
83
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.js","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EACL,SAAS,EACT,eAAe,EACf,cAAc,EACd,eAAe,EACf,IAAI,EAEJ,QAAQ,EACR,aAAa,GACd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAUvE,2EAA2E;AAC3E,SAAS,WAAW,CAAC,QAAgB;IACnC,OAAO,CACL,QAAQ,KAAK,WAAW;QACx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;QAAE,MAAM,IAAI,gBAAgB,EAAE,CAAC;IAC1D,MAAM,IAAI,KAAK,CAAC,0DAA0D,QAAQ,CAAC,MAAM,IAAI,CAAC,CAAC;AACjG,CAAC"}
@@ -0,0 +1,8 @@
1
+ export { type ConnectOptions, connectToRoom } from "./connect.js";
2
+ export type { Presence, PresenceConnection, PresenceOptions } from "./presence.js";
3
+ export type { RoomIdentity } from "./protocol.js";
4
+ export { type RealtimePublisher, realtime } from "./publisher.js";
5
+ export { defineRoom, type RoomClass, type RoomHookContext, type RoomOptions, } from "./room.js";
6
+ export { connectToRoomWithTicket, issueRoomTicket, type RoomTicket, type RoomTicketOptions, type TicketConnectOptions, } from "./ticket.js";
7
+ export { assertValidChannel, assertValidChannels, assertValidRoom, type JsonValue, type RealtimeEvent, validEvent, } from "./validation.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClE,YAAY,EAAE,QAAQ,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACnF,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,KAAK,iBAAiB,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EACL,UAAU,EACV,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,WAAW,GACjB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,GAC1B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,UAAU,GACX,MAAM,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { connectToRoom } from "./connect.js";
2
+ export { realtime } from "./publisher.js";
3
+ export { defineRoom, } from "./room.js";
4
+ export { connectToRoomWithTicket, issueRoomTicket, } from "./ticket.js";
5
+ export { assertValidChannel, assertValidChannels, assertValidRoom, validEvent, } from "./validation.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlE,OAAO,EAA0B,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EACL,UAAU,GAIX,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,uBAAuB,EACvB,eAAe,GAIhB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EAGf,UAAU,GACX,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Presence: who is connected to a room, since when, and when the room last answered their
3
+ * `"ping"`. The query and the selection (filters, order, limit) are shared by the room, the
4
+ * publisher and the fake, so the three agree. Every failure is a `TypeError` whose message never
5
+ * includes the value (identity ids are personal data).
6
+ */
7
+ import { type RoomIdentity } from "./protocol.js";
8
+ export interface PresenceOptions {
9
+ /** Only this identity's connections. */
10
+ readonly identity?: RoomIdentity;
11
+ /** Only connections on this channel. */
12
+ readonly channel?: string;
13
+ /** Only connections seen (connected or answered a `"ping"`) in the last N seconds, 1 to 86 400. */
14
+ readonly activeWithinSeconds?: number;
15
+ /** At most this many connections in the result. Default 100, 1 to 1000. */
16
+ readonly limit?: number;
17
+ }
18
+ export interface PresenceConnection {
19
+ /** Only `id` and `kind`. */
20
+ readonly identity: RoomIdentity;
21
+ readonly channels: readonly string[];
22
+ readonly connectedAt: Date;
23
+ /** The last `"ping"` the room answered, or `connectedAt` when there was none yet. */
24
+ readonly lastSeenAt: Date;
25
+ }
26
+ export interface Presence {
27
+ /** Open connections, oldest first, at most `limit`. */
28
+ readonly connections: readonly PresenceConnection[];
29
+ /** How many connections matched before `limit` was applied. */
30
+ readonly total: number;
31
+ }
32
+ /** A validated query: a frozen copy with `limit` filled in. */
33
+ export interface PresenceQuery {
34
+ readonly identity?: RoomIdentity;
35
+ readonly channel?: string;
36
+ readonly activeWithinSeconds?: number;
37
+ readonly limit: number;
38
+ }
39
+ /** One connection as the room (or the fake) sees it; times are epoch milliseconds. */
40
+ export interface PresenceRecord {
41
+ readonly identity: RoomIdentity;
42
+ readonly channels: readonly string[];
43
+ readonly connectedAt: number;
44
+ readonly lastSeenAt: number;
45
+ }
46
+ export declare const DEFAULT_PRESENCE_LIMIT = 100;
47
+ export declare const MAX_PRESENCE_LIMIT = 1000;
48
+ export declare const MAX_ACTIVE_WITHIN_SECONDS = 86400;
49
+ /** Validates presence options (`undefined` means none) and returns a frozen query. */
50
+ export declare function validPresenceQuery(options: unknown): PresenceQuery;
51
+ /** True when `value` is a usable epoch-milliseconds time. */
52
+ export declare function isTime(value: unknown): value is number;
53
+ /**
54
+ * Applies the query to the connections: filters, oldest first (a stable sort, so ties keep the
55
+ * input order), then `limit`. `total` counts the matches before `limit`.
56
+ */
57
+ export declare function selectPresence(records: readonly PresenceRecord[], query: PresenceQuery, now: number): {
58
+ records: PresenceRecord[];
59
+ total: number;
60
+ };
61
+ /** The public, frozen form of a record. */
62
+ export declare function presenceConnection(record: PresenceRecord): PresenceConnection;
63
+ /**
64
+ * Parses one entry of the room's answer. Throws a `TypeError` (without the value) when it is not
65
+ * well-formed.
66
+ */
67
+ export declare function presenceRecord(value: unknown): PresenceRecord;
68
+ //# sourceMappingURL=presence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.d.ts","sourceRoot":"","sources":["../src/presence.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,KAAK,YAAY,EAAiB,MAAM,eAAe,CAAC;AAGjE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