@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 @@
1
+ {"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum. Legacy values without\n * metadata remain readable, but cannot safely backfill another tier.\n */\nexport class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async get(key: string): Promise<unknown> {\n return (await this.getEntry(key))?.value;\n }\n\n async getEntry(key: string): Promise<{ value: unknown; expiresAt?: number } | undefined> {\n const { value, metadata } = await this.ns.getWithMetadata<unknown, unknown>(key, 'json');\n if (value === null) return undefined;\n if (typeof metadata === 'object' && metadata !== null && 'velaCacheExpiresAt' in metadata) {\n const expiresAt = metadata.velaCacheExpiresAt;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= Date.now())\n return undefined;\n return { value, expiresAt };\n }\n return { value };\n }\n\n async set(key: string, value: unknown, ttl?: number): Promise<void> {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))\n throw new TypeError('Cache TTL must be finite and nonnegative.');\n if (ttl !== undefined) return this.setEntry(key, { value, expiresAt: Date.now() + ttl * 1000 });\n await this.ns.put(key, JSON.stringify(value));\n }\n\n async setEntry(key: string, entry: CacheEntry): Promise<void> {\n if (!Number.isFinite(entry.expiresAt)) throw new TypeError('Cache expiry must be finite.');\n const remaining = (entry.expiresAt - Date.now()) / 1000;\n if (remaining <= 0) return this.del(key);\n await this.ns.put(key, JSON.stringify(entry.value), {\n expirationTtl: Math.max(60, Math.ceil(remaining)),\n metadata: { velaCacheExpiresAt: entry.expiresAt },\n });\n }\n\n async del(key: string): Promise<void> {\n await this.ns.delete(key);\n }\n\n /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */\n async clear(): Promise<void> {\n let cursor: string | undefined;\n do {\n const list = await this.ns.list(cursor ? { cursor } : undefined);\n await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));\n cursor = list.list_complete ? undefined : list.cursor;\n } while (cursor);\n }\n}\n\n/**\n * Optional, eventually consistent generation store. Use a dedicated KV namespace\n * without TTL/lifecycle cleanup. Never delete/reset generations while entries can\n * survive. Concurrent writes and cached/negative reads prevent strong invalidation;\n * this is unsuitable for strict read-after-write or authorization revocation.\n */\nexport class KVCacheInvalidationStore implements CacheInvalidationStore {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async getVersion(key: string): Promise<string> {\n const value: unknown = await this.ns.get(key, 'json');\n if (value === null) return 'initial';\n if (typeof value !== 'string' || value.length === 0 || value.length > 2048)\n throw new TypeError('Invalid cache generation.');\n return value;\n }\n async invalidate(key: string): Promise<void> {\n await this.ns.put(key, JSON.stringify(crypto.randomUUID()));\n }\n}\n\n/**\n * `CacheModule`'s value store over the KV namespace named `binding`, read from\n * each application's `ENV` when an operation needs it:\n * `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\nexport function kvCache(ref: { binding: string }): EnvFactory<CacheStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheStore(() => namespace(env));\n}\n\n/**\n * `CacheModule`'s generation store over a dedicated KV namespace named\n * `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see\n * {@link KVCacheInvalidationStore}.\n */\nexport function kvCacheInvalidation(ref: { binding: string }): EnvFactory<CacheInvalidationStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheInvalidationStore(() => namespace(env));\n}\n"],"mappings":";;AAaA,MAAM,eAAe,WACnB,OAAO,WAAW,aAAa,eAAe;;;;;;AAOhD,IAAa,eAAb,MAAoF;CAClF;CACA,YAAY,WAA8B;EACxC,KAAK,aAAa,YAAY,SAAS;CACzC;CAEA,IAAY,KAAkB;EAC5B,OAAO,KAAK,WAAW;CACzB;CAEA,MAAM,IAAI,KAA+B;EACvC,QAAQ,MAAM,KAAK,SAAS,GAAG,EAAA,EAAI;CACrC;CAEA,MAAM,SAAS,KAA0E;EACvF,MAAM,EAAE,OAAO,aAAa,MAAM,KAAK,GAAG,gBAAkC,KAAK,MAAM;EACvF,IAAI,UAAU,MAAM,OAAO,KAAA;EAC3B,IAAI,OAAO,aAAa,YAAY,aAAa,QAAQ,wBAAwB,UAAU;GACzF,MAAM,YAAY,SAAS;GAC3B,IAAI,OAAO,cAAc,YAAY,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,KAAK,IAAI,GACxF,OAAO,KAAA;GACT,OAAO;IAAE;IAAO;GAAU;EAC5B;EACA,OAAO,EAAE,MAAM;CACjB;CAEA,MAAM,IAAI,KAAa,OAAgB,KAA6B;EAClE,IAAI,QAAQ,KAAA,MAAc,CAAC,OAAO,SAAS,GAAG,KAAK,MAAM,IACvD,MAAM,IAAI,UAAU,2CAA2C;EACjE,IAAI,QAAQ,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AA2B;EACjD,OAAO;CACT;CACA,MAAM,WAAW,KAA4B;EAC3C,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,CAAC,CAAC;CAC5D;AACF;;;;;;AAOA,SAAgB,QAAQ,KAAkD;CACxE,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,mBAAmB,UAAU,GAAG,CAAC;AACvD;;;;;;AAOA,SAAgB,oBAAoB,KAA8D;CAChG,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,+BAA+B,UAAU,GAAG,CAAC;AACnE"}
@@ -0,0 +1,62 @@
1
+ //#region src/services/kv-flag.driver.ts
2
+ /**
3
+ * Cloudflare KV-backed {@link FeatureFlagDriver}. Flags are stored as JSON
4
+ * values under an optional key prefix and read with `get(key, 'json')`. Reads
5
+ * are type-checked against the requested type: a missing key or a value of the
6
+ * wrong JSON type returns the caller's `fallback`. KV has no targeting, so the
7
+ * evaluation context is ignored.
8
+ *
9
+ * The driver stays honest — it does **not** swallow errors. A KV failure (or a
10
+ * `SyntaxError` from a malformed stored value) propagates; the never-throw
11
+ * guarantee lives in `@velajs/feature-flags`'s service layer.
12
+ *
13
+ * Placed like {@link KVCacheStore}: construct it in a wiring factory over a
14
+ * resolved {@link KVNamespace}.
15
+ *
16
+ * ```ts
17
+ * FeatureFlagsModule.forRootAsync({
18
+ * inject: [ENV],
19
+ * useFactory: (env: WorkerEnv) => ({ drivers: [new KvFlagDriver(env.CACHE, { prefix: 'flag:' })] }),
20
+ * });
21
+ * ```
22
+ */
23
+ var KvFlagDriver = class {
24
+ ns;
25
+ name;
26
+ prefix;
27
+ constructor(ns, options = {}) {
28
+ this.ns = ns;
29
+ this.name = options.name ?? "kv";
30
+ this.prefix = options.prefix ?? "";
31
+ }
32
+ getBoolean(key, fallback, _ctx) {
33
+ return this.read(key, fallback, (v) => typeof v === "boolean");
34
+ }
35
+ getString(key, fallback, _ctx) {
36
+ return this.read(key, fallback, (v) => typeof v === "string");
37
+ }
38
+ getNumber(key, fallback, _ctx) {
39
+ return this.read(key, fallback, (v) => typeof v === "number");
40
+ }
41
+ getObject(key, fallback, _ctx) {
42
+ return this.read(key, fallback, (v) => typeof v === "object" && v !== null);
43
+ }
44
+ /**
45
+ * Reads and JSON-parses the (prefixed) key, returning the parsed value only
46
+ * when `matches` accepts its type; otherwise the caller's fallback. A missing
47
+ * key reads as `null` → fallback. Read/parse errors are left to propagate.
48
+ */
49
+ async read(key, fallback, matches) {
50
+ const value = await this.ns.get(this.prefix + key, "json");
51
+ if (value === null || value === void 0) return fallback;
52
+ return matches(value) ? value : fallback;
53
+ }
54
+ };
55
+ /** Convenience factory for {@link KvFlagDriver}. */
56
+ function kvFlagDriver(kv, options) {
57
+ return new KvFlagDriver(kv, options);
58
+ }
59
+ //#endregion
60
+ export { KvFlagDriver, kvFlagDriver };
61
+
62
+ //# sourceMappingURL=kv-flag.driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv-flag.driver.js","names":[],"sources":["../../src/services/kv-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext } from '@velajs/feature-flags';\n\nexport interface KvFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"kv\"`. */\n name?: string;\n /** Prefix prepended to every flag key before the KV read. Default `\"\"` (none). */\n prefix?: string;\n}\n\n/**\n * Cloudflare KV-backed {@link FeatureFlagDriver}. Flags are stored as JSON\n * values under an optional key prefix and read with `get(key, 'json')`. Reads\n * are type-checked against the requested type: a missing key or a value of the\n * wrong JSON type returns the caller's `fallback`. KV has no targeting, so the\n * evaluation context is ignored.\n *\n * The driver stays honest — it does **not** swallow errors. A KV failure (or a\n * `SyntaxError` from a malformed stored value) propagates; the never-throw\n * guarantee lives in `@velajs/feature-flags`'s service layer.\n *\n * Placed like {@link KVCacheStore}: construct it in a wiring factory over a\n * resolved {@link KVNamespace}.\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [new KvFlagDriver(env.CACHE, { prefix: 'flag:' })] }),\n * });\n * ```\n */\nexport class KvFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly prefix: string;\n\n constructor(\n private readonly ns: KVNamespace,\n options: KvFlagDriverOptions = {},\n ) {\n this.name = options.name ?? 'kv';\n this.prefix = options.prefix ?? '';\n }\n\n getBoolean(key: string, fallback: boolean, _ctx?: FlagContext): Promise<boolean> {\n return this.read(key, fallback, (v) => typeof v === 'boolean');\n }\n\n getString(key: string, fallback: string, _ctx?: FlagContext): Promise<string> {\n return this.read(key, fallback, (v) => typeof v === 'string');\n }\n\n getNumber(key: string, fallback: number, _ctx?: FlagContext): Promise<number> {\n return this.read(key, fallback, (v) => typeof v === 'number');\n }\n\n getObject(key: string, fallback: object, _ctx?: FlagContext): Promise<unknown> {\n return this.read(key, fallback, (v) => typeof v === 'object' && v !== null);\n }\n\n /**\n * Reads and JSON-parses the (prefixed) key, returning the parsed value only\n * when `matches` accepts its type; otherwise the caller's fallback. A missing\n * key reads as `null` → fallback. Read/parse errors are left to propagate.\n */\n private async read<T>(\n key: string,\n fallback: T,\n matches: (value: unknown) => value is T,\n ): Promise<T> {\n const value = await this.ns.get(this.prefix + key, 'json');\n if (value === null || value === undefined) return fallback;\n return matches(value) ? value : fallback;\n }\n}\n\n/** Convenience factory for {@link KvFlagDriver}. */\nexport function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver {\n return new KvFlagDriver(kv, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,eAAb,MAAuD;CAKlC;CAJnB;CACA;CAEA,YACE,IACA,UAA+B,CAAC,GAChC;EAFiB,KAAA,KAAA;EAGjB,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,SAAS,QAAQ,UAAU;CAClC;CAEA,WAAW,KAAa,UAAmB,MAAsC;EAC/E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,SAAS;CAC/D;CAEA,UAAU,KAAa,UAAkB,MAAqC;EAC5E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,QAAQ;CAC9D;CAEA,UAAU,KAAa,UAAkB,MAAqC;EAC5E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,QAAQ;CAC9D;CAEA,UAAU,KAAa,UAAkB,MAAsC;EAC7E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,YAAY,MAAM,IAAI;CAC5E;;;;;;CAOA,MAAc,KACZ,KACA,UACA,SACY;EACZ,MAAM,QAAQ,MAAM,KAAK,GAAG,IAAI,KAAK,SAAS,KAAK,MAAM;EACzD,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;EAClD,OAAO,QAAQ,KAAK,IAAI,QAAQ;CAClC;AACF;;AAGA,SAAgB,aAAa,IAAiB,SAA6C;CACzF,OAAO,IAAI,aAAa,IAAI,OAAO;AACrC"}
@@ -0,0 +1,30 @@
1
+ import { r2 } from "../bindings.js";
2
+ import { r2Driver } from "@velajs/storage/drivers/r2";
3
+ //#region src/storage/r2-storage.ts
4
+ /**
5
+ * The native R2 driver for `@velajs/storage`, reading its bucket from the
6
+ * application's `ENV` by name:
7
+ *
8
+ * ```ts
9
+ * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
10
+ * ```
11
+ *
12
+ * `StorageModule` builds the driver on the first storage operation of each
13
+ * application, so a static module graph serves every environment and boot
14
+ * touches no binding. A missing or mistyped binding fails that operation with
15
+ * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot
16
+ * presign uploads; serve downloads through `publicBaseUrl` or the module's
17
+ * `http: { download: 'proxy' }` controller.
18
+ */
19
+ function r2Storage(options) {
20
+ const { binding, ...driver } = options;
21
+ const bucket = r2({ binding });
22
+ return (env) => r2Driver({
23
+ ...driver,
24
+ bucket: bucket(env)
25
+ });
26
+ }
27
+ //#endregion
28
+ export { r2Storage };
29
+
30
+ //# sourceMappingURL=r2-storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })\n * ```\n *\n * `StorageModule` builds the driver on the first storage operation of each\n * application, so a static module graph serves every environment and boot\n * touches no binding. A missing or mistyped binding fails that operation with\n * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot\n * presign uploads; serve downloads through `publicBaseUrl` or the module's\n * `http: { download: 'proxy' }` controller.\n */\nexport function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>> {\n const { binding, ...driver } = options;\n const bucket = r2({ binding });\n return (env) => r2Driver({ ...driver, bucket: bucket(env) });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAgB,UAAU,SAAgE;CACxF,MAAM,EAAE,SAAS,GAAG,WAAW;CAC/B,MAAM,SAAS,GAAG,EAAE,QAAQ,CAAC;CAC7B,QAAQ,QAAQ,SAAS;EAAE,GAAG;EAAQ,QAAQ,OAAO,GAAG;CAAE,CAAC;AAC7D"}
@@ -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,YAAY,MAAM,WAAW,GAAG,IAC7C,IAAI,QAAQ,IAAI,IAAI,OAAO,kBAAkB,GAAG,IAAI,IACpD,IAAI,QAAQ,OAAO,IAAI;GAC7B,MAAM,WAAW,MAAM,IAAI,MAAM,SAASA,OAAK,QAAQ,CAAC;GACxD,UAAU,IAAI,QAAQ;GACtB,OAAO;EACT;EACA,MAAM,MAAM,OAAO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,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"}
@@ -6,5 +6,4 @@ declare module '@velajs/vela' {
6
6
  */
7
7
  interface VelaEnv extends Cloudflare.Env {}
8
8
  }
