@velajs/cloudflare 1.30.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 (76) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +260 -74
  3. package/dist/bindings.js +77 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application.js +7 -34
  6. package/dist/cloudflare-application.js.map +1 -1
  7. package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
  8. package/dist/cloudflare-factory.js +84 -28
  9. package/dist/cloudflare-factory.js.map +1 -1
  10. package/dist/diagnostics.js +18 -0
  11. package/dist/diagnostics.js.map +1 -0
  12. package/dist/durable-objects.d.ts +6 -2
  13. package/dist/index.d.ts +160 -455
  14. package/dist/index.js +7 -13
  15. package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
  16. package/dist/platform.js +22 -0
  17. package/dist/platform.js.map +1 -0
  18. package/dist/queue/cloudflare-queues.js +7 -7
  19. package/dist/queue/cloudflare-queues.js.map +1 -1
  20. package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
  21. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
  22. package/dist/root-module-C23bUwt_.d.ts +11 -0
  23. package/dist/schedule-diagnostics.js +8 -15
  24. package/dist/schedule-diagnostics.js.map +1 -1
  25. package/dist/services/kv-cache.store.js +33 -7
  26. package/dist/services/kv-cache.store.js.map +1 -1
  27. package/dist/storage/r2-storage.js +30 -0
  28. package/dist/storage/r2-storage.js.map +1 -0
  29. package/dist/storage.d.ts +28 -0
  30. package/dist/storage.js +2 -0
  31. package/dist/testing.d.ts +96 -0
  32. package/dist/testing.js +111 -0
  33. package/dist/testing.js.map +1 -0
  34. package/dist/websocket/binding-gateways.js +33 -0
  35. package/dist/websocket/binding-gateways.js.map +1 -0
  36. package/dist/websocket/cf-room-registry.js +3 -1
  37. package/dist/websocket/cf-room-registry.js.map +1 -1
  38. package/dist/websocket/do-bootstrap.js +36 -15
  39. package/dist/websocket/do-bootstrap.js.map +1 -1
  40. package/dist/websocket/do-live.js +49 -90
  41. package/dist/websocket/do-live.js.map +1 -1
  42. package/dist/websocket/do-state.js.map +1 -1
  43. package/dist/websocket/live-driver.js +149 -0
  44. package/dist/websocket/live-driver.js.map +1 -0
  45. package/dist/websocket/room-id.js +11 -1
  46. package/dist/websocket/room-id.js.map +1 -1
  47. package/dist/websocket/websocket.durable-object.js +14 -10
  48. package/dist/websocket/websocket.durable-object.js.map +1 -1
  49. package/dist/websocket/worker-transport.js +80 -0
  50. package/dist/websocket/worker-transport.js.map +1 -0
  51. package/package.json +23 -6
  52. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
  53. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
  54. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
  55. package/dist/storage/r2-storage.driver.js +0 -67
  56. package/dist/storage/r2-storage.driver.js.map +0 -1
  57. package/dist/storage/storage-key-claim.js +0 -74
  58. package/dist/storage/storage-key-claim.js.map +0 -1
  59. package/dist/storage/storage-manager.service.js +0 -38
  60. package/dist/storage/storage-manager.service.js.map +0 -1
  61. package/dist/storage/storage.controller.js +0 -64
  62. package/dist/storage/storage.controller.js.map +0 -1
  63. package/dist/storage/storage.module.js +0 -25
  64. package/dist/storage/storage.module.js.map +0 -1
  65. package/dist/storage/storage.service.js +0 -64
  66. package/dist/storage/storage.service.js.map +0 -1
  67. package/dist/storage/storage.tokens.js +0 -7
  68. package/dist/storage/storage.tokens.js.map +0 -1
  69. package/dist/websocket/broadcast.js +0 -32
  70. package/dist/websocket/broadcast.js.map +0 -1
  71. package/dist/websocket/cloudflare-websocket.module.js +0 -25
  72. package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
  73. package/dist/websocket/websocket-routing.js +0 -133
  74. package/dist/websocket/websocket-routing.js.map +0 -1
  75. package/dist/websocket/ws-server-holder.js +0 -38
  76. package/dist/websocket/ws-server-holder.js.map +0 -1
