@velajs/cloudflare 1.29.0 → 1.31.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 (85) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/README.md +262 -75
  3. package/dist/bindings.js +77 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application.js +282 -0
  6. package/dist/cloudflare-application.js.map +1 -0
  7. package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
  8. package/dist/cloudflare-factory.js +165 -0
  9. package/dist/cloudflare-factory.js.map +1 -0
  10. package/dist/decorators/queue-consumer.js +39 -0
  11. package/dist/decorators/queue-consumer.js.map +1 -0
  12. package/dist/diagnostics.js +18 -0
  13. package/dist/diagnostics.js.map +1 -0
  14. package/dist/durable-objects.d.ts +8 -5
  15. package/dist/durable-objects.js +2 -524
  16. package/dist/environment.js +19 -0
  17. package/dist/environment.js.map +1 -0
  18. package/dist/index.d.ts +163 -456
  19. package/dist/index.js +15 -1276
  20. package/dist/nonce/durable-object-nonce.store.js +33 -0
  21. package/dist/nonce/durable-object-nonce.store.js.map +1 -0
  22. package/dist/nonce/nonce-validation.js +18 -0
  23. package/dist/nonce/nonce-validation.js.map +1 -0
  24. package/dist/nonce/nonce.durable-object.js +54 -0
  25. package/dist/nonce/nonce.durable-object.js.map +1 -0
  26. package/dist/{nonce.durable-object-Df4CZi-0.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -12
  27. package/dist/platform.js +22 -0
  28. package/dist/platform.js.map +1 -0
  29. package/dist/queue/cloudflare-queues.js +215 -0
  30. package/dist/queue/cloudflare-queues.js.map +1 -0
  31. package/dist/queues.d.ts +1 -2
  32. package/dist/queues.js +1 -214
  33. package/dist/rate-limit/cloudflare-rate-limit.store.js +79 -0
  34. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -0
  35. package/dist/root-module-C23bUwt_.d.ts +11 -0
  36. package/dist/schedule-diagnostics.js +44 -0
  37. package/dist/schedule-diagnostics.js.map +1 -0
  38. package/dist/scheduled-event.js +68 -0
  39. package/dist/scheduled-event.js.map +1 -0
  40. package/dist/services/flagship-flag.driver.js +52 -0
  41. package/dist/services/flagship-flag.driver.js.map +1 -0
  42. package/dist/services/kv-cache.store.js +108 -0
  43. package/dist/services/kv-cache.store.js.map +1 -0
  44. package/dist/services/kv-flag.driver.js +62 -0
  45. package/dist/services/kv-flag.driver.js.map +1 -0
  46. package/dist/storage/r2-storage.js +30 -0
  47. package/dist/storage/r2-storage.js.map +1 -0
  48. package/dist/storage.d.ts +28 -0
  49. package/dist/storage.js +2 -0
  50. package/dist/testing.d.ts +96 -0
  51. package/dist/testing.js +111 -0
  52. package/dist/testing.js.map +1 -0
  53. package/dist/vela-env-DFvyoNT3.d.ts +1 -2
  54. package/dist/websocket/binding-gateways.js +33 -0
  55. package/dist/websocket/binding-gateways.js.map +1 -0
  56. package/dist/websocket/cf-room-registry.js +139 -0
  57. package/dist/websocket/cf-room-registry.js.map +1 -0
  58. package/dist/websocket/cf-ws-client.js +94 -0
  59. package/dist/websocket/cf-ws-client.js.map +1 -0
  60. package/dist/websocket/do-bootstrap.js +77 -0
  61. package/dist/websocket/do-bootstrap.js.map +1 -0
  62. package/dist/websocket/do-live.js +143 -0
  63. package/dist/websocket/do-live.js.map +1 -0
  64. package/dist/websocket/do-pitr.js +81 -0
  65. package/dist/websocket/do-pitr.js.map +1 -0
  66. package/dist/websocket/do-state.js +7 -0
  67. package/dist/websocket/do-state.js.map +1 -0
  68. package/dist/websocket/do-websocket-host.js +169 -0
  69. package/dist/websocket/do-websocket-host.js.map +1 -0
  70. package/dist/websocket/live-driver.js +149 -0
  71. package/dist/websocket/live-driver.js.map +1 -0
  72. package/dist/websocket/room-id.js +37 -0
  73. package/dist/websocket/room-id.js.map +1 -0
  74. package/dist/websocket/websocket.durable-object.js +142 -0
  75. package/dist/websocket/websocket.durable-object.js.map +1 -0
  76. package/dist/websocket/worker-transport.js +80 -0
  77. package/dist/websocket/worker-transport.js.map +1 -0
  78. package/dist/websocket/ws-attachment.js +79 -0
  79. package/dist/websocket/ws-attachment.js.map +1 -0
  80. package/package.json +26 -7
  81. package/dist/durable-objects.js.map +0 -1
  82. package/dist/index.js.map +0 -1
  83. package/dist/nonce-validation-Dy8z05A9.js +0 -522
  84. package/dist/nonce-validation-Dy8z05A9.js.map +0 -1
  85. package/dist/queues.js.map +0 -1
@@ -0,0 +1,94 @@
1
+ import { rejectedAttachment, socketAttachment } from "./ws-attachment.js";
2
+ import { MAX_WS_ATTACHMENT_BYTES } from "./do-state.js";
3
+ import { DEFAULT_WS_MAX_FRAME_BYTES, DEFAULT_WS_MAX_JOINED_ROOMS, WebSocketSendGate, assertWebSocketRoomId } from "@velajs/vela/websocket";
4
+ //#region src/websocket/cf-ws-client.ts
5
+ const encoder = new TextEncoder();
6
+ /**
7
+ * Core `WsClient` over a native Cloudflare `WebSocket` inside a Durable Object.
8
+ * Per-connection state lives in the hibernation attachment (survives eviction),
9
+ * so a fresh `CfWsClient` is reconstructed per message with no in-memory state.
10
+ */
11
+ var CfWsClient = class {
12
+ ctx;
13
+ ws;
14
+ sendGate;
15
+ #attachment;
16
+ constructor(ctx, ws, sendGate = new WebSocketSendGate()) {
17
+ this.ctx = ctx;
18
+ this.ws = ws;
19
+ this.sendGate = sendGate;
20
+ this.#attachment = socketAttachment(ws) ?? rejectedAttachment();
21
+ }
22
+ get id() {
23
+ return this.#attachment.connId;
24
+ }
25
+ /** The gateway route path this socket connected on (used to route messages). */
26
+ get path() {
27
+ return this.#attachment.path;
28
+ }
29
+ get rooms() {
30
+ return new Set(this.#attachment.rooms);
31
+ }
32
+ get data() {
33
+ return this.#attachment.data;
34
+ }
35
+ set data(value) {
36
+ this.#attachment.data = value;
37
+ }
38
+ get raw() {
39
+ return this.ws;
40
+ }
41
+ get maxFrameBytes() {
42
+ const value = this.#attachment.maxFrameBytes;
43
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : DEFAULT_WS_MAX_FRAME_BYTES;
44
+ }
45
+ send(event, data, id) {
46
+ this.sendRaw(JSON.stringify(id !== void 0 ? {
47
+ id,
48
+ event,
49
+ data
50
+ } : {
51
+ event,
52
+ data
53
+ }));
54
+ }
55
+ sendRaw(payload) {
56
+ this.trySendRaw(payload);
57
+ }
58
+ trySendRaw(payload) {
59
+ if (this.#attachment.state === "rejected") return "closed";
60
+ return this.sendGate.trySend(this.ws, payload, this.maxFrameBytes);
61
+ }
62
+ join(room) {
63
+ assertWebSocketRoomId(room);
64
+ if (!this.#attachment.rooms.includes(room)) {
65
+ if (this.#attachment.rooms.length >= DEFAULT_WS_MAX_JOINED_ROOMS) throw new Error(`A WebSocket may join at most ${DEFAULT_WS_MAX_JOINED_ROOMS} rooms`);
66
+ this.#attachment.rooms.push(room);
67
+ this.persist();
68
+ }
69
+ }
70
+ leave(room) {
71
+ const next = this.#attachment.rooms.filter((r) => r !== room);
72
+ if (next.length !== this.#attachment.rooms.length) {
73
+ this.#attachment.rooms = next;
74
+ this.persist();
75
+ }
76
+ }
77
+ /** Persist `data`/room mutations to the hibernation attachment. */
78
+ commit() {
79
+ this.persist();
80
+ }
81
+ close(code, reason) {
82
+ this.ws.close(code, reason);
83
+ }
84
+ persist() {
85
+ if (this.#attachment.state === "rejected") throw new Error("Invalid WebSocket attachment");
86
+ const serialized = JSON.stringify(this.#attachment);
87
+ if (encoder.encode(serialized).length > MAX_WS_ATTACHMENT_BYTES) throw new Error("WebSocket attachment exceeds the 16 KiB Cloudflare limit. Store large per-connection state in Durable Object storage keyed by connId instead.");
88
+ this.ws.serializeAttachment(this.#attachment);
89
+ }
90
+ };
91
+ //#endregion
92
+ export { CfWsClient };
93
+
94
+ //# sourceMappingURL=cf-ws-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cf-ws-client.js","names":[],"sources":["../../src/websocket/cf-ws-client.ts"],"sourcesContent":["import { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { WebSocketSendResult, WsClient } from '@velajs/vela/websocket';\nimport {\n assertWebSocketRoomId,\n DEFAULT_WS_MAX_FRAME_BYTES,\n DEFAULT_WS_MAX_JOINED_ROOMS,\n WebSocketSendGate,\n} from '@velajs/vela/websocket';\nimport {\n MAX_WS_ATTACHMENT_BYTES,\n type DoStateLike,\n type WsAttachment,\n type WsLike,\n} from './do-state';\nconst encoder = new TextEncoder();\n\n/**\n * Core `WsClient` over a native Cloudflare `WebSocket` inside a Durable Object.\n * Per-connection state lives in the hibernation attachment (survives eviction),\n * so a fresh `CfWsClient` is reconstructed per message with no in-memory state.\n */\nexport class CfWsClient<\n TData extends Record<string, unknown> = Record<string, unknown>,\n> implements WsClient<TData> {\n readonly #attachment: WsAttachment;\n\n constructor(\n private readonly ctx: DoStateLike,\n private readonly ws: WsLike,\n private readonly sendGate = new WebSocketSendGate(),\n ) {\n this.#attachment = socketAttachment(ws) ?? rejectedAttachment();\n }\n\n get id(): string {\n return this.#attachment.connId;\n }\n\n /** The gateway route path this socket connected on (used to route messages). */\n get path(): string {\n return this.#attachment.path;\n }\n\n get rooms(): ReadonlySet<string> {\n return new Set(this.#attachment.rooms);\n }\n\n get data(): TData {\n return this.#attachment.data as TData;\n }\n\n set data(value: TData) {\n this.#attachment.data = value;\n }\n\n get raw(): unknown {\n return this.ws;\n }\n\n get maxFrameBytes(): number {\n const value = this.#attachment.maxFrameBytes;\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n ? value\n : DEFAULT_WS_MAX_FRAME_BYTES;\n }\n\n send(event: string, data?: unknown, id?: string): void {\n this.sendRaw(JSON.stringify(id !== undefined ? { id, event, data } : { event, data }));\n }\n\n sendRaw(payload: string): void {\n this.trySendRaw(payload);\n }\n\n trySendRaw(payload: string): WebSocketSendResult {\n if (this.#attachment.state === 'rejected') return 'closed';\n return this.sendGate.trySend(this.ws, payload, this.maxFrameBytes);\n }\n\n join(room: string): void {\n assertWebSocketRoomId(room);\n if (!this.#attachment.rooms.includes(room)) {\n if (this.#attachment.rooms.length >= DEFAULT_WS_MAX_JOINED_ROOMS) {\n throw new Error(`A WebSocket may join at most ${DEFAULT_WS_MAX_JOINED_ROOMS} rooms`);\n }\n this.#attachment.rooms.push(room);\n this.persist();\n }\n }\n\n leave(room: string): void {\n const next = this.#attachment.rooms.filter((r) => r !== room);\n if (next.length !== this.#attachment.rooms.length) {\n this.#attachment.rooms = next;\n this.persist();\n }\n }\n\n /** Persist `data`/room mutations to the hibernation attachment. */\n commit(): void {\n this.persist();\n }\n\n close(code?: number, reason?: string): void {\n this.ws.close(code, reason);\n }\n\n private persist(): void {\n if (this.#attachment.state === 'rejected') throw new Error('Invalid WebSocket attachment');\n const serialized = JSON.stringify(this.#attachment);\n if (encoder.encode(serialized).length > MAX_WS_ATTACHMENT_BYTES) {\n throw new Error(\n `WebSocket attachment exceeds the 16 KiB Cloudflare limit. Store large ` +\n `per-connection state in Durable Object storage keyed by connId instead.`,\n );\n }\n this.ws.serializeAttachment(this.#attachment);\n }\n}\n"],"mappings":";;;;AAcA,MAAM,UAAU,IAAI,YAAY;;;;;;AAOhC,IAAa,aAAb,MAE6B;CAIR;CACA;CACA;CALnB;CAEA,YACE,KACA,IACA,WAA4B,IAAI,kBAAkB,GAClD;EAHiB,KAAA,MAAA;EACA,KAAA,KAAA;EACA,KAAA,WAAA;EAEjB,KAAK,cAAc,iBAAiB,EAAE,KAAK,mBAAmB;CAChE;CAEA,IAAI,KAAa;EACf,OAAO,KAAK,YAAY;CAC1B;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,YAAY;CAC1B;CAEA,IAAI,QAA6B;EAC/B,OAAO,IAAI,IAAI,KAAK,YAAY,KAAK;CACvC;CAEA,IAAI,OAAc;EAChB,OAAO,KAAK,YAAY;CAC1B;CAEA,IAAI,KAAK,OAAc;EACrB,KAAK,YAAY,OAAO;CAC1B;CAEA,IAAI,MAAe;EACjB,OAAO,KAAK;CACd;CAEA,IAAI,gBAAwB;EAC1B,MAAM,QAAQ,KAAK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CloudflarePlatform } from "../platform.js";
2
+ import { gatewayRoomObject } from "./worker-transport.js";
3
+ import { CfWsClient } from "./cf-ws-client.js";
4
+ import { durableObjectLivePlatform, initDoLive } from "./do-live.js";
5
+ import { CfRoomRegistry } from "./cf-room-registry.js";
6
+ import { VelaApplication } from "@velajs/vela";
7
+ import { WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
8
+ import { bootstrap } from "@velajs/vela/internal";
9
+ //#region src/websocket/do-bootstrap.ts
10
+ /** Whether a Durable Object id names this object. */
11
+ function isThisObject(id, ctx) {
12
+ const equals = typeof id === "object" && id !== null ? Reflect.get(id, "equals") : void 0;
13
+ if (typeof equals === "function") return Reflect.apply(equals, id, [ctx.id]) === true;
14
+ return String(id) === ctx.id.toString();
15
+ }
16
+ /**
17
+ * A `Gateways` push from inside a WebSocket Durable Object: this object's own
18
+ * gateway room is delivered to its sockets; any other room goes to that
19
+ * room's object over its broadcast RPC, as from the Worker.
20
+ */
21
+ async function deliverFromDurableObject(ctx, env, registry, { gatewayPath, binding, room, command }) {
22
+ const target = gatewayRoomObject(env, gatewayPath, binding, room);
23
+ if (isThisObject(target.id, ctx)) await registry.deliverLocal(command);
24
+ else await target.call("broadcast", command);
25
+ }
26
+ /**
27
+ * Slim DI bootstrap for the Durable Object isolate: wires the container and runs
28
+ * `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)
29
+ * WITHOUT building the Hono app/routes the DO never serves. The DO's `env` is
30
+ * seeded as the global ENV before providers construct, next to this object's
31
+ * platform: `WebSocketModule` builds its server over this object's sockets,
32
+ * `Gateways` pushes to this object's room locally and forwards other rooms to
33
+ * their objects, and `LiveModule` delivers locally with a SQLite cursor log
34
+ * when the class is SQLite-backed.
35
+ */
36
+ async function buildDoRuntime(rootModule, ctx, options) {
37
+ const registry = new CfRoomRegistry(ctx);
38
+ const driver = local();
39
+ driver.bind(registry);
40
+ const server = new WsServerImpl(driver);
41
+ const { container, routeManager, loader } = await bootstrap(rootModule, { configureContainer: (target) => {
42
+ registerCloudflarePlatform(target, options.env, {
43
+ websocket: {
44
+ createServer: () => server,
45
+ deliver: (delivery) => deliverFromDurableObject(ctx, options.env, registry, delivery)
46
+ },
47
+ live: durableObjectLivePlatform(ctx)
48
+ });
49
+ } });
50
+ if (!container.has(WsDispatcher)) throw new Error("[vela] A WebSocket Durable Object serves the gateways of WebSocketModule: import WebSocketModule.forRoot() from @velajs/vela/websocket in the application it is built from.");
51
+ const app = new VelaApplication(container, routeManager);
52
+ app.setInstances(await loader.resolveAllInstances());
53
+ await app.callOnModuleInit();
54
+ await app.callOnApplicationBootstrap();
55
+ const wsEntrypoints = app.entrypoints.ofKind("websocket", readWsEntrypointMeta);
56
+ const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);
57
+ registry.setSendPolicyResolver((path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy);
58
+ registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));
59
+ registry.setDeliveryAuthorizer((client) => {
60
+ const path = client instanceof CfWsClient ? client.path : "";
61
+ return dispatcher.authorizeDelivery(path, client);
62
+ });
63
+ const live = initDoLive(app, ctx, registry);
64
+ return {
65
+ container,
66
+ dispatcher,
67
+ registry,
68
+ server,
69
+ gatewayPaths: wsEntrypoints.map((ep) => ep.meta.path),
70
+ live,
71
+ close: (signal) => app.close(signal)
72
+ };
73
+ }
74
+ //#endregion
75
+ export { buildDoRuntime };
76
+
77
+ //# sourceMappingURL=do-bootstrap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do-bootstrap.js","names":[],"sources":["../../src/websocket/do-bootstrap.ts"],"sourcesContent":["import { VelaApplication } from '@velajs/vela';\nimport { bootstrap } from '@velajs/vela/internal';\nimport type { DynamicModule, Type, VelaEnv } from '@velajs/vela';\nimport type { Container } from '@velajs/vela/module-kit';\nimport { local, readWsEntrypointMeta, WsDispatcher, WsServerImpl } from '@velajs/vela/websocket';\nimport type { GatewayDelivery, WsServer } from '@velajs/vela/websocket';\nimport type { LiveEngine } from '@velajs/vela/live';\nimport { registerCloudflarePlatform } from '../platform';\nimport { CfWsClient } from './cf-ws-client';\nimport { CfRoomRegistry } from './cf-room-registry';\nimport { durableObjectLivePlatform, initDoLive } from './do-live';\nimport type { DoStateLike } from './do-state';\nimport { gatewayRoomObject } from './worker-transport';\n\nexport interface DoRuntime {\n /** The Durable Object application's container. */\n container: Container;\n dispatcher: WsDispatcher;\n registry: CfRoomRegistry;\n /** The server gateways inject: it broadcasts to this object's hibernatable sockets. */\n server: WsServer;\n /** Gateway paths from `app.entrypoints.ofKind('websocket')` (discovery order). */\n gatewayPaths: string[];\n /** The live-query engine (undefined when the app doesn't import LiveModule). */\n live?: LiveEngine;\n close(signal?: string): Promise<void>;\n}\n\n/** Whether a Durable Object id names this object. */\nfunction isThisObject(id: unknown, ctx: DoStateLike): boolean {\n const equals: unknown =\n typeof id === 'object' && id !== null ? Reflect.get(id, 'equals') : undefined;\n if (typeof equals === 'function') return Reflect.apply(equals, id, [ctx.id]) === true;\n return String(id) === ctx.id.toString();\n}\n\n/**\n * A `Gateways` push from inside a WebSocket Durable Object: this object's own\n * gateway room is delivered to its sockets; any other room goes to that\n * room's object over its broadcast RPC, as from the Worker.\n */\nasync function deliverFromDurableObject(\n ctx: DoStateLike,\n env: VelaEnv,\n registry: CfRoomRegistry,\n { gatewayPath, binding, room, command }: GatewayDelivery,\n): Promise<void> {\n const target = gatewayRoomObject(env, gatewayPath, binding, room);\n if (isThisObject(target.id, ctx)) await registry.deliverLocal(command);\n else await target.call('broadcast', command);\n}\n\n/**\n * Slim DI bootstrap for the Durable Object isolate: wires the container and runs\n * `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)\n * WITHOUT building the Hono app/routes the DO never serves. The DO's `env` is\n * seeded as the global ENV before providers construct, next to this object's\n * platform: `WebSocketModule` builds its server over this object's sockets,\n * `Gateways` pushes to this object's room locally and forwards other rooms to\n * their objects, and `LiveModule` delivers locally with a SQLite cursor log\n * when the class is SQLite-backed.\n */\nexport async function buildDoRuntime(\n rootModule: Type | DynamicModule,\n ctx: DoStateLike,\n options: { env: VelaEnv },\n): Promise<DoRuntime> {\n const registry = new CfRoomRegistry(ctx);\n const driver = local();\n driver.bind(registry);\n const server = new WsServerImpl(driver);\n\n const { container, routeManager, loader } = await bootstrap(rootModule, {\n configureContainer: (target) => {\n registerCloudflarePlatform(target, options.env, {\n websocket: {\n createServer: () => server,\n deliver: (delivery) => deliverFromDurableObject(ctx, options.env, registry, delivery),\n },\n live: durableObjectLivePlatform(ctx),\n });\n },\n });\n if (!container.has(WsDispatcher)) {\n throw new Error(\n '[vela] A WebSocket Durable Object serves the gateways of WebSocketModule: import ' +\n 'WebSocketModule.forRoot() from @velajs/vela/websocket in the application it is built from.',\n );\n }\n\n const app = new VelaApplication(container, routeManager);\n app.setInstances(await loader.resolveAllInstances());\n await app.callOnModuleInit();\n await app.callOnApplicationBootstrap();\n\n // The entrypoint registry is the transport contract: one 'websocket' entry\n // per discovered gateway ({ meta: { path, dispatcher } }). Built by\n // callOnApplicationBootstrap(), so this slim no-routes path has it too.\n const wsEntrypoints = app.entrypoints.ofKind('websocket', readWsEntrypointMeta);\n const dispatcher = wsEntrypoints[0]?.meta.dispatcher ?? app.get(WsDispatcher);\n registry.setSendPolicyResolver(\n (path) => wsEntrypoints.find((entry) => entry.meta.path === path)?.meta.options.sendPolicy,\n );\n registry.setFrameLimitResolver((path) => dispatcher.getGatewayMaxFrameBytes(path));\n registry.setDeliveryAuthorizer((client) => {\n const path = client instanceof CfWsClient ? client.path : '';\n return dispatcher.authorizeDelivery(path, client);\n });\n\n // Live queries: replay hibernation-persisted subscriptions into the fresh engine.\n const live = initDoLive(app, ctx, registry);\n\n return {\n container,\n // Zero gateways still yields a live dispatcher (module imported, nothing\n // decorated) — fall back to resolving it directly.\n dispatcher,\n registry,\n server,\n gatewayPaths: wsEnt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AI,YAAY,OAAO,aAAa,oBAAoB;CAC9E,MAAM,aAAa,cAAc,EAAE,EAAE,KAAK,cAAc,IAAI,IAAI,YAAY;CAC5E,SAAS,uBACN,SAAS,cAAc,MAAM,UAAU,MAAM,KAAK,SAAS,IAAI,CAAC,EAAE,KAAK,QAAQ,UAClF;CACA,SAAS,uBAAuB,SAAS,WAAW,wBAAwB,IAAI,CAAC;CACjF,SAAS,uBAAuB,WAAW;EACzC,MAAM,OAAO,kBAAkB,aAAa,OAAO,OAAO;EAC1D,OAAO,WAAW,kBAAkB,MAAM,MAAM;CAClD,CAAC;CAGD,MAAM,OAAO,WAAW,KAAK,KAAK,QAAQ;CAE1C,OAAO;EACL;EAGA;EACA;EACA;EACA,cAAc,cAAc,KAAK,OAAO,GAAG,KAAK,IAAI;EACpD;EACA,QAAQ,WAAoB,IAAI,MAAM,MAAM;CAC9C;AACF"}
@@ -0,0 +1,143 @@
1
+ import { gatewayObjectRoom, roomToDurableId } from "./room-id.js";
2
+ import { CfLiveDriver } from "./live-driver.js";
3
+ import { CfWsClient } from "./cf-ws-client.js";
4
+ import { LiveEngine, localLive, readPersistedLiveSubscriptions } from "@velajs/vela/live";
5
+ //#region src/websocket/do-live.ts
6
+ const DEFAULT_MAX_LOG_ROWS = 4096;
7
+ /**
8
+ * The durable `CursorLog`: an append-only tag-invalidation log in the DO's
9
+ * SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in
10
+ * `__vela_live_meta`. Because the cursor survives hibernation AND trims (it is
11
+ * read from `sqlite_sequence`, lunora's `ctx-db-cdc.ts` trick), a reconnecting
12
+ * client whose gap the log still covers gets a tiny `resume` instead of a
13
+ * re-run — the real-resume half of the live protocol.
14
+ *
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.
20
+ */
21
+ var DoCursorLog = class {
22
+ sql;
23
+ maxRows;
24
+ epoch;
25
+ constructor(sql, maxRows = DEFAULT_MAX_LOG_ROWS) {
26
+ this.sql = sql;
27
+ this.maxRows = maxRows;
28
+ sql.exec("CREATE TABLE IF NOT EXISTS __vela_live_log (seq INTEGER PRIMARY KEY AUTOINCREMENT, ts REAL NOT NULL, tags TEXT NOT NULL)");
29
+ sql.exec("CREATE TABLE IF NOT EXISTS __vela_live_meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)");
30
+ const row = sql.exec("SELECT v FROM __vela_live_meta WHERE k = 'epoch'").toArray()[0];
31
+ if (row && typeof row.v === "string") this.epoch = row.v;
32
+ else {
33
+ this.epoch = crypto.randomUUID();
34
+ sql.exec("INSERT INTO __vela_live_meta (k, v) VALUES ('epoch', ?)", this.epoch);
35
+ }
36
+ }
37
+ append(tags) {
38
+ this.sql.exec("INSERT INTO __vela_live_log (ts, tags) VALUES (?, ?)", Date.now(), JSON.stringify(tags));
39
+ const stamp = this.current();
40
+ if (stamp.cursor > this.maxRows) this.sql.exec("DELETE FROM __vela_live_log WHERE seq <= ?", stamp.cursor - this.maxRows);
41
+ return stamp;
42
+ }
43
+ current() {
44
+ let cursor = 0;
45
+ try {
46
+ const row = this.sql.exec("SELECT seq FROM sqlite_sequence WHERE name = '__vela_live_log'").toArray()[0];
47
+ cursor = typeof row?.seq === "number" ? row.seq : Number(row?.seq ?? 0);
48
+ } catch {
49
+ cursor = 0;
50
+ }
51
+ return {
52
+ cursor,
53
+ epoch: this.epoch
54
+ };
55
+ }
56
+ evaluateResume(sinceCursor, sinceEpoch, subscriptionTags) {
57
+ const { cursor, epoch } = this.current();
58
+ if (sinceEpoch !== epoch) return "snapshot";
59
+ if (sinceCursor > cursor) return "snapshot";
60
+ if (sinceCursor === cursor) return "resume";
61
+ const minRow = this.sql.exec("SELECT MIN(seq) AS m FROM __vela_live_log").toArray()[0];
62
+ const min = minRow?.m == null ? void 0 : Number(minRow.m);
63
+ if (min === void 0 || min > sinceCursor + 1) return "snapshot";
64
+ const subTags = new Set(subscriptionTags);
65
+ for (const row of this.sql.exec("SELECT tags FROM __vela_live_log WHERE seq > ?", sinceCursor).toArray()) {
66
+ let tags;
67
+ try {
68
+ tags = JSON.parse(String(row.tags));
69
+ } catch {
70
+ return "snapshot";
71
+ }
72
+ if (Array.isArray(tags) && tags.some((tag) => typeof tag === "string" && subTags.has(tag))) return "rerun";
73
+ }
74
+ return "resume";
75
+ }
76
+ };
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;
89
+ }
90
+ }
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();
106
+ }
107
+ };
108
+ }
109
+ /**
110
+ * DO-side wiring after lifecycle, called from `buildDoRuntime`: replay every hibernation-persisted
111
+ * subscription into the (fresh) engine so an eviction is invisible to
112
+ * subscribers. Returns the engine for the `invalidate` RPC, or undefined when
113
+ * the app doesn't use LiveModule.
114
+ */
115
+ function initDoLive(app, ctx, registry) {
116
+ const entry = app.entrypoints.ofKind("live")[0];
117
+ if (!entry) return void 0;
118
+ if (typeof entry.meta !== "object" || entry.meta === null || !("engine" in entry.meta)) throw new Error("Invalid live entrypoint metadata.");
119
+ const engine = entry.meta.engine;
120
+ if (!(engine instanceof LiveEngine)) throw new Error("Invalid live entrypoint engine.");
121
+ for (const ws of ctx.getWebSockets()) {
122
+ const client = registry?.clientFor(ws) ?? new CfWsClient(ctx, ws);
123
+ if (!client.id) continue;
124
+ for (const record of readPersistedLiveSubscriptions(client)) engine.restoreSubscription(client.path, client, record);
125
+ }
126
+ return engine;
127
+ }
128
+ /**
129
+ * Invalidate live tags in a room from a Worker (controller / cron / queue
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.
133
+ */
134
+ async function liveInvalidateToRoom(ns, gatewayPath, room, tags) {
135
+ return ns.get(roomToDurableId(ns, gatewayPath, gatewayObjectRoom(gatewayPath, room))).invalidate({
136
+ room,
137
+ tags
138
+ });
139
+ }
140
+ //#endregion
141
+ export { DoCursorLog, durableObjectLivePlatform, initDoLive, liveInvalidateToRoom };
142
+
143
+ //# sourceMappingURL=do-live.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do-live.js","names":[],"sources":["../../src/websocket/do-live.ts"],"sourcesContent":["import type { 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,UAA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E1D;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"}
@@ -0,0 +1,81 @@
1
+ //#region src/websocket/do-pitr.ts
2
+ const PITR_UNAVAILABLE_CODE = "PITR_UNAVAILABLE";
3
+ /**
4
+ * Thrown when a DO's storage lacks the SQLite bookmark API (non-SQLite DO, or a
5
+ * local runtime without PITR). Carries a stable `code` + HTTP 409 `status`, and
6
+ * a recognizable `name`/message so the studio port can map it to
7
+ * `TIMETRAVEL_UNAVAILABLE` even after the error crosses the Worker→DO RPC hop
8
+ * (which preserves `name` + `message`, not arbitrary own-properties).
9
+ */
10
+ var DoPitrUnavailableError = class extends Error {
11
+ code = PITR_UNAVAILABLE_CODE;
12
+ status = 409;
13
+ constructor(message = "Durable Object point-in-time recovery is unavailable on this storage") {
14
+ super(`${PITR_UNAVAILABLE_CODE}: ${message}`);
15
+ this.name = "DoPitrUnavailableError";
16
+ }
17
+ };
18
+ /**
19
+ * True when `error` signals DO PITR unavailability. Robust across the Worker→DO
20
+ * RPC hop: checks the `code` own-property (same process) AND the `name` / message
21
+ * sentinel (survive RPC serialization) so a downstream can classify it either way.
22
+ */
23
+ function isDoPitrUnavailable(error) {
24
+ if (typeof error !== "object" || error === null) return false;
25
+ const record = error;
26
+ if (record.code === PITR_UNAVAILABLE_CODE) return true;
27
+ if (record.name === "DoPitrUnavailableError") return true;
28
+ return typeof record.message === "string" && record.message.startsWith(`${PITR_UNAVAILABLE_CODE}:`);
29
+ }
30
+ /** Normalize an epoch-ms number / ISO string / Date to the `number | Date` the DO API accepts. */
31
+ function toStorageTime(time) {
32
+ if (typeof time === "number") return time;
33
+ if (time instanceof Date) return time;
34
+ const asNumber = Number(time);
35
+ return time.trim() !== "" && Number.isFinite(asNumber) ? asNumber : new Date(time);
36
+ }
37
+ /**
38
+ * Read a DO's current bookmark, and — when `time` is given — the bookmark closest
39
+ * to that instant. Throws {@link DoPitrUnavailableError} when a needed method is
40
+ * absent, never `undefined is not a function`.
41
+ */
42
+ async function readDoPitrBookmark(storage, time) {
43
+ const getCurrent = storage.getCurrentBookmark;
44
+ if (typeof getCurrent !== "function") throw new DoPitrUnavailableError();
45
+ const current = await getCurrent.call(storage);
46
+ if (time === void 0) return { current };
47
+ const getForTime = storage.getBookmarkForTime;
48
+ if (typeof getForTime !== "function") throw new DoPitrUnavailableError();
49
+ return {
50
+ current,
51
+ forTime: await getForTime.call(storage, toStorageTime(time))
52
+ };
53
+ }
54
+ /**
55
+ * Arm a PITR restore. Resolves the target (an explicit `bookmark` WINS over
56
+ * `time`), arms it via `onNextSessionRestoreBookmark`, and returns the undo
57
+ * bookmark the DO reports for the pre-restore state. Does NOT abort — the caller
58
+ * decides whether to restart now. Throws {@link DoPitrUnavailableError} when the
59
+ * arming API (or the by-time resolver a `time` target needs) is absent.
60
+ */
61
+ async function armDoPitr(storage, opts) {
62
+ const armRestore = storage.onNextSessionRestoreBookmark;
63
+ if (typeof armRestore !== "function") throw new DoPitrUnavailableError();
64
+ let target;
65
+ if (opts.bookmark !== void 0) target = opts.bookmark;
66
+ else if (opts.time !== void 0) {
67
+ const getForTime = storage.getBookmarkForTime;
68
+ if (typeof getForTime !== "function") throw new DoPitrUnavailableError();
69
+ target = await getForTime.call(storage, toStorageTime(opts.time));
70
+ } else throw new DoPitrUnavailableError("a target bookmark or time is required to arm a restore");
71
+ const undoBookmark = await armRestore.call(storage, target);
72
+ return {
73
+ restoredTo: target,
74
+ undoBookmark,
75
+ restarted: opts.restart === true
76
+ };
77
+ }
78
+ //#endregion
79
+ export { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark };
80
+
81
+ //# sourceMappingURL=do-pitr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do-pitr.js","names":[],"sources":["../../src/websocket/do-pitr.ts"],"sourcesContent":["/**\n * Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a\n * SQLite-backed DO's native bookmark API. A SQLite Durable Object exposes three\n * storage methods (last-30-days PITR):\n *\n * - `getCurrentBookmark()` — an opaque bookmark for the storage's current state.\n * - `getBookmarkForTime(t)` — the bookmark closest to a wall-clock instant.\n * - `onNextSessionRestoreBookmark(b)` — arm a restore to bookmark `b`; the DO\n * restores to it the next time it starts a session, and the call RETURNS a\n * bookmark for the state JUST BEFORE the restore (the undo handle).\n *\n * These methods are ABSENT on a non-SQLite DO (key-value storage) and in some\n * local-dev runtimes, so this module models storage structurally with all three\n * methods OPTIONAL and degrades to a typed {@link DoPitrUnavailableError} (a\n * `code: 'PITR_UNAVAILABLE'`, HTTP 409 error) rather than an\n * `undefined is not a function` TypeError when a needed method is missing.\n *\n * Neither wrapper aborts the DO — `armDoPitr` only ARMS the restore and returns\n * the undo bookmark; the caller (the WS-DO RPC method) decides whether to\n * `ctx.abort()` to apply it immediately vs. on the next natural restart.\n *\n * This file is `cloudflare:workers`-free and pulls in NOTHING from `@velajs/vela`\n * or `@velajs/studio` — it is the raw capability the studio `TimeTravelPort`\n * wraps. Dependency direction is one-way: studio → cloudflare, never the reverse.\n */\n\n/**\n * The subset of `DurableObjectStorage` this module touches, with every method\n * OPTIONAL so it structurally models a non-SQLite DO whose storage has none of\n * them. A real `DurableObjectStorage` (whose methods are required) is assignable\n * to this shape.\n */\nexport interface DoPitrStorage {\n getCurrentBookmark?(): Promise<string>;\n getBookmarkForTime?(timestamp: number | Date): Promise<string>;\n onNextSessionRestoreBookmark?(bookmark: string): Promise<string>;\n}\n\n/** A read of a DO's current bookmark (+ the by-time bookmark when a time is given). */\nexport interface DoPitrBookmarkRead {\n /** The bookmark for the DO storage's current state. */\n current: string;\n /** The bookmark closest to the requested time (only when `time` was passed). */\n forTime?: string;\n}\n\n/** Arming input for {@link armDoPitr}: a target (bookmark WINS over time) + restart intent. */\nexport interface DoPitrArmOptions {\n /** An explicit target bookmark. Takes precedence over `time`. */\n bookmark?: string;\n /** A wall-clock target (epoch ms, ISO string, or Date), resolved to a bookmark. */\n time?: number | string | Date;\n /** Caller intent to restart-now; recorded on the result. `armDoPitr` never aborts. */\n restart?: boolean;\n}\n\n/** The result of arming a PITR restore (before any restart is applied). */\nexport interface DoPitrArmResult {\n /** The bookmark the restore is armed to. */\n restoredTo: string;\n /** The bookmark for the pre-restore state — restore to this to undo. */\n undoBookmark: string;\n /** Whether a restart-now was requested (the RPC layer performs the actual abort). */\n restarted: boolean;\n}\n\n/** The RPC surface a PITR-capable Vela WebSocket DO stub exposes to a Worker. */\nexport interface VelaDoPitrRpc {\n pitrCurrentBookmark(): Promise<DoPitrBookmarkRead>;\n pitrBookmarkForTime(time: number | string): Promise<DoPitrBookmarkRead>;\n pitrArmRestore(opts: DoPitrArmOptions): Promise<DoPitrArmResult>;\n}\n\n/** Structural view of a DO id (avoids depending on `@cloudflare/workers-types` downstream). */\nexport interface DoPitrId {\n toString(): string;\n readonly name?: string | null;\n}\n\n/**\n * Structural view of a DO namespace binding whose stubs speak the PITR RPC. A\n * downstream (the studio `@velajs/studio/cloudflare` port) types the app's\n * namespace binding as this shape to reach the PITR methods without importing\n * `@cloudflare/workers-types`.\n */\nexport interface DoPitrNamespace {\n idFromName(name: string): DoPitrId;\n get(id: DoPitrId): VelaDoPitrRpc;\n}\n\nconst PITR_UNAVAILABLE_CODE = 'PITR_UNAVAILABLE';\n\n/**\n * Thrown when a DO's storage lacks the SQLite bookmark API (non-SQLite DO, or a\n * local runtime without PITR). Carries a stable `code` + HTTP 409 `status`, and\n * a recognizable `name`/message so the studio port can map it to\n * `TIMETRAVEL_UNAVAILABLE` even after the error crosses the Worker→DO RPC hop\n * (which preserves `name` + `message`, not arbitrary own-properties).\n */\nexport class DoPitrUnavailableError extends Error {\n readonly code = PITR_UNAVAILABLE_CODE;\n readonly status = 409;\n\n constructor(message = 'Durable Object point-in-time recovery is unavailable on this storage') {\n super(`${PITR_UNAVAILABLE_CODE}: ${message}`);\n this.name = 'DoPitrUnavailableError';\n }\n}\n\n/**\n * True when `error` signals DO PITR unavailability. Robust across the Worker→DO\n * RPC hop: checks the `code` own-property (same process) AND the `name` / message\n * sentinel (survive RPC serialization) so a downstream can classify it either way.\n */\nexport function isDoPitrUnavailable(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const record = error as { code?: unknown; name?: unknown; message?: unknown };\n if (record.code === PITR_UNAVAILABLE_CODE) return true;\n if (record.name === 'DoPitrUnavailableError') return true;\n return (\n typeof record.message === 'string' && record.message.startsWith(`${PITR_UNAVAILABLE_CODE}:`)\n );\n}\n\n/** Normalize an epoch-ms number / ISO string / Date to the `number | Date` the DO API accepts. */\nfunction toStorageTime(time: number | string | Date): number | Date {\n if (typeof time === 'number') return time;\n if (time instanceof Date) return time;\n const asNumber = Number(time);\n return time.trim() !== '' && Number.isFinite(asNumber) ? asNumber : new Date(time);\n}\n\n/**\n * Read a DO's current bookmark, and — when `time` is given — the bookmark closest\n * to that instant. Throws {@link DoPitrUnavailableError} when a needed method is\n * absent, never `undefined is not a function`.\n */\nexport async function readDoPitrBookmark(\n storage: DoPitrStorage,\n time?: number | string | Date,\n): Promise<DoPitrBookmarkRead> {\n const getCurrent = storage.getCurrentBookmark;\n if (typeof getCurrent !== 'function') throw new DoPitrUnavailableError();\n const current = await getCurrent.call(storage);\n if (time === undefined) return { current };\n const getForTime = storage.getBookmarkForTime;\n if (typeof getForTime !== 'function') throw new DoPitrUnavailableError();\n const forTime = await getForTime.call(storage, toStorageTime(time));\n return { current, forTime };\n}\n\n/**\n * Arm a PITR restore. Resolves the target (an explicit `bookmark` WINS over\n * `time`), arms it via `onNextSessionRestoreBookmark`, and returns the undo\n * bookmark the DO reports for the pre-restore state. Does NOT abort — the caller\n * decides whether to restart now. Throws {@link DoPitrUnavailableError} when the\n * arming API (or the by-time resolver a `time` target needs) is absent.\n */\nexport async function armDoPitr(\n storage: DoPitrStorage,\n opts: DoPitrArmOptions,\n): Promise<DoPitrArmResult> {\n const armRestore = storage.onNextSessionRestoreBookmark;\n if (typeof armRestore !== 'function') throw new DoPitrUnavailableError();\n\n let target: string;\n if (opts.bookmark !== undefined) {\n target = opts.bookmark;\n } else if (opts.time !== undefined) {\n const getForTime = storage.getBookmarkForTime;\n if (typeof getForTime !== 'function') throw new DoPitrUnavailableError();\n target = await getForTime.call(storage, toStorageTime(opts.time));\n } else {\n throw new DoPitrUnavailableError('a target bookmark or time is required to arm a restore');\n }\n\n const undoBookmark = await armRestore.call(storage, target);\n return { restoredTo: target, undoBookmark, restarted: opts.restart === true };\n}\n"],"mappings":";AA0FA,MAAM,wBAAwB;;;;;;;;AAS9B,IAAa,yBAAb,cAA4C,MAAM;CAChD,OAAgB;CAChB,SAAkB;CAElB,YAAY,UAAU,wEAAwE;EAC5F,MAAM,GAAG,sBAAsB,IAAI,SAAS;EAC5C,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAgB,oBAAoB,OAAyB;CAC3D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAS;CACf,IAAI,OAAO,SAAS,uBAAuB,OAAO;CAClD,IAAI,OAAO,SAAS,0BAA0B,OAAO;CACrD,OACE,OAAO,OAAO,YAAY,YAAY,OAAO,QAAQ,WAAW,GAAG,sBAAsB,EAAE;AAE/F;;AAGA,SAAS,cAAc,MAA6C;CAClE,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,IAAI,gBAAgB,MAAM,OAAO;CACjC,MAAM,WAAW,OAAO,IAAI;CAC5B,OAAO,KAAK,KAAK,MAAM,MAAM,OAAO,SAAS,QAAQ,IAAI,WAAW,IAAI,KAAK,IAAI;AACnF;;;;;;AAOA,eAAsB,mBACpB,SACA,MAC6B;CAC7B,MAAM,aAAa,QAAQ;CAC3B,IAAI,OAAO,eAAe,YAAY,MAAM,IAAI,uBAAuB;CACvE,MAAM,UAAU,MAAM,WAAW,KAAK,OAAO;CAC7C,IAAI,SAAS,KAAA,GAAW,OAAO,EAAE,QAAQ;CACzC,MAAM,aAAa,QAAQ;CAC3B,IAAI,OAAO,eAAe,YAAY,MAAM,IAAI,uBAAuB;CAEvE,OAAO;EAAE;EAAS,SAAA,MADI,WAAW,KAAK,SAAS,cAAc,IAAI,CAAC;CACxC;AAC5B;;;;;;;;AASA,eAAsB,UACpB,SACA,MAC0B;CAC1B,MAAM,aAAa,QAAQ;CAC3B,IAAI,OAAO,eAAe,YAAY,MAAM,IAAI,uBAAuB;CAEvE,IAAI;CACJ,IAAI,KAAK,aAAa,KAAA,GACpB,SAAS,KAAK;MACT,IAAI,KAAK,SAAS,KAAA,GAAW;EAClC,MAAM,aAAa,QAAQ;EAC3B,IAAI,OAAO,eAAe,YAAY,MAAM,IAAI,uBAAuB;EACvE,SAAS,MAAM,WAAW,KAAK,SAAS,cAAc,KAAK,IAAI,CAAC;CAClE,OACE,MAAM,IAAI,uBAAuB,wDAAwD;CAG3F,MAAM,eAAe,MAAM,WAAW,KAAK,SAAS,MAAM;CAC1D,OAAO;EAAE,YAAY;EAAQ;EAAc,WAAW,KAAK,YAAY;CAAK;AAC9E"}
@@ -0,0 +1,7 @@
1
+ //#region src/websocket/do-state.ts
2
+ /** Cloudflare's serialized WebSocket hibernation attachment ceiling. */
3
+ const MAX_WS_ATTACHMENT_BYTES = 16384;
4
+ //#endregion
5
+ export { MAX_WS_ATTACHMENT_BYTES };
6
+
7
+ //# sourceMappingURL=do-state.js.map
@@ -0,0 +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 /**\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,169 @@
1
+ import { connTag, roomTag } from "./room-id.js";
2
+ import { socketAttachment } from "./ws-attachment.js";
3
+ import { MAX_WS_ATTACHMENT_BYTES } from "./do-state.js";
4
+ import { WsMessageQueue, assertBroadcastCommandFits } from "@velajs/vela/websocket";
5
+ //#region src/websocket/do-websocket-host.ts
6
+ /**
7
+ * The socket lifecycle inside a WebSocket Durable Object, decoupled from the
8
+ * `cloudflare:workers` base class so it is unit-testable with fakes. The thin
9
+ * `VelaWebSocketDurableObject` shell forwards its hibernation callbacks here.
10
+ */
11
+ var DoWebSocketHost = class {
12
+ ctx;
13
+ dispatcher;
14
+ registry;
15
+ gatewayPaths;
16
+ #messages = /* @__PURE__ */ new WeakMap();
17
+ constructor(ctx, dispatcher, registry, gatewayPaths = []) {
18
+ this.ctx = ctx;
19
+ this.dispatcher = dispatcher;
20
+ this.registry = registry;
21
+ this.gatewayPaths = gatewayPaths;
22
+ }
23
+ /** The single registered gateway's path — a fallback when the Worker didn't forward `x-vela-path`. */
24
+ defaultPath() {
25
+ return this.gatewayPaths[0];
26
+ }
27
+ /**
28
+ * Accept a hibernatable socket: tag it with its hub room + connection id,
29
+ * persist the attachment, then await `OnGatewayConnection` before the caller
30
+ * returns 101. A rejected lifecycle hook closes and fails the upgrade.
31
+ */
32
+ async accept(ws, path, roomId, userId, expiresAtMs, principal) {
33
+ const maxFrameBytes = this.dispatcher.getGatewayMaxFrameBytes(path);
34
+ if (maxFrameBytes === void 0) return false;
35
+ if (expiresAtMs !== void 0 && (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= Date.now())) return false;
36
+ if (principal !== void 0 && (expiresAtMs === void 0 || userId !== principal.subject || !principal.issuer || !principal.tenantId) || expiresAtMs !== void 0 && principal === void 0) return false;
37
+ const connId = crypto.randomUUID();
38
+ const attachment = {
39
+ version: 1,
40
+ connId,
41
+ state: "pending",
42
+ userId,
43
+ principal: principal === void 0 ? void 0 : {
44
+ issuer: principal.issuer,
45
+ subject: principal.subject,
46
+ principalType: principal.principalType
47
+ },
48
+ tenantId: principal?.tenantId,
49
+ expiresAtMs,
50
+ path,
51
+ maxFrameBytes,
52
+ rooms: [roomId],
53
+ data: {
54
+ ...userId ? { userId } : {},
55
+ ...principal ? {
56
+ principal: {
57
+ issuer: principal.issuer,
58
+ subject: principal.subject,
59
+ principalType: principal.principalType
60
+ },
61
+ tenantId: principal.tenantId
62
+ } : {},
63
+ ...expiresAtMs !== void 0 ? { expiresAtMs } : {}
64
+ }
65
+ };
66
+ if (new TextEncoder().encode(JSON.stringify(attachment)).byteLength > MAX_WS_ATTACHMENT_BYTES) return false;
67
+ try {
68
+ this.ctx.acceptWebSocket(ws, [roomTag(roomId), connTag(connId)]);
69
+ ws.serializeAttachment(attachment);
70
+ } catch {
71
+ try {
72
+ ws.close(1008, "Connection rejected");
73
+ } catch {}
74
+ return false;
75
+ }
76
+ const client = this.registry.clientFor(ws);
77
+ try {
78
+ await this.registry.admitting(ws, () => this.dispatcher.handleOpen(path, client));
79
+ if (!this.transition(ws, "active", "pending")) throw new Error(socketAttachment(ws)?.state === "rejected" ? "WebSocket was rejected while OnGatewayConnection was running: a frame arrived before the connection hook completed, or the connection closed or failed" : "Unable to persist authorized WebSocket state");
80
+ return true;
81
+ } catch (err) {
82
+ await this.dispatcher.handleError(path, client, err).catch(() => {});
83
+ this.transition(ws, "rejected");
84
+ try {
85
+ ws.close(1008, "Connection rejected");
86
+ } catch {}
87
+ return false;
88
+ }
89
+ }
90
+ async onMessage(ws, message) {
91
+ if (!this.isActive(ws)) {
92
+ this.reject(ws, "Connection is not authorized");
93
+ return;
94
+ }
95
+ let queue = this.#messages.get(ws);
96
+ if (!queue) {
97
+ const path = socketAttachment(ws)?.path;
98
+ const options = this.dispatcher.collectEntrypoints().find((entry) => entry.meta.path === path)?.meta.options;
99
+ queue = new WsMessageQueue(() => this.reject(ws, "WebSocket message budget exceeded", 1013), options?.maxPendingMessages, options?.maxPendingBytes);
100
+ this.#messages.set(ws, queue);
101
+ }
102
+ await queue.run(message, async () => {
103
+ if (!this.isActive(ws)) return;
104
+ const client = this.registry.clientFor(ws);
105
+ await this.dispatcher.dispatchMessage(client.path, client, message);
106
+ });
107
+ }
108
+ async onClose(ws, code, reason) {
109
+ this.#messages.get(ws)?.stop();
110
+ if (!this.isActive(ws, false)) {
111
+ this.transition(ws, "rejected");
112
+ try {
113
+ ws.close();
114
+ } catch {}
115
+ return;
116
+ }
117
+ const client = this.registry.clientFor(ws);
118
+ await this.dispatcher.handleClose(client.path, client, code, reason);
119
+ try {
120
+ if (code === 1e3 || code >= 3e3 && code <= 4999) ws.close(code, reason);
121
+ else ws.close();
122
+ } catch {}
123
+ }
124
+ async onError(ws, err) {
125
+ if (!this.isActive(ws, false)) {
126
+ this.reject(ws, "Connection failed before authorization");
127
+ return;
128
+ }
129
+ const client = this.registry.clientFor(ws);
130
+ await this.dispatcher.handleError(client.path, client, err);
131
+ }
132
+ /** Deliver a broadcast command to this DO's local sockets (RPC entry point). */
133
+ broadcast(cmd) {
134
+ assertBroadcastCommandFits(cmd, this.dispatcher.getMaximumGatewayFrameBytes());
135
+ return this.registry.deliverLocal(cmd);
136
+ }
137
+ transition(ws, state, expectedState) {
138
+ try {
139
+ const attachment = socketAttachment(ws);
140
+ if (!attachment) return false;
141
+ if (expectedState !== void 0 && attachment.state !== expectedState) return false;
142
+ attachment.state = state;
143
+ ws.serializeAttachment(attachment);
144
+ return true;
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+ isActive(ws, checkExpiry = true) {
150
+ try {
151
+ const attachment = socketAttachment(ws);
152
+ if (!attachment || attachment.state !== "active") return false;
153
+ return !checkExpiry || attachment.expiresAtMs === void 0 || Number.isSafeInteger(attachment.expiresAtMs) && attachment.expiresAtMs > Date.now();
154
+ } catch {
155
+ return false;
156
+ }
157
+ }
158
+ reject(ws, reason, code = 1008) {
159
+ this.#messages.get(ws)?.stop();
160
+ this.transition(ws, "rejected");
161
+ try {
162
+ ws.close(code, reason);
163
+ } catch {}
164
+ }
165
+ };
166
+ //#endregion
167
+ export { DoWebSocketHost };
168
+
169
+ //# sourceMappingURL=do-websocket-host.js.map