9
- export {};
10
- //# sourceMappingURL=vela-env-DFvyoNT3.d.ts.map
9
+ export {};
@@ -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"}
@@ -0,0 +1,139 @@
1
+ import { rejectedAttachment, socketAttachment } from "./ws-attachment.js";
2
+ import { CfWsClient } from "./cf-ws-client.js";
3
+ import { WebSocketSendGate } from "@velajs/vela/websocket";
4
+ //#region src/websocket/cf-room-registry.ts
5
+ /**
6
+ * Core `RoomRegistry` backed by a Durable Object's hibernatable sockets. Room
7
+ * membership lives in tags (hub room, set at accept) + the attachment (dynamic
8
+ * `join()`), never in DO instance fields — so it survives hibernation with zero
9
+ * rehydration.
10
+ */
11
+ var CfRoomRegistry = class {
12
+ ctx;
13
+ #sendGates = /* @__PURE__ */ new WeakMap();
14
+ #admitting = /* @__PURE__ */ new WeakSet();
15
+ #sendPolicyForPath;
16
+ setSendPolicyResolver(resolve) {
17
+ this.#sendPolicyForPath = resolve;
18
+ }
19
+ deliveryAuthorizer;
20
+ frameLimitForPath;
21
+ constructor(ctx) {
22
+ this.ctx = ctx;
23
+ }
24
+ setDeliveryAuthorizer(authorizer) {
25
+ this.deliveryAuthorizer = authorizer;
26
+ }
27
+ /** Reconcile pre-migration/woken attachments with authoritative gateway metadata. */
28
+ setFrameLimitResolver(resolver) {
29
+ this.frameLimitForPath = resolver;
30
+ }
31
+ /**
32
+ * Run `admit` (the connection hook) with `ws` marked as being admitted, so a
33
+ * broadcast issued meanwhile (for example `server.emit()` announcing the new
34
+ * connection) skips the still-pending socket instead of rejecting it.
35
+ */
36
+ async admitting(ws, admit) {
37
+ this.#admitting.add(ws);
38
+ try {
39
+ return await admit();
40
+ } finally {
41
+ this.#admitting.delete(ws);
42
+ }
43
+ }
44
+ register(_client) {}
45
+ leaveAll(_client) {}
46
+ join(client, room) {
47
+ return client.join(room);
48
+ }
49
+ leave(client, room) {
50
+ return client.leave(room);
51
+ }
52
+ localIdsInRoom(room) {
53
+ return this.socketsForRoom(room).map((ws) => this.attachmentOf(ws).connId);
54
+ }
55
+ deliverLocal(cmd) {
56
+ const excludeIds = new Set(cmd.exceptIds ?? []);
57
+ const excludeRooms = cmd.exceptRooms ?? [];
58
+ const targets = cmd.rooms.length === 0 ? this.ctx.getWebSockets() : this.collectRooms(cmd.rooms);
59
+ const seen = /* @__PURE__ */ new Set();
60
+ const selected = [];
61
+ for (const ws of targets) {
62
+ const stored = this.attachmentOf(ws);
63
+ if (cmd.gatewayPath !== void 0 && stored.path !== cmd.gatewayPath) continue;
64
+ const att = this.reconcileFrameLimit(ws, stored);
65
+ if (att.state === "pending" && this.#admitting.has(ws)) continue;
66
+ if (att.state !== "active" || att.expiresAtMs !== void 0 && (!Number.isSafeInteger(att.expiresAtMs) || att.expiresAtMs <= Date.now())) {
67
+ try {
68
+ att.state = "rejected";
69
+ ws.serializeAttachment(att);
70
+ ws.close(1008, "identity expired or connection rejected");
71
+ } catch {}
72
+ continue;
73
+ }
74
+ if (seen.has(att.connId)) continue;
75
+ seen.add(att.connId);
76
+ if (excludeIds.has(att.connId)) continue;
77
+ if (excludeRooms.some((r) => att.rooms.includes(r))) continue;
78
+ selected.push({
79
+ ws,
80
+ client: this.clientFor(ws)
81
+ });
82
+ }
83
+ if (!this.deliveryAuthorizer) {
84
+ for (const { client } of selected) client.sendRaw(cmd.frame);
85
+ return;
86
+ }
87
+ return Promise.all(selected.map(async ({ ws, client }) => {
88
+ let allowed = false;
89
+ try {
90
+ allowed = await this.deliveryAuthorizer(client) === true;
91
+ } catch {
92
+ allowed = false;
93
+ }
94
+ if (allowed) client.sendRaw(cmd.frame);
95
+ else this.reject(ws, "delivery authorization revoked");
96
+ })).then(() => void 0);
97
+ }
98
+ collectRooms(rooms) {
99
+ const set = /* @__PURE__ */ new Set();
100
+ for (const room of rooms) for (const ws of this.socketsForRoom(room)) set.add(ws);
101
+ return [...set];
102
+ }
103
+ socketsForRoom(room) {
104
+ return this.ctx.getWebSockets().filter((ws) => this.attachmentOf(ws).rooms.includes(room));
105
+ }
106
+ attachmentOf(ws) {
107
+ return socketAttachment(ws) ?? rejectedAttachment();
108
+ }
109
+ /** Reconstruct a `WsClient` for a raw socket (e.g. inside gateway lifecycle scans). */
110
+ clientFor(ws) {
111
+ this.reconcileFrameLimit(ws, this.attachmentOf(ws));
112
+ let gate = this.#sendGates.get(ws);
113
+ if (!gate) {
114
+ gate = new WebSocketSendGate(this.#sendPolicyForPath?.(this.attachmentOf(ws).path));
115
+ this.#sendGates.set(ws, gate);
116
+ }
117
+ return new CfWsClient(this.ctx, ws, gate);
118
+ }
119
+ reconcileFrameLimit(ws, attachment) {
120
+ const expected = this.frameLimitForPath?.(attachment.path);
121
+ if (expected !== void 0 && attachment.maxFrameBytes !== expected) {
122
+ attachment.maxFrameBytes = expected;
123
+ ws.serializeAttachment(attachment);
124
+ }
125
+ return attachment;
126
+ }
127
+ reject(ws, reason) {
128
+ try {
129
+ const attachment = this.attachmentOf(ws);
130
+ attachment.state = "rejected";
131
+ ws.serializeAttachment(attachment);
132
+ ws.close(1008, reason);
133
+ } catch {}
134
+ }
135
+ };
136
+ //#endregion
137
+ export { CfRoomRegistry };
138
+
139
+ //# sourceMappingURL=cf-room-registry.js.map
@@ -0,0 +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 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;CA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