@@ -0,0 +1,28 @@
1
+ import "./vela-env-DFvyoNT3.js";
2
+ import { EnvFactory } from "@velajs/vela/module-kit";
3
+ import { StorageDriver } from "@velajs/storage";
4
+ import { R2DriverOptions } from "@velajs/storage/drivers/r2";
5
+ //#region src/storage/r2-storage.d.ts
6
+ /** `r2Storage` options: the bucket's binding name and the native driver's settings. */
7
+ interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {
8
+ /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */
9
+ binding: string;
10
+ }
11
+ /**
12
+ * The native R2 driver for `@velajs/storage`, reading its bucket from the
13
+ * application's `ENV` by name:
14
+ *
15
+ * ```ts
16
+ * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
17
+ * ```
18
+ *
19
+ * `StorageModule` builds the driver on the first storage operation of each
20
+ * application, so a static module graph serves every environment and boot
21
+ * touches no binding. A missing or mistyped binding fails that operation with
22
+ * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot
23
+ * presign uploads; serve downloads through `publicBaseUrl` or the module's
24
+ * `http: { download: 'proxy' }` controller.
25
+ */
26
+ export declare function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>>;
27
+ //#endregion
28
+ export type { R2StorageOptions };
@@ -0,0 +1,2 @@
1
+ import { r2Storage } from "./storage/r2-storage.js";
2
+ export { r2Storage };
@@ -0,0 +1,96 @@
1
+ import "./vela-env-DFvyoNT3.js";
2
+ import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
3
+ import { a as CloudflareWorkerOptions } from "./cloudflare-factory-eGiet0mg.js";
4
+ import { VelaEnv } from "@velajs/vela";
5
+ import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
6
+ import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
7
+ //#region src/testing.d.ts
8
+ export interface TestingWorkerOptions extends CloudflareWorkerOptions {
9
+ /**
10
+ * The Workers environment the application is built for and every event
11
+ * carries. Defaults to the test Worker's `env` from `cloudflare:workers`,
12
+ * with the bindings the Vitest pool's Wrangler configuration declares.
13
+ */
14
+ env?: VelaEnv;
15
+ /**
16
+ * Adjust the testing module before it compiles: `overrideProvider`,
17
+ * `overrideModule().useModule()`, enhancer overrides and `useMocker`.
18
+ */
19
+ overrides?: (module: TestingModuleBuilder) => TestingModuleBuilder;
20
+ }
21
+ /** One message of a {@link TestingWorker.queue} batch. */
22
+ export interface TestingQueueMessage<Body = unknown> {
23
+ readonly body: Body;
24
+ /** Defaults to a random UUID. */
25
+ readonly id?: string;
26
+ /** The delivery attempt, 1-based; defaults to 1. */
27
+ readonly attempts?: number;
28
+ readonly timestamp?: Date | number;
29
+ }
30
+ /** What the queue handler did with a batch: `cloudflare:test`'s `getQueueResult()`, plus its outcome. */
31
+ export interface TestingQueueResult {
32
+ /** `'exception'` when the handler rejected: Cloudflare then retries every message it did not acknowledge. */
33
+ readonly outcome: 'ok' | 'exception';
34
+ /** The handler's rejection, when `outcome` is `'exception'`. */
35
+ readonly error?: unknown;
36
+ readonly ackAll: boolean;
37
+ readonly retryBatch: {
38
+ readonly retry: boolean;
39
+ readonly delaySeconds?: number;
40
+ };
41
+ /** Ids of the messages acknowledged one by one. */
42
+ readonly explicitAcks: readonly string[];
43
+ readonly retryMessages: readonly {
44
+ readonly msgId: string;
45
+ readonly delaySeconds?: number;
46
+ }[];
47
+ }
48
+ /** The Worker's `fetch`, `queue` and `scheduled` handlers for one test application. */
49
+ export interface TestingWorker {
50
+ /** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */
51
+ readonly module: TestingModule;
52
+ readonly env: VelaEnv;
53
+ /** Send a request through the Worker's `fetch` handler; a path resolves against `http://localhost`. */
54
+ fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
55
+ /** Deliver one batch of the physical `queue` to the Worker's `queue` handler. */
56
+ queue(queue: string, messages: readonly TestingQueueMessage[]): Promise<TestingQueueResult>;
57
+ /**
58
+ * Fire the cron trigger `cron` and wait for its `@Cron` jobs. Rejects when
59
+ * no job declares `cron`: Cloudflare delivers the literal trigger expression.
60
+ */
61
+ scheduled(cron: string, options?: {
62
+ scheduledTime?: Date | number;
63
+ }): Promise<void>;
64
+ /** Wait for background work (`waitUntil`) of every event, then close the application. */
65
+ close(): Promise<void>;
66
+ }
67
+ /**
68
+ * Build `rootModule` as `createCloudflareWorker(rootModule, options)` does
69
+ * (its adapters, then its `configure` hook), through `@velajs/testing`, and
70
+ * drive its Worker handlers inside the Workers Vitest pool.
71
+ *
72
+ * ```ts
73
+ * const worker = await createTestingWorker(AppModule, {
74
+ * overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),
75
+ * });
76
+ * const response = await worker.fetch('/todos');
77
+ * const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);
78
+ * await worker.scheduled('0 3 * * *');
79
+ * await worker.close();
80
+ * ```
81
+ */
82
+ export declare function createTestingWorker(rootModule: CloudflareRoot, options?: TestingWorkerOptions): Promise<TestingWorker>;
83
+ /**
84
+ * A queue message carrying a Vela job envelope, as `QueueClient.add()` sends
85
+ * it: `queue` is the logical queue a `@Processor` handles, and `job` a job
86
+ * definition (whose wire input `data` must match) or a job name.
87
+ */
88
+ export declare function queueJob<const D extends QueueJobDefinition>(queue: string, job: D, data: QueueJobInput<D>, options?: {
89
+ id?: string;
90
+ attempts?: number;
91
+ }): TestingQueueMessage<QueueJob>;
92
+ export declare function queueJob(queue: string, job: string, data: unknown, options?: {
93
+ id?: string;
94
+ attempts?: number;
95
+ }): TestingQueueMessage<QueueJob>;
96
+ //#endregion
@@ -0,0 +1,111 @@
1
+ import { CloudflareApplication } from "./cloudflare-application.js";
2
+ import { cloudflareCreateOptions, configureCloudflareApplication } from "./cloudflare-factory.js";
3
+ import { parseCronMetadata } from "@velajs/vela/module-kit";
4
+ import { env } from "cloudflare:workers";
5
+ import * as cloudflareTest from "cloudflare:test";
6
+ import { Test } from "@velajs/testing";
7
+ //#region src/testing.ts
8
+ const pool = cloudflareTest;
9
+ /**
10
+ * Build `rootModule` as `createCloudflareWorker(rootModule, options)` does
11
+ * (its adapters, then its `configure` hook), through `@velajs/testing`, and
12
+ * drive its Worker handlers inside the Workers Vitest pool.
13
+ *
14
+ * ```ts
15
+ * const worker = await createTestingWorker(AppModule, {
16
+ * overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),
17
+ * });
18
+ * const response = await worker.fetch('/todos');
19
+ * const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);
20
+ * await worker.scheduled('0 3 * * *');
21
+ * await worker.close();
22
+ * ```
23
+ */
24
+ async function createTestingWorker(rootModule, options = {}) {
25
+ const { env: env$1 = env, overrides, configure, ...appOptions } = options;
26
+ const builder = Test.createTestingModule({ imports: [rootModule] }, cloudflareCreateOptions({
27
+ ...appOptions,
28
+ env: env$1
29
+ }));
30
+ const module = await (overrides ? overrides(builder) : builder).compile();
31
+ let app;
32
+ try {
33
+ app = await configureCloudflareApplication(new CloudflareApplication(await module.createApplication(), env$1), env$1, configure);
34
+ } catch (error) {
35
+ await module.close();
36
+ throw error;
37
+ }
38
+ const contexts = /* @__PURE__ */ new Set();
39
+ const context = () => {
40
+ const ctx = pool.createExecutionContext();
41
+ contexts.add(ctx);
42
+ return ctx;
43
+ };
44
+ const responses = /* @__PURE__ */ new Set();
45
+ return {
46
+ module,
47
+ env: env$1,
48
+ async fetch(input, init) {
49
+ const request = typeof input === "string" && input.startsWith("/") ? new Request(new URL(input, "http://localhost"), init) : new Request(input, init);
50
+ const response = await app.fetch(request, env$1, context());
51
+ responses.add(response);
52
+ return response;
53
+ },
54
+ async queue(queue, messages) {
55
+ const batch = pool.createMessageBatch(queue, messages.map((message) => ({
56
+ id: message.id ?? crypto.randomUUID(),
57
+ timestamp: message.timestamp ?? Date.now(),
58
+ attempts: message.attempts ?? 1,
59
+ body: message.body
60
+ })));
61
+ const ctx = context();
62
+ try {
63
+ await app.queue(batch, env$1, ctx);
64
+ } catch (error) {
65
+ return {
66
+ ...await pool.getQueueResult(batch, ctx),
67
+ outcome: "exception",
68
+ error
69
+ };
70
+ }
71
+ return {
72
+ ...await pool.getQueueResult(batch, ctx),
73
+ outcome: "ok"
74
+ };
75
+ },
76
+ async scheduled(cron, { scheduledTime } = {}) {
77
+ const declared = app.entrypoints.ofKind("schedule:cron", parseCronMetadata).map((entry) => entry.meta.expression);
78
+ if (!declared.includes(cron)) throw new Error(`No @Cron job declares ${JSON.stringify(cron)}. Declared: ${declared.map((expression) => JSON.stringify(expression)).join(", ") || "(none)"}.`);
79
+ const ctx = context();
80
+ await app.scheduled(pool.createScheduledController({
81
+ cron,
82
+ scheduledTime
83
+ }), env$1, ctx);
84
+ await pool.waitOnExecutionContext(ctx);
85
+ },
86
+ async close() {
87
+ await Promise.all([...responses].map((response) => response.bodyUsed ? void 0 : response.body?.cancel().catch(() => {})));
88
+ responses.clear();
89
+ await Promise.all([...contexts].map((ctx) => pool.waitOnExecutionContext(ctx)));
90
+ contexts.clear();
91
+ await module.close();
92
+ }
93
+ };
94
+ }
95
+ function queueJob(queue, job, data, { id = crypto.randomUUID(), attempts = 1 } = {}) {
96
+ return {
97
+ id,
98
+ attempts,
99
+ body: {
100
+ id,
101
+ queue,
102
+ name: typeof job === "string" ? job : job.name,
103
+ data,
104
+ attempt: attempts
105
+ }
106
+ };
107
+ }
108
+ //#endregion
109
+ export { createTestingWorker, queueJob };
110
+
111
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","names":["workersEnv","env"],"sources":["../src/testing.ts"],"sourcesContent":["import './vela-env';\n// @ts-expect-error `cloudflare:test` is the virtual module of the Workers Vitest pool\n// (@cloudflare/vitest-plugin); it is typed below instead of by this package's build.\nimport * as cloudflareTest from 'cloudflare:test';\nimport { env as workersEnv } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport { parseCronMetadata } from '@velajs/vela/module-kit';\nimport type { QueueJob, QueueJobDefinition, QueueJobInput } from '@velajs/vela/queue';\nimport { Test, type TestingModule, type TestingModuleBuilder } from '@velajs/testing';\nimport { CloudflareApplication } from './cloudflare-application';\nimport {\n cloudflareCreateOptions,\n configureCloudflareApplication,\n type CloudflareWorkerOptions,\n} from './cloudflare-factory';\nimport type { CloudflareRoot } from './root-module';\n\n/** The `cloudflare:test` helpers this module drives (see @cloudflare/vitest-plugin). */\ninterface WorkersTestPool {\n createExecutionContext(): ExecutionContext;\n waitOnExecutionContext(ctx: ExecutionContext): Promise<void>;\n createScheduledController(options?: {\n scheduledTime?: Date | number;\n cron?: string;\n }): ScheduledController;\n createMessageBatch<Body>(\n queueName: string,\n messages: { id: string; timestamp: Date | number; attempts: number; body: Body }[],\n ): MessageBatch<Body>;\n getQueueResult(\n batch: MessageBatch,\n ctx: ExecutionContext,\n ): Promise<Omit<TestingQueueResult, 'error'>>;\n}\n\nconst pool: WorkersTestPool = cloudflareTest;\n\nexport interface TestingWorkerOptions extends CloudflareWorkerOptions {\n /**\n * The Workers environment the application is built for and every event\n * carries. Defaults to the test Worker's `env` from `cloudflare:workers`,\n * with the bindings the Vitest pool's Wrangler configuration declares.\n */\n env?: VelaEnv;\n /**\n * Adjust the testing module before it compiles: `overrideProvider`,\n * `overrideModule().useModule()`, enhancer overrides and `useMocker`.\n */\n overrides?: (module: TestingModuleBuilder) => TestingModuleBuilder;\n}\n\n/** One message of a {@link TestingWorker.queue} batch. */\nexport interface TestingQueueMessage<Body = unknown> {\n readonly body: Body;\n /** Defaults to a random UUID. */\n readonly id?: string;\n /** The delivery attempt, 1-based; defaults to 1. */\n readonly attempts?: number;\n readonly timestamp?: Date | number;\n}\n\n/** What the queue handler did with a batch: `cloudflare:test`'s `getQueueResult()`, plus its outcome. */\nexport interface TestingQueueResult {\n /** `'exception'` when the handler rejected: Cloudflare then retries every message it did not acknowledge. */\n readonly outcome: 'ok' | 'exception';\n /** The handler's rejection, when `outcome` is `'exception'`. */\n readonly error?: unknown;\n readonly ackAll: boolean;\n readonly retryBatch: { readonly retry: boolean; readonly delaySeconds?: number };\n /** Ids of the messages acknowledged one by one. */\n readonly explicitAcks: readonly string[];\n readonly retryMessages: readonly { readonly msgId: string; readonly delaySeconds?: number }[];\n}\n\n/** The Worker's `fetch`, `queue` and `scheduled` handlers for one test application. */\nexport interface TestingWorker {\n /** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */\n readonly module: TestingModule;\n readonly env: VelaEnv;\n /** Send a request through the Worker's `fetch` handler; a path resolves against `http://localhost`. */\n fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;\n /** Deliver one batch of the physical `queue` to the Worker's `queue` handler. */\n queue(queue: string, messages: readonly TestingQueueMessage[]): Promise<TestingQueueResult>;\n /**\n * Fire the cron trigger `cron` and wait for its `@Cron` jobs. Rejects when\n * no job declares `cron`: Cloudflare delivers the literal trigger expression.\n */\n scheduled(cron: string, options?: { scheduledTime?: Date | number }): Promise<void>;\n /** Wait for background work (`waitUntil`) of every event, then close the application. */\n close(): Promise<void>;\n}\n\n/**\n * Build `rootModule` as `createCloudflareWorker(rootModule, options)` does\n * (its adapters, then its `configure` hook), through `@velajs/testing`, and\n * drive its Worker handlers inside the Workers Vitest pool.\n *\n * ```ts\n * const worker = await createTestingWorker(AppModule, {\n * overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),\n * });\n * const response = await worker.fetch('/todos');\n * const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);\n * await worker.scheduled('0 3 * * *');\n * await worker.close();\n * ```\n */\nexport async function createTestingWorker(\n rootModule: CloudflareRoot,\n options: TestingWorkerOptions = {},\n): Promise<TestingWorker> {\n const { env = workersEnv, overrides, configure, ...appOptions } = options;\n const builder = Test.createTestingModule(\n { imports: [rootModule] },\n cloudflareCreateOptions({ ...appOptions, env }),\n );\n const module = await (overrides ? overrides(builder) : builder).compile();\n let app: CloudflareApplication;\n try {\n app = await configureCloudflareApplication(\n new CloudflareApplication(await module.createApplication(), env),\n env,\n configure,\n );\n } catch (error) {\n await module.close();\n throw error;\n }\n const contexts = new Set<ExecutionContext>();\n const context = (): ExecutionContext => {\n const ctx = pool.createExecutionContext();\n contexts.add(ctx);\n return ctx;\n };\n // A request completes once its response body is consumed: close() cancels\n // the bodies a test never read, so waiting for its background work ends.\n const responses = new Set<Response>();\n return {\n module,\n env,\n async fetch(input, init) {\n const request =\n typeof input === 'string' && input.startsWith('/')\n ? new Request(new URL(input, 'http://localhost'), init)\n : new Request(input, init);\n const response = await app.fetch(request, env, context());\n responses.add(response);\n return response;\n },\n async queue(queue, messages) {\n const batch = pool.createMessageBatch(\n queue,\n messages.map((message) => ({\n id: message.id ?? crypto.randomUUID(),\n timestamp: message.timestamp ?? Date.now(),\n attempts: message.attempts ?? 1,\n body: message.body,\n })),\n );\n const ctx = context();\n try {\n await app.queue(batch, env, ctx);\n } catch (error) {\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'exception', error };\n }\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'ok' };\n },\n async scheduled(cron, { scheduledTime } = {}) {\n const declared = app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .map((entry) => entry.meta.expression);\n if (!declared.includes(cron)) {\n throw new Error(\n `No @Cron job declares ${JSON.stringify(cron)}. Declared: ` +\n `${declared.map((expression) => JSON.stringify(expression)).join(', ') || '(none)'}.`,\n );\n }\n const ctx = context();\n await app.scheduled(pool.createScheduledController({ cron, scheduledTime }), env, ctx);\n await pool.waitOnExecutionContext(ctx);\n },\n async close() {\n await Promise.all(\n [...responses].map((response) =>\n response.bodyUsed ? undefined : response.body?.cancel().catch(() => {}),\n ),\n );\n responses.clear();\n await Promise.all([...contexts].map((ctx) => pool.waitOnExecutionContext(ctx)));\n contexts.clear();\n await module.close();\n },\n };\n}\n\n/**\n * A queue message carrying a Vela job envelope, as `QueueClient.add()` sends\n * it: `queue` is the logical queue a `@Processor` handles, and `job` a job\n * definition (whose wire input `data` must match) or a job name.\n */\nexport function queueJob<const D extends QueueJobDefinition>(\n queue: string,\n job: D,\n data: QueueJobInput<D>,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string,\n data: unknown,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string | QueueJobDefinition,\n data: unknown,\n { id = crypto.randomUUID(), attempts = 1 }: { id?: string; attempts?: number } = {},\n): TestingQueueMessage<QueueJob> {\n const name = typeof job === 'string' ? job : job.name;\n return { id, attempts, body: { id, queue, name, data, attempt: attempts } };\n}\n"],"mappings":";;;;;;;AAmCA,MAAM,OAAwB;;;;;;;;;;;;;;;;AAwE9B,eAAsB,oBACpB,YACA,UAAgC,CAAC,GACT;CACxB,MAAM,EAAE,KAAA,QAAMA,KAAY,WAAW,WAAW,GAAG,eAAe;CAClE,MAAM,UAAU,KAAK,oBACnB,EAAE,SAAS,CAAC,UAAU,EAAE,GACxB,wBAAwB;EAAE,GAAG;EAAY,KAAA;CAAI,CAAC,CAChD;CACA,MAAM,SAAS,OAAO,YAAY,UAAU,OAAO,IAAI,QAAA,CAAS,QAAQ;CACxE,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,+BACV,IAAI,sBAAsB,MAAM,OAAO,kBAAkB,GAAGC,KAAG,GAC/DA,OACA,SACF;CACF,SAAS,OAAO;EACd,MAAM,OAAO,MAAM;EACnB,MAAM;CACR;CACA,MAAM,2BAAW,IAAI,IAAsB;CAC3C,MAAM,gBAAkC;EACtC,MAAM,MAAM,KAAK,uBAAuB;EACxC,SAAS,IAAI,GAAG;EAChB,OAAO;CACT;CAGA,MAAM,4BAAY,IAAI,IAAc;CACpC,OAAO;EACL;EACA,KAAA;EACA,MAAM,MAAM,OAAO,MAAM;GACvB,MAAM,UACJ,OAAO,UAAU,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S,CAAC,CAAC,KAAK,aAClB,SAAS,WAAW,KAAA,IAAY,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC,CACxE,CACF;GACA,UAAU,MAAM;GAChB,MAAM,QAAQ,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAK,QAAQ,KAAK,uBAAuB,GAAG,CAAC,CAAC;GAC9E,SAAS,MAAM;GACf,MAAM,OAAO,MAAM;EACrB;CACF;AACF;AAmBA,SAAgB,SACd,OACA,KACA,MACA,EAAE,KAAK,OAAO,WAAW,GAAG,WAAW,MAA0C,CAAC,GACnD;CAE/B,OAAO;EAAE;EAAI;EAAU,MAAM;GAAE;GAAI;GAAO,MAD7B,OAAO,QAAQ,WAAW,MAAM,IAAI;GACD;GAAM,SAAS;EAAS;CAAE;AAC5E"}
@@ -0,0 +1,33 @@
1
+ import { reportDiagnostic } from "../diagnostics.js";
2
+ import { WS_GATEWAY_METADATA, WS_SERVER } from "@velajs/vela/websocket";
3
+ //#region src/websocket/binding-gateways.ts
4
+ /**
5
+ * The application's gateways that name a `binding`, in discovery order, once
6
+ * per path. Read from decorator metadata, so lifecycle hooks can use it.
7
+ */
8
+ function bindingGateways(discovery) {
9
+ const gateways = /* @__PURE__ */ new Map();
10
+ for (const { metatype, meta } of discovery.providersWithMeta(WS_GATEWAY_METADATA, { metadataOnly: true })) {
11
+ const path = meta.path ?? "";
12
+ if (typeof meta.binding !== "string" || gateways.has(path)) continue;
13
+ gateways.set(path, {
14
+ path,
15
+ binding: meta.binding,
16
+ name: metatype.name
17
+ });
18
+ }
19
+ return [...gateways.values()];
20
+ }
21
+ /**
22
+ * `WebSocketModule` mounts the Worker's upgrade routes. An application with a
23
+ * binding-backed gateway but without that module answers its upgrades with
24
+ * 404, so report each such gateway through the diagnostics policy.
25
+ */
26
+ function reportUnservedGateways(container, discovery) {
27
+ if (container.has(WS_SERVER)) return;
28
+ for (const { name, binding, path } of bindingGateways(discovery)) reportDiagnostic(container, `[vela] ${name} is a @WebSocketGateway with binding '${binding}', but the application does not import WebSocketModule.forRoot() from @velajs/vela/websocket, so upgrades to '${path}' answer 404 instead of reaching its Durable Object.`);
29
+ }
30
+ //#endregion
31
+ export { bindingGateways, reportUnservedGateways };
32
+
33
+ //# sourceMappingURL=binding-gateways.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding-gateways.js","names":[],"sources":["../../src/websocket/binding-gateways.ts"],"sourcesContent":["import type { Container, DiscoveryService } from '@velajs/vela/module-kit';\nimport {\n WS_GATEWAY_METADATA,\n WS_SERVER,\n type WebSocketGatewayOptions,\n} from '@velajs/vela/websocket';\nimport { reportDiagnostic } from '../diagnostics';\n\n/** A gateway whose rooms live in Durable Objects: its path and namespace binding. */\nexport interface BindingGateway {\n path: string;\n binding: string;\n /** The gateway class name, for diagnostics. */\n name: string;\n}\n\n/**\n * The application's gateways that name a `binding`, in discovery order, once\n * per path. Read from decorator metadata, so lifecycle hooks can use it.\n */\nexport function bindingGateways(discovery: DiscoveryService): BindingGateway[] {\n const gateways = new Map<string, BindingGateway>();\n for (const { metatype, meta } of discovery.providersWithMeta<WebSocketGatewayOptions>(\n WS_GATEWAY_METADATA,\n { metadataOnly: true },\n )) {\n const path = meta.path ?? '';\n if (typeof meta.binding !== 'string' || gateways.has(path)) continue;\n gateways.set(path, {\n path,\n binding: meta.binding,\n name: metatype.name,\n });\n }\n return [...gateways.values()];\n}\n\n/**\n * `WebSocketModule` mounts the Worker's upgrade routes. An application with a\n * binding-backed gateway but without that module answers its upgrades with\n * 404, so report each such gateway through the diagnostics policy.\n */\nexport function reportUnservedGateways(container: Container, discovery: DiscoveryService): void {\n if (container.has(WS_SERVER)) return;\n for (const { name, binding, path } of bindingGateways(discovery)) {\n reportDiagnostic(\n container,\n `[vela] ${name} is a @WebSocketGateway with binding '${binding}', but the application ` +\n `does not import WebSocketModule.forRoot() from @velajs/vela/websocket, so upgrades ` +\n `to '${path}' answer 404 instead of reaching its Durable Object.`,\n );\n }\n}\n"],"mappings":";;;;;;;AAoBA,SAAgB,gBAAgB,WAA+C;CAC7E,MAAM,2BAAW,IAAI,IAA4B;CACjD,KAAK,MAAM,EAAE,UAAU,UAAU,UAAU,kBACzC,qBACA,EAAE,cAAc,KAAK,CACvB,GAAG;EACD,MAAM,OAAO,KAAK,QAAQ;EAC1B,IAAI,OAAO,KAAK,YAAY,YAAY,SAAS,IAAI,IAAI,GAAG;EAC5D,SAAS,IAAI,MAAM;GACjB;GACA,SAAS,KAAK;GACd,MAAM,SAAS;EACjB,CAAC;CACH;CACA,OAAO,CAAC,GAAG,SAAS,OAAO,CAAC;AAC9B;;;;;;AAOA,SAAgB,uBAAuB,WAAsB,WAAmC;CAC9F,IAAI,UAAU,IAAI,SAAS,GAAG;CAC9B,KAAK,MAAM,EAAE,MAAM,SAAS,UAAU,gBAAgB,SAAS,GAC7D,iBACE,WACA,UAAU,KAAK,wCAAwC,QAAQ,gHAEtD,KAAK,qDAChB;AAEJ"}
@@ -59,7 +59,9 @@ var CfRoomRegistry = class {
59
59
  const seen = /* @__PURE__ */ new Set();
60
60
  const selected = [];
61
61
  for (const ws of targets) {
62
- const att = this.reconcileFrameLimit(ws, this.attachmentOf(ws));
62
+ const stored = this.attachmentOf(ws);
63
+ if (cmd.gatewayPath !== void 0 && stored.path !== cmd.gatewayPath) continue;
64
+ const att = this.reconcileFrameLimit(ws, stored);
63
65
  if (att.state === "pending" && this.#admitting.has(ws)) continue;
64
66
  if (att.state !== "active" || att.expiresAtMs !== void 0 && (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now())) {
65
67
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"cf-room-registry.js","names":[],"sources":["../../src/websocket/cf-room-registry.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const att = this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n // A socket still in its connection hook is not admitted yet: it receives no\n // room frames, and its own accept() settles it. Rejecting it here would\n // close every client whose handleConnection broadcasts to the room. Other\n // pending sockets fall through and are rejected below.\n if (att.state === 'pending' && this.#admitting.has(ws)) continue;\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,iBAAb,MAAoD;CAerB;CAd7B,6BAAsB,IAAI,QAAmC;CAI7D,6BAAsB,IAAI,QAAgB;CAC1C;CAEA,sBAAsB,SAAkE;EACtF,KAAK,qBAAqB;CAC5B;CAEA;CACA;CAEA,YAAY,KAAmC;EAAlB,KAAA,MAAA;CAAmB;CAEhD,sBAAsB,YAAoE;EACxF,KAAK,qBAAqB;CAC5B;;CAGA,sBAAsB,UAAsD;EAC1E,KAAK,oBAAoB;CAC3B;;;;;;CAOA,MAAM,UAAa,IAAY,OAAqC;EAClE,KAAK,WAAW,IAAI,EAAE;EACtB,IAAI;G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,aAAa,KAAA,KAAa,WAAW,kBAAkB,UAAU;GACnE,WAAW,gBAAgB;GAC3B,GAAG,oBAAoB,UAAU;EACnC;EACA,OAAO;CACT;CAEA,OAAe,IAAY,QAAsB;EAC/C,IAAI;GACF,MAAM,aAAa,KAAK,aAAa,EAAE;GACvC,WAAW,QAAQ;GACnB,GAAG,oBAAoB,UAAU;GACjC,GAAG,MAAM,MAAM,MAAM;EACvB,QAAQ,CAER;CACF;AACF"}
1
+ {"version":3,"file":"cf-room-registry.js","names":[],"sources":["../../src/websocket/cf-room-registry.ts"],"sourcesContent":["import { WebSocketSendGate, type WebSocketSendPolicy } from '@velajs/vela/websocket';\nimport { socketAttachment, rejectedAttachment } from './ws-attachment';\nimport type { BroadcastCommand, RoomRegistry, WsClient } from '@velajs/vela/websocket';\nimport type { DoStateLike, WsAttachment, WsLike } from './do-state';\nimport { CfWsClient } from './cf-ws-client';\n\n/**\n * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room\n * membership lives in tags (hub room, set at accept) + the attachment (dynamic\n * `join()`), never in DO instance fields — so it survives hibernation with zero\n * rehydration.\n */\nexport class CfRoomRegistry implements RoomRegistry {\n readonly #sendGates = new WeakMap<WsLike, WebSocketSendGate>();\n // Sockets whose OnGatewayConnection hook is running in this instance. They\n // are still `pending`, so broadcasts skip them; any other pending socket\n // never finished admission and is closed when a broadcast reaches it.\n readonly #admitting = new WeakSet<WsLike>();\n #sendPolicyForPath?: (path: string) => WebSocketSendPolicy | undefined;\n\n setSendPolicyResolver(resolve: (path: string) => WebSocketSendPolicy | undefined): void {\n this.#sendPolicyForPath = resolve;\n }\n\n private deliveryAuthorizer?: (client: WsClient) => boolean | Promise<boolean>;\n private frameLimitForPath?: (path: string) => number | undefined;\n\n constructor(private readonly ctx: DoStateLike) {}\n\n setDeliveryAuthorizer(authorizer: (client: WsClient) => boolean | Promise<boolean>): void {\n this.deliveryAuthorizer = authorizer;\n }\n\n /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */\n setFrameLimitResolver(resolver: (path: string) => number | undefined): void {\n this.frameLimitForPath = resolver;\n }\n\n /**\n * Run `admit` (the connection hook) with `ws` marked as being admitted, so a\n * broadcast issued meanwhile (for example `server.emit()` announcing the new\n * connection) skips the still-pending socket instead of rejecting it.\n */\n async admitting<T>(ws: WsLike, admit: () => Promise<T>): Promise<T> {\n this.#admitting.add(ws);\n try {\n return await admit();\n } finally {\n this.#admitting.delete(ws);\n }\n }\n\n // CF sockets are registered with the DO by `acceptWebSocket`; nothing to track.\n register(_client: WsClient): void {}\n leaveAll(_client: WsClient): void {}\n\n join(client: WsClient, room: string): void | Promise<void> {\n return client.join(room);\n }\n\n leave(client: WsClient, room: string): void | Promise<void> {\n return client.leave(room);\n }\n\n localIdsInRoom(room: string): string[] {\n return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);\n }\n\n deliverLocal(cmd: BroadcastCommand): void | Promise<void> {\n const excludeIds = new Set(cmd.exceptIds ?? []);\n const excludeRooms = cmd.exceptRooms ?? [];\n\n // Empty `rooms` => GLOBAL (every socket in this DO). Otherwise the union of\n // targeted rooms, deduped per connection.\n const targets =\n cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);\n\n const seen = new Set<string>();\n const selected: Array<{ ws: WsLike; client: WsClient }> = [];\n for (const ws of targets) {\n const stored = this.attachmentOf(ws);\n // A gateway-scoped push never touches another gateway's sockets.\n if (cmd.gatewayPath !== undefined && stored.path !== cmd.gatewayPath) continue;\n const att = this.reconcileFrameLimit(ws, stored);\n // A socket still in its connection hook is not admitted yet: it receives no\n // room frames, and its own accept() settles it. Rejecting it here would\n // close every client whose handleConnection broadcasts to the room. Other\n // pending sockets fall through and are rejected below.\n if (att.state === 'pending' && this.#admitting.has(ws)) continue;\n if (\n att.state !== 'active' ||\n (att.expiresAtMs !== undefined &&\n (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now()))\n ) {\n try {\n att.state = 'rejected';\n ws.serializeAttachment(att);\n ws.close(1008, 'identity expired or connection rejected');\n } catch {\n // already closed or malformed attachment\n }\n continue;\n }\n if (seen.has(att.connId)) continue;\n seen.add(att.connId);\n if (excludeIds.has(att.connId)) continue;\n if (excludeRooms.some((r) => att.rooms.includes(r))) continue;\n selected.push({ ws, client: this.clientFor(ws) });\n }\n\n if (!this.deliveryAuthorizer) {\n for (const { client } of selected) client.sendRaw(cmd.frame);\n return;\n }\n return Promise.all(\n selected.map(async ({ ws, client }) => {\n let allowed = false;\n try {\n allowed = (await this.deliveryAuthorizer!(client)) === true;\n } catch {\n allowed = false;\n }\n if (allowed) client.sendRaw(cmd.frame);\n else this.reject(ws, 'delivery authorization revoked');\n }),\n ).then(() => undefined);\n }\n\n private collectRooms(rooms: string[]): WsLike[] {\n const set = new Set<WsLike>();\n for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);\n return [...set];\n }\n\n private socketsForRoom(room: string): WsLike[] {\n // Membership is the attachment's `rooms`, NOT the hibernation tag: tags are\n // immutable after acceptWebSocket, so a socket that left its hub room still\n // carries the tag. Since one DO ≈ one room, scanning all sockets in the DO\n // and filtering by attachment is both correct and cheap.\n return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));\n }\n\n private attachmentOf(ws: WsLike): WsAttachment {\n return socketAttachment(ws) ?? rejectedAttachment();\n }\n\n /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */\n clientFor(ws: WsLike): CfWsClient {\n this.reconcileFrameLimit(ws, this.attachmentOf(ws));\n let gate = this.#sendGates.get(ws);\n if (!gate) {\n gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));\n this.#sendGates.set(ws, gate);\n }\n return new CfWsClient(this.ctx, ws, gate);\n }\n\n private reconcileFrameLimit(ws: WsLike, attachment: WsAttachment): WsAttachment {\n const expected = this.frameLimitForPath?.(attachment.path);\n if (expected !== undefined && attachment.maxFrameBytes !== expected) {\n attachment.maxFrameBytes = expected;\n ws.serializeAttachment(attachment);\n }\n return attachment;\n }\n\n private reject(ws: WsLike, reason: string): void {\n try {\n const attachment = this.attachmentOf(ws);\n attachment.state = 'rejected';\n ws.serializeAttachment(attachment);\n ws.close(1008, reason);\n } catch {\n // already closed or malformed attachment\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,iBAAb,MAAoD;CAerB;CAd7B,6BAAsB,IAAI,QAAmC;CAI7D,6BAAsB,IAAI,QAAgB;CAC1C;CAEA,sBAAsB,SAAkE;EACtF,KAAK,qBAAqB;CAC5B;CAEA;CACA;CAEA,YAAY,KAAmC;EAAlB,KAAA,MAAA;CAAmB;CAEhD,sBAAsB,YAAoE;EACxF,KAAK,qBAAqB;CAC5B;;CAGA,sBAAsB,UAAsD;EAC1E,KAAK,oBAAoB;CAC3B;;;;;;CAOA,MAAM,UAAa,IAAY,OAAqC;EAClE,KAAK,WAAW,IAAI,EAAE;EACtB,IAAI;GACF,OAAO,MAAM,MAAM;EACrB,UAAU;GACR,KAAK,WAAW,OAAO,EAAE;EAC3B;CACF;CAGA,SAAS,SAAyB,CAAC;CACnC,SAAS,SAAyB,CAAC;CAEnC,KAAK,QAAkB,MAAoC;EACzD,OAAO,OAAO,KAAK,IAAI;CACzB;CAEA,MAAM,QAAkB,MAAoC;EAC1D,OAAO,OAAO,MAAM,IAAI;CAC1B;CAEA,eAAe,MAAwB;EACrC,OAAO,KAAK,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,KAAK,aAAa,EAAE,CAAC,CAAC,MAAM;CAC3E;CAEA,aAAa,KAA6C;EACxD,MAAM,aAAa,IAAI,IAAI,IAAI,aAAa,CAAC,CAAC;EAC9C,MAAM,eAAe,IAAI,eAAe,CAAC;EAIzC,MAAM,UACJ,IAAI,MAAM,WAAW,IAAI,KAAK,IAAI,cAAc,IAAI,KAAK,aAAa,IAAI,KAAK;EAEjF,MAAM,uBAAO,IAAI,IAAY;EAC7B,MAAM,WAAoD,CAAC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AK,eAAe,IAAI,GAAG,IAAI,IAAI,EAAE;EAChF,OAAO,CAAC,GAAG,GAAG;CAChB;CAEA,eAAuB,MAAwB;EAK7C,OAAO,KAAK,IAAI,cAAc,CAAC,CAAC,QAAQ,OAAO,KAAK,aAAa,EAAE,CAAC,CAAC,MAAM,SAAS,IAAI,CAAC;CAC3F;CAEA,aAAqB,IAA0B;EAC7C,OAAO,iBAAiB,EAAE,KAAK,mBAAmB;CACpD;;CAGA,UAAU,IAAwB;EAChC,KAAK,oBAAoB,IAAI,KAAK,aAAa,EAAE,CAAC;EAClD,IAAI,OAAO,KAAK,WAAW,IAAI,EAAE;EACjC,IAAI,CAAC,MAAM;GACT,OAAO,IAAI,kBAAkB,KAAK,qBAAqB,KAAK,aAAa,EAAE,CAAC,CAAC,IAAI,CAAC;GAClF,KAAK,WAAW,IAAI,IAAI,IAAI;EAC9B;EACA,OAAO,IAAI,WAAW,KAAK,KAAK,IAAI,IAAI;CAC1C;CAEA,oBAA4B,IAAY,YAAwC;EAC9E,MAAM,WAAW,KAAK,oBAAoB,WAAW,IAAI;EACzD,IAAI,aAAa,KAAA,KAAa,WAAW,kBAAkB,UAAU;GACnE,WAAW,gBAAgB;GAC3B,GAAG,oBAAoB,UAAU;EACnC;EACA,OAAO;CACT;CAEA,OAAe,IAAY,QAAsB;EAC/C,IAAI;GACF,MAAM,aAAa,KAAK,aAAa,EAAE;GACvC,WAAW,QAAQ;GACnB,GAAG,oBAAoB,UAAU;GACjC,GAAG,MAAM,MAAM,MAAM;EACvB,QAAQ,CAER;CACF;AACF"}
@@ -1,35 +1,55 @@
1
- import { registerCloudflareEnvironment } from "../environment.js";
1
+ import { registerCloudflarePlatform } from "../platform.js";
2
+ import { gatewayRoomObject } from "./worker-transport.js";
2
3
  import { CfWsClient } from "./cf-ws-client.js";
3
- import { initDoLive, initializeDoLiveResources } from "./do-live.js";
4
- import { WsServerHolder } from "./ws-server-holder.js";
4
+ import { durableObjectLivePlatform, initDoLive } from "./do-live.js";
5
5
  import { CfRoomRegistry } from "./cf-room-registry.js";
6
6
  import { VelaApplication } from "@velajs/vela";
7
- import { WS_SERVER, WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
7
+ import { WsDispatcher, WsServerImpl, local, readWsEntrypointMeta } from "@velajs/vela/websocket";
8
8
  import { bootstrap } from "@velajs/vela/internal";
9
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
+ }
10
26
  /**
11
27
  * Slim DI bootstrap for the Durable Object isolate: wires the container and runs
12
28
  * `OnModuleInit`/`OnApplicationBootstrap` (so `WsDispatcher` discovers gateways)
13
29
  * WITHOUT building the Hono app/routes the DO never serves. The DO's `env` is
14
- * seeded as the global ENV before providers construct, and the ctx-backed server
15
- * is bound before bootstrap lifecycle so gateway `afterInit`/handlers see it.
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.
16
35
  */
17
36
  async function buildDoRuntime(rootModule, ctx, options) {
18
- const { container, routeManager, loader } = await bootstrap(rootModule, { configureContainer: (container) => {
19
- registerCloudflareEnvironment(container, options.env);
20
- } });
21
37
  const registry = new CfRoomRegistry(ctx);
22
38
  const driver = local();
23
39
  driver.bind(registry);
24
40
  const server = new WsServerImpl(driver);
25
- if (container.has(WS_SERVER)) {
26
- const holder = await container.resolveAsync(WS_SERVER);
27
- if (!(holder instanceof WsServerHolder)) throw new Error("[vela] The WebSocket Durable Object found a WS_SERVER from the core WebSocketModule, which cannot reach Durable Object sockets. On Cloudflare, import CloudflareWebSocketModule.forRoot() instead of WebSocketModule.forRoot().");
28
- holder.setTarget(server);
29
- }
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.");
30
51
  const app = new VelaApplication(container, routeManager);
31
52
  app.setInstances(await loader.resolveAllInstances());
32
- initializeDoLiveResources(container, ctx);
33
53
  await app.callOnModuleInit();
34
54
  await app.callOnApplicationBootstrap();
35
55
  const wsEntrypoints = app.entrypoints.ofKind("websocket", readWsEntrypointMeta);
@@ -42,6 +62,7 @@ async function buildDoRuntime(rootModule, ctx, options) {
42
62
  });
43
63
  const live = initDoLive(app, ctx, registry);
44
64
  return {
65
+ container,
45
66
  dispatcher,
46
67
  registry,
47
68
  server,
@@ -1 +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 {\n local,\n readWsEntrypointMeta,\n WsDispatcher,\n WsServerImpl,\n WS_SERVER,\n} from '@velajs/vela/websocket';\nimport type { WsServer } from '@velajs/vela/websocket';\nimport type { LiveEngine } from '@velajs/vela/live';\nimport { registerCloudflareEnvironment } from '../environment';\nimport { CfWsClient } from './cf-ws-client';\nimport { CfRoomRegistry } from './cf-room-registry';\nimport { initDoLive, initializeDoLiveResources } from './do-live';\nimport type { DoStateLike } from './do-state';\nimport { WsServerHolder } from './ws-server-holder';\n\nexport interface DoRuntime {\n dispatcher: WsDispatcher;\n registry: CfRoomRegistry;\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/**\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, and the ctx-backed server\n * is bound before bootstrap lifecycle so gateway `afterInit`/handlers see it.\n */\nexport async function buildDoRuntime(\n rootModule: Type | DynamicModule,\n ctx: DoStateLike,\n options: { env: VelaEnv },\n): Promise<DoRuntime> {\n const { container, routeManager, loader } = await bootstrap(rootModule, {\n configureContainer: (container) => {\n registerCloudflareEnvironment(container, options.env);\n },\n });\n\n const registry = new CfRoomRegistry(ctx);\n const driver = local();\n driver.bind(registry);\n const server = new WsServerImpl(driver);\n\n if (container.has(WS_SERVER)) {\n const holder = await container.resolveAsync(WS_SERVER);\n // The core WebSocketModule's server broadcasts through its own sync driver,\n // which never reaches this Durable Object's hibernatable sockets.\n if (!(holder instanceof WsServerHolder)) {\n throw new Error(\n '[vela] The WebSocket Durable Object found a WS_SERVER from the core WebSocketModule, ' +\n 'which cannot reach Durable Object sockets. On Cloudflare, import ' +\n 'CloudflareWebSocketModule.forRoot() instead of WebSocketModule.forRoot().',\n );\n }\n holder.setTarget(server);\n }\n\n const app = new VelaApplication(container, routeManager);\n app.setInstances(await loader.resolveAllInstances());\n initializeDoLiveResources(container, ctx);\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: wire the SQLite cursor log + local driver mode and replay\n // hibernation-persisted subscriptions into the fresh engine.\n const live = initDoLive(app, ctx, registry);\n\n return {\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: wsEntrypoints.map((ep) => ep.meta.path),\n live,\n close: (signal?: string) => app.close(signal),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,eAAsB,eACpB,YACA,KACA,SACoB;CACpB,MAAM,EAAE,WAAW,cAAc,WAAW,MAAM,UAAU,YAAY,EACtE,qBAAqB,cAAc;EACjC,8BAA8B,WAAW,QAAQ,GAAG;CACtD,EACF,CAAC;CAED,MAAM,WAAW,IAAI,eAAe,GAAG;CACvC,MAAM,SAAS,MAAM;CACrB,OAAO,KAAK,QAAQ;CACpB,MAAM,SAAS,IAAI,aAAa,MAAM;CAEtC,IAAI,UAAU,IAAI,SAAS,GAAG;EAC5B,MAAM,SAAS,MAAM,UAAU,aAAa,SAAS;EAGrD,IAAI,EAAE,kBAAkB,iBACtB,MAAM,IAAI,MACR,iOAGF;EAEF,OAAO,UAAU,MAAM;CACzB;CAEA,MAAM,MAAM,IAAI,gBAAgB,WAAW,YAAY;CACvD,IAAI,aAAa,MAAM,OAAO,oBAAoB,CAAC;CACnD,0BAA0B,WAAW,GAAG;CACxC,MAAM,IAAI,iBAAiB;CAC3B,MAAM,IAAI,2BAA2B;CAKrC,MAAM,gBAAgB,IAAI,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;CAID,MAAM,OAAO,WAAW,KAAK,KAAK,QAAQ;CAE1C,OAAO;EAGL;EACA;EACA;EACA,cAAc,cAAc,KAAK,OAAO,GAAG,KAAK,IAAI;EACpD;EACA,QAAQ,WAAoB,IAAI,MAAM,MAAM;CAC9C;AACF"}
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: wsEntrypoints.map((ep) => ep.meta.path),\n live,\n close: (signal?: string) => app.close(signal),\n };\n}\n"],"mappings":";;;;;;;;;;AA6BA,SAAS,aAAa,IAAa,KAA2B;CAC5D,MAAM,SACJ,OAAO,OAAO,YAAY,OAAO,OAAO,QAAQ,IAAI,IAAI,QAAQ,IAAI,KAAA;CACtE,IAAI,OAAO,WAAW,YAAY,OAAO,QAAQ,MAAM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