@velajs/cloudflare 1.34.0 → 1.36.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 (112) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +48 -9
  3. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorate.js +1 -2
  4. package/dist/_virtual/_@oxc-project_runtime@0.160.0/helpers/esm/decorateMetadata.js +5 -0
  5. package/dist/_virtual/_@oxc-project_runtime@0.160.0/helpers/esm/decorateParam.js +7 -0
  6. package/dist/bindings.js +1 -2
  7. package/dist/{cloudflare-application-Dsscb3Mo.d.ts → cloudflare-application-Zw9th_-h.d.ts} +2 -7
  8. package/dist/cloudflare-application.js +3 -4
  9. package/dist/cloudflare-application.js.map +1 -1
  10. package/dist/{cloudflare-factory-DM9CBvNH.d.ts → cloudflare-factory-Ab6XoKqO.d.ts} +5 -9
  11. package/dist/cloudflare-factory.js +6 -7
  12. package/dist/cloudflare-factory.js.map +1 -1
  13. package/dist/decorators/queue-consumer.js +1 -2
  14. package/dist/diagnostics.js +1 -2
  15. package/dist/durable-object/boot.js +5 -6
  16. package/dist/durable-object/host-dispatch.js +4 -5
  17. package/dist/durable-object/host-dispatch.js.map +1 -1
  18. package/dist/durable-object/host-methods.js +1 -2
  19. package/dist/durable-object/tokens.js +1 -2
  20. package/dist/durable-object/vela-durable-object.js +3 -4
  21. package/dist/durable-objects.d.ts +7 -19
  22. package/dist/durable-objects.js +1 -1
  23. package/dist/email/email-dispatch.js +1 -2
  24. package/dist/email/on-email.js +2 -3
  25. package/dist/email.d.ts +2 -6
  26. package/dist/email.js +1 -1
  27. package/dist/entrypoint/vela-entrypoint.js +4 -5
  28. package/dist/entrypoints.d.ts +3 -5
  29. package/dist/entrypoints.js +1 -2
  30. package/dist/environment.js +1 -2
  31. package/dist/host/host-invoker.js +2 -3
  32. package/dist/host/host-invoker.js.map +1 -1
  33. package/dist/host/host-members.js +1 -2
  34. package/dist/{host-members-DECj_4yz.d.ts → host-members-bKCWuJP2.d.ts} +0 -2
  35. package/dist/index.d.ts +99 -38
  36. package/dist/index.js +6 -5
  37. package/dist/nonce/durable-object-nonce.store.js +1 -2
  38. package/dist/nonce/nonce-validation.js +1 -2
  39. package/dist/nonce/nonce.durable-object.js +2 -3
  40. package/dist/nonce/nonce.durable-object.js.map +1 -1
  41. package/dist/{nonce.durable-object-Bg1e0BMD.d.ts → nonce.durable-object-Csuy3U9e.d.ts} +0 -4
  42. package/dist/pipelines.d.ts +1 -3
  43. package/dist/pipelines.js +1 -2
  44. package/dist/platform.js +2 -3
  45. package/dist/queue/cloudflare-queues.js +6 -7
  46. package/dist/queue/cloudflare-queues.js.map +1 -1
  47. package/dist/queue-events/consume.js +1 -2
  48. package/dist/queue-events/consume.js.map +1 -1
  49. package/dist/queue-events.d.ts +1 -2
  50. package/dist/queue-events.js +1 -2
  51. package/dist/queues.d.ts +2 -4
  52. package/dist/queues.js +1 -2
  53. package/dist/rate-limit/cloudflare-rate-limit.store.js +1 -2
  54. package/dist/rate-limit/d1-throttler.store.js +96 -0
  55. package/dist/rate-limit/d1-throttler.store.js.map +1 -0
  56. package/dist/root-module.js +1 -2
  57. package/dist/rpc/entrypoint-error.js +1 -2
  58. package/dist/rpc/entrypoint-error.js.map +1 -1
  59. package/dist/schedule-diagnostics.js +2 -3
  60. package/dist/schedule-diagnostics.js.map +1 -1
  61. package/dist/scheduled-event.js +1 -2
  62. package/dist/services/flagship-flag.driver.js +1 -2
  63. package/dist/services/flagship-flag.driver.js.map +1 -1
  64. package/dist/services/kv-cache.store.js +1 -2
  65. package/dist/services/kv-cache.store.js.map +1 -1
  66. package/dist/services/kv-flag.driver.js +1 -2
  67. package/dist/services/kv-flag.driver.js.map +1 -1
  68. package/dist/storage/r2-storage.js +3 -4
  69. package/dist/storage/r2-storage.js.map +1 -1
  70. package/dist/storage.d.ts +2 -4
  71. package/dist/storage.js +1 -2
  72. package/dist/tail/on-tail.js +2 -3
  73. package/dist/tail/tail-dispatch.js +2 -3
  74. package/dist/tail.d.ts +2 -6
  75. package/dist/tail.js +1 -2
  76. package/dist/testing.d.ts +5 -5
  77. package/dist/testing.js +6 -6
  78. package/dist/testing.js.map +1 -1
  79. package/dist/tracing.d.ts +1 -3
  80. package/dist/tracing.js +3 -4
  81. package/dist/{vela-env-DFvyoNT3.d.ts → vela-env-5graXefc.d.ts} +0 -1
  82. package/dist/websocket/binding-gateways.js +2 -3
  83. package/dist/websocket/cf-room-registry.js +2 -3
  84. package/dist/websocket/cf-room-registry.js.map +1 -1
  85. package/dist/websocket/cf-ws-client.js +2 -3
  86. package/dist/websocket/cf-ws-client.js.map +1 -1
  87. package/dist/websocket/do-bootstrap.js +5 -6
  88. package/dist/websocket/do-live.js +4 -5
  89. package/dist/websocket/do-live.js.map +1 -1
  90. package/dist/websocket/do-pitr.js +1 -2
  91. package/dist/websocket/do-pitr.js.map +1 -1
  92. package/dist/websocket/do-state.js +1 -2
  93. package/dist/websocket/do-websocket-host.js +3 -4
  94. package/dist/websocket/do-websocket-host.js.map +1 -1
  95. package/dist/websocket/live-driver.js +3 -4
  96. package/dist/websocket/live-driver.js.map +1 -1
  97. package/dist/websocket/room-id.js +1 -2
  98. package/dist/websocket/websocket.durable-object.js +5 -6
  99. package/dist/websocket/websocket.durable-object.js.map +1 -1
  100. package/dist/websocket/worker-transport.js +3 -4
  101. package/dist/websocket/ws-attachment.js +1 -2
  102. package/dist/worker-events.js +1 -2
  103. package/dist/workflow/portable-workflow-step.js +61 -0
  104. package/dist/workflow/portable-workflow-step.js.map +1 -0
  105. package/dist/workflow/vela-workflow-definition.js +77 -0
  106. package/dist/workflow/vela-workflow-definition.js.map +1 -0
  107. package/dist/workflow/vela-workflow.js +2 -3
  108. package/dist/workflow-definitions.d.ts +31 -0
  109. package/dist/workflow-definitions.js +1 -0
  110. package/dist/workflows.d.ts +2 -4
  111. package/dist/workflows.js +1 -2
  112. package/package.json +31 -21
