@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,106 @@
1
+ /**
2
+ * Names and events, validated the same way by the room, the publisher, the fake and the client.
3
+ * No imports and no runtime-specific APIs: this module also ships in the browser client.
4
+ *
5
+ * Every failure is a programming error (the values are built by the server), so it is a plain
6
+ * `TypeError` whose message never includes the value.
7
+ */
8
+ /** Room and channel names. */
9
+ export const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$/;
10
+ /** Event types. */
11
+ export const EVENT_TYPE_PATTERN = /^[a-z0-9][a-z0-9._:-]{0,63}$/;
12
+ /** Channels a connection may join. */
13
+ export const MAX_CHANNELS = 8;
14
+ /** Default and smallest-common size of a serialized frame, in UTF-8 bytes. */
15
+ export const DEFAULT_MAX_EVENT_BYTES = 16_384;
16
+ /** Upper bound for `maxEventBytes` (the frame also travels in a request to the room). */
17
+ export const MAX_EVENT_BYTES_LIMIT = 1_048_576;
18
+ const MAX_DEPTH = 32;
19
+ const encoder = new TextEncoder();
20
+ export function assertValidRoom(room) {
21
+ if (typeof room !== "string" || !NAME_PATTERN.test(room)) {
22
+ throw new TypeError("realtime: the room name must be 1 to 128 characters of A-Z, a-z, 0-9, ':', '.', '_' or '-', starting with a letter or digit.");
23
+ }
24
+ }
25
+ export function assertValidChannel(channel) {
26
+ if (typeof channel !== "string" || !NAME_PATTERN.test(channel)) {
27
+ throw new TypeError("realtime: a channel name must be 1 to 128 characters of A-Z, a-z, 0-9, ':', '.', '_' or '-', starting with a letter or digit.");
28
+ }
29
+ }
30
+ export function assertValidChannels(channels) {
31
+ if (!Array.isArray(channels) || channels.length < 1 || channels.length > MAX_CHANNELS) {
32
+ throw new TypeError(`realtime: channels must be an array of 1 to ${MAX_CHANNELS} names.`);
33
+ }
34
+ for (const channel of channels)
35
+ assertValidChannel(channel);
36
+ if (new Set(channels).size !== channels.length) {
37
+ throw new TypeError("realtime: channels must not repeat.");
38
+ }
39
+ }
40
+ function isPlainObject(value) {
41
+ const proto = Object.getPrototypeOf(value);
42
+ return proto === Object.prototype || proto === null;
43
+ }
44
+ function copyJson(value, depth, seen) {
45
+ if (value === null || typeof value === "string" || typeof value === "boolean")
46
+ return value;
47
+ if (typeof value === "number") {
48
+ if (!Number.isFinite(value)) {
49
+ throw new TypeError("realtime: event data must not hold NaN or infinite numbers.");
50
+ }
51
+ return value;
52
+ }
53
+ if (typeof value !== "object") {
54
+ throw new TypeError("realtime: event data must be JSON (no undefined, functions, symbols or bigints).");
55
+ }
56
+ if (depth >= MAX_DEPTH) {
57
+ throw new TypeError(`realtime: event data must not nest deeper than ${MAX_DEPTH} levels.`);
58
+ }
59
+ if (seen.has(value))
60
+ throw new TypeError("realtime: event data must not hold cycles.");
61
+ seen.add(value);
62
+ let copy;
63
+ if (Array.isArray(value)) {
64
+ copy = Object.freeze(value.map((item) => copyJson(item, depth + 1, seen)));
65
+ }
66
+ else {
67
+ if (!isPlainObject(value)) {
68
+ throw new TypeError("realtime: event data must hold only plain objects and arrays.");
69
+ }
70
+ // `fromEntries` defines own properties, so a "__proto__" key stays a plain key.
71
+ copy = Object.freeze(Object.fromEntries(Object.keys(value).map((key) => [
72
+ key,
73
+ copyJson(value[key], depth + 1, seen),
74
+ ])));
75
+ }
76
+ seen.delete(value);
77
+ return copy;
78
+ }
79
+ /** The frame sent to clients: `{"channel":…,"type":…,"data":…}`, `data` omitted when absent. */
80
+ export function eventFrame(event) {
81
+ return JSON.stringify(event.data === undefined
82
+ ? { channel: event.channel, type: event.type }
83
+ : { channel: event.channel, type: event.type, data: event.data });
84
+ }
85
+ /**
86
+ * Returns a frozen, validated copy of `event` (only `channel`, `type` and `data` are kept).
87
+ * The serialized frame must be at most `maxEventBytes` UTF-8 bytes (default 16 384).
88
+ */
89
+ export function validEvent(event, maxEventBytes = DEFAULT_MAX_EVENT_BYTES) {
90
+ if (typeof event !== "object" || event === null || Array.isArray(event)) {
91
+ throw new TypeError("realtime: the event must be an object with channel, type and data.");
92
+ }
93
+ const { channel, type, data } = event;
94
+ assertValidChannel(channel);
95
+ if (typeof type !== "string" || !EVENT_TYPE_PATTERN.test(type)) {
96
+ throw new TypeError("realtime: the event type must be 1 to 64 characters of a-z, 0-9, '.', '_', ':' or '-', starting with a letter or digit.");
97
+ }
98
+ const copy = Object.freeze(data === undefined
99
+ ? { channel, type }
100
+ : { channel, type, data: copyJson(data, 0, new Set()) });
101
+ if (encoder.encode(eventFrame(copy)).byteLength > maxEventBytes) {
102
+ throw new TypeError(`realtime: the serialized event is larger than ${maxEventBytes} bytes.`);
103
+ }
104
+ return copy;
105
+ }
106
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAmBH,8BAA8B;AAC9B,MAAM,CAAC,MAAM,YAAY,GAAG,qCAAqC,CAAC;AAClE,mBAAmB;AACnB,MAAM,CAAC,MAAM,kBAAkB,GAAG,8BAA8B,CAAC;AACjE,sCAAsC;AACtC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC;AAC9B,8EAA8E;AAC9E,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAC9C,yFAAyF;AACzF,MAAM,CAAC,MAAM,qBAAqB,GAAG,SAAS,CAAC;AAE/C,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,MAAM,UAAU,eAAe,CAAC,IAAa;IAC3C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACzD,MAAM,IAAI,SAAS,CACjB,8HAA8H,CAC/H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,OAAgB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D,aAAa,SAAS,CAAC,CAAC;IAC/F,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
package/llms.txt ADDED
@@ -0,0 +1,189 @@
1
+ # @cardonjs/realtime-do
2
+
3
+ Real-time for Cardón apps on Cloudflare Durable Objects. A room (one Durable Object) holds
4
+ hibernating WebSockets; the API publishes small events to it after saving data; a reconnecting
5
+ browser client receives them and reloads what changed. Events flow server to client only and carry
6
+ a hint (ids), never the record: the database stays the source of truth. The main entry runs on
7
+ Cloudflare Workers only (it needs a Durable Object namespace binding). `./client` has zero
8
+ dependencies and runs in browsers. `./testing` is an in-memory fake with no runtime requirements.
9
+
10
+ Full documentation: README.md in this package.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @cardonjs/realtime-do @cardonjs/core
16
+ ```
17
+
18
+ `@cardonjs/core` is the only peer dependency. The types `DurableObjectNamespace` and
19
+ `DurableObjectState` come from `@cloudflare/workers-types` (as in
20
+ `@cardonjs/config/tsconfig.workers.json`). The client needs only the DOM types. Wrangler: bind the
21
+ room class under `[[durable_objects.bindings]]` and create it with a `new_sqlite_classes` migration.
22
+
23
+ ## Exports
24
+
25
+ ### `@cardonjs/realtime-do`
26
+ - `defineRoom<Env>(options?: RoomOptions<Env>): RoomClass<Env>`: returns the Durable Object class
27
+ to export from the Worker entry under the Wrangler `class_name`. Options (checked when it runs,
28
+ a bad value throws `TypeError`): `maxConnections` (default 1000, 1 to 32 768),
29
+ `maxConnectionsPerIdentity` (default 5, or `maxConnections` if smaller; 1 to `maxConnections`),
30
+ `maxEventBytes` (default 16 384, 256 to 1 048 576), `maxConnectionAgeSeconds` (default 3600,
31
+ 1 to 604 800), hooks `onConnect` and `onDisconnect`, which get
32
+ `{ room, identity, channels, connectedAt, connections, identityConnections, env }` (`channels`
33
+ frozen, `connectedAt` a `Date`; `connections` and `identityConnections` are the room's and this
34
+ identity's open connections after the change: `identityConnections` 1 in `onConnect` is its
35
+ first connection, 0 in `onDisconnect` means its last one closed).
36
+ - `connectToRoom(namespace, room, request, options: ConnectOptions): Promise<Response>`: opens a
37
+ socket from a route and resolves with the 101 response to return. `options` is
38
+ `{ identity, channels, allowedOrigins }`, all required. Throws `ValidationError` (400) when the
39
+ request is not a `GET` with `Upgrade: websocket`, `ForbiddenError` (403) when `Origin` is missing
40
+ or not exactly in `allowedOrigins`, `RateLimitedError` (429) when the room is full, the identity
41
+ has too many connections, or it was disconnected less than 60 s ago. Invalid arguments throw
42
+ `TypeError`.
43
+ - `realtime(namespace: DurableObjectNamespace): RealtimePublisher`: synchronous, no I/O; throws
44
+ right away when the value is not a Durable Object namespace. The publisher has
45
+ `publish(room, event): Promise<{ delivered: number }>` (0 when nobody is connected),
46
+ `count(room): Promise<number>` (open connections) and
47
+ `disconnect(room, { id, kind }): Promise<{ closed: number }>` (closes that identity's sockets in
48
+ the room with 4001 and refuses its connects there for 60 seconds) and
49
+ `presence(room, options?: PresenceOptions): Promise<Presence>`: open connections, oldest first,
50
+ as frozen `{ identity: { id, kind }, channels, connectedAt: Date, lastSeenAt: Date }`
51
+ (`lastSeenAt`: last answered `"ping"`, else `connectedAt`) plus `total` (matches before
52
+ `limit`). Options: `identity`, `channel` (both: intersection), `activeWithinSeconds` (1 to
53
+ 86 400), `limit` (default 100, 1 to 1000; it counts connections, not people). Expired and
54
+ closing sockets are not listed. `identity` narrows the listing to that identity's sockets, but
55
+ the lazy expiry that runs first may sweep every socket after a wake-up: any query is bounded by
56
+ `maxConnections`, not free.
57
+ - `validEvent(event: unknown, maxEventBytes = 16_384): RealtimeEvent`: returns a frozen, validated
58
+ copy (only `channel`, `type`, `data`); throws `TypeError` when invalid or too large.
59
+ - `assertValidRoom(room: unknown)`, `assertValidChannel(channel: unknown)`: assert a valid name,
60
+ else `TypeError`.
61
+ - `assertValidChannels(channels: unknown)`: asserts 1 to 8 valid channel names without repeats.
62
+ - Types: `ConnectOptions`, `RoomIdentity` (`{ id: string; kind: "user" | "service" }`),
63
+ `RealtimePublisher`, `Presence`, `PresenceConnection`, `PresenceOptions`, `RoomClass`,
64
+ `RoomHookContext`, `RoomOptions`, `JsonValue`,
65
+ `RealtimeEvent` (`{ channel: string; type: string; data?: JsonValue }`).
66
+
67
+ ### `@cardonjs/realtime-do/client`
68
+ - `createRealtimeClient(options: RealtimeClientOptions): RealtimeClient`: reconnecting browser
69
+ client. Required: `url` (`wss://…`, or a path resolved against `location`), `onEvent(event)`,
70
+ `onResync()` (called on every reconnect and on each fallback poll while disconnected). Optional:
71
+ `onStatus(status)`, `pollIntervalMs` (30 000; 0 disables polling), `pingIntervalMs` (25 000),
72
+ `pongTimeoutMs` (10 000), `minBackoffMs` (1000), `maxBackoffMs` (30 000), and `WebSocket` and
73
+ `random` (injectable for tests). Returns `{ status, close() }`.
74
+ - Types: `ConnectionStatus` (`"connecting" | "open" | "reconnecting" | "closed"`),
75
+ `RealtimeClientOptions`, `RealtimeClient`, `JsonValue`, `RealtimeEvent`.
76
+
77
+ ### `@cardonjs/realtime-do/testing`
78
+ - `memoryRealtime(options?: MemoryRealtimeOptions): MemoryRealtime`: test-only `RealtimePublisher`
79
+ that validates with the same rules and records calls in `published` (`{ room, event }`) and
80
+ `disconnected` (`{ room, identity: { id, kind } }`) and `presenceQueries` (`{ room, query }`,
81
+ the validated query with `limit` filled in; assert a forbidden path never queried presence, or
82
+ that the query was scoped). There are no connections: `count(room)` and
83
+ `publish`'s `delivered` return what `setCount(room, n)` set (default 0); `disconnect` resolves
84
+ with `{ closed: 0 }`. `presence(room, options?)` lists what
85
+ `setPresence(room, connections: FakeConnection[])` set (`{ identity, channels, connectedAt: Date,
86
+ lastSeenAt?: Date }`; times after `Date.now()` throw `TypeError`), with the room's validation,
87
+ filters, order and limit;
88
+ `activeWithinSeconds` is measured against `Date.now()`. `clear()` forgets the recorded calls,
89
+ counts and connections. Option: `maxEventBytes` (default 16 384).
90
+ - Types: `PublishedEvent`, `DisconnectCall`, `PresenceQueryCall`, `PresenceQuery`,
91
+ `FakeConnection`, `MemoryRealtime`, `MemoryRealtimeOptions`.
92
+
93
+ ## Minimal example
94
+
95
+ ```ts
96
+ import { getIdentity } from "@cardonjs/auth";
97
+ import { type CardonEnv, defineModule, ForbiddenError, idSchema } from "@cardonjs/core";
98
+ import { connectToRoom, defineRoom, realtime } from "@cardonjs/realtime-do";
99
+ import { createRoute, z } from "@hono/zod-openapi";
100
+
101
+ type Bindings = { BOARD_ROOMS: DurableObjectNamespace; APP_ORIGIN: string };
102
+ declare const boards: { isMember(boardId: string, userId: string): Promise<boolean> }; // yours
103
+
104
+ export const adapters = (env: Bindings) => ({ boards, live: realtime(env.BOARD_ROOMS) });
105
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
106
+
107
+ const liveRoute = createRoute({
108
+ method: "get",
109
+ path: "/{boardId}/live",
110
+ tags: ["Boards"],
111
+ summary: "Open the board's live updates (WebSocket upgrade)",
112
+ request: { params: z.object({ boardId: idSchema }) },
113
+ responses: { 101: { description: "Switching to the WebSocket protocol" } },
114
+ });
115
+
116
+ export const boardsModule = defineModule<AppEnv>({
117
+ name: "boards",
118
+ prefix: "/v1/boards",
119
+ routes: (app) => {
120
+ app.openapi(liveRoute, async (c) => {
121
+ const { boardId } = c.req.valid("param");
122
+ const identity = getIdentity(c); // the app's auth guard already ran
123
+ const member = await c.var.adapters.boards.isMember(boardId, identity.id);
124
+ if (!member) throw new ForbiddenError();
125
+ return connectToRoom(c.env.BOARD_ROOMS, `board:${boardId}`, c.req.raw, {
126
+ identity, // only id and kind reach the room
127
+ channels: ["cards"], // chosen by the server, never by the client
128
+ allowedOrigins: [c.env.APP_ORIGIN], // e.g. "https://app.example.com"
129
+ });
130
+ });
131
+ },
132
+ });
133
+
134
+ // The Durable Object class, exported under the `class_name` of the Wrangler config.
135
+ export const BoardRoom = defineRoom<Bindings>();
136
+ ```
137
+
138
+ ## Rules and common mistakes
139
+
140
+ - Authenticate and authorize the room in the route, before `connectToRoom`. `onConnect` is not a
141
+ gate: if it throws, the error is logged and the connection stays.
142
+ - Never forward a client request to the room stub (`stub.fetch(c.req.raw)` or any proxy route): the
143
+ room trusts what it receives, identity included. Only `connectToRoom` and `realtime()` call it.
144
+ - `allowedOrigins` holds exact origins (`https://host[:port]`). An empty list or `"*"` throws;
145
+ `http:` is accepted only for `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`. The check stops
146
+ cross-site WebSocket hijacking (browsers send the cookie on cross-site upgrades).
147
+ - Channels are chosen by the server, never by the client. Room and channel names match
148
+ `^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$`; event `type` matches `^[a-z0-9][a-z0-9._:-]{0,63}$`.
149
+ - Event `data` is optional and JSON only (no `undefined`, functions, non-finite numbers, cycles or
150
+ class instances). Keep it to ids; the client reloads the record through the API.
151
+ - Publish after the data is saved, in `c.executionCtx.waitUntil(...)` with a `.catch`: a failed
152
+ publish must not fail the request. Depend on the `RealtimePublisher` type, not on the binding.
153
+ - Rate limit the connect route per user with core's `rateLimit` (after the guard).
154
+ - After revoking a user's access, call `disconnect(room, { id, kind })`. `maxConnectionAgeSeconds`
155
+ makes clients come back through the route to authenticate again (close code 4000).
156
+ - Client: `wss:` is required except from an `http:` page on a local development host. Do not put a
157
+ session token or API key in the socket URL; the upgrade uses the same-site session cookie.
158
+ - Client: if `onResync` gets a 401 or 403 from your API, call `client.close()`; otherwise it keeps
159
+ retrying with backoff. Call `client.close()` when leaving the page.
160
+ - Presence returns identity ids, and `connectedAt` / `lastSeenAt` are activity data: authorize the
161
+ caller before exposing it in a route, and do not send other people's ids or times to clients
162
+ without a reason (a count or a yes/no is often enough; coarsen times when needed).
163
+ - A yes/no route (`presence(room, { identity, limit: 1 })`) is a probe unless it authorizes both
164
+ the room and the caller's right to see that specific identity; never take the target id from
165
+ the client without that check. Join/leave signals reveal timing too.
166
+ - Listing who is online: keep `kind === "user"` (services connect too and may share an id with a
167
+ user), dedupe per id, and treat `total > connections.length` as a cut list (or set `limit`).
168
+ - "Online" is `activeWithinSeconds`: the browser client pings every 25 s, so 60 is a sensible
169
+ value; a client that does not use `./client` must send the text `"ping"` to count as active.
170
+ - The framework broadcasts nothing about presence. To signal joins and leaves, publish
171
+ `{ channel: "presence", type: "presence.changed" }` (no ids) with `realtime(env.BINDING)` only
172
+ when presence changes: in `onConnect` when `identityConnections === 1`, in `onDisconnect` when
173
+ `identityConnections === 0`. Each signal makes every listening client reload through your
174
+ authorized route, so: clients debounce with jitter (one reload per burst, a few seconds later);
175
+ the presence route is rate limited per user and may cache its answer per room for a few
176
+ seconds; prefer narrow queries (`identity`, `total`). Connect/close churn still signals each
177
+ round: the connect route's rate limit is what bounds it.
178
+ - Close codes: 1008 protocol violation (client sent something other than `"ping"`; client stops),
179
+ 4000 connection past its age (client reconnects), 4001 disconnected by the server.
180
+ - `memoryRealtime()` is test-only: nothing is delivered anywhere.
181
+
182
+ ## Out of scope
183
+
184
+ - Cross-origin clients: the upgrade is authenticated by a same-site cookie; there are no tokens in
185
+ URLs and no one-time ticket yet.
186
+ - Client to server messages other than the keep-alive ping.
187
+ - Message history or replay, subscriptions after connect, binary frames, alarms.
188
+ - Presence broadcast by the framework, presence across rooms in one query, custom per-connection
189
+ metadata, closing idle connections on a timer.
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@cardonjs/realtime-do",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.3",
4
+ "description": "Real-time for Cardón apps on Cloudflare Durable Objects: a room with hibernating WebSockets, connect and publish helpers, a reconnecting browser client and an in-memory fake.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cardonjs/cardon.git",
9
+ "directory": "packages/realtime-do"
10
+ },
11
+ "homepage": "https://github.com/cardonjs/cardon/tree/main/packages/realtime-do#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cardonjs/cardon/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./client": {
23
+ "types": "./dist/client.d.ts",
24
+ "default": "./dist/client.js"
25
+ },
26
+ "./testing": {
27
+ "types": "./dist/testing.d.ts",
28
+ "default": "./dist/testing.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "llms.txt"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "peerDependencies": {
39
+ "@cardonjs/core": "^0.5.1"
40
+ },
41
+ "devDependencies": {
42
+ "@cloudflare/workers-types": "5.20261114.1",
43
+ "@hono/zod-openapi": "1.6.3",
44
+ "@scalar/hono-api-reference": "0.12.20",
45
+ "hono": "4.13.18",
46
+ "miniflare": "4.20260730.0",
47
+ "rolldown": "1.2.19",
48
+ "typescript": "7.0.2",
49
+ "vitest": "5.1.0",
50
+ "zod": "4.6.7",
51
+ "@cardonjs/auth": "0.2.6",
52
+ "@cardonjs/config": "0.0.0",
53
+ "@cardonjs/core": "0.5.1",
54
+ "@cardonjs/testing": "0.6.0"
55
+ },
56
+ "scripts": {
57
+ "build": "tsc -p tsconfig.build.json",
58
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
59
+ "test": "vitest run"
60
+ }
6
61
  }