@velajs/cloudflare 1.30.0 → 1.32.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/README.md +407 -77
  3. package/dist/bindings.js +93 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
  6. package/dist/cloudflare-application.js +15 -34
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +227 -38
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/diagnostics.js +18 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/durable-object/boot.js +76 -0
  14. package/dist/durable-object/boot.js.map +1 -0
  15. package/dist/durable-object/host-dispatch.js +134 -0
  16. package/dist/durable-object/host-dispatch.js.map +1 -0
  17. package/dist/durable-object/host-methods.js +47 -0
  18. package/dist/durable-object/host-methods.js.map +1 -0
  19. package/dist/durable-object/tokens.js +17 -0
  20. package/dist/durable-object/tokens.js.map +1 -0
  21. package/dist/durable-object/vela-durable-object.js +121 -0
  22. package/dist/durable-object/vela-durable-object.js.map +1 -0
  23. package/dist/durable-objects.d.ts +136 -10
  24. package/dist/durable-objects.js +3 -1
  25. package/dist/email/email-dispatch.js +65 -0
  26. package/dist/email/email-dispatch.js.map +1 -0
  27. package/dist/email/on-email.js +57 -0
  28. package/dist/email/on-email.js.map +1 -0
  29. package/dist/email.d.ts +51 -0
  30. package/dist/email.js +3 -0
  31. package/dist/entrypoint/vela-entrypoint.js +160 -0
  32. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  33. package/dist/entrypoints.d.ts +93 -0
  34. package/dist/entrypoints.js +2 -0
  35. package/dist/host/host-invoker.js +276 -0
  36. package/dist/host/host-invoker.js.map +1 -0
  37. package/dist/host/host-members.js +73 -0
  38. package/dist/host/host-members.js.map +1 -0
  39. package/dist/host-members-DECj_4yz.d.ts +13 -0
  40. package/dist/index.d.ts +211 -445
  41. package/dist/index.js +8 -13
  42. package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
  43. package/dist/platform.js +22 -0
  44. package/dist/platform.js.map +1 -0
  45. package/dist/queue/cloudflare-queues.js +7 -7
  46. package/dist/queue/cloudflare-queues.js.map +1 -1
  47. package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
  48. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
  49. package/dist/root-module.js +19 -0
  50. package/dist/root-module.js.map +1 -0
  51. package/dist/rpc/entrypoint-error.js +145 -0
  52. package/dist/rpc/entrypoint-error.js.map +1 -0
  53. package/dist/schedule-diagnostics.js +8 -15
  54. package/dist/schedule-diagnostics.js.map +1 -1
  55. package/dist/services/kv-cache.store.js +33 -7
  56. package/dist/services/kv-cache.store.js.map +1 -1
  57. package/dist/storage/r2-storage.js +30 -0
  58. package/dist/storage/r2-storage.js.map +1 -0
  59. package/dist/storage.d.ts +28 -0
  60. package/dist/storage.js +2 -0
  61. package/dist/tail/on-tail.js +46 -0
  62. package/dist/tail/on-tail.js.map +1 -0
  63. package/dist/tail/tail-dispatch.js +67 -0
  64. package/dist/tail/tail-dispatch.js.map +1 -0
  65. package/dist/tail.d.ts +39 -0
  66. package/dist/tail.js +2 -0
  67. package/dist/testing.d.ts +148 -0
  68. package/dist/testing.js +188 -0
  69. package/dist/testing.js.map +1 -0
  70. package/dist/websocket/binding-gateways.js +33 -0
  71. package/dist/websocket/binding-gateways.js.map +1 -0
  72. package/dist/websocket/cf-room-registry.js +3 -1
  73. package/dist/websocket/cf-room-registry.js.map +1 -1
  74. package/dist/websocket/do-bootstrap.js +64 -40
  75. package/dist/websocket/do-bootstrap.js.map +1 -1
  76. package/dist/websocket/do-live.js +49 -90
  77. package/dist/websocket/do-live.js.map +1 -1
  78. package/dist/websocket/do-state.js.map +1 -1
  79. package/dist/websocket/live-driver.js +149 -0
  80. package/dist/websocket/live-driver.js.map +1 -0
  81. package/dist/websocket/room-id.js +11 -1
  82. package/dist/websocket/room-id.js.map +1 -1
  83. package/dist/websocket/websocket.durable-object.js +51 -18
  84. package/dist/websocket/websocket.durable-object.js.map +1 -1
  85. package/dist/websocket/worker-transport.js +80 -0
  86. package/dist/websocket/worker-transport.js.map +1 -0
  87. package/dist/worker-events.js +49 -0
  88. package/dist/worker-events.js.map +1 -0
  89. package/dist/workflow/vela-workflow.js +104 -0
  90. package/dist/workflow/vela-workflow.js.map +1 -0
  91. package/dist/workflows.d.ts +82 -0
  92. package/dist/workflows.js +2 -0
  93. package/package.json +39 -6
  94. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
  95. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
  96. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
  97. package/dist/storage/r2-storage.driver.js +0 -67
  98. package/dist/storage/r2-storage.driver.js.map +0 -1
  99. package/dist/storage/storage-key-claim.js +0 -74
  100. package/dist/storage/storage-key-claim.js.map +0 -1
  101. package/dist/storage/storage-manager.service.js +0 -38
  102. package/dist/storage/storage-manager.service.js.map +0 -1
  103. package/dist/storage/storage.controller.js +0 -64
  104. package/dist/storage/storage.controller.js.map +0 -1
  105. package/dist/storage/storage.module.js +0 -25
  106. package/dist/storage/storage.module.js.map +0 -1
  107. package/dist/storage/storage.service.js +0 -64
  108. package/dist/storage/storage.service.js.map +0 -1
  109. package/dist/storage/storage.tokens.js +0 -7
  110. package/dist/storage/storage.tokens.js.map +0 -1
  111. package/dist/websocket/broadcast.js +0 -32
  112. package/dist/websocket/broadcast.js.map +0 -1
  113. package/dist/websocket/cloudflare-websocket.module.js +0 -25
  114. package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
  115. package/dist/websocket/websocket-routing.js +0 -133
  116. package/dist/websocket/websocket-routing.js.map +0 -1
  117. package/dist/websocket/ws-server-holder.js +0 -38
  118. package/dist/websocket/ws-server-holder.js.map +0 -1
@@ -1,8 +1,8 @@
1
- import { roomToDurableId } from "./room-id.js";
1
+ import { gatewayObjectRoom, roomToDurableId } from "./room-id.js";
2
+ import { CfLiveDriver } from "./live-driver.js";
2
3
  import { CfWsClient } from "./cf-ws-client.js";
3
- import { LIVE_CURSOR_LOG, LIVE_DRIVER, LiveEngine, readPersistedLiveSubscriptions } from "@velajs/vela/live";
4
+ import { LiveEngine, localLive, readPersistedLiveSubscriptions } from "@velajs/vela/live";
4
5
  //#region src/websocket/do-live.ts
5
- const DEFAULT_ROOM = "default";
6
6
  const DEFAULT_MAX_LOG_ROWS = 4096;
7
7
  /**
8
8
  * The durable `CursorLog`: an append-only tag-invalidation log in the DO's
@@ -12,23 +12,19 @@ const DEFAULT_MAX_LOG_ROWS = 4096;
12
12
  * client whose gap the log still covers gets a tiny `resume` instead of a
13
13
  * re-run — the real-resume half of the live protocol.
14
14
  *
15
- * Constructed un-initialized at module-composition time (the same app module
16
- * bootstraps in the Worker AND in each DO); `initDoLive` wires the SQLite
17
- * handle inside the DO. In the Worker isolate it stays un-initialized — and is
18
- * never consulted there, because `durableObjectLive()` routes every
19
- * invalidation to the room DO's log (one log scope per room, exactly the
20
- * protocol's model).
15
+ * The Cloudflare adapter gives `LiveModule` one inside every SQLite-backed
16
+ * WebSocket Durable Object (wrangler: `new_sqlite_classes`); a class without
17
+ * SQLite keeps an in-memory log. The Worker never consults a log: its
18
+ * invalidations go to the room Durable Object, one log scope per room, exactly
19
+ * the protocol's model.
21
20
  */