package/dist/index.d.ts CHANGED
@@ -1,20 +1,15 @@
1
- import "./vela-env-DFvyoNT3.js";
2
- import { a as ScheduledEvent, i as CloudflareScheduledEvent, n as MountOpenApiOptions, r as CLOUDFLARE_SCHEDULED_EVENT, t as CloudflareApplication } from "./cloudflare-application-Dsscb3Mo.js";
3
- import { _ as defineCloudflareApp, a as CloudflareApp, c as CloudflareEntrypointDescriptor, d as CloudflareWorkerOptions, f as CloudflareWorkflowDescriptor, g as createCloudflareWorker, h as createCloudflareApp, i as CLOUDFLARE_WORKFLOW, l as CloudflareWorker, m as cloudflareAdapter, n as CLOUDFLARE_ENTRYPOINT, o as CloudflareAppOptions, p as CreateCloudflareAppOptions, r as CLOUDFLARE_WORKER, s as CloudflareDurableObjectDescriptor, t as CLOUDFLARE_DURABLE_OBJECT, u as CloudflareWorkerDescriptor, v as isCloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
4
- import { a as DoPitrId, c as DoPitrUnavailableError, d as isDoPitrUnavailable, f as readDoPitrBookmark, i as DoPitrBookmarkRead, l as VelaDoPitrRpc, n as DoPitrArmOptions, o as DoPitrNamespace, r as DoPitrArmResult, s as DoPitrStorage, t as VelaNonceDurableObject, u as armDoPitr } from "./nonce.durable-object-Bg1e0BMD.js";
5
- import { DynamicModule, Type, VelaEnv } from "@velajs/vela";
6
- import { Binding, BindingRef, EnvFactory, RuntimeAdapter } from "@velajs/vela/module-kit";
7
- import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
8
- import { BroadcastCommand } from "@velajs/vela/websocket";
1
+ import "./vela-env-5graXefc.js";
2
+ import { _ as defineCloudflareApp, a as CloudflareApp, c as CloudflareEntrypointDescriptor, d as CloudflareWorkerOptions, f as CloudflareWorkflowDescriptor, g as createCloudflareWorker, h as createCloudflareApp, i as CLOUDFLARE_WORKFLOW, l as CloudflareWorker, m as cloudflareAdapter, n as CLOUDFLARE_ENTRYPOINT, o as CloudflareAppOptions, p as CreateCloudflareAppOptions, r as CLOUDFLARE_WORKER, s as CloudflareDurableObjectDescriptor, t as CLOUDFLARE_DURABLE_OBJECT, u as CloudflareWorkerDescriptor, v as isCloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-Ab6XoKqO.js";
3
+ import { a as ScheduledEvent, i as CloudflareScheduledEvent, n as MountOpenApiOptions, r as CLOUDFLARE_SCHEDULED_EVENT, t as CloudflareApplication } from "./cloudflare-application-Zw9th_-h.js";
4
+ import { Binding, BindingRef, EnvFactory } from "@velajs/vela/module-kit";
9
5
  import { CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, CacheStore } from "@velajs/vela/cache";
10
- import { FeatureFlagDriver, FlagContext, FlagEvaluationDetails } from "@velajs/feature-flags";
6
+ import { a as DoPitrId, c as DoPitrUnavailableError, d as isDoPitrUnavailable, f as readDoPitrBookmark, i as DoPitrBookmarkRead, l as VelaDoPitrRpc, n as DoPitrArmOptions, o as DoPitrNamespace, r as DoPitrArmResult, s as DoPitrStorage, t as VelaNonceDurableObject, u as armDoPitr } from "./nonce.durable-object-Csuy3U9e.js";
7
+ import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
8
+ import { VelaEnv } from "@velajs/vela";
11
9
  import { ThrottlerStore } from "@velajs/vela/throttler";
12
10
  import { NonceStore } from "@velajs/vela/security";
13
- //#region src/websocket/room-id.d.ts
14
11
  /** Stable, collision-free Durable Object name for one gateway's room. */
15
12
  export declare function durableObjectRoomName(gatewayPath: string, roomId: string): string;
16
- //#endregion
17
- //#region src/rpc/entrypoint-error.d.ts
18
13
  /** What a failed JS-RPC call of a Vela entrypoint carries across the RPC boundary. */
19
14
  interface EntrypointErrorInit {
20
15
  /** An HTTP error status, 400–599. */
@@ -64,8 +59,6 @@ export declare class EntrypointError extends Error implements EntrypointErrorIni
64
59
  * this is false.
65
60
  */
66
61
  export declare function isEntrypointError(error: unknown): error is EntrypointError;
67
- //#endregion
68
- //#region src/bindings.d.ts
69
62
  export declare const kv: (ref: BindingRef) => Binding<KVNamespace<string>>;
70
63
  export declare const r2: (ref: BindingRef) => Binding<R2Bucket>;
71
64
  export declare const d1: (ref: BindingRef) => Binding<D1Database>;
@@ -84,8 +77,6 @@ export declare const rateLimit: (ref: BindingRef) => Binding<RateLimit>;
84
77
  export declare function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>>;
85
78
  export declare const flagship: (ref: BindingRef) => Binding<Flagship>;
86
79
  export declare const secretsStoreSecret: (ref: BindingRef) => Binding<SecretsStoreSecret>;
87
- //#endregion
88
- //#region src/services/kv-cache.store.d.ts
89
80
  /** A KV namespace, or a function that reads it when an operation needs it. */
90
81
  type KVNamespaceSource = KVNamespace | (() => KVNamespace);
91
82
  /**
@@ -137,8 +128,52 @@ export declare function kvCache(ref: {
137
128
  export declare function kvCacheInvalidation(ref: {
138
129
  binding: string;
139
130
  }): EnvFactory<CacheInvalidationStore>;
140
- //#endregion
141
- //#region src/services/flagship-flag.driver.d.ts
131
+ /**
132
+ * The cross-package contract every feature-flag backend implements.
133
+ *
134
+ * This is the seam that platform packages plug into: `@velajs/cloudflare`
135
+ * ships a Flagship-binding driver and a KV-backed driver against this exact
136
+ * interface, `@velajs/feature-flags` ships {@link MemoryFlagDriver}. A driver
137
+ * maps a key + fallback (+ optional targeting context) onto a value and
138
+ * returns the `fallback` when it cannot resolve the key. Unexpected failures
139
+ * may reject; the service owns the never-throw boundary.
140
+ *
141
+ * Optional detail methods preserve provider metadata. Without one, the service
142
+ * reports UNKNOWN: a returned fallback cannot be distinguished from a hit.
143
+ */
144
+ interface FeatureFlagDriver {
145
+ readonly name: string;
146
+ getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean>;
147
+ getString(key: string, fallback: string, ctx?: FlagContext): Promise<string>;
148
+ getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number>;
149
+ /** Object payloads remain unknown until the service applies the caller's parser. */
150
+ getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown>;
151
+ getBooleanDetails?(key: string, fallback: boolean, ctx?: FlagContext): Promise<FlagEvaluationDetails<boolean>>;
152
+ getStringDetails?(key: string, fallback: string, ctx?: FlagContext): Promise<FlagEvaluationDetails<string>>;
153
+ getNumberDetails?(key: string, fallback: number, ctx?: FlagContext): Promise<FlagEvaluationDetails<number>>;
154
+ getObjectDetails?(key: string, fallback: object, ctx?: FlagContext): Promise<FlagEvaluationDetails<unknown>>;
155
+ }
156
+ /**
157
+ * A value a feature flag can resolve to. Mirrors the four evaluation methods
158
+ * on {@link FeatureFlagDriver}.
159
+ */
160
+ type FlagValue = boolean | string | number | object;
161
+ /**
162
+ * A free-form evaluation context handed to a driver (for targeting: user id,
163
+ * plan, country, …). Drivers that don't do targeting ignore it.
164
+ */
165
+ type FlagContext = Record<string, unknown>;
166
+ /** Provider-defined reason, or UNKNOWN for drivers without evaluation metadata. */
167
+ type FlagEvaluationReason = string;
168
+ /** Provider metadata is preserved; unavailable reasons are UNKNOWN. */
169
+ interface FlagEvaluationDetails<T = FlagValue> {
170
+ flagKey: string;
171
+ value: T;
172
+ reason: FlagEvaluationReason;
173
+ variant?: string;
174
+ errorCode?: string;
175
+ errorMessage?: string;
176
+ }
142
177
  /**
143
178
  * The subset of a Cloudflare **Flagship** binding this driver evaluates against
144
179
  * — typed value methods and optional evaluation details. The binding itself returns the supplied
@@ -204,8 +239,6 @@ export declare class FlagshipFlagDriver implements FeatureFlagDriver {
204
239
  }
205
240
  /** Convenience factory for {@link FlagshipFlagDriver}. */
206
241
  export declare function flagshipFlagDriver(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions): FlagshipFlagDriver;
207
- //#endregion
208
- //#region src/services/kv-flag.driver.d.ts
209
242
  interface KvFlagDriverOptions {
210
243
  /** Driver name used for `use(name)` / default-driver selection. Default `"kv"`. */
211
244
  name?: string;
@@ -251,8 +284,6 @@ export declare class KvFlagDriver implements FeatureFlagDriver {
251
284
  }
252
285
  /** Convenience factory for {@link KvFlagDriver}. */
253
286
  export declare function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver;
254
- //#endregion
255
- //#region src/decorators/queue-consumer.d.ts
256
287
  interface QueueConsumerMetadata {
257
288
  queueName: string;
258
289
  methodName: string;
@@ -275,16 +306,12 @@ interface QueueConsumerMetadata {
275
306
  * ```
276
307
  */
277
308
  export declare function QueueConsumer(queueName: string): MethodDecorator;
278
- //#endregion
279
- //#region src/websocket/do-state.d.ts
280
309
  /** Structural view of the DO's SQLite handle (`ctx.storage.sql`, requires `new_sqlite_classes`). */
281
310
  interface SqlStorageLike {
282
311
  exec(query: string, ...bindings: unknown[]): {
283
312
  toArray(): Record<string, unknown>[];
284
313
  };
285
314
  }
286
- //#endregion
287
- //#region src/websocket/binding-gateways.d.ts
288
315
  /** A gateway whose rooms live in Durable Objects: its path and namespace binding. */
289
316
  interface BindingGateway {
290
317
  path: string;
@@ -292,15 +319,11 @@ interface BindingGateway {
292
319
  /** The gateway class name, for diagnostics. */
293
320
  name: string;
294
321
  }
295
- //#endregion
296
- //#region src/websocket/worker-transport.d.ts
297
322
  /** One gateway room's Durable Object: its id, and calls to its operations. */
298
323
  interface GatewayRoomObject {
299
324
  readonly id: unknown;
300
325
  call(method: string, ...args: unknown[]): Promise<unknown>;
301
326
  }
302
- //#endregion
303
- //#region src/websocket/live-driver.d.ts
304
327
  interface DurableObjectLiveOptions {
305
328
  /**
306
329
  * Durable Object namespace binding that holds the gateway's rooms, read from
@@ -366,8 +389,6 @@ declare class CfLiveDriver implements LiveDriver {
366
389
  * ```
367
390
  */
368
391
  export declare function durableObjectLive(options?: DurableObjectLiveOptions): CfLiveDriver;
369
- //#endregion
370
- //#region src/websocket/do-live.d.ts
371
392
  /**
372
393
  * The durable `CursorLog`: an append-only tag-invalidation log in the DO's
373
394
  * SQLite (`__vela_live_log`, AUTOINCREMENT seq = cursor) plus an epoch UUID in
@@ -398,8 +419,6 @@ export declare class DoCursorLog implements CursorLog {
398
419
  * gateway without roomParam keeps every room in one object, named by its path.
399
420
  */
400
421
  export declare function liveInvalidateToRoom(ns: LiveNamespace, gatewayPath: string, room: string, tags: string[]): Promise<CommitStamp | undefined>;
401
- //#endregion
402
- //#region src/rate-limit/cloudflare-rate-limit.store.d.ts
403
422
  interface RateLimitStoreOptions {
404
423
  /**
405
424
  * The Workers Rate Limiting binding (declared under `ratelimits`) that
@@ -434,8 +453,51 @@ interface RateLimitStoreOptions {
434
453
  * throttlers against the bindings when the application starts.
435
454
  */
436
455
  export declare function rateLimitStore(options: RateLimitStoreOptions): EnvFactory<ThrottlerStore>;
437
- //#endregion
438
- //#region src/nonce/durable-object-nonce.store.d.ts
456
+ interface D1ThrottlerStoreOptions {
457
+ /** The D1 binding (declared under `d1_databases`) that holds the counters. */
458
+ binding: string;
459
+ /** Counter table, created by {@link d1ThrottlerMigration}. Default `vela_rate_limits`. */
460
+ table?: string;
461
+ /** Bound attacker-influenced tracking keys before they reach D1. Default 1024 bytes. */
462
+ maxKeyBytes?: number;
463
+ /**
464
+ * Remove up to this many ended windows on about one count in 100, so the
465
+ * table does not grow with every client ever seen. Default 100; 0 never
466
+ * prunes (prune on a schedule instead).
467
+ */
468
+ pruneBatch?: number;
469
+ }
470
+ /** A D1 store with its table and a way to drop ended windows on a schedule. */
471
+ interface D1ThrottlerStore extends ThrottlerStore {
472
+ /** Delete up to `limit` ended windows; answers how many went. */
473
+ prune(limit?: number): Promise<number>;
474
+ }
475
+ /**
476
+ * The statements that create the counter table and its expiry index, for a D1
477
+ * migration file (each one a complete statement; end them with `;`).
478
+ */
479
+ export declare function d1ThrottlerMigration(options?: {
480
+ table?: string;
481
+ }): string[];
482
+ /**
483
+ * `ThrottlerModule` storage on D1, read from each application's `ENV` by name:
484
+ *
485
+ * ```ts
486
+ * ThrottlerModule.forRoot({
487
+ * throttlers: [{ name: 'login', ttl: 10 * 60_000, limit: 30 }],
488
+ * storage: d1ThrottlerStore({ binding: 'DB' }),
489
+ * })
490
+ * ```
491
+ *
492
+ * Every count is one `INSERT … ON CONFLICT … RETURNING` statement: D1 runs it
493
+ * atomically on the database's primary, so all isolates and locations share
494
+ * one exact fixed-window counter per key, with windows of any length and
495
+ * `@Throttle()` overrides. Each counted request costs one D1 write, and about
496
+ * one in 100 also deletes up to `pruneBatch` ended windows. The store
497
+ * also reads and resets counters, which `FailureCounter` needs. Create the
498
+ * table with {@link d1ThrottlerMigration}.
499
+ */
500
+ export declare function d1ThrottlerStore(options: D1ThrottlerStoreOptions): EnvFactory<D1ThrottlerStore>;
439
501
  /** The generated Workers binding type for {@link VelaNonceDurableObject}. */
440
502
  type DurableObjectNonceNamespace = DurableObjectNamespace<VelaNonceDurableObject>;
441
503
  interface DurableObjectNonceStoreOptions {
@@ -461,5 +523,4 @@ interface DurableObjectNonceStoreOptions {
461
523
  * the Durable Object is accepted.
462
524
  */
463
525
  export declare function durableObjectNonceStore(options: DurableObjectNonceStoreOptions): NonceStore;
464
- //#endregion
465
- export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, type CfLiveDriver, type CloudflareApp, type CloudflareAppOptions, CloudflareApplication, type CloudflareDurableObjectDescriptor, type CloudflareEntrypointDescriptor, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorker, type CloudflareWorkerDescriptor, type CloudflareWorkerOptions, type CloudflareWorkflowDescriptor, type CreateCloudflareAppOptions, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type EntrypointErrorInit, type FlagshipBinding, type FlagshipFlagDriverOptions, type KVNamespaceSource, type KvFlagDriverOptions, type LiveNamespace, type MountOpenApiOptions, type QueueConsumerMetadata, type RateLimitStoreOptions, type ScheduledEvent, type VelaDoPitrRpc, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, isDoPitrUnavailable, readDoPitrBookmark };
526
+ export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, type CfLiveDriver, type CloudflareApp, type CloudflareAppOptions, CloudflareApplication, type CloudflareDurableObjectDescriptor, type CloudflareEntrypointDescriptor, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorker, type CloudflareWorkerDescriptor, type CloudflareWorkerOptions, type CloudflareWorkflowDescriptor, type CreateCloudflareAppOptions, type D1ThrottlerStore, type D1ThrottlerStoreOptions, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type EntrypointErrorInit, type FlagshipBinding, type FlagshipFlagDriverOptions, type KVNamespaceSource, type KvFlagDriverOptions, type LiveNamespace, type MountOpenApiOptions, type QueueConsumerMetadata, type RateLimitStoreOptions, type ScheduledEvent, type VelaDoPitrRpc, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, isDoPitrUnavailable, readDoPitrBookmark };
package/dist/index.js CHANGED
@@ -1,16 +1,17 @@
1
1
  import { durableObjectRoomName } from "./websocket/room-id.js";
2
- import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
3
- import { CloudflareApplication } from "./cloudflare-application.js";
4
- import { d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow } from "./bindings.js";
5
- import { durableObjectLive } from "./websocket/live-driver.js";
6
2
  import { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp } from "./cloudflare-factory.js";
3
+ import { CloudflareApplication } from "./cloudflare-application.js";
7
4
  import { EntrypointError, isEntrypointError } from "./rpc/entrypoint-error.js";
5
+ import { d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow } from "./bindings.js";
8
6
  import { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation } from "./services/kv-cache.store.js";
9
7
  import { FlagshipFlagDriver, flagshipFlagDriver } from "./services/flagship-flag.driver.js";
10
8
  import { KvFlagDriver, kvFlagDriver } from "./services/kv-flag.driver.js";
11
9
  import { QueueConsumer } from "./decorators/queue-consumer.js";
10
+ import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
12
11
  import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookmark } from "./websocket/do-pitr.js";
13
12
  import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
13
+ import { durableObjectLive } from "./websocket/live-driver.js";
14
+ import { d1ThrottlerMigration, d1ThrottlerStore } from "./rate-limit/d1-throttler.store.js";
14
15
  import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
15
16
  import { durableObjectNonceStore } from "./nonce/durable-object-nonce.store.js";
16
- export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, EntrypointError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, defineCloudflareApp, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagship, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, secretsStoreSecret, workflow };
17
+ export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, EntrypointError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, d1ThrottlerMigration, d1ThrottlerStore, defineCloudflareApp, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagship, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, secretsStoreSecret, workflow };
@@ -1,5 +1,5 @@
1
1
  import { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from "./nonce-validation.js";
2
- //#region src/nonce/durable-object-nonce.store.ts
2
+ // src/nonce/durable-object-nonce.store.ts
3
3
  const APP_NAMESPACE_PREFIX = "vela:nonce:v1:";
4
4
  const MAX_APP_NAMESPACE_BYTES = 128;
5
5
  /**
@@ -27,7 +27,6 @@ function durableObjectNonceStore(options) {
27
27
  }
28
28
  } };
29
29
  }
30
- //#endregion
31
30
  export { durableObjectNonceStore };
32
31
 
33
32
  //# sourceMappingURL=durable-object-nonce.store.js.map
@@ -1,4 +1,4 @@
1
- //#region src/nonce/nonce-validation.ts
1
+ // src/nonce/nonce-validation.ts
2
2
  const encoder = new TextEncoder();
3
3
  const MAX_NONCE_BYTES = 512;
4
4
  function isCanonicalBoundedText(value, maxBytes) {
@@ -12,7 +12,6 @@ function isCanonicalBoundedText(value, maxBytes) {
12
12
  function isValidExpiry(expEpochSeconds, nowEpochSeconds) {
13
13
  return typeof expEpochSeconds === "number" && Number.isSafeInteger(expEpochSeconds) && expEpochSeconds > 0 && expEpochSeconds >= nowEpochSeconds;
14
14
  }
15
- //#endregion
16
15
  export { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry };
17
16
 
18
17
  //# sourceMappingURL=nonce-validation.js.map
@@ -1,6 +1,6 @@
1
- import { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from "./nonce-validation.js";
2
1
  import { DurableObject } from "cloudflare:workers";
3
- //#region src/nonce/nonce.durable-object.ts
2
+ import { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from "./nonce-validation.js";
3
+ // src/nonce/nonce.durable-object.ts
4
4
  const EXPIRED_DELETE_BATCH = 1024;
5
5
  const CREATE_TABLE = "CREATE TABLE IF NOT EXISTS __vela_nonce_claims (nonce TEXT PRIMARY KEY NOT NULL, expires_at INTEGER NOT NULL CHECK (expires_at > 0)) WITHOUT ROWID";
6
6
  const CREATE_EXPIRY_INDEX = "CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)";
@@ -48,7 +48,6 @@ var VelaNonceDurableObject = class extends DurableObject {
48
48
  }
49
49
  }
50
50
  };
51
- //#endregion
52
51
  export { VelaNonceDurableObject };
53
52
 
54
53
  //# sourceMappingURL=nonce.durable-object.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"nonce.durable-object.js","names":[],"sources":["../../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;AAEA,MAAM,uBAAuB;AAE7B,MAAM,eACJ;AAIF,MAAM,sBACJ;AACF,MAAM,iBACJ;AAIF,MAAM,eACJ;;;;;;;;;AAmBF,IAAa,yBAAb,cAA4C,cAAuC;CACjF;CAEA,YAAY,KAAyB,KAA8B;EACjE,MAAM,KAAK,GAAG;EACd,IAAI;GACF,MAAM,MAAM,IAAI,SAAS;GACzB,IAAI,CAAC,OAAO,OAAO,IAAI,SAAS,YAAY;GAC5C,IAAI,KAAK,YAAY;GACrB,IAAI,KAAK,mBAAmB;GAC5B,KAAK,MAAM;EACb,QAAQ;GAEN,KAAK,MAAM,KAAA;EACb;CACF;CAEA,MAAM,MAAM,OAAe,iBAA2C;EACpE,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAK;EACzC,IAAI,CAAC,uBAAuB,OAAO,eAAe,KAAK,CAAC,cAAc,iBAAiB,GAAG,GACxF,OAAO;EAGT,IAAI;GAGF,IAAI,KAAK,gBAAgB,KAAK,oBAAoB;GAElD,MAAM,SAAS,IAAI,KAAK,cAAc,OAAO,eAAe;GAC5D,IAAI,CAAC,UAAU,OAAO,OAAO,YAAY,YAAY,OAAO;GAC5D,MAAM,OAAgB,OAAO,QAAQ;GACrC,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,GAAG,OAAO;GAEtD,MAAM,MAAe,KAAK;GAC1B,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,OAAO;GACpD,IACE,CAAC,OAAO,OAAO,KAAK,OAAO,KAC3B,CAAC,OAAO,OAAO,KAAK,YAAY,KAChC,EAAE,WAAW,QACb,EAAE,gBAAgB,MAElB,OAAO;GAET,OAAO,IAAI,UAAU,SAAS,IAAI,eAAe;EACnD,QAAQ;GACN,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"nonce.durable-object.js","names":[],"sources":["../../src/nonce/nonce.durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport { MAX_NONCE_BYTES, isCanonicalBoundedText, isValidExpiry } from './nonce-validation';\nconst EXPIRED_DELETE_BATCH = 1_024;\n\nconst CREATE_TABLE =\n 'CREATE TABLE IF NOT EXISTS __vela_nonce_claims (' +\n 'nonce TEXT PRIMARY KEY NOT NULL, ' +\n 'expires_at INTEGER NOT NULL CHECK (expires_at > 0)' +\n ') WITHOUT ROWID';\nconst CREATE_EXPIRY_INDEX =\n 'CREATE INDEX IF NOT EXISTS __vela_nonce_claims_expiry ON __vela_nonce_claims (expires_at)';\nconst DELETE_EXPIRED =\n 'DELETE FROM __vela_nonce_claims WHERE nonce IN (' +\n 'SELECT nonce FROM __vela_nonce_claims ' +\n 'WHERE expires_at < ? ORDER BY expires_at LIMIT ?' +\n ')';\nconst INSERT_CLAIM =\n 'INSERT INTO __vela_nonce_claims (nonce, expires_at) VALUES (?, ?) ' +\n 'ON CONFLICT(nonce) DO NOTHING RETURNING nonce, expires_at';\n\ninterface NonceSqlCursor {\n toArray(): Record<string, unknown>[];\n}\n\ninterface NonceSqlStorage {\n exec(query: string, ...bindings: unknown[]): NonceSqlCursor;\n}\n\n/**\n * SQLite Durable Object that atomically consumes nonces.\n *\n * Export this class from the Worker entry and register it through a Wrangler\n * `new_sqlite_classes` migration. `INSERT ... ON CONFLICT DO NOTHING RETURNING`\n * is the single-use decision; all SQL runs synchronously before the RPC method\n * yields, and the nonce primary key is the final concurrency boundary.\n */\nexport class VelaNonceDurableObject extends DurableObject<Record<string, unknown>> {\n private sql?: NonceSqlStorage;\n\n constructor(ctx: DurableObjectState, env: Record<string, unknown>) {\n super(ctx, env);\n try {\n const sql = ctx.storage?.sql;\n if (!sql || typeof sql.exec !== 'function') return;\n sql.exec(CREATE_TABLE);\n sql.exec(CREATE_EXPIRY_INDEX);\n this.sql = sql;\n } catch {\n // A non-SQLite/misconfigured class stays fail-closed: every claim denies.\n this.sql = undefined;\n }\n }\n\n async claim(nonce: string, expEpochSeconds: number): Promise<boolean> {\n const sql = this.sql;\n if (!sql) return false;\n\n const now = Math.floor(Date.now() / 1_000);\n if (!isCanonicalBoundedText(nonce, MAX_NONCE_BYTES) || !isValidExpiry(expEpochSeconds, now)) {\n return false;\n }\n\n try {\n // Keep cleanup bounded so one claim cannot monopolize the DO. Entries at\n // exactly `now` remain: Vela's invocation verifier accepts `now === exp`.\n sql.exec(DELETE_EXPIRED, now, EXPIRED_DELETE_BATCH);\n\n const cursor = sql.exec(INSERT_CLAIM, nonce, expEpochSeconds);\n if (!cursor || typeof cursor.toArray !== 'function') return false;\n const rows: unknown = cursor.toArray();\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n\n const row: unknown = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n if (\n !Object.hasOwn(row, 'nonce') ||\n !Object.hasOwn(row, 'expires_at') ||\n !('nonce' in row) ||\n !('expires_at' in row)\n ) {\n return false;\n }\n return row.nonce === nonce && row.expires_at === expEpochSeconds;\n } catch {\n return false;\n }\n }\n}\n"],"mappings":";;;AAEA,MAAM,uBAAuB;AAE7B,MAAM,eACJ;AAIF,MAAM,sBACJ;AACF,MAAM,iBACJ;AAIF,MAAM,eACJ;;;;;;;;;AAmBF,IAAa,yBAAb,cAA4C,cAAuC;CACzE;CAER,YAAY,KAAyB,KAA8B;EACjE,MAAM,KAAK,GAAG;EACd,IAAI;GACF,MAAM,MAAM,IAAI,SAAS;GACzB,IAAI,CAAC,OAAO,OAAO,IAAI,SAAS,YAAY;GAC5C,IAAI,KAAK,YAAY;GACrB,IAAI,KAAK,mBAAmB;GAC5B,KAAK,MAAM;EACb,QAAQ;GAEN,KAAK,MAAM,KAAA;EACb;CACF;CAEA,MAAM,MAAM,OAAe,iBAA2C;EACpE,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAK;EACzC,IAAI,CAAC,uBAAuB,OAAO,eAAe,KAAK,CAAC,cAAc,iBAAiB,GAAG,GACxF,OAAO;EAGT,IAAI;GAGF,IAAI,KAAK,gBAAgB,KAAK,oBAAoB;GAElD,MAAM,SAAS,IAAI,KAAK,cAAc,OAAO,eAAe;GAC5D,IAAI,CAAC,UAAU,OAAO,OAAO,YAAY,YAAY,OAAO;GAC5D,MAAM,OAAgB,OAAO,QAAQ;GACrC,IAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,KAAK,WAAW,GAAG,OAAO;GAEtD,MAAM,MAAe,KAAK;GAC1B,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,OAAO;GACpD,IACE,CAAC,OAAO,OAAO,KAAK,OAAO,KAC3B,CAAC,OAAO,OAAO,KAAK,YAAY,KAChC,EAAE,WAAW,QACb,EAAE,gBAAgB,MAElB,OAAO;GAET,OAAO,IAAI,UAAU,SAAS,IAAI,eAAe;EACnD,QAAQ;GACN,OAAO;EACT;CACF;AACF"}
@@ -1,5 +1,4 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
- //#region src/websocket/do-pitr.d.ts
3
2
  /**
4
3
  * Durable Object point-in-time recovery (PITR) — thin, testable wrappers over a
5
4
  * SQLite-backed DO's native bookmark API. A SQLite Durable Object exposes three
@@ -114,8 +113,6 @@ declare function readDoPitrBookmark(storage: DoPitrStorage, time?: number | stri
114
113
  * arming API (or the by-time resolver a `time` target needs) is absent.
115
114
  */
116
115
  declare function armDoPitr(storage: DoPitrStorage, opts: DoPitrArmOptions): Promise<DoPitrArmResult>;
117
- //#endregion
118
- //#region src/nonce/nonce.durable-object.d.ts
119
116
  /**
120
117
  * SQLite Durable Object that atomically consumes nonces.
121
118
  *
@@ -129,5 +126,4 @@ declare class VelaNonceDurableObject extends DurableObject<Record<string, unknow
129
126
  constructor(ctx: DurableObjectState, env: Record<string, unknown>);
130
127
  claim(nonce: string, expEpochSeconds: number): Promise<boolean>;
131
128
  }
132
- //#endregion
133
129
  export { DoPitrId as a, DoPitrUnavailableError as c, isDoPitrUnavailable as d, readDoPitrBookmark as f, DoPitrBookmarkRead as i, VelaDoPitrRpc as l, DoPitrArmOptions as n, DoPitrNamespace as o, DoPitrArmResult as r, DoPitrStorage as s, VelaNonceDurableObject as t, armDoPitr as u };
@@ -1,5 +1,4 @@
1
1
  import { StandardSchemaV1 } from "@velajs/vela/validation";
2
- //#region src/pipelines.d.ts
3
2
  /** The native stream handle remains usable independently of the writer. */
4
3
  export interface PipelinesBinding<Output = Record<string, unknown>> {
5
4
  readonly send: (records: Output[]) => Promise<void>;
@@ -16,5 +15,4 @@ export interface PipelinesWriter<Input> {
16
15
  */
17
16
  export declare function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>, { schema }: {
18
17
  readonly schema: S;
19
- }): PipelinesWriter<StandardSchemaV1.InferInput<S>>;
20
- //#endregion
18
+ }): PipelinesWriter<StandardSchemaV1.InferInput<S>>;
package/dist/pipelines.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { SchemaValidationError, isStandardSchema, parseSchemaAsync } from "@velajs/vela/validation";
2
- //#region src/pipelines.ts
2
+ // src/pipelines.ts
3
3
  const MAX_BATCH_BYTES = 5e6;
4
4
  const encoder = new TextEncoder();
5
5
  /**
@@ -81,7 +81,6 @@ function snapshotJson(value, path, ancestors) {
81
81
  ancestors.delete(value);
82
82
  }
83
83
  }
84
- //#endregion
85
84
  export { createPipelinesWriter };
86
85
 
87
86
  //# sourceMappingURL=pipelines.js.map
package/dist/platform.js CHANGED
@@ -1,8 +1,8 @@
1
- import { registerCloudflareEnvironment } from "./environment.js";
2
1
  import { defineProvider } from "@velajs/vela";
3
2
  import { LIVE_PLATFORM } from "@velajs/vela/live";
4
3
  import { WS_TRANSPORT } from "@velajs/vela/websocket";
5
- //#region src/platform.ts
4
+ import { registerCloudflareEnvironment } from "./environment.js";
5
+ // src/platform.ts
6
6
  /**
7
7
  * Seed the application's ENV and its platform wiring, as global tokens,
8
8
  * before any module loads: `WebSocketModule` and `LiveModule` read
@@ -16,7 +16,6 @@ function registerCloudflarePlatform(container, env, platform) {
16
16
  container.register(defineProvider(LIVE_PLATFORM, { useValue: platform.live }));
17
17
  container.markGlobalToken(LIVE_PLATFORM);
18
18
  }
19
- //#endregion
20
19
  export { registerCloudflarePlatform };
21
20
 
22
21
  //# sourceMappingURL=platform.js.map
@@ -1,7 +1,7 @@
1
- import { QUEUE_PRODUCER } from "../bindings.js";
2
- import { resolveBinding } from "@velajs/vela/module-kit";
3
1
  import { QueueBatchError, observeMessage, parseQueueJob } from "@velajs/vela/queue";
4
- //#region src/queue/cloudflare-queues.ts
2
+ import { resolveBinding } from "@velajs/vela/module-kit";
3
+ import { QUEUE_PRODUCER } from "../bindings.js";
4
+ // src/queue/cloudflare-queues.ts
5
5
  /** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */
6
6
  const QUEUE_SEND_LIMITS = Object.freeze({
7
7
  /** Messages per `sendBatch` call. */
@@ -102,8 +102,8 @@ function createDriver({ env, queues }) {
102
102
  for (const queue of queues.all()) for (const physical of queue.consumers) pins.set(physical, [...pins.get(physical) ?? [], queue.name]);
103
103
  const producerFor = (name) => {
104
104
  const registration = queues.get(name);
105
- if (!registration) throw new Error(`Queue '${name}' is not registered. Add QueueModule.registerQueue({ name: '${name}', binding }) to the module that produces it.`);
106
- if (registration.binding === void 0) throw new Error(`Queue '${name}' has no producer binding. Register it with QueueModule.registerQueue({ name: '${name}', binding: 'YOUR_QUEUE' }), where the binding is a queues.producers[].binding of this Worker.`);
105
+ if (!registration) throw new Error(`Queue '${name}' is not registered. Add QueueModule.forFeature([{ name: '${name}', binding }]) to the module that produces it.`);
106
+ if (registration.binding === void 0) throw new Error(`Queue '${name}' has no producer binding. Register it with QueueModule.forFeature([{ name: '${name}', binding: 'YOUR_QUEUE' }]), where the binding is a queues.producers[].binding of this Worker.`);
107
107
  try {
108
108
  return resolveBinding(env, { binding: registration.binding }, QUEUE_PRODUCER);
109
109
  } catch (error) {
@@ -171,7 +171,7 @@ function createDriver({ env, queues }) {
171
171
  *
172
172
  * ```ts
173
173
  * QueueModule.forRoot({ driver: cloudflareQueues() })
174
- * QueueModule.registerQueue({ name: 'email', binding: 'EMAIL_QUEUE' })
174
+ * QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])
175
175
  * ```
176
176
  *
177
177
  * Each application gets its own driver. Producing reads the registered binding
@@ -209,7 +209,6 @@ async function consumeQueueBatch(batch, dispatch, options = {}) {
209
209
  if (errors.length === 1) throw errors[0];
210
210
  if (errors.length > 1) throw new AggregateError(errors, "Queue batch deliveries failed.");
211
211
  }
212
- //#endregion
213
212
  export { QUEUE_SEND_LIMITS, cloudflareQueues, consumeQueueBatch, estimateQueueMessageBytes };
214
213
 
215
214
  //# sourceMappingURL=cloudflare-queues.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-queues.js","names":[],"sources":["../../src/queue/cloudflare-queues.ts"],"sourcesContent":["import { observeMessage, parseQueueJob, QueueBatchError } from '@velajs/vela/queue';\nimport { resolveBinding } from '@velajs/vela/module-kit';\nimport { QUEUE_PRODUCER } from '../bindings';\nimport type {\n AddJobOptions,\n QueueDispatchFn,\n QueueDispatchResult,\n QueueDriver,\n QueueDriverContext,\n QueueDriverFactory,\n QueueEnqueueRequest,\n QueueJob,\n QueueMessageLike,\n} from '@velajs/vela/queue';\n\n/** The native producer surface the driver uses: a Wrangler `queues.producers` binding. */\nexport interface CloudflareQueueProducer {\n // Both older void-returning bindings and current metric-returning bindings work.\n send(message: QueueJob, options?: QueueSendOptions): Promise<unknown>;\n sendBatch?(messages: Iterable<MessageSendRequest<QueueJob>>): Promise<unknown>;\n}\n\n/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */\nexport const QUEUE_SEND_LIMITS = Object.freeze({\n /** Messages per `sendBatch` call. */\n messages: 100,\n /** Estimated bytes per `sendBatch` call. */\n batchBytes: 256_000,\n /** Estimated bytes per message. */\n messageBytes: 128_000,\n});\n\n/** Allowance for the platform's per-message framing on top of the body estimate. */\nconst MESSAGE_MARGIN_BYTES = 256;\nconst MAX_DELAY_MS = 86_400_000;\n\n/**\n * A string's size as JSON (UTF-8, quoted, escaped) or as V8 serializes it\n * (one byte per character, two for a string holding any character above\n * U+00FF), whichever is larger.\n */\nfunction stringBytes(text: string): number {\n let json = 2;\n let wide = false;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code > 0xff) wide = true;\n if (code < 0x20) json += 6;\n else if (code === 0x22 || code === 0x5c) json += 2;\n else if (code < 0x80) json += 1;\n else if (code < 0x800) json += 2;\n else if (code >= 0xd800 && code <= 0xdfff) json += 2;\n else json += 3;\n }\n return Math.max(json, (wide ? text.length * 2 : text.length) + 5);\n}\n\nfunction measure(value: unknown, seen: Set<object>): number {\n switch (typeof value) {\n case 'string':\n return stringBytes(value);\n case 'number':\n return Math.max(String(value).length, 9);\n case 'bigint':\n return String(value).length + 9;\n case 'boolean':\n return 5;\n case 'object':\n break;\n default:\n return 9;\n }\n if (value === null) return 4;\n // V8 serializes a repeated reference as a back-reference.\n if (seen.has(value)) return 9;\n seen.add(value);\n let bytes = 2;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n bytes += value.byteLength + 9;\n } else if (value instanceof Date) {\n bytes += 26;\n } else if (value instanceof Map) {\n for (const [key, item] of value) bytes += measure(key, seen) + measure(item, seen) + 2;\n } else if (value instanceof Set) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else if (Array.isArray(value)) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else {\n for (const key of Object.keys(value)) {\n bytes += stringBytes(key) + measure(Reflect.get(value, key), seen) + 2;\n }\n }\n return bytes;\n}\n\n/**\n * A conservative size estimate of one native queue message: the larger of the\n * body's JSON and V8 sizes, plus a per-message margin.\n */\nexport function estimateQueueMessageBytes(body: unknown): number {\n return measure(body, new Set()) + MESSAGE_MARGIN_BYTES;\n}\n\nfunction delaySeconds(options: AddJobOptions | undefined): number | undefined {\n const delayMs = options?.delayMs;\n if (delayMs === undefined) return undefined;\n if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > MAX_DELAY_MS) {\n throw new RangeError('Queue delayMs must be between 0 and 86400000.');\n }\n return Math.ceil(delayMs / 1000);\n}\n\nfunction nativeBatch(payload: unknown): { queue: string; messages: QueueMessageLike[] } {\n if (\n typeof payload !== 'object' ||\n payload === null ||\n !('queue' in payload) ||\n typeof payload.queue !== 'string' ||\n !('messages' in payload) ||\n !Array.isArray(payload.messages)\n )\n throw new TypeError('Invalid native queue batch.');\n const messages: QueueMessageLike[] = [];\n for (const message of payload.messages as unknown[]) {\n if (\n typeof message !== 'object' ||\n message === null ||\n !('body' in message) ||\n !('ack' in message) ||\n typeof message.ack !== 'function' ||\n !('retry' in message) ||\n typeof message.retry !== 'function' ||\n !('id' in message) ||\n typeof message.id !== 'string' ||\n !('timestamp' in message) ||\n !(message.timestamp instanceof Date) ||\n !('attempts' in message) ||\n typeof message.attempts !== 'number'\n )\n throw new TypeError('Invalid native queue message.');\n messages.push(message as QueueMessageLike);\n }\n return { queue: payload.queue, messages };\n}\n\ninterface PreparedMessage {\n readonly id: string;\n readonly queue: string;\n readonly bytes: number;\n readonly request: MessageSendRequest<QueueJob>;\n}\n\n/** Split in order: a new call starts at 100 messages, at the byte budget, or at another queue. */\nfunction chunk(messages: readonly PreparedMessage[]): PreparedMessage[][] {\n const chunks: PreparedMessage[][] = [];\n let current: PreparedMessage[] = [];\n let bytes = 0;\n for (const message of messages) {\n if (\n current.length > 0 &&\n (current.length === QUEUE_SEND_LIMITS.messages ||\n bytes + message.bytes > QUEUE_SEND_LIMITS.batchBytes ||\n current[0]!.queue !== message.queue)\n ) {\n chunks.push(current);\n current = [];\n bytes = 0;\n }\n current.push(message);\n bytes += message.bytes;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction createDriver({ env, queues }: QueueDriverContext): QueueDriver {\n // Physical queue -> the logical queues registrations pin to it.\n const pins = new Map<string, string[]>();\n for (const queue of queues.all()) {\n for (const physical of queue.consumers) {\n pins.set(physical, [...(pins.get(physical) ?? []), queue.name]);\n }\n }\n\n // Resolved on every send from this application's ENV, never cached.\n const producerFor = (name: string): CloudflareQueueProducer => {\n const registration = queues.get(name);\n if (!registration) {\n throw new Error(\n `Queue '${name}' is not registered. Add QueueModule.registerQueue({ name: '${name}', ` +\n `binding }) to the module that produces it.`,\n );\n }\n if (registration.binding === undefined) {\n throw new Error(\n `Queue '${name}' has no producer binding. Register it with ` +\n `QueueModule.registerQueue({ name: '${name}', binding: 'YOUR_QUEUE' }), where the ` +\n `binding is a queues.producers[].binding of this Worker.`,\n );\n }\n try {\n return resolveBinding(env, { binding: registration.binding }, QUEUE_PRODUCER);\n } catch (error) {\n throw new Error(\n `Queue '${name}' cannot send: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n };\n\n return {\n kind: 'cloudflare',\n entrypoints: [{ kind: 'cf:queue:module', meta: { consumers: [...pins.keys()] } }],\n\n async consume(payload: unknown, dispatch: QueueDispatchFn): Promise<void> {\n const batch = nativeBatch(payload);\n const pinned = pins.get(batch.queue);\n await consumeQueueBatch(\n batch,\n (job) => {\n // A pinned queue is consumed only from the physical queues it names.\n const expected = queues.get(job.queue)?.consumers ?? [];\n if (expected.length > 0 && !expected.includes(batch.queue)) {\n throw new Error(\n `Queue '${job.queue}' is consumed from ` +\n `${expected.map((queue) => `'${queue}'`).join(', ')}, not '${batch.queue}'.`,\n );\n }\n return dispatch(job);\n },\n pinned ? { queues: pinned } : {},\n );\n },\n\n async enqueue(job: QueueJob, options?: AddJobOptions): Promise<void> {\n const delay = delaySeconds(options);\n await producerFor(job.queue).send(\n parseQueueJob(job),\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n },\n\n async enqueueBatch(requests: readonly QueueEnqueueRequest[]): Promise<void> {\n // Validate every job and resolve every binding before the first send.\n const messages = requests.map(({ job, options }): PreparedMessage => {\n const body = parseQueueJob(job);\n const bytes = estimateQueueMessageBytes(body);\n if (bytes > QUEUE_SEND_LIMITS.messageBytes) {\n throw new RangeError(\n `Queue job '${job.id}' is an estimated ${bytes} bytes, over the ` +\n `${QUEUE_SEND_LIMITS.messageBytes}-byte Cloudflare message limit. Store large ` +\n `payloads elsewhere (for example in R2) and enqueue a reference.`,\n );\n }\n const delay = delaySeconds(options);\n return {\n id: job.id,\n queue: job.queue,\n bytes,\n request: delay === undefined ? { body } : { body, delaySeconds: delay },\n };\n });\n const producers = new Map<string, CloudflareQueueProducer>();\n for (const { queue } of messages) {\n if (!producers.has(queue)) producers.set(queue, producerFor(queue));\n }\n const accepted: string[] = [];\n for (const part of chunk(messages)) {\n const producer = producers.get(part[0]!.queue)!;\n try {\n if (typeof producer.sendBatch === 'function') {\n // eslint-disable-next-line no-await-in-loop\n await producer.sendBatch(part.map(({ request }) => request));\n accepted.push(...part.map(({ id }) => id));\n } else {\n for (const { id, request } of part) {\n const delay = request.delaySeconds;\n // eslint-disable-next-line no-await-in-loop\n await producer.send(\n request.body,\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n accepted.push(id);\n }\n }\n } catch (error) {\n throw new QueueBatchError(\n accepted,\n messages.slice(accepted.length).map(({ id }) => id),\n error,\n );\n }\n }\n },\n };\n}\n\n/**\n * The Cloudflare Queues driver for `QueueModule`:\n *\n * ```ts\n * QueueModule.forRoot({ driver: cloudflareQueues() })\n * QueueModule.registerQueue({ name: 'email', binding: 'EMAIL_QUEUE' })\n * ```\n *\n * Each application gets its own driver. Producing reads the registered binding\n * from that application's `ENV` when a job is added and awaits the native\n * send; `addBulk` uses `sendBatch`, chunked to {@link QUEUE_SEND_LIMITS}.\n * Consuming is native too: the Worker's `queue()` handler routes every batch\n * that no `@QueueConsumer` claims through `QueueModule`, one message at a time,\n * by each job's logical `queue`, with the module's dispatch policy (signed\n * dispatch included). A registration's `consumer` pins its queue to that\n * physical queue: the queue's jobs are accepted only from it, and it only\n * carries the queues pinned to it. A message that is not a job envelope,\n * belongs to an unregistered queue, or fails stays unacknowledged, so\n * Cloudflare retries it and then dead-letters it.\n */\nexport function cloudflareQueues(): QueueDriverFactory {\n return (context) => createDriver(context);\n}\n\nexport interface ConsumeQueueBatchOptions {\n /**\n * Accept only jobs of these logical queues; any other message fails and is\n * retried. By default every job envelope is accepted.\n */\n readonly queues?: readonly string[];\n}\n\n/**\n * Settle native messages one job at a time. Attempts come from the host.\n * Process every message; ack successful/unsettled deliveries, then rethrow any\n * failures so the host retries the unsettled remainder. Explicit settlement wins.\n * The callback must await all work that should determine delivery success.\n */\nexport async function consumeQueueBatch(\n batch: { readonly queue: string; readonly messages: readonly QueueMessageLike[] },\n dispatch: (job: QueueJob, message: QueueMessageLike) => Promise<QueueDispatchResult | void>,\n options: ConsumeQueueBatchOptions = {},\n): Promise<void> {\n const errors: unknown[] = [];\n for (const message of batch.messages) {\n try {\n const job = parseQueueJob(message.body, message.attempts);\n if (options.queues && !options.queues.includes(job.queue)) {\n throw new Error(\n `Queue '${job.queue}' is not consumed from '${batch.queue}', which accepts ` +\n `${options.queues.map((queue) => `'${queue}'`).join(', ')}.`,\n );\n }\n const observed = observeMessage(message);\n // eslint-disable-next-line no-await-in-loop\n const result = await dispatch(job, observed.message);\n if (result?.handled === 0) throw new Error(`Queue job '${job.name}' has no handler.`);\n if (observed.disposition().outcome === 'unsettled') observed.message.ack();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Queue batch deliveries failed.');\n}\n"],"mappings":";;;;;AAuBA,MAAa,oBAAoB,OAAO,OAAO;;CAE7C,UAAU;;CAEV,YAAY;;CAEZ,cAAc;AAChB,CAAC;;AAGD,MAAM,uBAAuB;AAC7B,MAAM,eAAe;;;;;;AAOrB,SAAS,YAAY,MAAsB;CACzC,IAAI,OAAO;CACX,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,MAAM,OAAO,KAAK,WAAW,KAAK;EAClC,IAAI,OAAO,KAAM,OAAO;EACxB,IAAI,OAAO,IAAM,QAAQ;OACpB,IAAI,SAAS,MAAQ,SAAS,IAAM,QAAQ;OAC5C,IAAI,OAAO,KAAM,QAAQ;OACzB,IAAI,OAAO,MAAO,QAAQ;OAC1B,IAAI,QAAQ,SAAU,QAAQ,OAAQ,QAAQ;OAC9C,QAAQ;CACf;CACA,OAAO,KAAK,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,KAAK,UAAU,CAAC;AAClE;AAEA,SAAS,QAAQ,OAAgB,MAA2B;CAC1D,QAAQ,OAAO,OAAf;EACE,KAAK,UACH,OAAO,YAAY,KAAK;EAC1B,KAAK,UACH,OAAO,KAAK,IAAI,OAAO,KAAK,CAAC,CAAC,QAAQ,CAAC;EACzC,KAAK,UACH,OAAO,OAAO,KAAK,CAAC,CAAC,SAAS;EAChC,KAAK,WACH,OAAO;EACT,KAAK,UACH;EACF,SACE,OAAO;CACX;CACA,IAAI,UAAU,MAAM,OAAO;CAE3B,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CACd,IAAI,QAAQ;CACZ,IAAI,YAAY,OAAO,KAAK,KAAK,iBAAiB,aAChD,SAAS,MAAM,aAAa;MACvB,I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,mBACrD,QAAQ,OAAO,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,EAC9D;EAEF,MAAM,WAAW,eAAe,OAAO;EAGvC,KAAI,MADiB,SAAS,KAAK,SAAS,OAAO,EAAA,EACvC,YAAY,GAAG,MAAM,IAAI,MAAM,cAAc,IAAI,KAAK,kBAAkB;EACpF,IAAI,SAAS,YAAY,CAAC,CAAC,YAAY,aAAa,SAAS,QAAQ,IAAI;CAC3E,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAEF,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;CACtC,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,gCAAgC;AAC1F"}
1
+ {"version":3,"file":"cloudflare-queues.js","names":[],"sources":["../../src/queue/cloudflare-queues.ts"],"sourcesContent":["import { observeMessage, parseQueueJob, QueueBatchError } from '@velajs/vela/queue';\nimport { resolveBinding } from '@velajs/vela/module-kit';\nimport { QUEUE_PRODUCER } from '../bindings';\nimport type {\n AddJobOptions,\n QueueDispatchFn,\n QueueDispatchResult,\n QueueDriver,\n QueueDriverContext,\n QueueDriverFactory,\n QueueEnqueueRequest,\n QueueJob,\n QueueMessageLike,\n} from '@velajs/vela/queue';\n\n/** The native producer surface the driver uses: a Wrangler `queues.producers` binding. */\nexport interface CloudflareQueueProducer {\n // Both older void-returning bindings and current metric-returning bindings work.\n send(message: QueueJob, options?: QueueSendOptions): Promise<unknown>;\n sendBatch?(messages: Iterable<MessageSendRequest<QueueJob>>): Promise<unknown>;\n}\n\n/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */\nexport const QUEUE_SEND_LIMITS = Object.freeze({\n /** Messages per `sendBatch` call. */\n messages: 100,\n /** Estimated bytes per `sendBatch` call. */\n batchBytes: 256_000,\n /** Estimated bytes per message. */\n messageBytes: 128_000,\n});\n\n/** Allowance for the platform's per-message framing on top of the body estimate. */\nconst MESSAGE_MARGIN_BYTES = 256;\nconst MAX_DELAY_MS = 86_400_000;\n\n/**\n * A string's size as JSON (UTF-8, quoted, escaped) or as V8 serializes it\n * (one byte per character, two for a string holding any character above\n * U+00FF), whichever is larger.\n */\nfunction stringBytes(text: string): number {\n let json = 2;\n let wide = false;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code > 0xff) wide = true;\n if (code < 0x20) json += 6;\n else if (code === 0x22 || code === 0x5c) json += 2;\n else if (code < 0x80) json += 1;\n else if (code < 0x800) json += 2;\n else if (code >= 0xd800 && code <= 0xdfff) json += 2;\n else json += 3;\n }\n return Math.max(json, (wide ? text.length * 2 : text.length) + 5);\n}\n\nfunction measure(value: unknown, seen: Set<object>): number {\n switch (typeof value) {\n case 'string':\n return stringBytes(value);\n case 'number':\n return Math.max(String(value).length, 9);\n case 'bigint':\n return String(value).length + 9;\n case 'boolean':\n return 5;\n case 'object':\n break;\n default:\n return 9;\n }\n if (value === null) return 4;\n // V8 serializes a repeated reference as a back-reference.\n if (seen.has(value)) return 9;\n seen.add(value);\n let bytes = 2;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n bytes += value.byteLength + 9;\n } else if (value instanceof Date) {\n bytes += 26;\n } else if (value instanceof Map) {\n for (const [key, item] of value) bytes += measure(key, seen) + measure(item, seen) + 2;\n } else if (value instanceof Set) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else if (Array.isArray(value)) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else {\n for (const key of Object.keys(value)) {\n bytes += stringBytes(key) + measure(Reflect.get(value, key), seen) + 2;\n }\n }\n return bytes;\n}\n\n/**\n * A conservative size estimate of one native queue message: the larger of the\n * body's JSON and V8 sizes, plus a per-message margin.\n */\nexport function estimateQueueMessageBytes(body: unknown): number {\n return measure(body, new Set()) + MESSAGE_MARGIN_BYTES;\n}\n\nfunction delaySeconds(options: AddJobOptions | undefined): number | undefined {\n const delayMs = options?.delayMs;\n if (delayMs === undefined) return undefined;\n if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > MAX_DELAY_MS) {\n throw new RangeError('Queue delayMs must be between 0 and 86400000.');\n }\n return Math.ceil(delayMs / 1000);\n}\n\nfunction nativeBatch(payload: unknown): { queue: string; messages: QueueMessageLike[] } {\n if (\n typeof payload !== 'object' ||\n payload === null ||\n !('queue' in payload) ||\n typeof payload.queue !== 'string' ||\n !('messages' in payload) ||\n !Array.isArray(payload.messages)\n )\n throw new TypeError('Invalid native queue batch.');\n const messages: QueueMessageLike[] = [];\n for (const message of payload.messages as unknown[]) {\n if (\n typeof message !== 'object' ||\n message === null ||\n !('body' in message) ||\n !('ack' in message) ||\n typeof message.ack !== 'function' ||\n !('retry' in message) ||\n typeof message.retry !== 'function' ||\n !('id' in message) ||\n typeof message.id !== 'string' ||\n !('timestamp' in message) ||\n !(message.timestamp instanceof Date) ||\n !('attempts' in message) ||\n typeof message.attempts !== 'number'\n )\n throw new TypeError('Invalid native queue message.');\n messages.push(message as QueueMessageLike);\n }\n return { queue: payload.queue, messages };\n}\n\ninterface PreparedMessage {\n readonly id: string;\n readonly queue: string;\n readonly bytes: number;\n readonly request: MessageSendRequest<QueueJob>;\n}\n\n/** Split in order: a new call starts at 100 messages, at the byte budget, or at another queue. */\nfunction chunk(messages: readonly PreparedMessage[]): PreparedMessage[][] {\n const chunks: PreparedMessage[][] = [];\n let current: PreparedMessage[] = [];\n let bytes = 0;\n for (const message of messages) {\n if (\n current.length > 0 &&\n (current.length === QUEUE_SEND_LIMITS.messages ||\n bytes + message.bytes > QUEUE_SEND_LIMITS.batchBytes ||\n current[0]!.queue !== message.queue)\n ) {\n chunks.push(current);\n current = [];\n bytes = 0;\n }\n current.push(message);\n bytes += message.bytes;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction createDriver({ env, queues }: QueueDriverContext): QueueDriver {\n // Physical queue -> the logical queues registrations pin to it.\n const pins = new Map<string, string[]>();\n for (const queue of queues.all()) {\n for (const physical of queue.consumers) {\n pins.set(physical, [...(pins.get(physical) ?? []), queue.name]);\n }\n }\n\n // Resolved on every send from this application's ENV, never cached.\n const producerFor = (name: string): CloudflareQueueProducer => {\n const registration = queues.get(name);\n if (!registration) {\n throw new Error(\n `Queue '${name}' is not registered. Add QueueModule.forFeature([{ name: '${name}', ` +\n `binding }]) to the module that produces it.`,\n );\n }\n if (registration.binding === undefined) {\n throw new Error(\n `Queue '${name}' has no producer binding. Register it with ` +\n `QueueModule.forFeature([{ name: '${name}', binding: 'YOUR_QUEUE' }]), where the ` +\n `binding is a queues.producers[].binding of this Worker.`,\n );\n }\n try {\n return resolveBinding(env, { binding: registration.binding }, QUEUE_PRODUCER);\n } catch (error) {\n throw new Error(\n `Queue '${name}' cannot send: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n };\n\n return {\n kind: 'cloudflare',\n entrypoints: [{ kind: 'cf:queue:module', meta: { consumers: [...pins.keys()] } }],\n\n async consume(payload: unknown, dispatch: QueueDispatchFn): Promise<void> {\n const batch = nativeBatch(payload);\n const pinned = pins.get(batch.queue);\n await consumeQueueBatch(\n batch,\n (job) => {\n // A pinned queue is consumed only from the physical queues it names.\n const expected = queues.get(job.queue)?.consumers ?? [];\n if (expected.length > 0 && !expected.includes(batch.queue)) {\n throw new Error(\n `Queue '${job.queue}' is consumed from ` +\n `${expected.map((queue) => `'${queue}'`).join(', ')}, not '${batch.queue}'.`,\n );\n }\n return dispatch(job);\n },\n pinned ? { queues: pinned } : {},\n );\n },\n\n async enqueue(job: QueueJob, options?: AddJobOptions): Promise<void> {\n const delay = delaySeconds(options);\n await producerFor(job.queue).send(\n parseQueueJob(job),\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n },\n\n async enqueueBatch(requests: readonly QueueEnqueueRequest[]): Promise<void> {\n // Validate every job and resolve every binding before the first send.\n const messages = requests.map(({ job, options }): PreparedMessage => {\n const body = parseQueueJob(job);\n const bytes = estimateQueueMessageBytes(body);\n if (bytes > QUEUE_SEND_LIMITS.messageBytes) {\n throw new RangeError(\n `Queue job '${job.id}' is an estimated ${bytes} bytes, over the ` +\n `${QUEUE_SEND_LIMITS.messageBytes}-byte Cloudflare message limit. Store large ` +\n `payloads elsewhere (for example in R2) and enqueue a reference.`,\n );\n }\n const delay = delaySeconds(options);\n return {\n id: job.id,\n queue: job.queue,\n bytes,\n request: delay === undefined ? { body } : { body, delaySeconds: delay },\n };\n });\n const producers = new Map<string, CloudflareQueueProducer>();\n for (const { queue } of messages) {\n if (!producers.has(queue)) producers.set(queue, producerFor(queue));\n }\n const accepted: string[] = [];\n for (const part of chunk(messages)) {\n const producer = producers.get(part[0]!.queue)!;\n try {\n if (typeof producer.sendBatch === 'function') {\n // eslint-disable-next-line no-await-in-loop\n await producer.sendBatch(part.map(({ request }) => request));\n accepted.push(...part.map(({ id }) => id));\n } else {\n for (const { id, request } of part) {\n const delay = request.delaySeconds;\n // eslint-disable-next-line no-await-in-loop\n await producer.send(\n request.body,\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n accepted.push(id);\n }\n }\n } catch (error) {\n throw new QueueBatchError(\n accepted,\n messages.slice(accepted.length).map(({ id }) => id),\n error,\n );\n }\n }\n },\n };\n}\n\n/**\n * The Cloudflare Queues driver for `QueueModule`:\n *\n * ```ts\n * QueueModule.forRoot({ driver: cloudflareQueues() })\n * QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])\n * ```\n *\n * Each application gets its own driver. Producing reads the registered binding\n * from that application's `ENV` when a job is added and awaits the native\n * send; `addBulk` uses `sendBatch`, chunked to {@link QUEUE_SEND_LIMITS}.\n * Consuming is native too: the Worker's `queue()` handler routes every batch\n * that no `@QueueConsumer` claims through `QueueModule`, one message at a time,\n * by each job's logical `queue`, with the module's dispatch policy (signed\n * dispatch included). A registration's `consumer` pins its queue to that\n * physical queue: the queue's jobs are accepted only from it, and it only\n * carries the queues pinned to it. A message that is not a job envelope,\n * belongs to an unregistered queue, or fails stays unacknowledged, so\n * Cloudflare retries it and then dead-letters it.\n */\nexport function cloudflareQueues(): QueueDriverFactory {\n return (context) => createDriver(context);\n}\n\nexport interface ConsumeQueueBatchOptions {\n /**\n * Accept only jobs of these logical queues; any other message fails and is\n * retried. By default every job envelope is accepted.\n */\n readonly queues?: readonly string[];\n}\n\n/**\n * Settle native messages one job at a time. Attempts come from the host.\n * Process every message; ack successful/unsettled deliveries, then rethrow any\n * failures so the host retries the unsettled remainder. Explicit settlement wins.\n * The callback must await all work that should determine delivery success.\n */\nexport async function consumeQueueBatch(\n batch: { readonly queue: string; readonly messages: readonly QueueMessageLike[] },\n dispatch: (job: QueueJob, message: QueueMessageLike) => Promise<QueueDispatchResult | void>,\n options: ConsumeQueueBatchOptions = {},\n): Promise<void> {\n const errors: unknown[] = [];\n for (const message of batch.messages) {\n try {\n const job = parseQueueJob(message.body, message.attempts);\n if (options.queues && !options.queues.includes(job.queue)) {\n throw new Error(\n `Queue '${job.queue}' is not consumed from '${batch.queue}', which accepts ` +\n `${options.queues.map((queue) => `'${queue}'`).join(', ')}.`,\n );\n }\n const observed = observeMessage(message);\n // eslint-disable-next-line no-await-in-loop\n const result = await dispatch(job, observed.message);\n if (result?.handled === 0) throw new Error(`Queue job '${job.name}' has no handler.`);\n if (observed.disposition().outcome === 'unsettled') observed.message.ack();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Queue batch deliveries failed.');\n}\n"],"mappings":";;;;;AAuBA,MAAa,oBAAoB,OAAO,OAAO;;CAE7C,UAAU;;CAEV,YAAY;;CAEZ,cAAc;AAChB,CAAC;;AAGD,MAAM,uBAAuB;AAC7B,MAAM,eAAe;;;;;;AAOrB,SAAS,YAAY,MAAsB;CACzC,IAAI,OAAO;CACX,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,MAAM,OAAO,KAAK,WAAW,KAAK;EAClC,IAAI,OAAO,KA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5 +1,5 @@
1
1
  import { isStandardSchema, validateSchema } from "@velajs/vela/validation";
2
- //#region src/queue-events/consume.ts
2
+ // src/queue-events/consume.ts
3
3
  var QueueEventError = class extends Error {
4
4
  code;
5
5
  constructor(code, options) {
@@ -114,7 +114,6 @@ async function consumeQueueEvents(batch, options) {
114
114
  }
115
115
  if (failures.length > 0) throw new QueueEventsBatchError(failures);
116
116
  }
117
- //#endregion
118
117
  export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
119
118
 
120
119
  //# sourceMappingURL=consume.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"consume.js","names":[],"sources":["../../src/queue-events/consume.ts"],"sourcesContent":["import { isStandardSchema, validateSchema, type StandardSchemaV1 } from '@velajs/vela/validation';\n\nexport interface QueueEvent<Payload = unknown> {\n readonly type: string;\n readonly source: Readonly<Record<string, unknown>> & { readonly type: string };\n readonly payload: Payload;\n readonly metadata: Readonly<Record<string, unknown>> & {\n readonly accountId: string;\n readonly eventSubscriptionId: string;\n readonly eventSchemaVersion: 1;\n readonly eventTimestamp: string;\n };\n}\n\n/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */\nexport interface QueueEventContext {\n readonly queue: string;\n readonly messageId: string;\n readonly timestamp: Date;\n readonly attempts: number;\n}\n\nexport type QueueEventErrorCode =\n | 'invalid-envelope'\n | 'unsupported-version'\n | 'unexpected-account'\n | 'unexpected-subscription'\n | 'unhandled-type'\n | 'unexpected-source'\n | 'invalid-payload'\n | 'handler-failed';\n\nexport class QueueEventError extends Error {\n constructor(\n readonly code: QueueEventErrorCode,\n options?: ErrorOptions,\n ) {\n super(`Queue event ${code}`, options);\n this.name = 'QueueEventError';\n }\n}\n\nexport interface QueueEventFailure {\n readonly messageId: string;\n readonly error: QueueEventError;\n}\n\n/** Successful siblings are already acknowledged; failures have requested native retries. */\nexport class QueueEventsBatchError extends AggregateError {\n constructor(readonly failures: readonly QueueEventFailure[]) {\n super(\n failures.map(({ error }) => error),\n `${failures.length} queue event(s) failed`,\n );\n this.name = 'QueueEventsBatchError';\n }\n}\n\nexport interface QueueEventOptions<Payload> {\n /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */\n readonly type: string;\n /** Exact matches for source.type and any source selectors required by the application. */\n readonly source: Readonly<Record<string, string>> & { readonly type: string };\n readonly schema: StandardSchemaV1<unknown, Payload>;\n readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;\n}\n\nconst dispatch = Symbol('queue-event-dispatch');\n\n/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */\nexport interface QueueEventHandler {\n readonly type: string;\n readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/** No module registration or global state: define handlers alongside their consuming provider. */\nexport function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler {\n if (\n !nonempty(options.type) ||\n !nonempty(options.source.type) ||\n !Object.values(options.source).every(nonempty)\n ) {\n throw new TypeError('Queue event type and source expectations must be nonempty strings');\n }\n if (!isStandardSchema(options.schema))\n throw new TypeError('Expected a Standard Schema validator');\n const { type, schema, handle } = options;\n const source = Object.entries(options.source);\n return Object.freeze({\n type,\n async [dispatch](event: QueueEvent, context: QueueEventContext) {\n if (!source.every(([key, value]) => event.source[key] === value)) {\n throw new QueueEventError('unexpected-source');\n }\n let payload: Payload;\n try {\n payload = await validateSchema(schema, event.payload);\n } catch (cause) {\n throw new QueueEventError('invalid-payload', { cause });\n }\n try {\n await handle({ ...event, payload }, context);\n } catch (cause) {\n throw new QueueEventError('handler-failed', { cause });\n }\n },\n });\n}\n\nexport interface ConsumeQueueEventsOptions {\n /** Dedicated physical queue name, also claimed by @QueueConsumer. */\n readonly queue: string;\n readonly accountId: string;\n readonly eventSubscriptionIds: readonly string[];\n /** One handler per exact event type; each may require source selectors. */\n readonly handlers: readonly QueueEventHandler[];\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseEvent(value: unknown): QueueEvent {\n if (\n !record(value) ||\n !nonempty(value.type) ||\n !record(value.source) ||\n !nonempty(value.source.type) ||\n !Object.hasOwn(value, 'payload') ||\n !record(value.metadata)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n const { source, metadata } = value;\n if (\n !nonempty(metadata.accountId) ||\n !nonempty(metadata.eventSubscriptionId) ||\n !Number.isInteger(metadata.eventSchemaVersion) ||\n !nonempty(metadata.eventTimestamp) ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(\n metadata.eventTimestamp,\n ) ||\n !Number.isFinite(Date.parse(metadata.eventTimestamp)) ||\n // Date.parse normalizes impossible dates such as February 30. Reject those too.\n new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !==\n metadata.eventTimestamp.slice(0, 10)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n if (metadata.eventSchemaVersion !== 1) throw new QueueEventError('unsupported-version');\n return {\n type: value.type,\n source: { ...source, type: value.source.type },\n payload: value.payload,\n metadata: {\n ...metadata,\n accountId: metadata.accountId,\n eventSubscriptionId: metadata.eventSubscriptionId,\n eventSchemaVersion: 1,\n eventTimestamp: metadata.eventTimestamp,\n },\n };\n}\n\n/**\n * Await each validated handler, then acknowledge that message. Every malformed,\n * unmatched or failing message requests retry; all siblings are attempted before\n * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.\n * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.\n */\nexport async function consumeQueueEvents(\n batch: MessageBatch<unknown>,\n options: ConsumeQueueEventsOptions,\n): Promise<void> {\n if (\n !nonempty(options.queue) ||\n !nonempty(options.accountId) ||\n options.eventSubscriptionIds.length === 0 ||\n !options.eventSubscriptionIds.every(nonempty)\n ) {\n throw new TypeError('Expected a physical queue, account and nonempty subscription allowlist');\n }\n if (batch.queue !== options.queue)\n throw new Error('Unexpected physical queue for platform events');\n const handlers = new Map<string, QueueEventHandler>();\n for (const handler of options.handlers) {\n if (handlers.has(handler.type))\n throw new TypeError(`Duplicate queue event handler: ${handler.type}`);\n handlers.set(handler.type, handler);\n }\n const accountId = options.accountId;\n const subscriptions = new Set(options.eventSubscriptionIds);\n const failures: QueueEventFailure[] = [];\n for (const message of batch.messages) {\n try {\n const event = parseEvent(message.body);\n if (event.metadata.accountId !== accountId) throw new QueueEventError('unexpected-account');\n if (!subscriptions.has(event.metadata.eventSubscriptionId))\n throw new QueueEventError('unexpected-subscription');\n const handler = handlers.get(event.type);\n if (!handler) throw new QueueEventError('unhandled-type');\n await handler[dispatch](event, {\n queue: batch.queue,\n messageId: message.id,\n timestamp: message.timestamp,\n attempts: message.attempts,\n });\n } catch (error) {\n message.retry();\n failures.push({\n messageId: message.id,\n error:\n error instanceof QueueEventError\n ? error\n : new QueueEventError('handler-failed', { cause: error }),\n });\n continue;\n }\n message.ack();\n }\n if (failures.length > 0) throw new QueueEventsBatchError(failures);\n}\n"],"mappings":";;AAgCA,IAAa,kBAAb,cAAqC,MAAM;CAE9B;CADX,YACE,MACA,SACA;EACA,MAAM,eAAe,QAAQ,OAAO;EAH3B,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CACnC;CAArB,YAAY,UAAiD;EAC3D,MACE,SAAS,KAAK,EAAE,YAAY,KAAK,GACjC,GAAG,SAAS,OAAO,uBACrB;EAJmB,KAAA,WAAA;EAKnB,KAAK,OAAO;CACd;AACF;AAWA,MAAM,WAAW,OAAO,sBAAsB;AAQ9C,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;AAGA,SAAgB,iBAA0B,SAAwD;CAChG,IACE,CAAC,SAAS,QAAQ,IAAI,KACtB,C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QAAQ,WAAW,QAAQ,IAAI;GACrC,IAAI,MAAM,SAAS,cAAc,WAAW,MAAM,IAAI,gBAAgB,oBAAoB;GAC1F,IAAI,CAAC,cAAc,IAAI,MAAM,SAAS,mBAAmB,GACvD,MAAM,IAAI,gBAAgB,yBAAyB;GACrD,MAAM,UAAU,SAAS,IAAI,MAAM,IAAI;GACvC,IAAI,CAAC,SAAS,MAAM,IAAI,gBAAgB,gBAAgB;GACxD,MAAM,QAAQ,SAAS,CAAC,OAAO;IAC7B,OAAO,MAAM;IACb,WAAW,QAAQ;IACnB,WAAW,QAAQ;IACnB,UAAU,QAAQ;GACpB,CAAC;EACH,SAAS,OAAO;GACd,QAAQ,MAAM;GACd,SAAS,KAAK;IACZ,WAAW,QAAQ;IACnB,OACE,iBAAiB,kBACb,QACA,IAAI,gBAAgB,kBAAkB,EAAE,OAAO,MAAM,CAAC;GAC9D,CAAC;GACD;EACF;EACA,QAAQ,IAAI;CACd;CACA,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,sBAAsB,QAAQ;AACnE"}
1
+ {"version":3,"file":"consume.js","names":[],"sources":["../../src/queue-events/consume.ts"],"sourcesContent":["import { isStandardSchema, validateSchema, type StandardSchemaV1 } from '@velajs/vela/validation';\n\nexport interface QueueEvent<Payload = unknown> {\n readonly type: string;\n readonly source: Readonly<Record<string, unknown>> & { readonly type: string };\n readonly payload: Payload;\n readonly metadata: Readonly<Record<string, unknown>> & {\n readonly accountId: string;\n readonly eventSubscriptionId: string;\n readonly eventSchemaVersion: 1;\n readonly eventTimestamp: string;\n };\n}\n\n/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */\nexport interface QueueEventContext {\n readonly queue: string;\n readonly messageId: string;\n readonly timestamp: Date;\n readonly attempts: number;\n}\n\nexport type QueueEventErrorCode =\n | 'invalid-envelope'\n | 'unsupported-version'\n | 'unexpected-account'\n | 'unexpected-subscription'\n | 'unhandled-type'\n | 'unexpected-source'\n | 'invalid-payload'\n | 'handler-failed';\n\nexport class QueueEventError extends Error {\n constructor(\n readonly code: QueueEventErrorCode,\n options?: ErrorOptions,\n ) {\n super(`Queue event ${code}`, options);\n this.name = 'QueueEventError';\n }\n}\n\nexport interface QueueEventFailure {\n readonly messageId: string;\n readonly error: QueueEventError;\n}\n\n/** Successful siblings are already acknowledged; failures have requested native retries. */\nexport class QueueEventsBatchError extends AggregateError {\n constructor(readonly failures: readonly QueueEventFailure[]) {\n super(\n failures.map(({ error }) => error),\n `${failures.length} queue event(s) failed`,\n );\n this.name = 'QueueEventsBatchError';\n }\n}\n\nexport interface QueueEventOptions<Payload> {\n /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */\n readonly type: string;\n /** Exact matches for source.type and any source selectors required by the application. */\n readonly source: Readonly<Record<string, string>> & { readonly type: string };\n readonly schema: StandardSchemaV1<unknown, Payload>;\n readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;\n}\n\nconst dispatch = Symbol('queue-event-dispatch');\n\n/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */\nexport interface QueueEventHandler {\n readonly type: string;\n readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/** No module registration or global state: define handlers alongside their consuming provider. */\nexport function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler {\n if (\n !nonempty(options.type) ||\n !nonempty(options.source.type) ||\n !Object.values(options.source).every(nonempty)\n ) {\n throw new TypeError('Queue event type and source expectations must be nonempty strings');\n }\n if (!isStandardSchema(options.schema))\n throw new TypeError('Expected a Standard Schema validator');\n const { type, schema, handle } = options;\n const source = Object.entries(options.source);\n return Object.freeze({\n type,\n async [dispatch](event: QueueEvent, context: QueueEventContext) {\n if (!source.every(([key, value]) => event.source[key] === value)) {\n throw new QueueEventError('unexpected-source');\n }\n let payload: Payload;\n try {\n payload = await validateSchema(schema, event.payload);\n } catch (cause) {\n throw new QueueEventError('invalid-payload', { cause });\n }\n try {\n await handle({ ...event, payload }, context);\n } catch (cause) {\n throw new QueueEventError('handler-failed', { cause });\n }\n },\n });\n}\n\nexport interface ConsumeQueueEventsOptions {\n /** Dedicated physical queue name, also claimed by @QueueConsumer. */\n readonly queue: string;\n readonly accountId: string;\n readonly eventSubscriptionIds: readonly string[];\n /** One handler per exact event type; each may require source selectors. */\n readonly handlers: readonly QueueEventHandler[];\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseEvent(value: unknown): QueueEvent {\n if (\n !record(value) ||\n !nonempty(value.type) ||\n !record(value.source) ||\n !nonempty(value.source.type) ||\n !Object.hasOwn(value, 'payload') ||\n !record(value.metadata)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n const { source, metadata } = value;\n if (\n !nonempty(metadata.accountId) ||\n !nonempty(metadata.eventSubscriptionId) ||\n !Number.isInteger(metadata.eventSchemaVersion) ||\n !nonempty(metadata.eventTimestamp) ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(\n metadata.eventTimestamp,\n ) ||\n !Number.isFinite(Date.parse(metadata.eventTimestamp)) ||\n // Date.parse normalizes impossible dates such as February 30. Reject those too.\n new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !==\n metadata.eventTimestamp.slice(0, 10)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n if (metadata.eventSchemaVersion !== 1) throw new QueueEventError('unsupported-version');\n return {\n type: value.type,\n source: { ...source, type: value.source.type },\n payload: value.payload,\n metadata: {\n ...metadata,\n accountId: metadata.accountId,\n eventSubscriptionId: metadata.eventSubscriptionId,\n eventSchemaVersion: 1,\n eventTimestamp: metadata.eventTimestamp,\n },\n };\n}\n\n/**\n * Await each validated handler, then acknowledge that message. Every malformed,\n * unmatched or failing message requests retry; all siblings are attempted before\n * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.\n * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.\n */\nexport async function consumeQueueEvents(\n batch: MessageBatch<unknown>,\n options: ConsumeQueueEventsOptions,\n): Promise<void> {\n if (\n !nonempty(options.queue) ||\n !nonempty(options.accountId) ||\n options.eventSubscriptionIds.length === 0 ||\n !options.eventSubscriptionIds.every(nonempty)\n ) {\n throw new TypeError('Expected a physical queue, account and nonempty subscription allowlist');\n }\n if (batch.queue !== options.queue)\n throw new Error('Unexpected physical queue for platform events');\n const handlers = new Map<string, QueueEventHandler>();\n for (const handler of options.handlers) {\n if (handlers.has(handler.type))\n throw new TypeError(`Duplicate queue event handler: ${handler.type}`);\n handlers.set(handler.type, handler);\n }\n const accountId = options.accountId;\n const subscriptions = new Set(options.eventSubscriptionIds);\n const failures: QueueEventFailure[] = [];\n for (const message of batch.messages) {\n try {\n const event = parseEvent(message.body);\n if (event.metadata.accountId !== accountId) throw new QueueEventError('unexpected-account');\n if (!subscriptions.has(event.metadata.eventSubscriptionId))\n throw new QueueEventError('unexpected-subscription');\n const handler = handlers.get(event.type);\n if (!handler) throw new QueueEventError('unhandled-type');\n await handler[dispatch](event, {\n queue: batch.queue,\n messageId: message.id,\n timestamp: message.timestamp,\n attempts: message.attempts,\n });\n } catch (error) {\n message.retry();\n failures.push({\n messageId: message.id,\n error:\n error instanceof QueueEventError\n ? error\n : new QueueEventError('handler-failed', { cause: error }),\n });\n continue;\n }\n message.ack();\n }\n if (failures.length > 0) throw new QueueEventsBatchError(failures);\n}\n"],"mappings":";;AAgCA,IAAa,kBAAb,cAAqC,MAAM;CAE9B;CADX,YACW,MACT,SACA;EACA,MAAM,eAAe,QAAQ,OAAO;EAH3B,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CACnC;CAArB,YAAqB,UAAwC;EAC3D,MACE,SAAS,KAAK,EA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