@velajs/cloudflare 1.33.0 → 1.35.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 (46) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +218 -4
  3. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +9 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +6 -0
  5. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +8 -0
  6. package/dist/bindings.js +25 -1
  7. package/dist/bindings.js.map +1 -1
  8. package/dist/{cloudflare-application-CXDy9C1R.d.ts → cloudflare-application-Dsscb3Mo.d.ts} +2 -2
  9. package/dist/cloudflare-application.js +1 -1
  10. package/dist/cloudflare-application.js.map +1 -1
  11. package/dist/{cloudflare-factory-CuFNUJJD.d.ts → cloudflare-factory-DM9CBvNH.d.ts} +5 -5
  12. package/dist/cloudflare-factory.js +1 -1
  13. package/dist/cloudflare-factory.js.map +1 -1
  14. package/dist/durable-objects.d.ts +1 -1
  15. package/dist/email.d.ts +1 -1
  16. package/dist/entrypoints.d.ts +1 -1
  17. package/dist/index.d.ts +76 -11
  18. package/dist/index.js +2 -2
  19. package/dist/pipelines.d.ts +20 -0
  20. package/dist/pipelines.js +87 -0
  21. package/dist/pipelines.js.map +1 -0
  22. package/dist/queue/cloudflare-queues.js +3 -3
  23. package/dist/queue/cloudflare-queues.js.map +1 -1
  24. package/dist/queue-events/consume.js +120 -0
  25. package/dist/queue-events/consume.js.map +1 -0
  26. package/dist/queue-events.d.ts +71 -0
  27. package/dist/queue-events.js +2 -0
  28. package/dist/queues.d.ts +1 -1
  29. package/dist/services/flagship-flag.driver.js +64 -6
  30. package/dist/services/flagship-flag.driver.js.map +1 -1
  31. package/dist/storage/r2-storage.js +1 -1
  32. package/dist/storage/r2-storage.js.map +1 -1
  33. package/dist/storage.d.ts +1 -1
  34. package/dist/tail.d.ts +1 -1
  35. package/dist/testing.d.ts +1 -1
  36. package/dist/tracing.d.ts +15 -0
  37. package/dist/tracing.js +24 -0
  38. package/dist/tracing.js.map +1 -0
  39. package/dist/workflow/portable-workflow-step.js +62 -0
  40. package/dist/workflow/portable-workflow-step.js.map +1 -0
  41. package/dist/workflow/vela-workflow-definition.js +78 -0
  42. package/dist/workflow/vela-workflow-definition.js.map +1 -0
  43. package/dist/workflow-definitions.d.ts +33 -0
  44. package/dist/workflow-definitions.js +2 -0
  45. package/dist/workflows.d.ts +1 -1
  46. package/package.json +32 -10
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n CorsOptions,\n GlobalPrefixOptions,\n Type,\n VelaApplication,\n VelaCreateOptions,\n VelaEnv,\n VelaSecurityOptions,\n VersioningOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment } from './environment';\nimport { registerCloudflarePlatform } from './platform';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { reportUnservedGateways } from './websocket/binding-gateways';\nimport { workerLivePlatform } from './websocket/live-driver';\nimport { workerWebSocketTransport } from './websocket/worker-transport';\nimport { defineWorkerEvents } from './worker-events';\nimport { withRootProviders, type CloudflareRoot } from './root-module';\n\nexport interface CloudflareAppOptions {\n globalPrefix?: string;\n /** Routes served without the global prefix (`{ exclude }`). */\n globalPrefixOptions?: GlobalPrefixOptions;\n /** URI versioning: the version segment prefix (default `'v'`). */\n versioning?: VersioningOptions;\n security?: VelaSecurityOptions;\n /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */\n cors?: CorsOptions | boolean;\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CloudflareWorkerOptions extends CloudflareAppOptions {\n /**\n * Finish each application's HTTP surface, such as extra Hono routes, once per\n * environment. It runs after the application is built and before any event,\n * including concurrent cold events, reaches it; a throw fails that\n * construction, and the next event retries. It must be synchronous and do no\n * I/O (a returned promise fails the construction): read bindings in\n * providers. Request middleware belongs in modules (`configure(consumer)`),\n * which can inject `ENV`.\n */\n configure?(app: CloudflareApplication, env: VelaEnv): void;\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareAppOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.registerQueue({ consumer: '${queue}' }) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also registers the Worker's platform wiring: `WebSocketModule`\n * forwards each authenticated gateway upgrade to the room's Durable Object,\n * and `LiveModule` sends invalidations there. It supplies the\n * `InternalDispatcher` transport, so signed queue and schedule dispatch\n * re-enter this application's routes, and reports, through the diagnostics\n * policy, schedule declarations a cron trigger cannot honor and binding-backed\n * gateways without `WebSocketModule`.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n // Cloudflare attests the client address in this header. Read directly:\n // hono/cloudflare-workers would also load its WebSocket upgrade helper.\n getClientIp: (c) => c.req.header('cf-connecting-ip') ?? null,\n configureContainer: (container) => {\n registerCloudflarePlatform(container, env, {\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n });\n registerScheduledEventSeed(container);\n },\n onBootstrap: ({ app, container, discovery }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n reportUnservedGateways(container, discovery);\n },\n };\n}\n\n/**\n * The `VelaFactory.create()` options an application for `options.env` is built\n * with: that environment (seeded as ENV and sent by test clients as `c.env`),\n * the Cloudflare adapter bound to it, then any further adapters.\n */\nexport function cloudflareCreateOptions(options: CreateCloudflareAppOptions): VelaCreateOptions {\n return {\n env: options.env,\n globalPrefix: options.globalPrefix,\n globalPrefixOptions: options.globalPrefixOptions,\n versioning: options.versioning,\n security: options.security,\n cors: options.cors,\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));\n return new CloudflareApplication(velaApp, options.env);\n}\n\n/**\n * Run a Worker's `configure` hook on the application built for `env`, as\n * `createCloudflareWorker()` does before any event reaches it: a throw or a\n * returned promise closes the application and fails the construction.\n */\nexport async function configureCloudflareApplication(\n app: CloudflareApplication,\n env: VelaEnv,\n configure: CloudflareWorkerOptions['configure'],\n): Promise<CloudflareApplication> {\n if (!configure) return app;\n try {\n const result: unknown = configure(app, env);\n if (result instanceof Promise) {\n // Observe the rejected work; the construction fails either way.\n result.catch(() => {});\n throw new TypeError(\n 'createCloudflareWorker configure must finish synchronously: it runs before any ' +\n 'event reaches the application, so read bindings and perform I/O in providers.',\n );\n }\n } catch (error) {\n await app.close().catch(() => {});\n throw error;\n }\n return app;\n}\n\n/**\n * The well-known key under which a Worker entry (`defineCloudflareApp().worker`\n * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:\n * `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\n\n/**\n * The well-known static key under which a Durable Object class that\n * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every\n * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:\n * `Symbol.for('vela.cloudflare.durableObject')`.\n */\nexport const CLOUDFLARE_DURABLE_OBJECT: unique symbol = Symbol.for('vela.cloudflare.durableObject');\n\n/**\n * The well-known static key under which a Workflow class that `VelaWorkflow()`\n * returns (and every class extending it) carries its\n * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.\n */\nexport const CLOUDFLARE_WORKFLOW: unique symbol = Symbol.for('vela.cloudflare.workflow');\n\n/**\n * The well-known static key under which a service entrypoint class that\n * `VelaEntrypoint()` returns (and every class extending it) carries its\n * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.\n */\nexport const CLOUDFLARE_ENTRYPOINT: unique symbol = Symbol.for('vela.cloudflare.entrypoint');\n\n/** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareDurableObjectDescriptor {\n /**\n * `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are\n * the host methods `rpc` names.\n * `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.\n */\n readonly kind: 'host' | 'websocket';\n readonly rootModule: CloudflareRoot;\n /** The host class of a `host` Durable Object. */\n readonly host?: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class the factory returned: an exported Durable Object class extends it. */\n readonly durableObject: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareWorkflowDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose `run(event, step)` each Workflow run calls. */\n readonly host: Type;\n /** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */\n readonly workflow: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareEntrypointDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose methods `methods` names. */\n readonly host: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */\n readonly entrypoint: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Worker entry is built from, for tools that load it outside a platform event. */\nexport interface CloudflareWorkerDescriptor {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Durable Object classes defined from the same {@link CloudflareApp}\n * (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in\n * definition order; empty for `createCloudflareWorker()`.\n */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /**\n * The service entrypoint classes defined from the app\n * (`VelaEntrypoint(app, Host, { rpc })`), in definition order.\n */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create()` of the Worker's root (the root module, with the\n * hosts of the app's Workflow and service entrypoint classes among its\n * providers) and `createOptions(env)`: the application without its Worker\n * handlers or the `configure` hook, which receives the Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */\nexport interface CloudflareWorker {\n fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;\n scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n /**\n * The Email Workers handler, present once a module imports `OnEmail` from\n * `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`\n * handlers, and rejects a message none of them accepts.\n */\n readonly email?: (\n message: ForwardableEmailMessage,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ) => Promise<void>;\n /**\n * The Tail Workers handler, present once a module imports `OnTail` from\n * `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers\n * and never rejects, even when the application fails to start (the error is\n * logged to the console, and the next batch retries).\n */\n readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;\n /**\n * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores\n * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.\n */\n readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;\n}\n\n/**\n * One Cloudflare application: a static root module and its options, shared\n * by the Worker's default export and every Durable Object, Workflow and\n * service entrypoint class defined from it. Create it once, at module scope\n * of the Worker entry, with {@link defineCloudflareApp}.\n */\nexport interface CloudflareApp {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Worker's handlers (`export default app.worker`): one application per\n * environment identity, built on the first event and shared by concurrent\n * cold events, the app's Workflows and its service entrypoints.\n */\n readonly worker: CloudflareWorker;\n /** The Durable Object classes defined from this app, in definition order. */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from this app, in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /** The service entrypoint classes defined from this app, in definition order. */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n}\n\n/** What an app definition records beyond its public members. */\ninterface AppState {\n readonly durableObjects: CloudflareDurableObjectDescriptor[];\n readonly workflows: CloudflareWorkflowDescriptor[];\n readonly entrypoints: CloudflareEntrypointDescriptor[];\n readonly application: (env: VelaEnv) => Promise<CloudflareApplication>;\n /** Whether the Worker started building an application: its providers are then fixed. */\n started: boolean;\n}\n\nconst states = new WeakMap<object, AppState>();\n\n/** Whether `value` is an app {@link defineCloudflareApp} returned. */\nexport function isCloudflareApp(value: unknown): value is CloudflareApp {\n return typeof value === 'object' && value !== null && states.has(value);\n}\n\nfunction stateOf(app: unknown, factory: string): AppState {\n const state = typeof app === 'object' && app !== null ? states.get(app) : undefined;\n if (state === undefined) {\n throw new TypeError(\n `${factory}() takes the app from defineCloudflareApp(AppModule, options), whose Worker ` +\n 'application it runs in: define the app once and pass it.',\n );\n }\n return state;\n}\n\n/**\n * @internal Record a Durable Object class defined from `app`, so the Worker\n * descriptor lists it. The `@velajs/cloudflare/durable-objects` factories call\n * it at class definition.\n */\nexport function registerDurableObject(\n app: CloudflareApp,\n descriptor: CloudflareDurableObjectDescriptor,\n): void {\n states.get(app)?.durableObjects.push(descriptor);\n}\n\n/** Hosts join the Worker's root providers, so they must be declared before it is built. */\nfunction assertNotStarted(state: AppState, factory: string, host: Type): void {\n if (!state.started) return;\n throw new Error(\n `${factory}(app, ${host.name}) was called after the app started building its Worker ` +\n 'application, whose providers are then fixed: define Workflow and service entrypoint ' +\n 'classes at module scope, in the module that defines the app.',\n );\n}\n\n/**\n * @internal Record a Workflow class defined from `app`: its host joins the\n * Worker application's root providers, and the Worker descriptor lists it.\n * `VelaWorkflow()` calls it at class definition; `app` is validated here.\n */\nexport function registerWorkflow(app: unknown, descriptor: CloudflareWorkflowDescriptor): void {\n const state = stateOf(app, 'VelaWorkflow');\n assertNotStarted(state, 'VelaWorkflow', descriptor.host);\n state.workflows.push(descriptor);\n}\n\n/**\n * @internal Record a service entrypoint class defined from `app`: its host\n * joins the Worker application's root providers, and the Worker descriptor\n * lists it. `VelaEntrypoint()` calls it at class definition; `app` is\n * validated here.\n */\nexport function registerEntrypoint(app: unknown, descriptor: CloudflareEntrypointDescriptor): void {\n const state = stateOf(app, 'VelaEntrypoint');\n assertNotStarted(state, 'VelaEntrypoint', descriptor.host);\n state.entrypoints.push(descriptor);\n}\n\n/**\n * @internal The Worker's application for `env`: the one its handlers use,\n * built on first use for each environment identity and shared by concurrent\n * events, so the app's Workflows and service entrypoints run in it too.\n */\nexport function cloudflareApplication(\n app: CloudflareApp,\n env: VelaEnv,\n): Promise<CloudflareApplication> {\n return stateOf(app, 'cloudflareApplication').application(env);\n}\n\n/**\n * Define one Cloudflare application from a static root module (a module class\n * or a `DynamicModule`) and its options. The Worker entry exports its Worker\n * and the Durable Object, Workflow and service entrypoint classes defined from\n * it, which share the root and the options: runtime `adapters` configure every\n * application and Durable Object context the app builds.\n *\n * ```ts\n * import { defineCloudflareApp } from '@velajs/cloudflare';\n * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';\n *\n * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });\n * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}\n * export default app.worker;\n * ```\n *\n * The Worker builds one application per environment identity. The app's\n * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in\n * that application, with their hosts added to the root module's providers;\n * each Durable Object instance boots its own application context. Declare the\n * classes in the module that defines the app: a class file importing the app\n * from the Worker entry would run before the entry defined it. Keep them in\n * the entry, or define the app in a module of its own that the entry and the\n * class files import. `createCloudflareWorker` is\n * `defineCloudflareApp(rootModule, options).worker`.\n */\nexport function defineCloudflareApp(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareApp {\n const { configure, ...appOptions } = options;\n const durableObjects: CloudflareDurableObjectDescriptor[] = [];\n const workflows: CloudflareWorkflowDescriptor[] = [];\n const entrypoints: CloudflareEntrypointDescriptor[] = [];\n // The Worker's root: the root module, with the hosts of the Workflow and\n // service entrypoint classes among its providers.\n const workerRoot = (): CloudflareRoot => {\n const hosts = [...new Set([...workflows, ...entrypoints].map(({ host }) => host))];\n return hosts.length === 0 ? rootModule : withRootProviders(rootModule, hosts);\n };\n // Weak keys stop this cache from retaining a replaced environment.\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(workerRoot(), { ...appOptions, env }),\n env,\n configure,\n );\n const state: AppState = {\n durableObjects,\n workflows,\n entrypoints,\n started: false,\n // Concurrent cold events share construction, including `configure`; a\n // failed construction is evicted so the next event can retry.\n application: (env) => {\n const existing = applications.get(env);\n if (existing) return existing;\n state.started = true;\n const pending = build(env);\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n },\n };\n const { application } = state;\n const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n durableObjects,\n workflows,\n entrypoints,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(workerRoot(), cloudflareCreateOptions({ ...appOptions, env })),\n };\n const worker: CloudflareWorker = {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\n },\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).queue(batch, env, ctx);\n },\n [CLOUDFLARE_WORKER]: descriptor,\n };\n // `email` and `tail` appear once a module imports their decorators.\n defineWorkerEvents(worker, application);\n const app: CloudflareApp = {\n rootModule,\n options,\n worker,\n durableObjects,\n workflows,\n entrypoints,\n };\n states.set(app, state);\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity: the Worker of\n * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share\n * construction, including `configure`; failed construction is evicted so the\n * next event can retry. Define the app with {@link defineCloudflareApp} when the\n * entry also exports Durable Object classes built from it.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n return defineCloudflareApp(rootModule, options).worker;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,CAAC,SAAS,UAAU,YAAY,MAAM,MAAM,WAAW,CAAC,CAC/F;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,UAAU,GAAG;EAClD,MAAM,CAAC,SAAS,YAAY,MAAM,MAAM,WAAW;EACnD,IAAI,UAAU,KAAA,KAAa,OAAO,IAA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AM,MAAM,SAAkB,KAAc,KAA0C;GACpF,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,SAAS,KAAK,GAAG;EACzD;EACA,MAAM,UACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,UAAU,OAAO,KAAK,GAAG;EAC3D;EACA,MAAM,MACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,OAAO,KAAK,GAAG;EACvD;GACC,oBAAoB;CACvB;CAEA,mBAAmB,QAAQ,WAAW;CACtC,MAAM,MAAqB;EACzB;EACA;EACA;EACA;EACA;EACA;CACF;CACA,OAAO,IAAI,KAAK,KAAK;CACrB,OAAO;AACT;;;;;;;;AASA,SAAgB,uBACd,YACA,UAAmC,CAAC,GAClB;CAClB,OAAO,oBAAoB,YAAY,OAAO,CAAC,CAAC;AAClD"}
1
+ {"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n CorsOptions,\n GlobalPrefixOptions,\n Type,\n VelaApplication,\n VelaCreateOptions,\n VelaEnv,\n VelaSecurityOptions,\n VersioningOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment } from './environment';\nimport { registerCloudflarePlatform } from './platform';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { reportUnservedGateways } from './websocket/binding-gateways';\nimport { workerLivePlatform } from './websocket/live-driver';\nimport { workerWebSocketTransport } from './websocket/worker-transport';\nimport { defineWorkerEvents } from './worker-events';\nimport { withRootProviders, type CloudflareRoot } from './root-module';\n\nexport interface CloudflareAppOptions {\n globalPrefix?: string;\n /** Routes served without the global prefix (`{ exclude }`). */\n globalPrefixOptions?: GlobalPrefixOptions;\n /** URI versioning: the version segment prefix (default `'v'`). */\n versioning?: VersioningOptions;\n security?: VelaSecurityOptions;\n /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */\n cors?: CorsOptions | boolean;\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CloudflareWorkerOptions extends CloudflareAppOptions {\n /**\n * Finish each application's HTTP surface, such as extra Hono routes, once per\n * environment. It runs after the application is built and before any event,\n * including concurrent cold events, reaches it; a throw fails that\n * construction, and the next event retries. It must be synchronous and do no\n * I/O (a returned promise fails the construction): read bindings in\n * providers. Request middleware belongs in modules (`configure(consumer)`),\n * which can inject `ENV`.\n */\n configure?(app: CloudflareApplication, env: VelaEnv): void;\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareAppOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.forFeature([{ consumer: '${queue}' }]) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also registers the Worker's platform wiring: `WebSocketModule`\n * forwards each authenticated gateway upgrade to the room's Durable Object,\n * and `LiveModule` sends invalidations there. It supplies the\n * `InternalDispatcher` transport, so signed queue and schedule dispatch\n * re-enter this application's routes, and reports, through the diagnostics\n * policy, schedule declarations a cron trigger cannot honor and binding-backed\n * gateways without `WebSocketModule`.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n // Cloudflare attests the client address in this header. Read directly:\n // hono/cloudflare-workers would also load its WebSocket upgrade helper.\n getClientIp: (c) => c.req.header('cf-connecting-ip') ?? null,\n configureContainer: (container) => {\n registerCloudflarePlatform(container, env, {\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n });\n registerScheduledEventSeed(container);\n },\n onBootstrap: ({ app, container, discovery }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n reportUnservedGateways(container, discovery);\n },\n };\n}\n\n/**\n * The `VelaFactory.create()` options an application for `options.env` is built\n * with: that environment (seeded as ENV and sent by test clients as `c.env`),\n * the Cloudflare adapter bound to it, then any further adapters.\n */\nexport function cloudflareCreateOptions(options: CreateCloudflareAppOptions): VelaCreateOptions {\n return {\n env: options.env,\n globalPrefix: options.globalPrefix,\n globalPrefixOptions: options.globalPrefixOptions,\n versioning: options.versioning,\n security: options.security,\n cors: options.cors,\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));\n return new CloudflareApplication(velaApp, options.env);\n}\n\n/**\n * Run a Worker's `configure` hook on the application built for `env`, as\n * `createCloudflareWorker()` does before any event reaches it: a throw or a\n * returned promise closes the application and fails the construction.\n */\nexport async function configureCloudflareApplication(\n app: CloudflareApplication,\n env: VelaEnv,\n configure: CloudflareWorkerOptions['configure'],\n): Promise<CloudflareApplication> {\n if (!configure) return app;\n try {\n const result: unknown = configure(app, env);\n if (result instanceof Promise) {\n // Observe the rejected work; the construction fails either way.\n result.catch(() => {});\n throw new TypeError(\n 'createCloudflareWorker configure must finish synchronously: it runs before any ' +\n 'event reaches the application, so read bindings and perform I/O in providers.',\n );\n }\n } catch (error) {\n await app.close().catch(() => {});\n throw error;\n }\n return app;\n}\n\n/**\n * The well-known key under which a Worker entry (`defineCloudflareApp().worker`\n * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:\n * `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\n\n/**\n * The well-known static key under which a Durable Object class that\n * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every\n * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:\n * `Symbol.for('vela.cloudflare.durableObject')`.\n */\nexport const CLOUDFLARE_DURABLE_OBJECT: unique symbol = Symbol.for('vela.cloudflare.durableObject');\n\n/**\n * The well-known static key under which a Workflow class that `VelaWorkflow()`\n * returns (and every class extending it) carries its\n * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.\n */\nexport const CLOUDFLARE_WORKFLOW: unique symbol = Symbol.for('vela.cloudflare.workflow');\n\n/**\n * The well-known static key under which a service entrypoint class that\n * `VelaEntrypoint()` returns (and every class extending it) carries its\n * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.\n */\nexport const CLOUDFLARE_ENTRYPOINT: unique symbol = Symbol.for('vela.cloudflare.entrypoint');\n\n/** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareDurableObjectDescriptor {\n /**\n * `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are\n * the host methods `rpc` names.\n * `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.\n */\n readonly kind: 'host' | 'websocket';\n readonly rootModule: CloudflareRoot;\n /** The host class of a `host` Durable Object. */\n readonly host?: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class the factory returned: an exported Durable Object class extends it. */\n readonly durableObject: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareWorkflowDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose `run(event, step)` each Workflow run calls. */\n readonly host: Type;\n /** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */\n readonly workflow: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareEntrypointDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose methods `methods` names. */\n readonly host: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */\n readonly entrypoint: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Worker entry is built from, for tools that load it outside a platform event. */\nexport interface CloudflareWorkerDescriptor {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Durable Object classes defined from the same {@link CloudflareApp}\n * (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in\n * definition order; empty for `createCloudflareWorker()`.\n */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /**\n * The service entrypoint classes defined from the app\n * (`VelaEntrypoint(app, Host, { rpc })`), in definition order.\n */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create()` of the Worker's root (the root module, with the\n * hosts of the app's Workflow and service entrypoint classes among its\n * providers) and `createOptions(env)`: the application without its Worker\n * handlers or the `configure` hook, which receives the Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */\nexport interface CloudflareWorker {\n fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;\n scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n /**\n * The Email Workers handler, present once a module imports `OnEmail` from\n * `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`\n * handlers, and rejects a message none of them accepts.\n */\n readonly email?: (\n message: ForwardableEmailMessage,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ) => Promise<void>;\n /**\n * The Tail Workers handler, present once a module imports `OnTail` from\n * `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers\n * and never rejects, even when the application fails to start (the error is\n * logged to the console, and the next batch retries).\n */\n readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;\n /**\n * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores\n * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.\n */\n readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;\n}\n\n/**\n * One Cloudflare application: a static root module and its options, shared\n * by the Worker's default export and every Durable Object, Workflow and\n * service entrypoint class defined from it. Create it once, at module scope\n * of the Worker entry, with {@link defineCloudflareApp}.\n */\nexport interface CloudflareApp {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Worker's handlers (`export default app.worker`): one application per\n * environment identity, built on the first event and shared by concurrent\n * cold events, the app's Workflows and its service entrypoints.\n */\n readonly worker: CloudflareWorker;\n /** The Durable Object classes defined from this app, in definition order. */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from this app, in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /** The service entrypoint classes defined from this app, in definition order. */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n}\n\n/** What an app definition records beyond its public members. */\ninterface AppState {\n readonly durableObjects: CloudflareDurableObjectDescriptor[];\n readonly workflows: CloudflareWorkflowDescriptor[];\n readonly entrypoints: CloudflareEntrypointDescriptor[];\n readonly application: (env: VelaEnv) => Promise<CloudflareApplication>;\n /** Whether the Worker started building an application: its providers are then fixed. */\n started: boolean;\n}\n\nconst states = new WeakMap<object, AppState>();\n\n/** Whether `value` is an app {@link defineCloudflareApp} returned. */\nexport function isCloudflareApp(value: unknown): value is CloudflareApp {\n return typeof value === 'object' && value !== null && states.has(value);\n}\n\nfunction stateOf(app: unknown, factory: string): AppState {\n const state = typeof app === 'object' && app !== null ? states.get(app) : undefined;\n if (state === undefined) {\n throw new TypeError(\n `${factory}() takes the app from defineCloudflareApp(AppModule, options), whose Worker ` +\n 'application it runs in: define the app once and pass it.',\n );\n }\n return state;\n}\n\n/**\n * @internal Record a Durable Object class defined from `app`, so the Worker\n * descriptor lists it. The `@velajs/cloudflare/durable-objects` factories call\n * it at class definition.\n */\nexport function registerDurableObject(\n app: CloudflareApp,\n descriptor: CloudflareDurableObjectDescriptor,\n): void {\n states.get(app)?.durableObjects.push(descriptor);\n}\n\n/** Hosts join the Worker's root providers, so they must be declared before it is built. */\nfunction assertNotStarted(state: AppState, factory: string, host: Type): void {\n if (!state.started) return;\n throw new Error(\n `${factory}(app, ${host.name}) was called after the app started building its Worker ` +\n 'application, whose providers are then fixed: define Workflow and service entrypoint ' +\n 'classes at module scope, in the module that defines the app.',\n );\n}\n\n/**\n * @internal Record a Workflow class defined from `app`: its host joins the\n * Worker application's root providers, and the Worker descriptor lists it.\n * `VelaWorkflow()` calls it at class definition; `app` is validated here.\n */\nexport function registerWorkflow(app: unknown, descriptor: CloudflareWorkflowDescriptor): void {\n const state = stateOf(app, 'VelaWorkflow');\n assertNotStarted(state, 'VelaWorkflow', descriptor.host);\n state.workflows.push(descriptor);\n}\n\n/**\n * @internal Record a service entrypoint class defined from `app`: its host\n * joins the Worker application's root providers, and the Worker descriptor\n * lists it. `VelaEntrypoint()` calls it at class definition; `app` is\n * validated here.\n */\nexport function registerEntrypoint(app: unknown, descriptor: CloudflareEntrypointDescriptor): void {\n const state = stateOf(app, 'VelaEntrypoint');\n assertNotStarted(state, 'VelaEntrypoint', descriptor.host);\n state.entrypoints.push(descriptor);\n}\n\n/**\n * @internal The Worker's application for `env`: the one its handlers use,\n * built on first use for each environment identity and shared by concurrent\n * events, so the app's Workflows and service entrypoints run in it too.\n */\nexport function cloudflareApplication(\n app: CloudflareApp,\n env: VelaEnv,\n): Promise<CloudflareApplication> {\n return stateOf(app, 'cloudflareApplication').application(env);\n}\n\n/**\n * Define one Cloudflare application from a static root module (a module class\n * or a `DynamicModule`) and its options. The Worker entry exports its Worker\n * and the Durable Object, Workflow and service entrypoint classes defined from\n * it, which share the root and the options: runtime `adapters` configure every\n * application and Durable Object context the app builds.\n *\n * ```ts\n * import { defineCloudflareApp } from '@velajs/cloudflare';\n * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';\n *\n * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });\n * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}\n * export default app.worker;\n * ```\n *\n * The Worker builds one application per environment identity. The app's\n * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in\n * that application, with their hosts added to the root module's providers;\n * each Durable Object instance boots its own application context. Declare the\n * classes in the module that defines the app: a class file importing the app\n * from the Worker entry would run before the entry defined it. Keep them in\n * the entry, or define the app in a module of its own that the entry and the\n * class files import. `createCloudflareWorker` is\n * `defineCloudflareApp(rootModule, options).worker`.\n */\nexport function defineCloudflareApp(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareApp {\n const { configure, ...appOptions } = options;\n const durableObjects: CloudflareDurableObjectDescriptor[] = [];\n const workflows: CloudflareWorkflowDescriptor[] = [];\n const entrypoints: CloudflareEntrypointDescriptor[] = [];\n // The Worker's root: the root module, with the hosts of the Workflow and\n // service entrypoint classes among its providers.\n const workerRoot = (): CloudflareRoot => {\n const hosts = [...new Set([...workflows, ...entrypoints].map(({ host }) => host))];\n return hosts.length === 0 ? rootModule : withRootProviders(rootModule, hosts);\n };\n // Weak keys stop this cache from retaining a replaced environment.\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(workerRoot(), { ...appOptions, env }),\n env,\n configure,\n );\n const state: AppState = {\n durableObjects,\n workflows,\n entrypoints,\n started: false,\n // Concurrent cold events share construction, including `configure`; a\n // failed construction is evicted so the next event can retry.\n application: (env) => {\n const existing = applications.get(env);\n if (existing) return existing;\n state.started = true;\n const pending = build(env);\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n },\n };\n const { application } = state;\n const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n durableObjects,\n workflows,\n entrypoints,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(workerRoot(), cloudflareCreateOptions({ ...appOptions, env })),\n };\n const worker: CloudflareWorker = {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\n },\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).queue(batch, env, ctx);\n },\n [CLOUDFLARE_WORKER]: descriptor,\n };\n // `email` and `tail` appear once a module imports their decorators.\n defineWorkerEvents(worker, application);\n const app: CloudflareApp = {\n rootModule,\n options,\n worker,\n durableObjects,\n workflows,\n entrypoints,\n };\n states.set(app, state);\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity: the Worker of\n * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share\n * construction, including `configure`; failed construction is evicted so the\n * next event can retry. Define the app with {@link defineCloudflareApp} when the\n * entry also exports Durable Object classes built from it.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n return defineCloudflareApp(rootModule, options).worker;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,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ACA;EACA;EACA,gBAAgB,QAAQ,wBAAwB;GAAE,GAAG;GAAY;EAAI,CAAC;EACtE,oBAAoB,QAClB,YAAY,OAAO,WAAW,GAAG,wBAAwB;GAAE,GAAG;GAAY;EAAI,CAAC,CAAC;CACpF;CACA,MAAM,SAA2B;EAC/B,MAAM,MAAM,SAAkB,KAAc,KAA0C;GACpF,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,SAAS,KAAK,GAAG;EACzD;EACA,MAAM,UACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,UAAU,OAAO,KAAK,GAAG;EAC3D;EACA,MAAM,MACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,OAAO,KAAK,GAAG;EACvD;GACC,oBAAoB;CACvB;CAEA,mBAAmB,QAAQ,WAAW;CACtC,MAAM,MAAqB;EACzB;EACA;EACA;EACA;EACA;EACA;CACF;CACA,OAAO,IAAI,KAAK,KAAK;CACrB,OAAO;AACT;;;;;;;;AASA,SAAgB,uBACd,YACA,UAAmC,CAAC,GAClB;CAClB,OAAO,oBAAoB,YAAY,OAAO,CAAC,CAAC;AAClD"}
@@ -1,5 +1,5 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import { a as CloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-CuFNUJJD.js";
2
+ import { a as CloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
3
3
  import { n as RpcMethods, t as RpcMethodOf } from "./host-members-DECj_4yz.js";
4
4
  import { l as VelaDoPitrRpc, t as VelaNonceDurableObject } from "./nonce.durable-object-Bg1e0BMD.js";
5
5
  import { DurableObject } from "cloudflare:workers";
package/dist/email.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import "./cloudflare-application-CXDy9C1R.js";
2
+ import "./cloudflare-application-Dsscb3Mo.js";
3
3
  import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
4
4
  //#region src/email/on-email.d.ts
5
5
  /** Options of {@link OnEmail}. */
@@ -1,5 +1,5 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import { a as CloudflareApp } from "./cloudflare-factory-CuFNUJJD.js";
2
+ import { a as CloudflareApp } from "./cloudflare-factory-DM9CBvNH.js";
3
3
  import { n as RpcMethods, t as RpcMethodOf } from "./host-members-DECj_4yz.js";
4
4
  import { WorkerEntrypoint } from "cloudflare:workers";
5
5
  import { InjectionToken, Type, VelaEnv } from "@velajs/vela";
package/dist/index.d.ts CHANGED
@@ -1,13 +1,12 @@
1
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-CXDy9C1R.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-CuFNUJJD.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
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";
5
+ import { DynamicModule, ExecutionContext, InjectionToken, Type, VelaEnv } from "@velajs/vela";
6
6
  import { Binding, BindingRef, EnvFactory, RuntimeAdapter } from "@velajs/vela/module-kit";
7
7
  import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
8
8
  import { BroadcastCommand } from "@velajs/vela/websocket";
9
9
  import { CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, CacheStore } from "@velajs/vela/cache";
10
- import { FeatureFlagDriver, FlagContext } from "@velajs/feature-flags";
11
10
  import { ThrottlerStore } from "@velajs/vela/throttler";
12
11
  import { NonceStore } from "@velajs/vela/security";
13
12
  //#region src/websocket/room-id.d.ts
@@ -82,6 +81,8 @@ export declare const rateLimit: (ref: BindingRef) => Binding<RateLimit>;
82
81
  * Workflow class declares.
83
82
  */
84
83
  export declare function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>>;
84
+ export declare const flagship: (ref: BindingRef) => Binding<Flagship>;
85
+ export declare const secretsStoreSecret: (ref: BindingRef) => Binding<SecretsStoreSecret>;
85
86
  //#endregion
86
87
  //#region src/services/kv-cache.store.d.ts
87
88
  /** A KV namespace, or a function that reads it when an operation needs it. */
@@ -136,20 +137,78 @@ export declare function kvCacheInvalidation(ref: {
136
137
  binding: string;
137
138
  }): EnvFactory<CacheInvalidationStore>;
138
139
  //#endregion
140
+ //#region ../feature-flags/dist/memory.driver-C5Vcv2gb.d.ts
141
+ //#region src/drivers/driver.d.ts
142
+ /**
143
+ * The cross-package contract every feature-flag backend implements.
144
+ *
145
+ * This is the seam that platform packages plug into: `@velajs/cloudflare`
146
+ * ships a Flagship-binding driver and a KV-backed driver against this exact
147
+ * interface, `@velajs/feature-flags` ships {@link MemoryFlagDriver}. A driver
148
+ * maps a key + fallback (+ optional targeting context) onto a value and
149
+ * returns the `fallback` when it cannot resolve the key. Unexpected failures
150
+ * may reject; the service owns the never-throw boundary.
151
+ *
152
+ * Optional detail methods preserve provider metadata. Without one, the service
153
+ * reports UNKNOWN: a returned fallback cannot be distinguished from a hit.
154
+ */
155
+ interface FeatureFlagDriver {
156
+ readonly name: string;
157
+ getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean>;
158
+ getString(key: string, fallback: string, ctx?: FlagContext): Promise<string>;
159
+ getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number>;
160
+ /** Object payloads remain unknown until the service applies the caller's parser. */
161
+ getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown>;
162
+ getBooleanDetails?(key: string, fallback: boolean, ctx?: FlagContext): Promise<FlagEvaluationDetails<boolean>>;
163
+ getStringDetails?(key: string, fallback: string, ctx?: FlagContext): Promise<FlagEvaluationDetails<string>>;
164
+ getNumberDetails?(key: string, fallback: number, ctx?: FlagContext): Promise<FlagEvaluationDetails<number>>;
165
+ getObjectDetails?(key: string, fallback: object, ctx?: FlagContext): Promise<FlagEvaluationDetails<unknown>>;
166
+ }
167
+ //#endregion
168
+ //#region src/feature-flags.types.d.ts
169
+ /**
170
+ * A value a feature flag can resolve to. Mirrors the four evaluation methods
171
+ * on {@link FeatureFlagDriver}.
172
+ */
173
+ type FlagValue = boolean | string | number | object;
174
+ /**
175
+ * A free-form evaluation context handed to a driver (for targeting: user id,
176
+ * plan, country, …). Drivers that don't do targeting ignore it.
177
+ */
178
+ type FlagContext = Record<string, unknown>;
179
+ /** Provider-defined reason, or UNKNOWN for drivers without evaluation metadata. */
180
+ type FlagEvaluationReason = string;
181
+ /** Provider metadata is preserved; unavailable reasons are UNKNOWN. */
182
+ interface FlagEvaluationDetails<T = FlagValue> {
183
+ flagKey: string;
184
+ value: T;
185
+ reason: FlagEvaluationReason;
186
+ variant?: string;
187
+ errorCode?: string;
188
+ errorMessage?: string;
189
+ }
190
+ //#endregion
139
191
  //#region src/services/flagship-flag.driver.d.ts
140
192
  /**
141
193
  * The subset of a Cloudflare **Flagship** binding this driver evaluates against
142
- * — the four typed value methods. The binding itself returns the supplied
194
+ * — typed value methods and optional evaluation details. The binding itself returns the supplied
143
195
  * `defaultValue` on evaluation errors; transport-level failures reject and are
144
196
  * left to propagate (never-throw is the service layer's job, not the driver's).
145
197
  *
146
198
  * @see https://developers.cloudflare.com/flagship/binding/
147
199
  */
200
+ type NativeFlagDetails<T> = Omit<FlagEvaluationDetails<T>, 'reason'> & {
201
+ reason?: string;
202
+ };
148
203
  interface FlagshipBinding {
149
- getBooleanValue(key: string, defaultValue: boolean, context?: FlagContext): Promise<boolean>;
150
- getStringValue(key: string, defaultValue: string, context?: FlagContext): Promise<string>;
151
- getNumberValue(key: string, defaultValue: number, context?: FlagContext): Promise<number>;
152
- getObjectValue(key: string, defaultValue: object, context?: FlagContext): Promise<unknown>;
204
+ getBooleanValue(key: string, defaultValue: boolean, context?: Record<string, string | number | boolean>): Promise<boolean>;
205
+ getStringValue(key: string, defaultValue: string, context?: Record<string, string | number | boolean>): Promise<string>;
206
+ getNumberValue(key: string, defaultValue: number, context?: Record<string, string | number | boolean>): Promise<number>;
207
+ getObjectValue(key: string, defaultValue: object, context?: Record<string, string | number | boolean>): Promise<unknown>;
208
+ getBooleanDetails?(key: string, defaultValue: boolean, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<boolean>>;
209
+ getStringDetails?(key: string, defaultValue: string, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<string>>;
210
+ getNumberDetails?(key: string, defaultValue: number, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<number>>;
211
+ getObjectDetails?(key: string, defaultValue: object, context?: Record<string, string | number | boolean>): Promise<NativeFlagDetails<unknown>>;
153
212
  }
154
213
  interface FlagshipFlagDriverOptions {
155
214
  /** Driver name used for `use(name)` / default-driver selection. Default `"flagship"`. */
@@ -159,8 +218,9 @@ interface FlagshipFlagDriverOptions {
159
218
  * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
160
219
  *
161
220
  * A thin, honest wrapper: each contract method maps 1:1 onto the binding's
162
- * corresponding value method, forwarding the caller's `fallback` (the binding's
163
- * `defaultValue`) and evaluation context. The binding resolves the fallback on
221
+ * corresponding native method, forwarding the caller's `fallback` (the binding's
222
+ * `defaultValue`) and validated scalar evaluation context. Optional detail methods
223
+ * preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on
164
224
  * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`
165
225
  * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
166
226
  * the never-throw guarantee.
@@ -186,6 +246,11 @@ export declare class FlagshipFlagDriver implements FeatureFlagDriver {
186
246
  getString(key: string, fallback: string, ctx?: FlagContext): Promise<string>;
187
247
  getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number>;
188
248
  getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown>;
249
+ getBooleanDetails(key: string, fallback: boolean, ctx?: FlagContext): Promise<FlagEvaluationDetails<boolean>>;
250
+ getStringDetails(key: string, fallback: string, ctx?: FlagContext): Promise<FlagEvaluationDetails<string>>;
251
+ getNumberDetails(key: string, fallback: number, ctx?: FlagContext): Promise<FlagEvaluationDetails<number>>;
252
+ getObjectDetails(key: string, fallback: object, ctx?: FlagContext): Promise<FlagEvaluationDetails<unknown>>;
253
+ private details;
189
254
  }
190
255
  /** Convenience factory for {@link FlagshipFlagDriver}. */
191
256
  export declare function flagshipFlagDriver(binding: FlagshipBinding | (() => FlagshipBinding), options?: FlagshipFlagDriverOptions): FlagshipFlagDriver;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { durableObjectRoomName } from "./websocket/room-id.js";
2
2
  import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
3
3
  import { CloudflareApplication } from "./cloudflare-application.js";
4
- import { d1, durableObject, kv, queue, r2, rateLimit, workflow } from "./bindings.js";
4
+ import { d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow } from "./bindings.js";
5
5
  import { durableObjectLive } from "./websocket/live-driver.js";
6
6
  import { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp } from "./cloudflare-factory.js";
7
7
  import { EntrypointError, isEntrypointError } from "./rpc/entrypoint-error.js";
@@ -13,4 +13,4 @@ import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookm
13
13
  import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
14
14
  import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
15
15
  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, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, workflow };
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 };
@@ -0,0 +1,20 @@
1
+ import { StandardSchemaV1 } from "@velajs/vela/validation";
2
+ //#region src/pipelines.d.ts
3
+ /** The native stream handle remains usable independently of the writer. */
4
+ export interface PipelinesBinding<Output = Record<string, unknown>> {
5
+ readonly send: (records: Output[]) => Promise<void>;
6
+ }
7
+ export interface PipelinesWriter<Input> {
8
+ /** Validate the entire nonempty batch, then await one native ingestion request. */
9
+ send(records: readonly Input[]): Promise<void>;
10
+ }
11
+ /**
12
+ * Bind a Standard Schema producer to one trusted, configured stream. Schema
13
+ * outputs must fit the binding's record type; send() accepts schema inputs.
14
+ * Resolution means ingestion acceptance only, not downstream delivery or query
15
+ * visibility. There is no retry, splitting, buffering, or cross-writer state.
16
+ */
17
+ export declare function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>, { schema }: {
18
+ readonly schema: S;
19
+ }): PipelinesWriter<StandardSchemaV1.InferInput<S>>;
20
+ //#endregion
@@ -0,0 +1,87 @@
1
+ import { SchemaValidationError, isStandardSchema, parseSchemaAsync } from "@velajs/vela/validation";
2
+ //#region src/pipelines.ts
3
+ const MAX_BATCH_BYTES = 5e6;
4
+ const encoder = new TextEncoder();
5
+ /**
6
+ * Bind a Standard Schema producer to one trusted, configured stream. Schema
7
+ * outputs must fit the binding's record type; send() accepts schema inputs.
8
+ * Resolution means ingestion acceptance only, not downstream delivery or query
9
+ * visibility. There is no retry, splitting, buffering, or cross-writer state.
10
+ */
11
+ function createPipelinesWriter(binding, { schema }) {
12
+ if (!binding || typeof binding.send !== "function") throw new TypeError("Pipelines requires a stream binding with send(records).");
13
+ if (!isStandardSchema(schema)) throw new TypeError("Pipelines requires a Standard Schema validator.");
14
+ return { async send(records) {
15
+ if (!Array.isArray(records) || records.length === 0) throw new TypeError("Pipelines requires a nonempty array of records.");
16
+ const inputs = [];
17
+ for (let index = 0; index < records.length; index++) {
18
+ const descriptor = Object.getOwnPropertyDescriptor(records, String(index));
19
+ if (!descriptor || !("value" in descriptor)) throw new TypeError(`Pipelines record ${index} must be an array element, not an accessor or hole.`);
20
+ inputs.push(descriptor.value);
21
+ }
22
+ const outputs = [];
23
+ let batchBytes = 2;
24
+ for (const [index, input] of inputs.entries()) {
25
+ let output;
26
+ try {
27
+ output = await parseSchemaAsync(schema, input);
28
+ } catch (error) {
29
+ if (error instanceof SchemaValidationError) throw new SchemaValidationError(error.issues.map((issue) => ({
30
+ ...issue,
31
+ path: [index, ...issue.path ?? []]
32
+ })));
33
+ throw error;
34
+ }
35
+ if (output === null || typeof output !== "object" || Array.isArray(output)) throw new TypeError(`Pipelines record ${index} must validate to a JSON object.`);
36
+ const snapshot = snapshotJson(output, [index], /* @__PURE__ */ new Set());
37
+ const bytes = encoder.encode(JSON.stringify(snapshot)).byteLength;
38
+ if (bytes > 4999998) throw new RangeError(`Pipelines record ${index} exceeds 4999998 JSON bytes.`);
39
+ batchBytes += bytes + (index === 0 ? 0 : 1);
40
+ if (batchBytes > MAX_BATCH_BYTES) throw new RangeError(`Pipelines batch exceeds ${MAX_BATCH_BYTES} JSON bytes.`);
41
+ outputs.push(snapshot);
42
+ }
43
+ await binding.send(outputs);
44
+ } };
45
+ }
46
+ function snapshotJson(value, path, ancestors) {
47
+ const invalid = (reason) => {
48
+ throw new TypeError(`Pipelines JSON value at ${JSON.stringify(path)} ${reason}.`);
49
+ };
50
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
51
+ if (typeof value === "number") {
52
+ if (!Number.isFinite(value)) invalid("must be finite");
53
+ return value;
54
+ }
55
+ if (typeof value !== "object") return invalid("is not representable");
56
+ if (ancestors.has(value)) return invalid("is circular");
57
+ const array = Array.isArray(value);
58
+ const prototype = Object.getPrototypeOf(value);
59
+ if (prototype !== null && prototype !== (array ? Array.prototype : Object.prototype)) return invalid("must use a plain object or array");
60
+ ancestors.add(value);
61
+ try {
62
+ const copy = array ? [] : {};
63
+ const keys = Reflect.ownKeys(value);
64
+ if (array && keys.length !== value.length + 1) return invalid("must be a dense array");
65
+ for (const key of keys) {
66
+ if (array && key === "length") continue;
67
+ if (typeof key !== "string") return invalid("cannot have symbol keys");
68
+ if (array && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length)) return invalid("cannot have extra array properties");
69
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
70
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return invalid("must contain only enumerable data properties");
71
+ const child = snapshotJson(descriptor.value, [...path, array ? Number(key) : key], ancestors);
72
+ Object.defineProperty(copy, key, {
73
+ value: child,
74
+ enumerable: true,
75
+ writable: true,
76
+ configurable: true
77
+ });
78
+ }
79
+ return copy;
80
+ } finally {
81
+ ancestors.delete(value);
82
+ }
83
+ }
84
+ //#endregion
85
+ export { createPipelinesWriter };
86
+
87
+ //# sourceMappingURL=pipelines.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipelines.js","names":[],"sources":["../src/pipelines.ts"],"sourcesContent":["import {\n isStandardSchema,\n parseSchemaAsync,\n SchemaValidationError,\n type StandardSchemaV1,\n} from '@velajs/vela/validation';\n\n/** The native stream handle remains usable independently of the writer. */\nexport interface PipelinesBinding<Output = Record<string, unknown>> {\n readonly send: (records: Output[]) => Promise<void>;\n}\n\nexport interface PipelinesWriter<Input> {\n /** Validate the entire nonempty batch, then await one native ingestion request. */\n send(records: readonly Input[]): Promise<void>;\n}\n\n// Current streams document 5 MB per ingestion request, without a separate record\n// cap. Use decimal MB conservatively, including JSON array brackets and commas.\n// https://developers.cloudflare.com/pipelines/platform/limits/\nconst MAX_BATCH_BYTES = 5_000_000;\nconst encoder = new TextEncoder();\n\n/**\n * Bind a Standard Schema producer to one trusted, configured stream. Schema\n * outputs must fit the binding's record type; send() accepts schema inputs.\n * Resolution means ingestion acceptance only, not downstream delivery or query\n * visibility. There is no retry, splitting, buffering, or cross-writer state.\n */\nexport function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(\n binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>,\n { schema }: { readonly schema: S },\n): PipelinesWriter<StandardSchemaV1.InferInput<S>> {\n if (!binding || typeof binding.send !== 'function') {\n throw new TypeError('Pipelines requires a stream binding with send(records).');\n }\n if (!isStandardSchema(schema)) {\n throw new TypeError('Pipelines requires a Standard Schema validator.');\n }\n\n return {\n async send(records) {\n if (!Array.isArray(records) || records.length === 0) {\n throw new TypeError('Pipelines requires a nonempty array of records.');\n }\n // Capture batch membership before the first asynchronous validation.\n const inputs: unknown[] = [];\n for (let index = 0; index < records.length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(records, String(index));\n if (!descriptor || !('value' in descriptor)) {\n throw new TypeError(\n `Pipelines record ${index} must be an array element, not an accessor or hole.`,\n );\n }\n inputs.push(descriptor.value);\n }\n\n const outputs: StandardSchemaV1.InferOutput<S>[] = [];\n let batchBytes = 2;\n for (const [index, input] of inputs.entries()) {\n let output: unknown;\n try {\n output = await parseSchemaAsync(schema, input);\n } catch (error) {\n if (error instanceof SchemaValidationError) {\n throw new SchemaValidationError(\n error.issues.map((issue) => ({ ...issue, path: [index, ...(issue.path ?? [])] })),\n );\n }\n throw error;\n }\n if (output === null || typeof output !== 'object' || Array.isArray(output)) {\n throw new TypeError(`Pipelines record ${index} must validate to a JSON object.`);\n }\n // Snapshot now: later async validators or callers may mutate earlier\n // outputs. The native send must receive exactly the JSON we checked.\n const snapshot = snapshotJson(output, [index], new Set());\n const bytes = encoder.encode(JSON.stringify(snapshot)).byteLength;\n if (bytes > MAX_BATCH_BYTES - 2) {\n throw new RangeError(\n `Pipelines record ${index} exceeds ${MAX_BATCH_BYTES - 2} JSON bytes.`,\n );\n }\n batchBytes += bytes + (index === 0 ? 0 : 1);\n if (batchBytes > MAX_BATCH_BYTES) {\n throw new RangeError(`Pipelines batch exceeds ${MAX_BATCH_BYTES} JSON bytes.`);\n }\n // The schema checked the shape; snapshotJson only copies JSON data and\n // rejects values JSON would silently drop or coerce.\n outputs.push(snapshot as StandardSchemaV1.InferOutput<S>);\n }\n await binding.send(outputs);\n },\n };\n}\n\nfunction snapshotJson(value: unknown, path: (string | number)[], ancestors: Set<object>): unknown {\n const invalid = (reason: string): never => {\n throw new TypeError(`Pipelines JSON value at ${JSON.stringify(path)} ${reason}.`);\n };\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) invalid('must be finite');\n return value;\n }\n if (typeof value !== 'object') return invalid('is not representable');\n if (ancestors.has(value)) return invalid('is circular');\n const array = Array.isArray(value);\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== (array ? Array.prototype : Object.prototype)) {\n return invalid('must use a plain object or array');\n }\n ancestors.add(value);\n try {\n // Native RPC bindings require ordinary objects, including when the input\n // has a null prototype. Define own properties below to preserve __proto__.\n const copy: Record<string, unknown> | unknown[] = array ? [] : {};\n const keys = Reflect.ownKeys(value);\n if (array && keys.length !== value.length + 1) return invalid('must be a dense array');\n for (const key of keys) {\n if (array && key === 'length') continue;\n if (typeof key !== 'string') return invalid('cannot have symbol keys');\n if (array && (!/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= value.length)) {\n return invalid('cannot have extra array properties');\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) {\n return invalid('must contain only enumerable data properties');\n }\n const child = snapshotJson(descriptor.value, [...path, array ? Number(key) : key], ancestors);\n Object.defineProperty(copy, key, {\n value: child,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return copy;\n } finally {\n ancestors.delete(value);\n }\n}\n"],"mappings":";;AAoBA,MAAM,kBAAkB;AACxB,MAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAgB,sBACd,SACA,EAAE,UAC+C;CACjD,IAAI,CAAC,WAAW,OAAO,QAAQ,SAAS,YACtC,MAAM,IAAI,UAAU,yDAAyD;CAE/E,IAAI,CAAC,iBAAiB,MAAM,GAC1B,MAAM,IAAI,UAAU,iDAAiD;CAGvE,OAAO,EACL,MAAM,KAAK,SAAS;EAClB,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,GAChD,MAAM,IAAI,UAAU,iDAAiD;EAGvE,MAAM,SAAoB,CAAC;EAC3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS;GACnD,MAAM,aAAa,OAAO,yBAAyB,SAAS,OAAO,KAAK,CAAC;GACzE,IAAI,CAAC,cAAc,EAAE,WAAW,aAC9B,MAAM,IAAI,UACR,oBAAoB,MAAM,oDAC5B;GAEF,OAAO,KAAK,WAAW,KAAK;EAC9B;EAEA,MAAM,UAA6C,CAAC;EACpD,IAAI,aAAa;EACjB,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ,GAAG;GAC7C,IAAI;GACJ,IAAI;IACF,SAAS,MAAM,iBAAiB,QAAQ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AAM,YAAY,OAAO,YACxE,OAAO,QAAQ,kCAAkC;CAEnD,UAAU,IAAI,KAAK;CACnB,IAAI;EAGF,MAAM,OAA4C,QAAQ,CAAC,IAAI,CAAC;EAChE,MAAM,OAAO,QAAQ,QAAQ,KAAK;EAClC,IAAI,SAAS,KAAK,WAAW,MAAM,SAAS,GAAG,OAAO,QAAQ,uBAAuB;EACrF,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI,SAAS,QAAQ,UAAU;GAC/B,IAAI,OAAO,QAAQ,UAAU,OAAO,QAAQ,yBAAyB;GACrE,IAAI,UAAU,CAAC,iBAAiB,KAAK,GAAG,KAAK,OAAO,GAAG,KAAK,MAAM,SAChE,OAAO,QAAQ,oCAAoC;GAErD,MAAM,aAAa,OAAO,yBAAyB,OAAO,GAAG;GAC7D,IAAI,CAAC,cAAc,EAAE,WAAW,eAAe,CAAC,WAAW,YACzD,OAAO,QAAQ,8CAA8C;GAE/D,MAAM,QAAQ,aAAa,WAAW,OAAO,CAAC,GAAG,MAAM,QAAQ,OAAO,GAAG,IAAI,GAAG,GAAG,SAAS;GAC5F,OAAO,eAAe,MAAM,KAAK;IAC/B,OAAO;IACP,YAAY;IACZ,UAAU;IACV,cAAc;GAChB,CAAC;EACH;EACA,OAAO;CACT,UAAU;EACR,UAAU,OAAO,KAAK;CACxB;AACF"}
@@ -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
@@ -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,KA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AAe,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,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,KA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