22
21
  var DoCursorLog = class {
23
- maxRows;
24
22
  sql;
23
+ maxRows;
25
24
  epoch;
26
- constructor(maxRows = DEFAULT_MAX_LOG_ROWS) {
27
- this.maxRows = maxRows;
28
- }
29
- /** @internal — called by `initDoLive` with the DO's `ctx.storage.sql`. */
30
- _initialize(sql) {
25
+ constructor(sql, maxRows = DEFAULT_MAX_LOG_ROWS) {
31
26
  this.sql = sql;
27
+ this.maxRows = maxRows;
32
28
  sql.exec("CREATE TABLE IF NOT EXISTS __vela_live_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, tags TEXT NOT NULL)");
33
29
  sql.exec("CREATE TABLE IF NOT EXISTS __vela_live_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)");
34
30
  const row = sql.exec("SELECT v FROM __vela_live_meta WHERE k = 'epoch'").toArray()[0];
@@ -39,38 +35,34 @@ var DoCursorLog = class {
39
35
  }
40
36
  }
41
37
  append(tags) {
42
- const sql = this.assertReady();
43
- sql.exec("INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)", Date.now(), JSON.stringify(tags));
38
+ this.sql.exec("INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)", Date.now(), JSON.stringify(tags));
44
39
  const stamp = this.current();
45
- if (stamp.cursor > this.maxRows) sql.exec("DELETE FROM __vela_live_log WHERE seq <= ?", stamp.cursor - this.maxRows);
40
+ if (stamp.cursor > this.maxRows) this.sql.exec("DELETE FROM __vela_live_log WHERE seq <= ?", stamp.cursor - this.maxRows);
46
41
  return stamp;
47
42
  }
48
43
  current() {
49
- const sql = this.assertReady();
50
44
  let cursor = 0;
51
45
  try {
52
- const row = sql.exec("SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'").toArray()[0];
46
+ const row = this.sql.exec("SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'").toArray()[0];
53
47
  cursor = typeof row?.seq === "number" ? row.seq : Number(row?.seq ?? 0);
54
48
  } catch {
55
49
  cursor = 0;
56
50
  }
57
- if (!this.epoch) throw new Error("DoCursorLog epoch is not initialized.");
58
51
  return {
59
52
  cursor,
60
53
  epoch: this.epoch
61
54
  };
62
55
  }
63
56
  evaluateResume(sinceCursor, sinceEpoch, subscriptionTags) {
64
- const sql = this.assertReady();
65
57
  const { cursor, epoch } = this.current();
66
58
  if (sinceEpoch !== epoch) return "snapshot";
67
59
  if (sinceCursor > cursor) return "snapshot";
68
60
  if (sinceCursor === cursor) return "resume";
69
- const minRow = sql.exec("SELECT MIN(seq) AS m FROM __vela_live_log").toArray()[0];
61
+ const minRow = this.sql.exec("SELECT MIN(seq) AS m FROM __vela_live_log").toArray()[0];
70
62
  const min = minRow?.m == null ? void 0 : Number(minRow.m);
71
63
  if (min === void 0 || min > sinceCursor + 1) return "snapshot";
72
64
  const subTags = new Set(subscriptionTags);
73
- for (const row of sql.exec("SELECT tags FROM __vela_live_log WHERE seq > ?", sinceCursor).toArray()) {
65
+ for (const row of this.sql.exec("SELECT tags FROM __vela_live_log WHERE seq > ?", sinceCursor).toArray()) {
74
66
  let tags;
75
67
  try {
76
68
  tags = JSON.parse(String(row.tags));
@@ -81,55 +73,38 @@ var DoCursorLog = class {
81
73
  }
82
74
  return "resume";
83
75
  }
84
- assertReady() {
85
- if (!this.sql) throw new Error("DoCursorLog is not initialized. It only runs inside a SQLite-backed Durable Object (wrangler: new_sqlite_classes) — Worker-side invalidations must go through durableObjectLive(), which routes them to the room DO's log.");
86
- return this.sql;
87
- }
88
76
  };
89
- /** One driver per application; construct from a LiveModule driver factory. */
90
- var CfLiveDriver = class {
91
- options;
92
- kind = "durable-object";
93
- sink;
94
- localMode = false;
95
- constructor(options) {
96
- this.options = options;
97
- }
98
- bind(sink) {
99
- this.sink = sink;
100
- }
101
- /** @internal — a DO dispatches to its own engine and SQLite log. */
102
- _setLocalMode() {
103
- this.localMode = true;
104
- }
105
- dispatch(cmd) {
106
- if (this.localMode) return this.sink?.applyInvalidation(cmd);
107
- const { namespace, gatewayPath, defaultRoom } = this.options;
108
- const room = cmd.room ?? defaultRoom ?? DEFAULT_ROOM;
109
- return namespace.get(roomToDurableId(namespace, gatewayPath, room)).invalidate({
110
- ...cmd,
111
- room
112
- });
77
+ /**
78
+ * The object's SQLite handle, or undefined when its class is not SQLite-backed.
79
+ * workerd exposes `ctx.storage.sql` on every class; without SQLite (wrangler
80
+ * `new_classes`) each statement throws, so probe with one.
81
+ */
82
+ function sqliteStorage(ctx) {
83
+ try {
84
+ const sql = ctx.storage?.sql;
85
+ sql?.exec("SELECT 1");
86
+ return sql;
87
+ } catch {
88
+ return;
113
89
  }
114
- };
115
- /** Use in LiveModule.forRootAsync: driver: () => durableObjectLive({ namespace: env.ROOMS, ... }). */
116
- function durableObjectLive(options) {
117
- return new CfLiveDriver(options);
118
90
  }
119
- /** @internal — prepare per-DO resources before user lifecycle hooks can invalidate. */
120
- function initializeDoLiveResources(container, ctx) {
121
- if (container.has(LIVE_CURSOR_LOG)) {
122
- const log = container.resolve(LIVE_CURSOR_LOG);
123
- if (log instanceof DoCursorLog) {
124
- const sql = ctx.storage?.sql;
125
- if (!sql) throw new Error("DoCursorLog requires a SQLite-backed Durable Object: add this class to wrangler's `migrations[].new_sqlite_classes`. Falling back is not possible — either enable SQLite or drop the `log: () => durableObjectCursorLog()` option (snapshot-on-reconnect semantics).");
126
- log._initialize(sql);
91
+ /**
92
+ * The live platform inside a WebSocket Durable Object: invalidations apply to
93
+ * this object's own engine (a `durableObjectLive()` driver switches to local
94
+ * delivery), and the cursor log lives in its SQLite storage when the class is
95
+ * SQLite-backed, in memory otherwise (snapshot-on-reconnect after eviction).
96
+ */
97
+ function durableObjectLivePlatform(ctx) {
98
+ return {
99
+ liveDriver: () => localLive(),
100
+ cursorLog() {
101
+ const sql = sqliteStorage(ctx);
102
+ return sql ? new DoCursorLog(sql) : void 0;
103
+ },
104
+ bindDriver(driver) {
105
+ if (driver instanceof CfLiveDriver) driver._setLocalMode();
127
106
  }
128
- }
129
- if (container.has(LIVE_DRIVER)) {
130
- const driver = container.resolve(LIVE_DRIVER);
131
- if (driver instanceof CfLiveDriver) driver._setLocalMode();
132
- }
107
+ };
133
108
  }
134
109
  /**
135
110
  * DO-side wiring after lifecycle, called from `buildDoRuntime`: replay every hibernation-persisted
@@ -150,35 +125,19 @@ function initDoLive(app, ctx, registry) {
150
125
  }
151
126
  return engine;
152
127
  }
153
- let workerLocalLiveWarned = false;
154
- /**
155
- * @internal Worker-isolate check, warned once per isolate. `localLive()` hands
156
- * invalidations to this isolate's own engine, but subscriptions are held by
157
- * the WebSocket Durable Object, so Worker-side writes would never reach them.
158
- */
159
- async function warnWorkerLocalLive(container) {
160
- if (workerLocalLiveWarned || container.getDiagnostics() === "silent") return;
161
- if (!container.has(LIVE_DRIVER)) return;
162
- if ((await container.resolveAsync(LIVE_DRIVER)).kind !== "local") return;
163
- workerLocalLiveWarned = true;
164
- console.warn("[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live in the WebSocket Durable Object, so invalidations sent from the Worker never reach them. Pass driver: () => durableObjectLive({ namespace, gatewayPath }) to LiveModule.");
165
- }
166
- /** Ergonomic alias: the log option for `LiveModule.forRoot` on Cloudflare. */
167
- function durableObjectCursorLog(maxRows) {
168
- return new DoCursorLog(maxRows);
169
- }
170
128
  /**
171
129
  * Invalidate live tags in a room from a Worker (controller / cron / queue
172
- * consumer) — the live sibling of `broadcastToRoom`. Returns the room log
173
- * scope's commit stamp for `Vela-Commit-Cursor` stamping.
130
+ * consumer) through an explicit namespace. Returns the room log scope's
131
+ * commit stamp for `Vela-Commit-Cursor` stamping. As with the live driver, a
132
+ * gateway without roomParam keeps every room in one object, named by its path.
174
133
  */
175
134
  async function liveInvalidateToRoom(ns, gatewayPath, room, tags) {
176
- return ns.get(roomToDurableId(ns, gatewayPath, room)).invalidate({
135
+ return ns.get(roomToDurableId(ns, gatewayPath, gatewayObjectRoom(gatewayPath, room))).invalidate({
177
136
  room,
178
137
  tags
179
138
  });
180
139
  }
181
140
  //#endregion
182
- export { CfLiveDriver, DoCursorLog, durableObjectCursorLog, durableObjectLive, initDoLive, initializeDoLiveResources, liveInvalidateToRoom, warnWorkerLocalLive };
141
+ export { DoCursorLog, durableObjectLivePlatform, initDoLive, liveInvalidateToRoom };
183
142
 
184
143
  //# sourceMappingURL=do-live.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"do-live.js","names":[],"sources":["../../src/websocket/do-live.ts"],"sourcesContent":["import type { CfRoomRegistry } from './cf-room-registry';\nimport type { Container } from '@velajs/vela/module-kit';\nimport {\n LIVE_CURSOR_LOG,\n LIVE_DRIVER,\n LiveEngine,\n readPersistedLiveSubscriptions,\n} from '@velajs/vela/live';\nimport type {\n CommitStamp,\n CursorLog,\n InvalidationCommand,\n LiveDriver,\n LiveInvalidationSink,\n ResumeVerdict,\n} from '@velajs/vela/live';\nimport { CfWsClient } from './cf-ws-client';\nimport type { DoStateLike, SqlStorageLike } from './do-state';\nimport { roomToDurableId } from './room-id';\n\nconst DEFAULT_ROOM = 'default';\nconst DEFAULT_MAX_LOG_ROWS = 4096;\n\n/**\n * The durable `CursorLog`: an append-only tag-invalidation log in the DO's\n * SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in\n * `__vela_live_meta`. Because the cursor survives hibernation AND trims (it is\n * read from `sqlite_sequence`, lunora's `ctx-db-cdc.ts` trick), a reconnecting\n * client whose gap the log still covers gets a tiny `resume` instead of a\n * re-run — the real-resume half of the live protocol.\n *\n * Constructed un-initialized at module-composition time (the same app module\n * bootstraps in the Worker AND in each DO); `initDoLive` wires the SQLite\n * handle inside the DO. In the Worker isolate it stays un-initialized — and is\n * never consulted there, because `durableObjectLive()` routes every\n * invalidation to the room DO's log (one log scope per room, exactly the\n * protocol's model).\n */\nexport class DoCursorLog implements CursorLog {\n private sql?: SqlStorageLike;\n private epoch?: string;\n\n constructor(private readonly maxRows = DEFAULT_MAX_LOG_ROWS) {}\n\n /** @internal — called by `initDoLive` with the DO's `ctx.storage.sql`. */\n _initialize(sql: SqlStorageLike): void {\n this.sql = sql;\n sql.exec(\n 'CREATE TABLE IF NOT EXISTS __vela_live_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, tags TEXT NOT NULL)',\n );\n sql.exec('CREATE TABLE IF NOT EXISTS __vela_live_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)');\n const row = sql.exec(\"SELECT v FROM __vela_live_meta WHERE k = 'epoch'\").toArray()[0];\n if (row && typeof row.v === 'string') {\n this.epoch = row.v;\n } else {\n this.epoch = crypto.randomUUID();\n sql.exec(\"INSERT INTO __vela_live_meta (k, v) VALUES ('epoch', ?)\", this.epoch);\n }\n }\n\n append(tags: string[]): CommitStamp {\n const sql = this.assertReady();\n sql.exec(\n 'INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)',\n Date.now(),\n JSON.stringify(tags),\n );\n const stamp = this.current();\n // Bounded retention: trimmed gaps degrade to snapshot-on-reconnect.\n if (stamp.cursor > this.maxRows) {\n sql.exec('DELETE FROM __vela_live_log WHERE seq <= ?', stamp.cursor - this.maxRows);\n }\n return stamp;\n }\n\n current(): CommitStamp {\n const sql = this.assertReady();\n // sqlite_sequence survives DELETE-based trims, so the cursor never\n // rewinds. The table itself only materializes on the first AUTOINCREMENT\n // insert — before that the log is empty and the cursor is 0.\n let cursor = 0;\n try {\n const row = sql\n .exec(\"SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'\")\n .toArray()[0];\n cursor = typeof row?.seq === 'number' ? row.seq : Number(row?.seq ?? 0);\n } catch {\n cursor = 0;\n }\n if (!this.epoch) throw new Error('DoCursorLog epoch is not initialized.');\n return { cursor, epoch: this.epoch };\n }\n\n evaluateResume(\n sinceCursor: number,\n sinceEpoch: string,\n subscriptionTags: string[],\n ): ResumeVerdict {\n const sql = this.assertReady();\n const { cursor, epoch } = this.current();\n if (sinceEpoch !== epoch) return 'snapshot'; // forked timeline (reset/recreated DO)\n if (sinceCursor > cursor) return 'snapshot'; // rollback guard\n if (sinceCursor === cursor) return 'resume';\n\n const minRow = sql.exec('SELECT MIN(seq) AS m FROM __vela_live_log').toArray()[0];\n const min = minRow?.m == null ? undefined : Number(minRow.m);\n // The log must still cover (sinceCursor, cursor] — a trimmed gap cannot be reasoned about.\n if (min === undefined || min > sinceCursor + 1) return 'snapshot';\n\n const subTags = new Set(subscriptionTags);\n for (const row of sql\n .exec('SELECT tags FROM __vela_live_log WHERE seq > ?', sinceCursor)\n .toArray()) {\n let tags: unknown;\n try {\n tags = JSON.parse(String(row.tags));\n } catch {\n return 'snapshot';\n }\n if (\n Array.isArray(tags) &&\n tags.some((tag: unknown) => typeof tag === 'string' && subTags.has(tag))\n )\n return 'rerun';\n }\n return 'resume';\n }\n\n private assertReady(): SqlStorageLike {\n if (!this.sql) {\n throw new Error(\n 'DoCursorLog is not initialized. It only runs inside a SQLite-backed Durable Object ' +\n '(wrangler: new_sqlite_classes) — Worker-side invalidations must go through durableObjectLive(), ' +\n \"which routes them to the room DO's log.\",\n );\n }\n return this.sql;\n }\n}\n\nexport interface DurableObjectLiveOptions {\n /** Native, RPC-typed namespace supplied by the application's environment. */\n namespace: LiveNamespace;\n /** Exact `@WebSocketGateway()` path sharing this room/log namespace. */\n gatewayPath: string;\n /** Room used when an invalidation names none. Matches the client default. */\n defaultRoom?: string;\n}\n\nexport interface LiveInvalidateStub {\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n}\n\n/** Only the native namespace operations required for live invalidation. */\nexport interface LiveNamespace {\n idFromName(name: string): DurableObjectId;\n get(id: DurableObjectId): LiveInvalidateStub;\n}\n\n/** One driver per application; construct from a LiveModule driver factory. */\nexport class CfLiveDriver implements LiveDriver {\n readonly kind = 'durable-object';\n private sink: LiveInvalidationSink | undefined;\n private localMode = false;\n\n constructor(private readonly options: DurableObjectLiveOptions) {}\n\n bind(sink: LiveInvalidationSink): void {\n this.sink = sink;\n }\n\n /** @internal — a DO dispatches to its own engine and SQLite log. */\n _setLocalMode(): void {\n this.localMode = true;\n }\n\n dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined {\n if (this.localMode) return this.sink?.applyInvalidation(cmd);\n const { namespace, gatewayPath, defaultRoom } = this.options;\n const room = cmd.room ?? defaultRoom ?? DEFAULT_ROOM;\n return namespace\n .get(roomToDurableId(namespace, gatewayPath, room))\n .invalidate({ ...cmd, room });\n }\n}\n\n/** Use in LiveModule.forRootAsync: driver: () => durableObjectLive({ namespace: env.ROOMS, ... }). */\nexport function durableObjectLive(options: DurableObjectLiveOptions): CfLiveDriver {\n return new CfLiveDriver(options);\n}\n\n/** The app-facing surface of the engine reached through `app.entrypoints.ofKind('live')`. */\ninterface EntrypointsApp {\n entrypoints: { ofKind(kind: string): Array<{ meta: unknown }> };\n}\n\n/** @internal — prepare per-DO resources before user lifecycle hooks can invalidate. */\nexport function initializeDoLiveResources(container: Container, ctx: DoStateLike): void {\n if (container.has(LIVE_CURSOR_LOG)) {\n const log = container.resolve(LIVE_CURSOR_LOG);\n if (log instanceof DoCursorLog) {\n const sql = ctx.storage?.sql;\n if (!sql) {\n throw new Error(\n 'DoCursorLog requires a SQLite-backed Durable Object: add this class to ' +\n \"wrangler's `migrations[].new_sqlite_classes`. Falling back is not possible — \" +\n 'either enable SQLite or drop the `log: () => durableObjectCursorLog()` option ' +\n '(snapshot-on-reconnect semantics).',\n );\n }\n log._initialize(sql);\n }\n }\n\n if (container.has(LIVE_DRIVER)) {\n const driver = container.resolve(LIVE_DRIVER);\n if (driver instanceof CfLiveDriver) driver._setLocalMode();\n }\n}\n\n/**\n * DO-side wiring after lifecycle, called from `buildDoRuntime`: replay every hibernation-persisted\n * subscription into the (fresh) engine so an eviction is invisible to\n * subscribers. Returns the engine for the `invalidate` RPC, or undefined when\n * the app doesn't use LiveModule.\n */\nexport function initDoLive(\n app: EntrypointsApp,\n ctx: DoStateLike,\n registry?: CfRoomRegistry,\n): LiveEngine | undefined {\n const entry = app.entrypoints.ofKind('live')[0];\n if (!entry) return undefined;\n if (typeof entry.meta !== 'object' || entry.meta === null || !('engine' in entry.meta)) {\n throw new Error('Invalid live entrypoint metadata.');\n }\n const engine = entry.meta.engine;\n if (!(engine instanceof LiveEngine)) throw new Error('Invalid live entrypoint engine.');\n\n // Wake-time replay: subscriptions ride the hibernation attachments.\n for (const ws of ctx.getWebSockets()) {\n const client = registry?.clientFor(ws) ?? new CfWsClient(ctx, ws);\n if (!client.id) continue;\n for (const record of readPersistedLiveSubscriptions(client)) {\n engine.restoreSubscription(client.path, client, record);\n }\n }\n\n return engine;\n}\n\nlet workerLocalLiveWarned = false;\n\n/**\n * @internal Worker-isolate check, warned once per isolate. `localLive()` hands\n * invalidations to this isolate's own engine, but subscriptions are held by\n * the WebSocket Durable Object, so Worker-side writes would never reach them.\n */\nexport async function warnWorkerLocalLive(container: Container): Promise<void> {\n if (workerLocalLiveWarned || container.getDiagnostics() === 'silent') return;\n if (!container.has(LIVE_DRIVER)) return;\n const driver = await container.resolveAsync(LIVE_DRIVER);\n if (driver.kind !== 'local') return;\n workerLocalLiveWarned = true;\n console.warn(\n '[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live in ' +\n 'the WebSocket Durable Object, so invalidations sent from the Worker never reach them. ' +\n 'Pass driver: () => durableObjectLive({ namespace, gatewayPath }) to LiveModule.',\n );\n}\n\n/** Ergonomic alias: the log option for `LiveModule.forRoot` on Cloudflare. */\nexport function durableObjectCursorLog(maxRows?: number): DoCursorLog {\n return new DoCursorLog(maxRows);\n}\n\n/**\n * Invalidate live tags in a room from a Worker (controller / cron / queue\n * consumer) — the live sibling of `broadcastToRoom`. Returns the room log\n * scope's commit stamp for `Vela-Commit-Cursor` stamping.\n */\nexport async function liveInvalidateToRoom(\n ns: LiveNamespace,\n gatewayPath: string,\n room: string,\n tags: string[],\n): Promise<CommitStamp | undefined> {\n const stub = ns.get(roomToDurableId(ns, gatewayPath, room));\n return stub.invalidate({ room, tags });\n}\n"],"mappings":";;;;AAoBA,MAAM,eAAe;AACrB,MAAM,uBAAuB;;;;;;;;;;;;;;;;AAiB7B,IAAa,cAAb,MAA8C;CAIf;CAH7B;CACA;CAEA,YAAY,UAA2B,sBAAsB;EAAhC,KAAA,UAAA;CAAiC;;CAG9D,YAAY,KAA2B;EACrC,KAAK,MAAM;EACX,IAAI,KACF,0HACF;EACA,IAA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{ CfRoomRegistry } from './cf-room-registry';\nimport { LiveEngine, localLive, readPersistedLiveSubscriptions } from '@velajs/vela/live';\nimport type { CommitStamp, CursorLog, LivePlatform, ResumeVerdict } from '@velajs/vela/live';\nimport { CfWsClient } from './cf-ws-client';\nimport type { DoStateLike, SqlStorageLike } from './do-state';\nimport { CfLiveDriver, type LiveNamespace } from './live-driver';\nimport { gatewayObjectRoom, roomToDurableId } from './room-id';\n\nconst DEFAULT_MAX_LOG_ROWS = 4096;\n\n/**\n * The durable `CursorLog`: an append-only tag-invalidation log in the DO's\n * SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in\n * `__vela_live_meta`. Because the cursor survives hibernation AND trims (it is\n * read from `sqlite_sequence`, lunora's `ctx-db-cdc.ts` trick), a reconnecting\n * client whose gap the log still covers gets a tiny `resume` instead of a\n * re-run — the real-resume half of the live protocol.\n *\n * The Cloudflare adapter gives `LiveModule` one inside every SQLite-backed\n * WebSocket Durable Object (wrangler: `new_sqlite_classes`); a class without\n * SQLite keeps an in-memory log. The Worker never consults a log: its\n * invalidations go to the room Durable Object, one log scope per room, exactly\n * the protocol's model.\n */\nexport class DoCursorLog implements CursorLog {\n private readonly epoch: string;\n\n constructor(\n private readonly sql: SqlStorageLike,\n private readonly maxRows = DEFAULT_MAX_LOG_ROWS,\n ) {\n sql.exec(\n 'CREATE TABLE IF NOT EXISTS __vela_live_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, tags TEXT NOT NULL)',\n );\n sql.exec('CREATE TABLE IF NOT EXISTS __vela_live_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)');\n const row = sql.exec(\"SELECT v FROM __vela_live_meta WHERE k = 'epoch'\").toArray()[0];\n if (row && typeof row.v === 'string') {\n this.epoch = row.v;\n } else {\n this.epoch = crypto.randomUUID();\n sql.exec(\"INSERT INTO __vela_live_meta (k, v) VALUES ('epoch', ?)\", this.epoch);\n }\n }\n\n append(tags: string[]): CommitStamp {\n this.sql.exec(\n 'INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)',\n Date.now(),\n JSON.stringify(tags),\n );\n const stamp = this.current();\n // Bounded retention: trimmed gaps degrade to snapshot-on-reconnect.\n if (stamp.cursor > this.maxRows) {\n this.sql.exec('DELETE FROM __vela_live_log WHERE seq <= ?', stamp.cursor - this.maxRows);\n }\n return stamp;\n }\n\n current(): CommitStamp {\n // sqlite_sequence survives DELETE-based trims, so the cursor never\n // rewinds. The table itself only materializes on the first AUTOINCREMENT\n // insert — before that the log is empty and the cursor is 0.\n let cursor = 0;\n try {\n const row = this.sql\n .exec(\"SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'\")\n .toArray()[0];\n cursor = typeof row?.seq === 'number' ? row.seq : Number(row?.seq ?? 0);\n } catch {\n cursor = 0;\n }\n return { cursor, epoch: this.epoch };\n }\n\n evaluateResume(\n sinceCursor: number,\n sinceEpoch: string,\n subscriptionTags: string[],\n ): ResumeVerdict {\n const { cursor, epoch } = this.current();\n if (sinceEpoch !== epoch) return 'snapshot'; // forked timeline (reset/recreated DO)\n if (sinceCursor > cursor) return 'snapshot'; // rollback guard\n if (sinceCursor === cursor) return 'resume';\n\n const minRow = this.sql.exec('SELECT MIN(seq) AS m FROM __vela_live_log').toArray()[0];\n const min = minRow?.m == null ? undefined : Number(minRow.m);\n // The log must still cover (sinceCursor, cursor] — a trimmed gap cannot be reasoned about.\n if (min === undefined || min > sinceCursor + 1) return 'snapshot';\n\n const subTags = new Set(subscriptionTags);\n for (const row of this.sql\n .exec('SELECT tags FROM __vela_live_log WHERE seq > ?', sinceCursor)\n .toArray()) {\n let tags: unknown;\n try {\n tags = JSON.parse(String(row.tags));\n } catch {\n return 'snapshot';\n }\n if (\n Array.isArray(tags) &&\n tags.some((tag: unknown) => typeof tag === 'string' && subTags.has(tag))\n )\n return 'rerun';\n }\n return 'resume';\n }\n}\n\n/**\n * The object's SQLite handle, or undefined when its class is not SQLite-backed.\n * workerd exposes `ctx.storage.sql` on every class; without SQLite (wrangler\n * `new_classes`) each statement throws, so probe with one.\n */\nfunction sqliteStorage(ctx: DoStateLike): SqlStorageLike | undefined {\n try {\n const sql = ctx.storage?.sql;\n sql?.exec('SELECT 1');\n return sql;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The live platform inside a WebSocket Durable Object: invalidations apply to\n * this object's own engine (a `durableObjectLive()` driver switches to local\n * delivery), and the cursor log lives in its SQLite storage when the class is\n * SQLite-backed, in memory otherwise (snapshot-on-reconnect after eviction).\n */\nexport function durableObjectLivePlatform(ctx: DoStateLike): LivePlatform {\n return {\n liveDriver: () => localLive(),\n cursorLog() {\n const sql = sqliteStorage(ctx);\n return sql ? new DoCursorLog(sql) : undefined;\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) driver._setLocalMode();\n },\n };\n}\n\n/** The app-facing surface of the engine reached through `app.entrypoints.ofKind('live')`. */\ninterface EntrypointsApp {\n entrypoints: { ofKind(kind: string): Array<{ meta: unknown }> };\n}\n\n/**\n * DO-side wiring after lifecycle, called from `buildDoRuntime`: replay every hibernation-persisted\n * subscription into the (fresh) engine so an eviction is invisible to\n * subscribers. Returns the engine for the `invalidate` RPC, or undefined when\n * the app doesn't use LiveModule.\n */\nexport function initDoLive(\n app: EntrypointsApp,\n ctx: DoStateLike,\n registry?: CfRoomRegistry,\n): LiveEngine | undefined {\n const entry = app.entrypoints.ofKind('live')[0];\n if (!entry) return undefined;\n if (typeof entry.meta !== 'object' || entry.meta === null || !('engine' in entry.meta)) {\n throw new Error('Invalid live entrypoint metadata.');\n }\n const engine = entry.meta.engine;\n if (!(engine instanceof LiveEngine)) throw new Error('Invalid live entrypoint engine.');\n\n // Wake-time replay: subscriptions ride the hibernation attachments.\n for (const ws of ctx.getWebSockets()) {\n const client = registry?.clientFor(ws) ?? new CfWsClient(ctx, ws);\n if (!client.id) continue;\n for (const record of readPersistedLiveSubscriptions(client)) {\n engine.restoreSubscription(client.path, client, record);\n }\n }\n\n return engine;\n}\n\n/**\n * Invalidate live tags in a room from a Worker (controller / cron / queue\n * consumer) through an explicit namespace. Returns the room log scope's\n * commit stamp for `Vela-Commit-Cursor` stamping. As with the live driver, a\n * gateway without roomParam keeps every room in one object, named by its path.\n */\nexport async function liveInvalidateToRoom(\n ns: LiveNamespace,\n gatewayPath: string,\n room: string,\n tags: string[],\n): Promise<CommitStamp | undefined> {\n const stub = ns.get(roomToDurableId(ns, gatewayPath, gatewayObjectRoom(gatewayPath, room)));\n return stub.invalidate({ room, tags });\n}\n"],"mappings":";;;;;AAQA,MAAM,uBAAuB;;;;;;;;;;;;;;;AAgB7B,IAAa,cAAb,MAA8C;CAIzB;CACA;CAJnB;CAEA,YACE,KACA,UAA2B,sBAC3B;EAFiB,KAAA,MAAA;EACA,KAAA,UAAA;EAEjB,IAAI,KACF,0HACF;EACA,IAAI,KAAK,mFAAmF;EAC5F,MAAM,MAAM,IAAI,KAAK,kDAAkD,CAAC,CAAC,QAAQ,CAAC,CAAC;EACnF,IAAI,OAAO,OAAO,IAAI,MAAM,UAC1B,KAAK,QAAQ,IAAI;OACZ;GACL,KAAK,QAAQ,OAAO,WAAW;GAC/B,IAAI,KAAK,2DAA2D,KAAK,KAAK;EAChF;CACF;CAEA,OAAO,MAA6B;EAClC,KAAK,IAAI,KACP,wDACA,KAAK,IAAI,GACT,KAAK,UAAU,IAAI,CACrB;EACA,MAAM,QAAQ,KAAK,QAAQ;EAE3B,IAAI,MAAM,SAAS,KAAK,SACtB,KAAK,IAAI,KAAK,8CAA8C,MAAM,SAAS,KAAK,OAAO;EAEzF,OAAO;CACT;CAEA,UAAuB;EAIrB,IAAI,SAAS;EACb,IAAI;GACF,MAAM,MAAM,KAAK,IACd,KAAK,gEAAgE,CAAC,CACtE,QAAQ,CAAC,CAAC;GACb,SAAS,OAAO,KAAK,QAAQ,WAAW,IAAI,MAAM,OAAO,KAAK,OAAO,CAAC;EACxE,QAAQ;GACN,SAAS;EACX;EACA,OAAO;GAAE;GAAQ,O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AC,OAAO,OAAO,KAAA;CACnB,IAAI,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,QAAQ,EAAE,YAAY,MAAM,OAC/E,MAAM,IAAI,MAAM,mCAAmC;CAErD,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,EAAE,kBAAkB,aAAa,MAAM,IAAI,MAAM,iCAAiC;CAGtF,KAAK,MAAM,MAAM,IAAI,cAAc,GAAG;EACpC,MAAM,SAAS,UAAU,UAAU,EAAE,KAAK,IAAI,WAAW,KAAK,EAAE;EAChE,IAAI,CAAC,OAAO,IAAI;EAChB,KAAK,MAAM,UAAU,+BAA+B,MAAM,GACxD,OAAO,oBAAoB,OAAO,MAAM,QAAQ,MAAM;CAE1D;CAEA,OAAO;AACT;;;;;;;AAQA,eAAsB,qBACpB,IACA,aACA,MACA,MACkC;CAElC,OADa,GAAG,IAAI,gBAAgB,IAAI,aAAa,kBAAkB,aAAa,IAAI,CAAC,CAC/E,CAAC,CAAC,WAAW;EAAE;EAAM;CAAK,CAAC;AACvC"}
@@ -1 +1 @@
1
- {"version":3,"file":"do-state.js","names":[],"sources":["../../src/websocket/do-state.ts"],"sourcesContent":["// Minimal structural views of the Durable Object runtime, so the transport\n// logic is unit-testable in Node with fakes. Real `DurableObjectState` and\n// `WebSocket` (from @cloudflare/workers-types) satisfy these structurally.\n\n/** Cloudflare's serialized WebSocket hibernation attachment ceiling. */\nexport const MAX_WS_ATTACHMENT_BYTES = 16_384;\n\nexport interface WsLike {\n readonly readyState?: number;\n readonly bufferedAmount?: number;\n send(message: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n serializeAttachment(value: unknown): void;\n deserializeAttachment(): unknown;\n}\n\n/** Structural view of the DO's SQLite handle (`ctx.storage.sql`, requires `new_sqlite_classes`). */\nexport interface SqlStorageLike {\n exec(query: string, ...bindings: unknown[]): { toArray(): Record<string, unknown>[] };\n}\n\nexport interface DoStateLike {\n readonly id: { toString(): string; readonly name?: string | null };\n acceptWebSocket(ws: WsLike, tags?: string[]): void;\n getWebSockets(tag?: string): WsLike[];\n setWebSocketAutoResponse?(pair: unknown): void;\n /** Present on SQLite-backed DOs — the live cursor log lives here. */\n readonly storage?: { sql?: SqlStorageLike };\n}\n\n/** Per-connection metadata persisted in the hibernation attachment (≤ 16 KiB). */\nexport interface WsAttachment {\n /** Absent on 1.x attachments created before versioned validation. */\n version?: 1;\n connId: string;\n /** Only active sockets may dispatch frames or receive fan-out. */\n state: 'pending' | 'active' | 'rejected';\n userId?: string;\n /** Verified, issuer-qualified connection principal. */\n principal?: {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n };\n /** Trusted server-derived tenant boundary for this connection. */\n tenantId?: string;\n /** Verified auth credential expiry in epoch milliseconds. */\n expiresAtMs?: number;\n /** The gateway route path this socket belongs to — used to route messages. */\n path: string;\n /** Validated inbound/outbound gateway frame ceiling, persisted across hibernation. */\n maxFrameBytes?: number;\n /** Dynamically-joined room names (the hub room is also a hibernation tag). */\n rooms: string[];\n data: Record<string, unknown>;\n}\n"],"mappings":";;AAKA,MAAa,0BAA0B"}
1
+ {"version":3,"file":"do-state.js","names":[],"sources":["../../src/websocket/do-state.ts"],"sourcesContent":["// Minimal structural views of the Durable Object runtime, so the transport\n// logic is unit-testable in Node with fakes. Real `DurableObjectState` and\n// `WebSocket` (from @cloudflare/workers-types) satisfy these structurally.\n\n/** Cloudflare's serialized WebSocket hibernation attachment ceiling. */\nexport const MAX_WS_ATTACHMENT_BYTES = 16_384;\n\nexport interface WsLike {\n readonly readyState?: number;\n readonly bufferedAmount?: number;\n send(message: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n serializeAttachment(value: unknown): void;\n deserializeAttachment(): unknown;\n}\n\n/** Structural view of the DO's SQLite handle (`ctx.storage.sql`, requires `new_sqlite_classes`). */\nexport interface SqlStorageLike {\n exec(query: string, ...bindings: unknown[]): { toArray(): Record<string, unknown>[] };\n}\n\nexport interface DoStateLike {\n readonly id: { toString(): string; readonly name?: string | null };\n acceptWebSocket(ws: WsLike, tags?: string[]): void;\n getWebSockets(tag?: string): WsLike[];\n setWebSocketAutoResponse?(pair: unknown): void;\n /**\n * workerd exposes `sql` on every class, but its statements throw unless the\n * class is SQLite-backed (`new_sqlite_classes`), where the live cursor log lives.\n */\n readonly storage?: { sql?: SqlStorageLike };\n}\n\n/** Per-connection metadata persisted in the hibernation attachment (≤ 16 KiB). */\nexport interface WsAttachment {\n /** Absent on 1.x attachments created before versioned validation. */\n version?: 1;\n connId: string;\n /** Only active sockets may dispatch frames or receive fan-out. */\n state: 'pending' | 'active' | 'rejected';\n userId?: string;\n /** Verified, issuer-qualified connection principal. */\n principal?: {\n issuer: string;\n subject: string;\n principalType: 'user' | 'service';\n };\n /** Trusted server-derived tenant boundary for this connection. */\n tenantId?: string;\n /** Verified auth credential expiry in epoch milliseconds. */\n expiresAtMs?: number;\n /** The gateway route path this socket belongs to — used to route messages. */\n path: string;\n /** Validated inbound/outbound gateway frame ceiling, persisted across hibernation. */\n maxFrameBytes?: number;\n /** Dynamically-joined room names (the hub room is also a hibernation tag). */\n rooms: string[];\n data: Record<string, unknown>;\n}\n"],"mappings":";;AAKA,MAAa,0BAA0B"}
@@ -0,0 +1,149 @@
1
+ import { gatewayObjectRoom } from "./room-id.js";
2
+ import { bindingGateways } from "./binding-gateways.js";
3
+ import { gatewayRoomObject } from "./worker-transport.js";
4
+ import { DiscoveryService } from "@velajs/vela/module-kit";
5
+ //#region src/websocket/live-driver.ts
6
+ const DEFAULT_ROOM = "default";
7
+ function describeFilter({ binding, gatewayPath }) {
8
+ return [...binding === void 0 ? [] : [`binding '${binding}'`], ...gatewayPath === void 0 ? [] : [`path '${gatewayPath}'`]].join(" and ");
9
+ }
10
+ /** A commit stamp a room object returned, validated before it reaches headers. */
11
+ function commitStamp(value) {
12
+ if (value === void 0) return void 0;
13
+ const cursor = typeof value === "object" && value !== null ? Reflect.get(value, "cursor") : void 0;
14
+ const epoch = typeof value === "object" && value !== null ? Reflect.get(value, "epoch") : void 0;
15
+ if (typeof cursor !== "number" || typeof epoch !== "string") throw new Error("Durable Object invalidate() returned an invalid commit stamp");
16
+ return {
17
+ cursor,
18
+ epoch
19
+ };
20
+ }
21
+ /**
22
+ * Delivers live invalidations to the room Durable Object of a
23
+ * `@WebSocketGateway({ binding })`, whose SQLite log stamps the commit. Inside
24
+ * that Durable Object the same driver applies invalidations locally.
25
+ */
26
+ var CfLiveDriver = class {
27
+ options;
28
+ kind = "durable-object";
29
+ #sink;
30
+ #local = false;
31
+ #context;
32
+ #target;
33
+ constructor(options = {}) {
34
+ this.options = options;
35
+ }
36
+ bind(sink) {
37
+ this.#sink = sink;
38
+ }
39
+ /** @internal The Worker's live platform supplies its environment and gateways. */
40
+ _attach(context) {
41
+ this.#context = context;
42
+ this.#target = void 0;
43
+ }
44
+ /** @internal A Durable Object dispatches to its own engine and SQLite log. */
45
+ _setLocalMode() {
46
+ this.#local = true;
47
+ }
48
+ /**
49
+ * @internal The Durable Object that holds one room's subscriptions. As for
50
+ * upgrades and `Gateways` pushes, a gateway without `roomParam` keeps every
51
+ * socket in one room, its path, so each of its rooms is in that object.
52
+ */
53
+ _room(room) {
54
+ const { env, binding, gatewayPath } = this.#resolveTarget();
55
+ return gatewayRoomObject(env, gatewayPath, binding, gatewayObjectRoom(gatewayPath, room));
56
+ }
57
+ dispatch(cmd) {
58
+ if (this.#local) return this.#sink?.applyInvalidation(cmd);
59
+ const room = cmd.room ?? this.options.defaultRoom ?? DEFAULT_ROOM;
60
+ return this._room(room).call("invalidate", {
61
+ ...cmd,
62
+ room
63
+ }).then(commitStamp);
64
+ }
65
+ #resolveTarget() {
66
+ if (this.#target) return this.#target;
67
+ const context = this.#context;
68
+ if (!context) throw new Error("durableObjectLive() needs the Cloudflare adapter: create the application with createCloudflareWorker(), createCloudflareApp() or cloudflareAdapter().");
69
+ let { binding, gatewayPath } = this.options;
70
+ const gateways = context.gateways();
71
+ if (binding === void 0 || gatewayPath === void 0) {
72
+ const candidates = gateways.filter((gateway) => (binding === void 0 || gateway.binding === binding) && (gatewayPath === void 0 || gateway.path === gatewayPath));
73
+ const [chosen, ...others] = candidates;
74
+ if (!chosen) {
75
+ const filter = describeFilter(this.options);
76
+ throw new Error(filter ? `durableObjectLive() found no @WebSocketGateway with ${filter}. Name the gateway that holds the subscriptions, with its binding.` : "LiveModule delivers Worker invalidations to the room Durable Object of a gateway, but no @WebSocketGateway names a binding. Declare one with { binding }, or pass driver: () => durableObjectLive({ binding, gatewayPath }).");
77
+ }
78
+ if (others.length > 0) {
79
+ const paths = candidates.map((gateway) => `'${gateway.path}'`).join(", ");
80
+ throw new Error(`LiveModule must choose where Worker invalidations go, but several binding-backed gateways (${paths}) could hold the subscriptions. Pass driver: () => durableObjectLive({ gatewayPath }) to LiveModule.`);
81
+ }
82
+ binding ??= chosen.binding;
83
+ gatewayPath ??= chosen.path;
84
+ }
85
+ const target = {
86
+ env: context.env,
87
+ binding,
88
+ gatewayPath
89
+ };
90
+ this.#target = target;
91
+ return target;
92
+ }
93
+ };
94
+ /**
95
+ * The Cloudflare live driver, for `LiveModule.forRoot({ driver })`. It is the
96
+ * default on Cloudflare, so name it only to choose a gateway, binding or
97
+ * default room:
98
+ *
99
+ * ```ts
100
+ * LiveModule.forRoot({ driver: () => durableObjectLive({ gatewayPath: '/rooms/:id/ws' }) })
101
+ * ```
102
+ */
103
+ function durableObjectLive(options = {}) {
104
+ return new CfLiveDriver(options);
105
+ }
106
+ let workerLocalLiveWarned = false;
107
+ /**
108
+ * The Worker isolate's live platform: invalidations default to the room
109
+ * Durable Object of the application's binding-backed gateway, chosen and read
110
+ * from `ENV` when first needed, and `LiveInspector` reads each room from that
111
+ * object. A configured local driver is warned about once per isolate:
112
+ * subscriptions live in the Durable Object, so it would reach none.
113
+ */
114
+ function workerLivePlatform(env, container) {
115
+ const context = {
116
+ env,
117
+ gateways: () => bindingGateways(container.resolve(DiscoveryService))
118
+ };
119
+ let bound;
120
+ return {
121
+ liveDriver: () => durableObjectLive(),
122
+ async inspect(room) {
123
+ if (!bound) throw new Error("LiveModule delivers locally in this Worker: no room to inspect");
124
+ const value = await bound._room(room).call("inspectLive");
125
+ const subscriptions = typeof value === "object" && value !== null ? Reflect.get(value, "subscriptions") : void 0;
126
+ const rooms = typeof value === "object" && value !== null ? Reflect.get(value, "rooms") : void 0;
127
+ if (!Array.isArray(subscriptions) || !Array.isArray(rooms)) throw new Error("Durable Object inspectLive() returned an invalid snapshot");
128
+ return {
129
+ subscriptions,
130
+ rooms
131
+ };
132
+ },
133
+ bindDriver(driver) {
134
+ if (driver instanceof CfLiveDriver) {
135
+ driver._attach(context);
136
+ bound = driver;
137
+ return;
138
+ }
139
+ if (driver.kind !== "local" || workerLocalLiveWarned) return;
140
+ if (container.getDiagnostics() === "silent") return;
141
+ workerLocalLiveWarned = true;
142
+ console.warn("[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live in the WebSocket Durable Object, so invalidations sent from the Worker never reach them. Remove the driver option to deliver through the gateway room Durable Object.");
143
+ }
144
+ };
145
+ }
146
+ //#endregion
147
+ export { CfLiveDriver, durableObjectLive, workerLivePlatform };
148
+
149
+ //# sourceMappingURL=live-driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-driver.js","names":[],"sources":["../../src/websocket/live-driver.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport { DiscoveryService, type Container } from '@velajs/vela/module-kit';\nimport type {\n CommitStamp,\n InvalidationCommand,\n LiveDriver,\n LiveInvalidationSink,\n LivePlatform,\n} from '@velajs/vela/live';\nimport { bindingGateways, type BindingGateway } from './binding-gateways';\nimport { gatewayObjectRoom } from './room-id';\nimport { gatewayRoomObject, type GatewayRoomObject } from './worker-transport';\n\nconst DEFAULT_ROOM = 'default';\n\nexport interface DurableObjectLiveOptions {\n /**\n * Durable Object namespace binding that holds the gateway's rooms, read from\n * the application's `ENV` when an invalidation first needs it. Defaults to\n * the `binding` of the chosen gateway.\n */\n binding?: string;\n /**\n * Exact `@WebSocketGateway()` path whose rooms hold the subscriptions.\n * Defaults to the single gateway backed by `binding` (or by any binding).\n */\n gatewayPath?: string;\n /**\n * Room used when an invalidation names none. Matches the client default. A\n * gateway without `roomParam` has one room, its path, which every\n * invalidation reaches.\n */\n defaultRoom?: string;\n}\n\nexport interface LiveInvalidateStub {\n invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;\n}\n\n/** Only the native namespace operations required for live invalidation. */\nexport interface LiveNamespace {\n idFromName(name: string): DurableObjectId;\n get(id: DurableObjectId): LiveInvalidateStub;\n}\n\n/** @internal What the Worker's live platform hands a driver. */\ninterface WorkerLiveContext {\n env: VelaEnv;\n gateways(): readonly Pick<BindingGateway, 'path' | 'binding'>[];\n}\n\n/** Where the Worker delivers invalidations: one gateway's room objects. */\ninterface LiveTarget {\n env: VelaEnv;\n binding: string;\n gatewayPath: string;\n}\n\nfunction describeFilter({ binding, gatewayPath }: DurableObjectLiveOptions): string {\n const parts = [\n ...(binding === undefined ? [] : [`binding '${binding}'`]),\n ...(gatewayPath === undefined ? [] : [`path '${gatewayPath}'`]),\n ];\n return parts.join(' and ');\n}\n\n/** A commit stamp a room object returned, validated before it reaches headers. */\nfunction commitStamp(value: unknown): CommitStamp | undefined {\n if (value === undefined) return undefined;\n const cursor: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'cursor') : undefined;\n const epoch: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'epoch') : undefined;\n if (typeof cursor !== 'number' || typeof epoch !== 'string') {\n throw new Error('Durable Object invalidate() returned an invalid commit stamp');\n }\n return { cursor, epoch };\n}\n\n/**\n * Delivers live invalidations to the room Durable Object of a\n * `@WebSocketGateway({ binding })`, whose SQLite log stamps the commit. Inside\n * that Durable Object the same driver applies invalidations locally.\n */\nexport class CfLiveDriver implements LiveDriver {\n readonly kind = 'durable-object';\n #sink: LiveInvalidationSink | undefined;\n #local = false;\n #context: WorkerLiveContext | undefined;\n #target: LiveTarget | undefined;\n\n constructor(private readonly options: DurableObjectLiveOptions = {}) {}\n\n bind(sink: LiveInvalidationSink): void {\n this.#sink = sink;\n }\n\n /** @internal The Worker's live platform supplies its environment and gateways. */\n _attach(context: WorkerLiveContext): void {\n this.#context = context;\n this.#target = undefined;\n }\n\n /** @internal A Durable Object dispatches to its own engine and SQLite log. */\n _setLocalMode(): void {\n this.#local = true;\n }\n\n /**\n * @internal The Durable Object that holds one room's subscriptions. As for\n * upgrades and `Gateways` pushes, a gateway without `roomParam` keeps every\n * socket in one room, its path, so each of its rooms is in that object.\n */\n _room(room: string): GatewayRoomObject {\n const { env, binding, gatewayPath } = this.#resolveTarget();\n return gatewayRoomObject(env, gatewayPath, binding, gatewayObjectRoom(gatewayPath, room));\n }\n\n dispatch(cmd: InvalidationCommand): Promise<CommitStamp | undefined> | CommitStamp | undefined {\n if (this.#local) return this.#sink?.applyInvalidation(cmd);\n const room = cmd.room ?? this.options.defaultRoom ?? DEFAULT_ROOM;\n return this._room(room)\n .call('invalidate', { ...cmd, room })\n .then(commitStamp);\n }\n\n #resolveTarget(): LiveTarget {\n if (this.#target) return this.#target;\n const context = this.#context;\n if (!context) {\n throw new Error(\n 'durableObjectLive() needs the Cloudflare adapter: create the application with ' +\n 'createCloudflareWorker(), createCloudflareApp() or cloudflareAdapter().',\n );\n }\n let { binding, gatewayPath } = this.options;\n const gateways = context.gateways();\n if (binding === undefined || gatewayPath === undefined) {\n const candidates = gateways.filter(\n (gateway) =>\n (binding === undefined || gateway.binding === binding) &&\n (gatewayPath === undefined || gateway.path === gatewayPath),\n );\n const [chosen, ...others] = candidates;\n if (!chosen) {\n const filter = describeFilter(this.options);\n throw new Error(\n filter\n ? `durableObjectLive() found no @WebSocketGateway with ${filter}. Name the gateway ` +\n 'that holds the subscriptions, with its binding.'\n : 'LiveModule delivers Worker invalidations to the room Durable Object of a ' +\n 'gateway, but no @WebSocketGateway names a binding. Declare one with ' +\n '{ binding }, or pass driver: () => durableObjectLive({ binding, gatewayPath }).',\n );\n }\n if (others.length > 0) {\n const paths = candidates.map((gateway) => `'${gateway.path}'`).join(', ');\n throw new Error(\n `LiveModule must choose where Worker invalidations go, but several binding-backed ` +\n `gateways (${paths}) could hold the subscriptions. Pass ` +\n 'driver: () => durableObjectLive({ gatewayPath }) to LiveModule.',\n );\n }\n binding ??= chosen.binding;\n gatewayPath ??= chosen.path;\n }\n const target: LiveTarget = { env: context.env, binding, gatewayPath };\n this.#target = target;\n return target;\n }\n}\n\n/**\n * The Cloudflare live driver, for `LiveModule.forRoot({ driver })`. It is the\n * default on Cloudflare, so name it only to choose a gateway, binding or\n * default room:\n *\n * ```ts\n * LiveModule.forRoot({ driver: () => durableObjectLive({ gatewayPath: '/rooms/:id/ws' }) })\n * ```\n */\nexport function durableObjectLive(options: DurableObjectLiveOptions = {}): CfLiveDriver {\n return new CfLiveDriver(options);\n}\n\nlet workerLocalLiveWarned = false;\n\n/**\n * The Worker isolate's live platform: invalidations default to the room\n * Durable Object of the application's binding-backed gateway, chosen and read\n * from `ENV` when first needed, and `LiveInspector` reads each room from that\n * object. A configured local driver is warned about once per isolate:\n * subscriptions live in the Durable Object, so it would reach none.\n */\nexport function workerLivePlatform(env: VelaEnv, container: Container): LivePlatform {\n const context: WorkerLiveContext = {\n env,\n gateways: () => bindingGateways(container.resolve(DiscoveryService)),\n };\n let bound: CfLiveDriver | undefined;\n return {\n liveDriver: () => durableObjectLive(),\n async inspect(room) {\n if (!bound) throw new Error('LiveModule delivers locally in this Worker: no room to inspect');\n const value: unknown = await bound._room(room).call('inspectLive');\n const subscriptions: unknown =\n typeof value === 'object' && value !== null\n ? Reflect.get(value, 'subscriptions')\n : undefined;\n const rooms: unknown =\n typeof value === 'object' && value !== null ? Reflect.get(value, 'rooms') : undefined;\n if (!Array.isArray(subscriptions) || !Array.isArray(rooms)) {\n throw new Error('Durable Object inspectLive() returned an invalid snapshot');\n }\n return { subscriptions, rooms };\n },\n bindDriver(driver) {\n if (driver instanceof CfLiveDriver) {\n driver._attach(context);\n bound = driver;\n return;\n }\n if (driver.kind !== 'local' || workerLocalLiveWarned) return;\n if (container.getDiagnostics() === 'silent') return;\n workerLocalLiveWarned = true;\n console.warn(\n '[vela] LiveModule is running localLive() in the Worker isolate: its subscriptions live ' +\n 'in the WebSocket Durable Object, so invalidations sent from the Worker never reach ' +\n 'them. Remove the driver option to deliver through the gateway room Durable Object.',\n );\n },\n };\n}\n"],"mappings":";;;;;AAaA,MAAM,eAAe;AA6CrB,SAAS,eAAe,EAAE,SAAS,eAAiD;CAKlF,OAAO,CAHL,GAAI,YAAY,KAAA,IAAY,CAAC,IAAI,CAAC,YAAY,QAAQ,EAAE,GACxD,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,CAAC,SAAS,YAAY,EAAE,CAEpD,CAAC,CAAC,KAAK,OAAO;AAC3B;;AAGA,SAAS,YAAY,OAAyC;CAC5D,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,SACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,QAAQ,IAAI,KAAA;CAC/E,MAAM,QACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,OAAO,IAAI,KAAA;CAC9E,IAAI,OAAO,WAAW,YAAY,OAAO,UAAU,UACjD,MAAM,IAAI,MAAM,8DAA8D;CAEhF,OAAO;EAAE;EAAQ;CAAM;AACzB;;;;;;AAOA,IAAa,eAAb,MAAgD;CAOjB;CAN7B,OAAgB;CAChB;CACA,SAAS;CACT;CACA;CAEA,YAAY,UAAqD,CAAC,GAAG;EAAxC,KAAA,UAAA;CAAyC;CAEtE,KAAK,MAAkC;EACrC,KAAK,QAAQ;CACf;;CAGA,QAAQ,SAAkC;EACxC,KAAK,WAAW;EAChB,KAAK,UAAU,KAAA;CACjB;;CAGA,gBAAsB;EACpB,KAAK,SAAS;CAChB;;;;;;CAOA,MAAM,MAAiC;EACrC,MAAM,EAAE,KAAK,SAAS,gBAAgB,KAAK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AAEA,IAAI,wBAAwB;;;;;;;;AAS5B,SAAgB,mBAAmB,KAAc,WAAoC;CACnF,MAAM,UAA6B;EACjC;EACA,gBAAgB,gBAAgB,UAAU,QAAQ,gBAAgB,CAAC;CACrE;CACA,IAAI;CACJ,OAAO;EACL,kBAAkB,kBAAkB;EACpC,MAAM,QAAQ,MAAM;GAClB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,gEAAgE;GAC5F,MAAM,QAAiB,MAAM,MAAM,MAAM,IAAI,CAAC,CAAC,KAAK,aAAa;GACjE,MAAM,gBACJ,OAAO,UAAU,YAAY,UAAU,OACnC,QAAQ,IAAI,OAAO,eAAe,IAClC,KAAA;GACN,MAAM,QACJ,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,IAAI,OAAO,OAAO,IAAI,KAAA;GAC9E,IAAI,CAAC,MAAM,QAAQ,aAAa,KAAK,CAAC,MAAM,QAAQ,KAAK,GACvD,MAAM,IAAI,MAAM,2DAA2D;GAE7E,OAAO;IAAE;IAAe;GAAM;EAChC;EACA,WAAW,QAAQ;GACjB,IAAI,kBAAkB,cAAc;IAClC,OAAO,QAAQ,OAAO;IACtB,QAAQ;IACR;GACF;GACA,IAAI,OAAO,SAAS,WAAW,uBAAuB;GACtD,IAAI,UAAU,eAAe,MAAM,UAAU;GAC7C,wBAAwB;GACxB,QAAQ,KACN,8PAGF;EACF;CACF;AACF"}
@@ -17,11 +17,21 @@ function durableObjectRoomName(gatewayPath, roomId) {
17
17
  if (encoder.encode(name).byteLength > MAX_DO_ROOM_NAME_BYTES) throw new Error("The gateway/room Durable Object name exceeds 1024 bytes");
18
18
  return name;
19
19
  }
20
+ const PATH_PARAM = /:[A-Za-z_]/;
21
+ /**
22
+ * The room whose Durable Object holds `room` of the gateway at `gatewayPath`.
23
+ * A gateway without roomParam (its path has no parameters) admits every
24
+ * upgrade into one room, its path, so each room it names lives in that object;
25
+ * upgrades, `Gateways` pushes and live invalidations resolve the same way.
26
+ */
27
+ function gatewayObjectRoom(gatewayPath, room) {
28
+ return PATH_PARAM.test(gatewayPath) ? room : gatewayPath;
29
+ }
20
30
  /** One Durable Object instance per gateway + room, addressed by name. */
21
31
  function roomToDurableId(ns, gatewayPath, roomId) {
22
32
  return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));
23
33
  }
24
34
  //#endregion
25
- export { connTag, durableObjectRoomName, roomTag, roomToDurableId };
35
+ export { connTag, durableObjectRoomName, gatewayObjectRoom, roomTag, roomToDurableId };
26
36
 
27
37
  //# sourceMappingURL=room-id.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"room-id.js","names":[],"sources":["../../src/websocket/room-id.ts"],"sourcesContent":["// Canonical room ↔ Durable Object mappings. The SAME functions are used by the\n// Worker upgrade route (to pick the DO) and by every server-initiated emit — so\n// a connection and a later broadcast always resolve to the same DO instance.\n\n/** Hibernation tag marking a socket's hub room (set at accept; immutable after). */\nexport function roomTag(roomId: string): string {\n return `room:${roomId}`;\n}\n\n/** Hibernation tag addressing one connection directly. */\nexport function connTag(connId: string): string {\n return `conn:${connId}`;\n}\n\nconst DO_ROOM_NAME_PREFIX = 'vela:ws:v2:';\nconst MAX_DO_ROOM_NAME_BYTES = 1_024;\nconst encoder = new TextEncoder();\n\n/** Stable, collision-free Durable Object name for one gateway's room. */\nexport function durableObjectRoomName(gatewayPath: string, roomId: string): string {\n if (\n typeof gatewayPath !== 'string' ||\n gatewayPath.length === 0 ||\n typeof roomId !== 'string' ||\n roomId.length === 0 ||\n /[\\u0000-\\u001f\\u007f]/.test(gatewayPath) ||\n /[\\u0000-\\u001f\\u007f]/.test(roomId)\n ) {\n throw new Error('A non-empty, control-free gateway path and room id are required');\n }\n const name = `${DO_ROOM_NAME_PREFIX}${encodeURIComponent(gatewayPath)}:${encodeURIComponent(roomId)}`;\n if (encoder.encode(name).byteLength > MAX_DO_ROOM_NAME_BYTES) {\n throw new Error('The gateway/room Durable Object name exceeds 1024 bytes');\n }\n return name;\n}\n\n/** One Durable Object instance per gateway + room, addressed by name. */\nexport function roomToDurableId(\n ns: Pick<DurableObjectNamespace, 'idFromName'>,\n gatewayPath: string,\n roomId: string,\n): DurableObjectId {\n return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));\n}\n"],"mappings":";;AAKA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;;AAGA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;AAEA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,UAAU,IAAI,YAAY;;AAGhC,SAAgB,sBAAsB,aAAqB,QAAwB;CACjF,IACE,OAAO,gBAAgB,YACvB,YAAY,WAAW,KACvB,OAAO,WAAW,YAClB,OAAO,WAAW,KAClB,wBAAwB,KAAK,WAAW,KACxC,wBAAwB,KAAK,MAAM,GAEnC,MAAM,IAAI,MAAM,iEAAiE;CAEnF,MAAM,OAAO,GAAG,sBAAsB,mBAAmB,WAAW,EAAE,GAAG,mBAAmB,MAAM;CAClG,IAAI,QAAQ,OAAO,IAAI,CAAC,CAAC,aAAa,wBACpC,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;AACT;;AAGA,SAAgB,gBACd,IACA,aACA,QACiB;CACjB,OAAO,GAAG,WAAW,sBAAsB,aAAa,MAAM,CAAC;AACjE"}
1
+ {"version":3,"file":"room-id.js","names":[],"sources":["../../src/websocket/room-id.ts"],"sourcesContent":["// Canonical room ↔ Durable Object mappings. The SAME functions are used by the\n// Worker upgrade route (to pick the DO) and by every server-initiated emit — so\n// a connection and a later broadcast always resolve to the same DO instance.\n\n/** Hibernation tag marking a socket's hub room (set at accept; immutable after). */\nexport function roomTag(roomId: string): string {\n return `room:${roomId}`;\n}\n\n/** Hibernation tag addressing one connection directly. */\nexport function connTag(connId: string): string {\n return `conn:${connId}`;\n}\n\nconst DO_ROOM_NAME_PREFIX = 'vela:ws:v2:';\nconst MAX_DO_ROOM_NAME_BYTES = 1_024;\nconst encoder = new TextEncoder();\n\n/** Stable, collision-free Durable Object name for one gateway's room. */\nexport function durableObjectRoomName(gatewayPath: string, roomId: string): string {\n if (\n typeof gatewayPath !== 'string' ||\n gatewayPath.length === 0 ||\n typeof roomId !== 'string' ||\n roomId.length === 0 ||\n /[\\u0000-\\u001f\\u007f]/.test(gatewayPath) ||\n /[\\u0000-\\u001f\\u007f]/.test(roomId)\n ) {\n throw new Error('A non-empty, control-free gateway path and room id are required');\n }\n const name = `${DO_ROOM_NAME_PREFIX}${encodeURIComponent(gatewayPath)}:${encodeURIComponent(roomId)}`;\n if (encoder.encode(name).byteLength > MAX_DO_ROOM_NAME_BYTES) {\n throw new Error('The gateway/room Durable Object name exceeds 1024 bytes');\n }\n return name;\n}\n\n// A path parameter (`:name`): a gateway declares roomParam exactly when its\n// path has one, which WsDispatcher validates at bootstrap.\nconst PATH_PARAM = /:[A-Za-z_]/;\n\n/**\n * The room whose Durable Object holds `room` of the gateway at `gatewayPath`.\n * A gateway without roomParam (its path has no parameters) admits every\n * upgrade into one room, its path, so each room it names lives in that object;\n * upgrades, `Gateways` pushes and live invalidations resolve the same way.\n */\nexport function gatewayObjectRoom(gatewayPath: string, room: string): string {\n return PATH_PARAM.test(gatewayPath) ? room : gatewayPath;\n}\n\n/** One Durable Object instance per gateway + room, addressed by name. */\nexport function roomToDurableId(\n ns: Pick<DurableObjectNamespace, 'idFromName'>,\n gatewayPath: string,\n roomId: string,\n): DurableObjectId {\n return ns.idFromName(durableObjectRoomName(gatewayPath, roomId));\n}\n"],"mappings":";;AAKA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;;AAGA,SAAgB,QAAQ,QAAwB;CAC9C,OAAO,QAAQ;AACjB;AAEA,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,UAAU,IAAI,YAAY;;AAGhC,SAAgB,sBAAsB,aAAqB,QAAwB;CACjF,IACE,OAAO,gBAAgB,YACvB,YAAY,WAAW,KACvB,OAAO,WAAW,YAClB,OAAO,WAAW,KAClB,wBAAwB,KAAK,WAAW,KACxC,wBAAwB,KAAK,MAAM,GAEnC,MAAM,IAAI,MAAM,iEAAiE;CAEnF,MAAM,OAAO,GAAG,sBAAsB,mBAAmB,WAAW,EAAE,GAAG,mBAAmB,MAAM;CAClG,IAAI,QAAQ,OAAO,IAAI,CAAC,CAAC,aAAa,wBACpC,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO;AACT;AAIA,MAAM,aAAa;;;;;;;AAQnB,SAAgB,kBAAkB,aAAqB,MAAsB;CAC3E,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO;AAC/C;;AAGA,SAAgB,gBACd,IACA,aACA,QACiB;CACjB,OAAO,GAAG,WAAW,sBAAsB,aAAa,MAAM,CAAC;AACjE"}
@@ -1,5 +1,8 @@
1
+ import { FORWARDED_UPGRADE_HEADERS } from "./worker-transport.js";
2
+ import { CLOUDFLARE_DURABLE_OBJECT, registerDurableObject } from "../cloudflare-factory.js";
1
3
  import { armDoPitr, readDoPitrBookmark } from "./do-pitr.js";
2
4
  import { DoWebSocketHost } from "./do-websocket-host.js";
5
+ import { durableObjectDefinition, startDurableObject } from "../durable-object/boot.js";
3
6
  import { buildDoRuntime } from "./do-bootstrap.js";
4
7
  import { DurableObject } from "cloudflare:workers";
5
8
  //#region src/websocket/websocket.durable-object.ts
@@ -10,22 +13,39 @@ const encoder = new TextEncoder();
10
13
  function isIdentityField(value) {
11
14
  return value !== null && value.length > 0 && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
12
15
  }
16
+ /** The RPC methods a WebSocket Durable Object exposes to the Worker and other objects. */
17
+ const WEBSOCKET_RPC_METHODS = [
18
+ "broadcast",
19
+ "invalidate",
20
+ "inspectLive",
21
+ "pitrCurrentBookmark",
22
+ "pitrBookmarkForTime",
23
+ "pitrArmRestore"
24
+ ];
13
25
  /**
14
26
  * Base class for the WebSocket Durable Object. The user exports a named subclass
15
- * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or
16
- * from a `DynamicModule` declared at module scope:
27
+ * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, a
28
+ * `DynamicModule` declared at module scope, or the app from
29
+ * `defineCloudflareApp`, whose runtime adapters the object shares:
17
30
  *
18
31
  * ```ts
19
- * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}
32
+ * const app = defineCloudflareApp(AppModule);
33
+ * export class ChatRoom extends VelaWebSocketDurableObject(app) {}
34
+ * export default app.worker;
20
35
  * ```
21
36
  *
22
37
  * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
23
38
  * bridge DO hibernation) and forwards every event into the runtime-agnostic
24
- * `WsDispatcher` via {@link DoWebSocketHost}. The DO's `env` is the
25
- * application's ENV, as in the Worker.
39
+ * `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core
40
+ * `WebSocketModule.forRoot()`: this object registers the platform that binds
41
+ * its server to these sockets, delivers live invalidations locally and keeps
42
+ * the live cursor log in its SQLite storage. The DO's `env` is the
43
+ * application's ENV, as in the Worker, and its application context injects
44
+ * `DO_STATE`, `DO_STORAGE` and `DO_ID` like every Vela Durable Object's.
26
45
  */
27
- function VelaWebSocketDurableObject(rootModule) {
28
- return class VelaWsDurableObject extends DurableObject {
46
+ function VelaWebSocketDurableObject(root) {
47
+ const definition = durableObjectDefinition(root);
48
+ class VelaWsDurableObject extends DurableObject {
29
49
  host;
30
50
  liveEngine;
31
51
  ready;
@@ -34,8 +54,12 @@ function VelaWebSocketDurableObject(rootModule) {
34
54
  try {
35
55
  ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG));
36
56
  } catch {}
37
- this.ready = ctx.blockConcurrencyWhile(async () => {
38
- const runtime = await buildDoRuntime(rootModule, ctx, { env });
57
+ this.ready = startDurableObject(ctx, "WebSocket", async () => {
58
+ const runtime = await buildDoRuntime(definition.rootModule, ctx, {
59
+ env,
60
+ adapters: definition.adapters,
61
+ state: ctx
62
+ });
39
63
  this.host = new DoWebSocketHost(ctx, runtime.dispatcher, runtime.registry, runtime.gatewayPaths);
40
64
  this.liveEngine = runtime.live;
41
65
  });
@@ -52,16 +76,16 @@ function VelaWebSocketDurableObject(rootModule) {
52
76
  await this.ready;
53
77
  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected WebSocket upgrade", { status: 426 });
54
78
  const url = new URL(request.url);
55
- const roomId = request.headers.get("x-vela-room") ?? this.ctx.id.name ?? url.pathname;
56
- const path = request.headers.get("x-vela-path") ?? this.host.defaultPath() ?? url.pathname;
57
- const userId = request.headers.get("x-vela-user") || void 0;
58
- const rawExpiresAtMs = request.headers.get("x-vela-expires-at-ms");
79
+ const roomId = request.headers.get(FORWARDED_UPGRADE_HEADERS.room) ?? this.ctx.id.name ?? url.pathname;
80
+ const path = request.headers.get(FORWARDED_UPGRADE_HEADERS.path) ?? this.host.defaultPath() ?? url.pathname;
81
+ const userId = request.headers.get(FORWARDED_UPGRADE_HEADERS.user) || void 0;
82
+ const rawExpiresAtMs = request.headers.get(FORWARDED_UPGRADE_HEADERS.expiresAtMs);
59
83
  const parsedExpiresAtMs = rawExpiresAtMs === null ? void 0 : Number(rawExpiresAtMs);
60
84
  if (parsedExpiresAtMs !== void 0 && (!Number.isSafeInteger(parsedExpiresAtMs) || parsedExpiresAtMs <= 0)) return new Response("Invalid WebSocket identity expiry", { status: 403 });
61
- const issuer = request.headers.get("x-vela-issuer");
62
- const subject = request.headers.get("x-vela-subject");
63
- const principalType = request.headers.get("x-vela-principal-type");
64
- const tenantId = request.headers.get("x-vela-tenant");
85
+ const issuer = request.headers.get(FORWARDED_UPGRADE_HEADERS.issuer);
86
+ const subject = request.headers.get(FORWARDED_UPGRADE_HEADERS.subject);
87
+ const principalType = request.headers.get(FORWARDED_UPGRADE_HEADERS.principalType);
88
+ const tenantId = request.headers.get(FORWARDED_UPGRADE_HEADERS.tenant);
65
89
  const hasPrincipalHeader = issuer !== null || subject !== null || principalType !== null || tenantId !== null;
66
90
  let principal;
67
91
  if (hasPrincipalHeader) {
@@ -93,7 +117,7 @@ function VelaWebSocketDurableObject(rootModule) {
93
117
  await this.ready;
94
118
  await this.host.onError(ws, error);
95
119
  }
96
- /** DO RPC — server-initiated broadcast forwarded from a Worker (see `broadcastToRoom`). */
120
+ /** DO RPC — a `Gateways` push forwarded from the Worker or another room's object. */
97
121
  async broadcast(cmd) {
98
122
  await this.ready;
99
123
  await this.host.broadcast(cmd);
@@ -130,7 +154,16 @@ function VelaWebSocketDurableObject(rootModule) {
130
154
  if (opts.restart === true) this.ctx.abort("vela PITR restore");
131
155
  return result;
132
156
  }
157
+ }
158
+ const descriptor = {
159
+ kind: "websocket",
160
+ rootModule: definition.rootModule,
161
+ methods: WEBSOCKET_RPC_METHODS,
162
+ durableObject: VelaWsDurableObject
133
163
  };
164
+ Object.defineProperty(VelaWsDurableObject, CLOUDFLARE_DURABLE_OBJECT, { value: descriptor });
165
+ if (definition.app) registerDurableObject(definition.app, descriptor);
166
+ return VelaWsDurableObject;
134
167
  }
135
168
  //#endregion
136
169
  export { VelaWebSocketDurableObject };