@cardonjs/realtime-do 0.0.0-stage → 0.2.3

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,50 @@
1
+ /**
2
+ * The internal protocol between the Worker-side helpers (`connectToRoom`, `realtime`) and the
3
+ * room. Requests travel only through the Durable Object binding, so the room trusts what they
4
+ * carry; it still validates it, because a malformed value must never reach a socket tag.
5
+ */
6
+ /** Who holds a connection. Roles and email are not stored: they would go stale. */
7
+ export interface RoomIdentity {
8
+ readonly id: string;
9
+ readonly kind: "user" | "service";
10
+ }
11
+ /** Base URL of the internal requests. Never leaves the binding. */
12
+ export declare const INTERNAL_ORIGIN = "https://realtime-do.internal";
13
+ export declare const PATH: {
14
+ readonly connect: "/connect";
15
+ readonly publish: "/publish";
16
+ readonly count: "/count";
17
+ readonly disconnect: "/disconnect";
18
+ /** POST `{ query }` (see `validPresenceQuery`); answers `{ connections, total }`, times in ms. */
19
+ readonly presence: "/presence";
20
+ };
21
+ /**
22
+ * Carries the connect parameters: JSON with everything outside printable ASCII escaped
23
+ * (`asciiJson`), because header values are bytes and a GET upgrade has no body.
24
+ */
25
+ export declare const CONNECT_HEADER = "x-cardon-realtime-connect";
26
+ /** Close codes. 1008: protocol violation; 4000: re-authenticate; 4001: closed by the server. */
27
+ export declare const CLOSE_PROTOCOL = 1008;
28
+ export declare const CLOSE_REAUTHENTICATE = 4000;
29
+ export declare const CLOSE_DISCONNECTED = 4001;
30
+ /** JSON with every character outside printable ASCII escaped, so it is a valid header value. */
31
+ export declare function asciiJson(value: unknown): string;
32
+ /**
33
+ * The socket tag of an identity, also the key of its revocation marker: `#identity:` + hex
34
+ * SHA-256 of `kind:id`. Fixed length (74 ASCII characters) and opaque, so a raw id never
35
+ * reaches a tag, a runtime error message or a log, and the same id under two kinds is two
36
+ * identities. Tags starting with `#` cannot collide with channels (letter or digit first).
37
+ */
38
+ export declare function identityTag(identity: RoomIdentity): Promise<string>;
39
+ /** The start of every identity tag (see `identityTag`). */
40
+ export declare const IDENTITY_TAG_PREFIX = "#identity:";
41
+ export declare function assertValidIdentityId(id: unknown): asserts id is string;
42
+ /** A frozen copy holding only `id` and `kind`. */
43
+ export declare function validIdentity(identity: unknown): RoomIdentity;
44
+ /**
45
+ * Fails fast when the value is not a Durable Object namespace binding (for example `env.ROOMS`
46
+ * is `undefined` because the binding is missing). Never includes the value.
47
+ */
48
+ export declare function assertNamespace(namespace: unknown, caller: string): asserts namespace is DurableObjectNamespace;
49
+ export declare function roomStub(namespace: DurableObjectNamespace, room: string): DurableObjectStub;
50
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,mFAAmF;AACnF,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;CACnC;AAED,mEAAmE;AACnE,eAAO,MAAM,eAAe,iCAAiC,CAAC;AAC9D,eAAO,MAAM,IAAI;aACf,OAAO,EAAE,UAAU;aACnB,OAAO,EAAE,UAAU;aACnB,KAAK,EAAE,QAAQ;aACf,UAAU,EAAE,aAAa;IACzB,kGAAkG;aAClG,QAAQ,EAAE,WAAW;CACb,CAAC;AACX;;;GAGG;AACH,eAAO,MAAM,cAAc,8BAA8B,CAAC;AAE1D,gGAAgG;AAChG,eAAO,MAAM,cAAc,OAAO,CAAC;AACnC,eAAO,MAAM,oBAAoB,OAAO,CAAC;AACzC,eAAO,MAAM,kBAAkB,OAAO,CAAC;AASvC,gGAAgG;AAChG,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKhD;AAMD;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAGzE;AAED,2DAA2D;AAC3D,eAAO,MAAM,mBAAmB,eAAe,CAAC;AAEhD,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,OAAO,GAAG,OAAO,CAAC,EAAE,IAAI,MAAM,CAYvE;AAED,kDAAkD;AAClD,wBAAgB,aAAa,CAAC,QAAQ,EAAE,OAAO,GAAG,YAAY,CAU7D;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,OAAO,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,IAAI,sBAAsB,CAY7C;AAED,wBAAgB,QAAQ,CAAC,SAAS,EAAE,sBAAsB,EAAE,IAAI,EAAE,MAAM,GAAG,iBAAiB,CAE3F"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The internal protocol between the Worker-side helpers (`connectToRoom`, `realtime`) and the
3
+ * room. Requests travel only through the Durable Object binding, so the room trusts what they
4
+ * carry; it still validates it, because a malformed value must never reach a socket tag.
5
+ */
6
+ /** Base URL of the internal requests. Never leaves the binding. */
7
+ export const INTERNAL_ORIGIN = "https://realtime-do.internal";
8
+ export const PATH = {
9
+ connect: "/connect",
10
+ publish: "/publish",
11
+ count: "/count",
12
+ disconnect: "/disconnect",
13
+ /** POST `{ query }` (see `validPresenceQuery`); answers `{ connections, total }`, times in ms. */
14
+ presence: "/presence",
15
+ };
16
+ /**
17
+ * Carries the connect parameters: JSON with everything outside printable ASCII escaped
18
+ * (`asciiJson`), because header values are bytes and a GET upgrade has no body.
19
+ */
20
+ export const CONNECT_HEADER = "x-cardon-realtime-connect";
21
+ /** Close codes. 1008: protocol violation; 4000: re-authenticate; 4001: closed by the server. */
22
+ export const CLOSE_PROTOCOL = 1008;
23
+ export const CLOSE_REAUTHENTICATE = 4000;
24
+ export const CLOSE_DISCONNECTED = 4001;
25
+ const MAX_IDENTITY_ID = 128;
26
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it rejects.
27
+ const CONTROL = /[\u0000-\u001f\u007f]/;
28
+ /** A lone surrogate, i.e. not well-formed UTF-16 (`isWellFormed()`, which ES2022 lacks). */
29
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
30
+ /** JSON with every character outside printable ASCII escaped, so it is a valid header value. */
31
+ export function asciiJson(value) {
32
+ return JSON.stringify(value).replace(/[^\x20-\x7e]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
33
+ }
34
+ function hex(bytes) {
35
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
36
+ }
37
+ /**
38
+ * The socket tag of an identity, also the key of its revocation marker: `#identity:` + hex
39
+ * SHA-256 of `kind:id`. Fixed length (74 ASCII characters) and opaque, so a raw id never
40
+ * reaches a tag, a runtime error message or a log, and the same id under two kinds is two
41
+ * identities. Tags starting with `#` cannot collide with channels (letter or digit first).
42
+ */
43
+ export async function identityTag(identity) {
44
+ const input = new TextEncoder().encode(`${identity.kind}:${identity.id}`);
45
+ return `${IDENTITY_TAG_PREFIX}${hex(await crypto.subtle.digest("SHA-256", input))}`;
46
+ }
47
+ /** The start of every identity tag (see `identityTag`). */
48
+ export const IDENTITY_TAG_PREFIX = "#identity:";
49
+ export function assertValidIdentityId(id) {
50
+ if (typeof id !== "string" ||
51
+ id.length < 1 ||
52
+ id.length > MAX_IDENTITY_ID ||
53
+ CONTROL.test(id) ||
54
+ LONE_SURROGATE.test(id)) {
55
+ throw new TypeError(`realtime: the identity id must be well-formed UTF-16, 1 to ${MAX_IDENTITY_ID} characters, without control characters.`);
56
+ }
57
+ }
58
+ /** A frozen copy holding only `id` and `kind`. */
59
+ export function validIdentity(identity) {
60
+ if (typeof identity !== "object" || identity === null) {
61
+ throw new TypeError("realtime: identity must be an object with id and kind.");
62
+ }
63
+ const { id, kind } = identity;
64
+ assertValidIdentityId(id);
65
+ if (kind !== "user" && kind !== "service") {
66
+ throw new TypeError('realtime: identity.kind must be "user" or "service".');
67
+ }
68
+ return Object.freeze({ id, kind });
69
+ }
70
+ /**
71
+ * Fails fast when the value is not a Durable Object namespace binding (for example `env.ROOMS`
72
+ * is `undefined` because the binding is missing). Never includes the value.
73
+ */
74
+ export function assertNamespace(namespace, caller) {
75
+ const candidate = namespace;
76
+ if (typeof candidate !== "object" ||
77
+ candidate === null ||
78
+ typeof candidate.idFromName !== "function" ||
79
+ typeof candidate.get !== "function") {
80
+ throw new TypeError(`${caller}: expected a Durable Object namespace binding. Declare it in the Wrangler config under [[durable_objects.bindings]] (name and class_name of the room class) and add a migration with new_sqlite_classes for that class.`);
81
+ }
82
+ }
83
+ export function roomStub(namespace, room) {
84
+ return namespace.get(namespace.idFromName(room));
85
+ }
86
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAQH,mEAAmE;AACnE,MAAM,CAAC,MAAM,eAAe,GAAG,8BAA8B,CAAC;AAC9D,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,OAAO,EAAE,UAAU;IACnB,OAAO,EAAE,UAAU;IACnB,KAAK,EAAE,QAAQ;IACf,UAAU,EAAE,aAAa;IACzB,kGAAkG;IAClG,QAAQ,EAAE,WAAW;CACb,CAAC;AACX;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAE1D,gGAAgG;AAChG,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC;AACnC,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AACzC,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEvC,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,mGAAmG;AACnG,MAAM,OAAO,GAAG,uBAAuB,CAAC;AAExC,4FAA4F;AAC5F,MAAM,cAAc,GAAG,wEAAwE,CAAC;AAEhG,gGAAgG;AAChG,M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,eAAe,0CAA0C,CACxH,CAAC;IACJ,CAAC;AACH,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,aAAa,CAAC,QAAiB;IAC7C,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtD,MAAM,IAAI,SAAS,CAAC,wDAAwD,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,QAAmC,CAAC;IACzD,qBAAqB,CAAC,EAAE,CAAC,CAAC;IAC1B,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QAC1C,MAAM,IAAI,SAAS,CAAC,sDAAsD,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AACrC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC7B,SAAkB,EAClB,MAAc;IAEd,MAAM,SAAS,GAAG,SAA+D,CAAC;IAClF,IACE,OAAO,SAAS,KAAK,QAAQ;QAC7B,SAAS,KAAK,IAAI;QAClB,OAAO,SAAS,CAAC,UAAU,KAAK,UAAU;QAC1C,OAAO,SAAS,CAAC,GAAG,KAAK,UAAU,EACnC,CAAC;QACD,MAAM,IAAI,SAAS,CACjB,GAAG,MAAM,yNAAyN,CACnO,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,SAAiC,EAAE,IAAY;IACtE,OAAO,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AACnD,CAAC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Publishes to rooms from the API. Business logic depends on `RealtimePublisher`, received
3
+ * through the adapters, not on the binding.
4
+ */
5
+ import { type Presence, type PresenceOptions } from "./presence.js";
6
+ import { type RoomIdentity } from "./protocol.js";
7
+ import { type RealtimeEvent } from "./validation.js";
8
+ export interface RealtimePublisher {
9
+ /** Sends the event to every connection on `event.channel`. Resolves with how many got it. */
10
+ publish(room: string, event: RealtimeEvent): Promise<{
11
+ delivered: number;
12
+ }>;
13
+ /** Open connections in the room (expired ones are closed first and not counted). */
14
+ count(room: string): Promise<number>;
15
+ /**
16
+ * After access is revoked: closes the identity's open connections in the room with 4001 and,
17
+ * for the next 60 seconds, refuses its new connections there (429), so a connect that passed
18
+ * the route's check just before the revocation cannot land afterwards. Resolves with how many
19
+ * open connections were closed.
20
+ */
21
+ disconnect(room: string, identity: RoomIdentity): Promise<{
22
+ closed: number;
23
+ }>;
24
+ /**
25
+ * Open connections in the room (expired ones are closed first and not listed), oldest first,
26
+ * with their identity, channels, connect time and last answered `"ping"`. Filters:
27
+ * `identity`, `channel` (both: their intersection), `activeWithinSeconds` (1 to 86 400);
28
+ * `limit` (default 100, 1 to 1000) caps the list and `total` says how many matched. Returns
29
+ * identity ids: authorize the caller before exposing it.
30
+ */
31
+ presence(room: string, options?: PresenceOptions): Promise<Presence>;
32
+ }
33
+ /**
34
+ * A `RealtimePublisher` over the room's Durable Object namespace. Synchronous and without I/O,
35
+ * so it is safe inside the adapters factory. Every argument is validated before any call to the
36
+ * room. The event size is checked against 1 MiB here and against `maxEventBytes` by the room.
37
+ */
38
+ export declare function realtime(namespace: DurableObjectNamespace): RealtimePublisher;
39
+ //# sourceMappingURL=publisher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../src/publisher.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,eAAe,EAKrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAIL,KAAK,YAAY,EAGlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAGL,KAAK,aAAa,EAEnB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,iBAAiB;IAChC,6FAA6F;IAC7F,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5E,oFAAoF;IACpF,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC;;;;;OAKG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC9E;;;;;;OAMG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtE;AAkED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,SAAS,EAAE,sBAAsB,GAAG,iBAAiB,CA0C7E"}
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Publishes to rooms from the API. Business logic depends on `RealtimePublisher`, received
3
+ * through the adapters, not on the binding.
4
+ */
5
+ import { presenceConnection, presenceRecord, validPresenceQuery, } from "./presence.js";
6
+ import { assertNamespace, INTERNAL_ORIGIN, PATH, roomStub, validIdentity, } from "./protocol.js";
7
+ import { assertValidRoom, MAX_EVENT_BYTES_LIMIT, validEvent, } from "./validation.js";
8
+ function isCount(value) {
9
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
10
+ }
11
+ /** Checks the status and returns the JSON body; never includes the request's values. */
12
+ async function readBody(response, what, rejected) {
13
+ if (response.status === 400) {
14
+ await response.body?.cancel();
15
+ throw new TypeError(`realtime: the room rejected the ${what} (${rejected}).`);
16
+ }
17
+ if (!response.ok) {
18
+ await response.body?.cancel();
19
+ throw new Error(`realtime: the room answered the ${what} with status ${response.status}.`);
20
+ }
21
+ try {
22
+ return await response.json();
23
+ }
24
+ catch {
25
+ // A parse error quotes the body, which may hold identity ids.
26
+ throw new Error(`realtime: the room answered the ${what} without JSON.`);
27
+ }
28
+ }
29
+ async function readCount(response, key, what, rejected) {
30
+ const body = (await readBody(response, what, rejected));
31
+ const value = body?.[key];
32
+ if (!isCount(value))
33
+ throw new Error(`realtime: the room answered the ${what} without a count.`);
34
+ return value;
35
+ }
36
+ /** Parses the room's presence answer strictly: frozen, dates as `Date`, at most `limit`. */
37
+ async function readPresence(response, limit) {
38
+ const body = (await readBody(response, "presence query", "invalid query"));
39
+ const total = body?.total;
40
+ const list = body?.connections;
41
+ if (!isCount(total) ||
42
+ !Array.isArray(list) ||
43
+ list.length > limit ||
44
+ list.length > total ||
45
+ (list.length < limit && list.length !== total)) {
46
+ throw new Error("realtime: the room answered the presence query without a valid list.");
47
+ }
48
+ let records;
49
+ try {
50
+ records = list.map((entry) => presenceRecord(entry));
51
+ }
52
+ catch {
53
+ // The entry is not echoed: it holds identity ids.
54
+ throw new Error("realtime: the room answered the presence query with an invalid entry.");
55
+ }
56
+ return Object.freeze({
57
+ connections: Object.freeze(records.map(presenceConnection)),
58
+ total,
59
+ });
60
+ }
61
+ /**
62
+ * A `RealtimePublisher` over the room's Durable Object namespace. Synchronous and without I/O,
63
+ * so it is safe inside the adapters factory. Every argument is validated before any call to the
64
+ * room. The event size is checked against 1 MiB here and against `maxEventBytes` by the room.
65
+ */
66
+ export function realtime(namespace) {
67
+ assertNamespace(namespace, "realtime");
68
+ const post = (room, path, body) => roomStub(namespace, room).fetch(`${INTERNAL_ORIGIN}${path}`, {
69
+ method: "POST",
70
+ headers: { "content-type": "application/json" },
71
+ body: JSON.stringify(body),
72
+ });
73
+ return Object.freeze({
74
+ async publish(room, event) {
75
+ assertValidRoom(room);
76
+ const valid = validEvent(event, MAX_EVENT_BYTES_LIMIT);
77
+ const response = await post(room, PATH.publish, { event: valid });
78
+ return {
79
+ delivered: await readCount(response, "delivered", "publish", "invalid event, or larger than the room's maxEventBytes"),
80
+ };
81
+ },
82
+ async count(room) {
83
+ assertValidRoom(room);
84
+ const response = await roomStub(namespace, room).fetch(`${INTERNAL_ORIGIN}${PATH.count}`);
85
+ return readCount(response, "count", "count", "invalid request");
86
+ },
87
+ async disconnect(room, identity) {
88
+ assertValidRoom(room);
89
+ const valid = validIdentity(identity);
90
+ const response = await post(room, PATH.disconnect, { identity: valid });
91
+ return { closed: await readCount(response, "closed", "disconnect", "invalid identity") };
92
+ },
93
+ async presence(room, options) {
94
+ assertValidRoom(room);
95
+ const query = validPresenceQuery(options);
96
+ const response = await post(room, PATH.presence, { query });
97
+ return readPresence(response, query.limit);
98
+ },
99
+ });
100
+ }
101
+ //# sourceMappingURL=publisher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publisher.js","sourceRoot":"","sources":["../src/publisher.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIL,kBAAkB,EAClB,cAAc,EACd,kBAAkB,GACnB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,eAAe,EACf,eAAe,EACf,IAAI,EAEJ,QAAQ,EACR,aAAa,GACd,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,eAAe,EACf,qBAAqB,EAErB,UAAU,GACX,MAAM,iBAAiB,CAAC;AAwBzB,SAAS,OAAO,CAAC,KAAc;IAC7B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAChF,CAAC;AAED,wFAAwF;AACxF,KAAK,UAAU,QAAQ,CAAC,QAAkB,EAAE,IAAY,EAAE,QAAgB;IACxE,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;QAC5B,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;QAC9B,MAAM,IAAI,SAAS,CAAC,mCAAmC,IAAI,KAAK,QAAQ,IAAI,CAAC,CAAC;IAChF,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EA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RPC) that holds
3
+ * hibernating WebSockets. The Worker talks to it with `stub.fetch` on internal URLs.
4
+ *
5
+ * Nothing about a connection lives in instance memory: channels and the identity (hashed) are
6
+ * the socket's tags, everything else is in its attachment, and revocation markers are in
7
+ * Durable Object storage, so the room behaves the same after the runtime evicts the instance
8
+ * and wakes it again for the next event. The only in-memory value is a cache (the earliest
9
+ * expiry), rebuilt by a full sweep after a wake-up.
10
+ */
11
+ import { type RoomIdentity } from "./protocol.js";
12
+ export interface RoomHookContext<Env> {
13
+ readonly room: string;
14
+ readonly identity: RoomIdentity;
15
+ /** The connection's channels (a frozen copy). */
16
+ readonly channels: readonly string[];
17
+ /** When the connection was accepted; in `onDisconnect`, how long it lasted is now minus this. */
18
+ readonly connectedAt: Date;
19
+ /**
20
+ * Open connections after the change; 0 means the room is now empty. Sockets that are closing
21
+ * are not counted here, but they still count against the caps until the runtime drops them.
22
+ */
23
+ readonly connections: number;
24
+ /**
25
+ * Open connections of this identity in the room after the change, counted the same way:
26
+ * 1 in `onConnect` is its first connection, 0 in `onDisconnect` means its last one closed.
27
+ */
28
+ readonly identityConnections: number;
29
+ readonly env: Env;
30
+ }
31
+ export interface RoomOptions<Env = unknown> {
32
+ /** Default 1000, at most 32 768. */
33
+ readonly maxConnections?: number;
34
+ /** Default 5, at most `maxConnections`. */
35
+ readonly maxConnectionsPerIdentity?: number;
36
+ /** Size limit of a serialized event, in UTF-8 bytes. Default 16 384, 256 to 1 048 576. */
37
+ readonly maxEventBytes?: number;
38
+ /**
39
+ * Default 3600, 1 to 604 800 (7 days). Each socket gets a random age between 90 % and 100 %
40
+ * of it, so sockets opened together do not all expire together.
41
+ */
42
+ readonly maxConnectionAgeSeconds?: number;
43
+ /**
44
+ * Runs after the socket is accepted, before the 101 response. **Not a gate**: a throw is
45
+ * logged and the connection stays. Authorize in the route, before `connectToRoom`.
46
+ */
47
+ onConnect?(context: RoomHookContext<Env>): void | Promise<void>;
48
+ /**
49
+ * Runs once per socket when its close completes (the runtime calls `webSocketClose`), so a
50
+ * peer that never answers a close frame delays it.
51
+ */
52
+ onDisconnect?(context: RoomHookContext<Env>): void | Promise<void>;
53
+ }
54
+ /** The class `defineRoom` returns. Export it from the Worker entry under the configured name. */
55
+ export type RoomClass<Env = unknown> = new (state: DurableObjectState, env: Env) => DurableObject;
56
+ /** Returns the Durable Object class the project exports from its Worker entry. */
57
+ export declare function defineRoom<Env = unknown>(options?: RoomOptions<Env>): RoomClass<Env>;
58
+ //# sourceMappingURL=room.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room.d.ts","sourceRoot":"","sources":["../src/room.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AASH,OAAO,EAQL,KAAK,YAAY,EAElB,MAAM,eAAe,CAAC;AAUvB,MAAM,WAAW,eAAe,CAAC,GAAG;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC,iDAAiD;IACjD,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,iGAAiG;IACjG,QAAQ,CAAC,WAAW,EAAE,IAAI,CAAC;IAC3B;;;OAGG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;OAGG;IACH,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;CACnB;AAED,MAAM,WAAW,WAAW,CAAC,GAAG,GAAG,OAAO;IACxC,oCAAoC;IACpC,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,2CAA2C;IAC3C,QAAQ,CAAC,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAC5C,0FAA0F;IAC1F,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,QAAQ,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC;IAC1C;;;OAGG;IACH,SAAS,CAAC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