@velajs/cloudflare 1.34.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.
- package/CHANGELOG.md +20 -0
- package/README.md +20 -3
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +6 -0
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +8 -0
- package/dist/cloudflare-application.js +1 -1
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory.js +1 -1
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/index.d.ts +52 -2
- package/dist/queue/cloudflare-queues.js +3 -3
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/queues.d.ts +1 -1
- package/dist/storage/r2-storage.js +1 -1
- package/dist/storage/r2-storage.js.map +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/workflow/portable-workflow-step.js +62 -0
- package/dist/workflow/portable-workflow-step.js.map +1 -0
- package/dist/workflow/vela-workflow-definition.js +78 -0
- package/dist/workflow/vela-workflow-definition.js.map +1 -0
- package/dist/workflow-definitions.d.ts +33 -0
- package/dist/workflow-definitions.js +2 -0
- package/package.json +20 -10
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.35.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 9a00506: Align module APIs with instance ownership: shared facilities use forRoot, local and named services use register, and Queue, I18n and Seeder contribute declarations through forFeature. Remove replaced APIs. Local registrations receive independent identities; reused definitions share within an application, and explicit keys retain conflict checks.
|
|
8
|
+
|
|
9
|
+
Require applications to attach exported guards and interceptors explicitly. Remove automatic installation and guard options while preserving policy ownership, request scope, phase ordering, testing overrides and integration-route exemptions. Keep translation contributions and mutable runtime configuration isolated per application, and return runtime-only settings from async factories. Storage separates structural httpController mounting from runtime http options.
|
|
10
|
+
|
|
11
|
+
Add schema-first GraphQL resolver and parameter decorators with exact provider ownership, endpoint selection and duplicate binding validation. Add the optional Cloudflare workflow-definitions entrypoint to host portable workflows and compiled agents with validated input, per-run dependency resolution, explicit dispatch authority and native replay/error semantics.
|
|
12
|
+
|
|
13
|
+
Update CLI output, runnable examples, packed consumers and migration documentation together. Keep root Cloudflare declarations usable without installing the optional Feature Flags peer. See docs/module-api-migration.md for the new signatures and required application changes. This is a coordinated breaking change on the 1.x line; no compatibility aliases are retained.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- Updated dependencies [9a00506]
|
|
18
|
+
- @velajs/vela@1.34.0
|
|
19
|
+
- @velajs/storage@1.34.0
|
|
20
|
+
- @velajs/feature-flags@1.33.0
|
|
21
|
+
- @velajs/testing@1.34.0
|
|
22
|
+
|
|
3
23
|
## 1.34.0
|
|
4
24
|
|
|
5
25
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -4,6 +4,12 @@ Nest-style modules, dependency injection, controllers, queue consumers, cron tri
|
|
|
4
4
|
and live WebSockets on Cloudflare Workers. HTTP routing uses Hono. Bindings use the
|
|
5
5
|
platform's native types.
|
|
6
6
|
|
|
7
|
+
The [native composition example](../../apps/cloudflare-composition/README.md)
|
|
8
|
+
combines request-scoped `ENV` injection with Browser Run Quick Actions, Workers AI
|
|
9
|
+
and AI Gateway, VPC through `HttpService`, and authorized R2-to-WebP Images transforms.
|
|
10
|
+
It keeps destination/model policy on the server, bounds I/O and cancellation, and
|
|
11
|
+
separates local emulation from opt-in live acceptance without additional packages.
|
|
12
|
+
|
|
7
13
|
## Native environment and application lifetime
|
|
8
14
|
|
|
9
15
|
The Worker's native environment is the framework `ENV` from `@velajs/vela`.
|
|
@@ -218,7 +224,7 @@ class EmailProcessor {
|
|
|
218
224
|
}
|
|
219
225
|
|
|
220
226
|
@Module({
|
|
221
|
-
imports: [QueueModule.
|
|
227
|
+
imports: [QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])],
|
|
222
228
|
providers: [Signup, EmailProcessor],
|
|
223
229
|
})
|
|
224
230
|
class EmailModule {}
|
|
@@ -241,7 +247,7 @@ share one physical queue. Each job runs through the module's dispatch policy,
|
|
|
241
247
|
including signed dispatch and its global guards. A message is acknowledged
|
|
242
248
|
after its processors succeed; a message that is not a job envelope, belongs to
|
|
243
249
|
an unregistered queue, or fails stays unacknowledged, so Cloudflare retries it
|
|
244
|
-
and then dead-letters it. `
|
|
250
|
+
and then dead-letters it. `forFeature({ name, consumer: 'email-production' })`
|
|
245
251
|
pins the queue to that physical queue: its jobs are accepted only from it, and
|
|
246
252
|
it carries only the queues pinned to it. A physical queue cannot be both a
|
|
247
253
|
`@QueueConsumer` queue and a pinned consumer. A `@QueueConsumer` owns its
|
|
@@ -604,6 +610,17 @@ instances from module options and helpers; `WorkflowParams<T>` reads a
|
|
|
604
610
|
Workflow's params from its class or host. See
|
|
605
611
|
[Workflows](../../docs/workflows.md).
|
|
606
612
|
|
|
613
|
+
For portable `defineWorkflow(...)` and compiled `@velajs/agent` definitions,
|
|
614
|
+
import `VelaWorkflowDefinition` from `@velajs/cloudflare/workflow-definitions`.
|
|
615
|
+
This separate entrypoint requires the optional `@velajs/workflow` peer; importing
|
|
616
|
+
`/workflows` does not load it. The helper accepts `{ params, inject, useFactory }`:
|
|
617
|
+
validate trigger data with `params`, resolve the typed injection tuple per run,
|
|
618
|
+
and return `{ definition, run }` from the factory. `run` is an explicit application
|
|
619
|
+
dispatcher. Native steps preserve retries, checkpoints and compensation, including
|
|
620
|
+
portable terminal-error conversion inside step/rollback callbacks. Export a named
|
|
621
|
+
subclass and register it in Wrangler just as above. See the
|
|
622
|
+
[portable bridge example](../workflow/README.md#cloudflare-and-dependency-injection).
|
|
623
|
+
|
|
607
624
|
## Service entrypoints, email and tail
|
|
608
625
|
|
|
609
626
|
`VelaEntrypoint(app, Host, { rpc })` from `@velajs/cloudflare/entrypoints`
|
|
@@ -733,7 +750,7 @@ is the one file-storage module. Its native R2 driver comes from the
|
|
|
733
750
|
import { StorageModule } from '@velajs/storage';
|
|
734
751
|
import { r2Storage } from '@velajs/cloudflare/storage';
|
|
735
752
|
|
|
736
|
-
StorageModule.
|
|
753
|
+
StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) });
|
|
737
754
|
```
|
|
738
755
|
|
|
739
756
|
The bucket is read from each application's `ENV` on its first storage
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateMetadata.js
|
|
2
|
+
function __decorateMetadata(k, v) {
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
4
|
+
}
|
|
5
|
+
//#endregion
|
|
6
|
+
export { __decorateMetadata as default };
|
|
@@ -250,7 +250,7 @@ var CloudflareApplication = class {
|
|
|
250
250
|
const raw = this.#app.entrypoints.ofKind("cf:queue").filter((ep) => entrypointString(ep.meta, "queueName") === batch.queue);
|
|
251
251
|
if (raw.length > 0) this.warnRawJobs(batch);
|
|
252
252
|
const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind("cf:queue:module");
|
|
253
|
-
if (handlers.length === 0) throw new Error(`No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) with a QueueModule.
|
|
253
|
+
if (handlers.length === 0) throw new Error(`No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) with a QueueModule.forFeature([]) for each queue it carries. The batch is rejected unacknowledged, so Cloudflare retries it and then routes it to the configured dead-letter queue.`);
|
|
254
254
|
await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));
|
|
255
255
|
}
|
|
256
256
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-application.js","names":[],"sources":["../src/cloudflare-application.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport type { CorsOptions, VelaApplication, ExceptionFilter, VelaEnv } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n getEntrypointModuleId,\n invokeScheduledJob,\n parseCronMetadata,\n resolveEntrypoint,\n resolveScopedComponentsAsync,\n resolveErrorReporter,\n runInEntrypointScope,\n shouldFilterCatch,\n} from '@velajs/vela/module-kit';\nimport type { ScheduleInvocation } from '@velajs/vela/schedule';\nimport type { Entrypoint } from '@velajs/vela/module-kit';\nimport { assertCloudflareEnvironment } from './environment';\nimport {\n CLOUDFLARE_SCHEDULED_EVENT,\n cloudflareScheduledEvent,\n type ScheduledEvent,\n} from './scheduled-event';\n\n/**\n * Options accepted by {@link CloudflareApplication.mountOpenApi}.\n *\n * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from\n * the underlying `VelaApplication.mountOpenApi` signature so consumers don't\n * have to reach into vela's internal subpaths to type the argument.\n */\nexport type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];\n\nfunction invoke(instance: object, methodName: string | symbol, args: unknown[]): unknown {\n // Decorator metadata names an instance method; inspect it before invoking.\n const method: unknown = Reflect.get(instance, methodName);\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${String(methodName)}' is not a function on ${instance.constructor.name}`,\n );\n }\n return Reflect.apply(method, instance, args);\n}\n\nfunction entrypointString(meta: unknown, property: string): string {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid entrypoint metadata.');\n const value: unknown = Reflect.get(meta, property);\n if (typeof value !== 'string')\n throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);\n return value;\n}\n\n/**\n * `QueueModule`'s native consumer reports each failure of a batch once itself\n * (processor failures where they ran, transport failures on settlement), so\n * its rejection is not reported again here.\n */\nconst SELF_REPORTING_KINDS = new Set(['cf:queue:module']);\n\nconst warnedRawJobs = new Set<string>();\n\n/** The logical queue of a Vela job envelope, without importing the queue subsystem. */\nfunction envelopeQueue(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const queue: unknown = Reflect.get(body, 'queue');\n if (\n typeof queue !== 'string' ||\n typeof Reflect.get(body, 'id') !== 'string' ||\n typeof Reflect.get(body, 'name') !== 'string' ||\n !('data' in body)\n ) {\n return undefined;\n }\n return queue;\n}\n\n/** Wait for every matching handler, even when one fails before its siblings. */\nasync function settleEntrypoints(work: readonly Promise<void>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * Wraps VelaApplication with Cloudflare-specific handlers:\n * - `fetch` — HTTP request handler (from Hono)\n * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose\n * expression is the trigger's exact string)\n * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,\n * then `QueueModule`'s native consumer)\n * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on\n * the underlying Hono app\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * export default {\n * fetch: app.fetch,\n * scheduled: app.scheduled.bind(app),\n * queue: app.queue.bind(app),\n * };\n * ```\n *\n * @example\n * ```ts\n * // Serve OpenAPI docs alongside your routes\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule);\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> JSON document\n * // GET /scalar -> Scalar UI (loads from CDN)\n * ```\n */\nexport class CloudflareApplication {\n readonly #app: VelaApplication;\n /** Scheduled triggers in flight; close() aborts their signals and awaits them. */\n readonly #scheduled = new Map<Promise<void>, AbortController>();\n\n constructor(\n app: VelaApplication,\n readonly env: VelaEnv,\n ) {\n this.#app = app;\n this.get = app.get.bind(app);\n }\n\n readonly fetch = async (\n request: Request,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ): Promise<Response> => {\n assertCloudflareEnvironment(this.env, env);\n return this.#app.fetch(request, env, ctx);\n };\n\n getHonoApp(): ReturnType<VelaApplication['getHonoApp']> {\n return this.#app.getHonoApp();\n }\n\n /**\n * Resolve a provider from the application's DI container (delegates to\n * `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,\n * which finishes the HTTP surface outside the DI request pipeline.\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * const auth = app.get(BetterAuthService);\n * ```\n */\n readonly get: VelaApplication['get'];\n\n get entrypoints(): VelaApplication['entrypoints'] {\n return this.#app.entrypoints;\n }\n\n /**\n * The application's DI container (delegates to `VelaApplication.getContainer`),\n * for dispatch seams that take it with `entrypoints`, such as\n * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.\n */\n getContainer(): ReturnType<VelaApplication['getContainer']> {\n return this.#app.getContainer();\n }\n\n /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */\n enableCors(options?: CorsOptions): this {\n this.#app.enableCors(options);\n return this;\n }\n\n /**\n * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the\n * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,\n * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when\n * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from\n * a CDN at runtime, nothing is bundled server-side.\n *\n * @example\n * ```ts\n * import { createOpenApiDocument } from '@velajs/vela/openapi';\n *\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule, {\n * info: { title: 'My API', version: '1.0.0' },\n * });\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> { openapi: '3.1.0', ... }\n * // GET /scalar -> Scalar UI HTML\n * ```\n */\n mountOpenApi(options: MountOpenApiOptions): this {\n this.#app.mountOpenApi(options);\n return this;\n }\n\n /**\n * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose\n * expression is exactly `event.cron` (the trigger string is compared as\n * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch\n * primitive every runtime shares. Each job receives only its\n * `ScheduleInvocation`, runs in a fresh invocation scope seeded with\n * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`\n * dispatch. The trigger settles after every matching job and its managed\n * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.\n */\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n _ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const jobs = this.#app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .filter((entry) => entry.meta.expression === event.cron);\n if (jobs.length === 0) return;\n\n const controller = new AbortController();\n const scheduledTime = event.scheduledTime ?? Date.now();\n // Shared by every matching job, so none of them can alter what another sees.\n const invocation: ScheduleInvocation = Object.freeze({\n kind: 'cron' as const,\n expression: event.cron,\n scheduledTime,\n signal: controller.signal,\n });\n const trigger = cloudflareScheduledEvent(event, scheduledTime);\n const container = this.#app.getContainer();\n const running = settleEntrypoints(\n jobs.map((entry) =>\n invokeScheduledJob(container, entry, invocation, {\n seed: (scope) => scope.setRequestInstance(CLOUDFLARE_SCHEDULED_EVENT, trigger),\n }),\n ),\n );\n this.#scheduled.set(running, controller);\n try {\n await running;\n } finally {\n this.#scheduled.delete(running);\n }\n }\n\n /**\n * Run one queue consumer inside a fresh request scope, through the shared\n * guard → interceptor pipeline (components declared with\n * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or\n * method). HTTP-global components deliberately do NOT apply — an HTTP auth\n * guard has no business rejecting a queue batch. Unclaimed errors are\n * reported once (`QueueModule`'s consumer reports its own) and rethrow so\n * the platform's retry semantics stay intact.\n */\n private async dispatchEntrypoint(\n ep: Entrypoint,\n payload: unknown,\n env: VelaEnv,\n platformContext: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n const targetClass = ep.token;\n if (typeof targetClass !== 'function') throw new Error('Entrypoint token must be a class.');\n if (ep.methodName === undefined) throw new Error('Entrypoint must declare a handler method.');\n const methodName = ep.methodName;\n const reportContext = {\n edge: 'queue' as const,\n source: `${targetClass.name}.${String(methodName)}`,\n };\n let reported: { error: unknown } | undefined;\n // A self-reporting handler's own rejection was already reported.\n let delegated: { error: unknown } | undefined;\n try {\n await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {\n const moduleId = getEntrypointModuleId(scope, ep);\n const context = buildEntrypointExecutionContext(\n ep.kind,\n targetClass,\n methodName,\n payload,\n moduleId,\n scope,\n );\n const invocationContext = {\n waitUntil(promise: Promise<unknown>): void {\n lifetime.waitUntil(promise);\n platformContext.waitUntil(promise);\n },\n };\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', targetClass, methodName, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync(\n 'guard',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: async () => [payload, env, invocationContext],\n invoke: async (args) => {\n const instance = await resolveEntrypoint(scope, ep);\n if (typeof instance !== 'object' || instance === null) {\n throw new Error('Entrypoint must resolve to an object.');\n }\n try {\n return await invoke(instance, methodName, args);\n } catch (error) {\n if (SELF_REPORTING_KINDS.has(ep.kind)) delegated = { error };\n throw error;\n }\n },\n });\n } catch (error) {\n if (delegated?.error !== error) {\n resolveErrorReporter(scope).report(error, reportContext);\n }\n for (const filter of filters) {\n if (shouldFilterCatch(filter, error)) {\n // Filters run closest-first; this is the framework catch hook.\n // eslint-disable-next-line no-await-in-loop, promise/valid-params\n await filter.catch(error, context);\n return;\n }\n }\n reported = { error };\n throw error;\n }\n });\n } catch (error) {\n // Managed completion happens after the handler's filter boundary. Report\n // a new completion failure without reporting an already-observed handler\n // failure twice; preserve both errors in the rejected invocation.\n if (!reported || reported.error !== error) {\n const completionError =\n reported && error instanceof AggregateError && error.errors[0] === reported.error\n ? error.errors[1]\n : error;\n resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);\n }\n throw error;\n }\n }\n\n /**\n * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read\n * from `app.entrypoints` claim a batch by its physical queue name and\n * receive it whole. A batch no handler claims goes to `QueueModule`'s native\n * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which\n * routes each job by its logical queue. Each dispatch runs inside a fresh\n * request-scoped child (request-scoped providers rebuild per batch — no\n * boot-time captives). A batch nothing claims rejects: resolving would let\n * Cloudflare acknowledge every message implicitly.\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 assertCloudflareEnvironment(this.env, env);\n const raw = this.#app.entrypoints\n .ofKind('cf:queue')\n .filter((ep) => entrypointString(ep.meta, 'queueName') === batch.queue);\n if (raw.length > 0) this.warnRawJobs(batch);\n const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind('cf:queue:module');\n\n if (handlers.length === 0) {\n throw new Error(\n `No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a ` +\n `provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) ` +\n `with a QueueModule.registerQueue() for each queue it carries. The batch is rejected ` +\n `unacknowledged, so Cloudflare retries it and then routes it to the configured ` +\n `dead-letter queue.`,\n );\n }\n\n await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));\n }\n\n /**\n * A raw `@QueueConsumer` owns its physical queue's batches and must not carry\n * jobs of a queue registered with `QueueModule`: those reach their\n * `@Processor` only if the raw handler dispatches them itself, while\n * `cloudflareQueues()` delivers registered queues. Warn once per physical and\n * logical queue (unless diagnostics are silent); the raw consumer still\n * receives and settles the batch.\n */\n private warnRawJobs(batch: { queue: string; messages: readonly unknown[] }): void {\n if (this.#app.getContainer().getDiagnostics() === 'silent') return;\n const registered = new Set(\n this.#app.entrypoints\n .ofKind('queue:registration')\n .map((entry) =>\n typeof entry.meta === 'object' && entry.meta !== null\n ? Reflect.get(entry.meta, 'name')\n : undefined,\n ),\n );\n if (registered.size === 0) return;\n for (const message of batch.messages) {\n const body =\n typeof message === 'object' && message !== null ? Reflect.get(message, 'body') : undefined;\n const queue = envelopeQueue(body);\n if (queue === undefined || !registered.has(queue)) continue;\n const warning =\n `[vela] @QueueConsumer('${batch.queue}') received jobs of registered queue '${queue}'. ` +\n `The raw consumer owns '${batch.queue}' and must not carry jobs of registered queues: ` +\n `they reach @Processor('${queue}') only if the raw handler dispatches them itself. ` +\n `Deliver '${queue}' through cloudflareQueues() instead: send it to a physical queue ` +\n `that no @QueueConsumer claims.`;\n if (warnedRawJobs.has(warning)) continue;\n warnedRawJobs.add(warning);\n console.warn(warning);\n }\n }\n\n /**\n * Abort the signals of scheduled jobs still running, wait for them and their\n * managed work to settle, then close the application.\n */\n async close(signal?: string): Promise<void> {\n for (const controller of this.#scheduled.values()) controller.abort();\n await Promise.allSettled(this.#scheduled.keys());\n return this.#app.close(signal);\n }\n}\n"],"mappings":";;;;AAgCA,SAAS,OAAO,UAAkB,YAA6B,MAA0B;CAEvF,MAAM,SAAkB,QAAQ,IAAI,UAAU,UAAU;CACxD,IAAI,OAAO,WAAW,YACpB,MAAM,IAAI,MACR,WAAW,OAAO,UAAU,EAAE,yBAAyB,SAAS,YAAY,MAC9E;CAEF,OAAO,QAAQ,MAAM,QAAQ,UAAU,IAAI;AAC7C;AAEA,SAAS,iBAAiB,MAAe,UAA0B;CACjE,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,8BAA8B;CAC7F,MAAM,QAAiB,QAAQ,IAAI,MAAM,QAAQ;CACjD,IAAI,OAAO,UAAU,UACn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IAAI,OAAO,GAAG;GAChC,cAAc,IAAI,OAAO;GACzB,QAAQ,KAAK,OAAO;EACtB;CACF;;;;;CAMA,MAAM,MAAM,QAAgC;EAC1C,KAAK,MAAM,cAAc,KAAK,WAAW,OAAO,GAAG,WAAW,MAAM;EACpE,MAAM,QAAQ,WAAW,KAAK,WAAW,KAAK,CAAC;EAC/C,OAAO,KAAK,KAAK,MAAM,MAAM;CAC/B;AACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare-application.js","names":[],"sources":["../src/cloudflare-application.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport type { CorsOptions, VelaApplication, ExceptionFilter, VelaEnv } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n getEntrypointModuleId,\n invokeScheduledJob,\n parseCronMetadata,\n resolveEntrypoint,\n resolveScopedComponentsAsync,\n resolveErrorReporter,\n runInEntrypointScope,\n shouldFilterCatch,\n} from '@velajs/vela/module-kit';\nimport type { ScheduleInvocation } from '@velajs/vela/schedule';\nimport type { Entrypoint } from '@velajs/vela/module-kit';\nimport { assertCloudflareEnvironment } from './environment';\nimport {\n CLOUDFLARE_SCHEDULED_EVENT,\n cloudflareScheduledEvent,\n type ScheduledEvent,\n} from './scheduled-event';\n\n/**\n * Options accepted by {@link CloudflareApplication.mountOpenApi}.\n *\n * Re-exposes vela's `MountOpenApiOptions` type — derived structurally from\n * the underlying `VelaApplication.mountOpenApi` signature so consumers don't\n * have to reach into vela's internal subpaths to type the argument.\n */\nexport type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];\n\nfunction invoke(instance: object, methodName: string | symbol, args: unknown[]): unknown {\n // Decorator metadata names an instance method; inspect it before invoking.\n const method: unknown = Reflect.get(instance, methodName);\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${String(methodName)}' is not a function on ${instance.constructor.name}`,\n );\n }\n return Reflect.apply(method, instance, args);\n}\n\nfunction entrypointString(meta: unknown, property: string): string {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid entrypoint metadata.');\n const value: unknown = Reflect.get(meta, property);\n if (typeof value !== 'string')\n throw new Error(`Invalid entrypoint metadata: ${property} must be a string.`);\n return value;\n}\n\n/**\n * `QueueModule`'s native consumer reports each failure of a batch once itself\n * (processor failures where they ran, transport failures on settlement), so\n * its rejection is not reported again here.\n */\nconst SELF_REPORTING_KINDS = new Set(['cf:queue:module']);\n\nconst warnedRawJobs = new Set<string>();\n\n/** The logical queue of a Vela job envelope, without importing the queue subsystem. */\nfunction envelopeQueue(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const queue: unknown = Reflect.get(body, 'queue');\n if (\n typeof queue !== 'string' ||\n typeof Reflect.get(body, 'id') !== 'string' ||\n typeof Reflect.get(body, 'name') !== 'string' ||\n !('data' in body)\n ) {\n return undefined;\n }\n return queue;\n}\n\n/** Wait for every matching handler, even when one fails before its siblings. */\nasync function settleEntrypoints(work: readonly Promise<void>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * Wraps VelaApplication with Cloudflare-specific handlers:\n * - `fetch` — HTTP request handler (from Hono)\n * - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose\n * expression is the trigger's exact string)\n * - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,\n * then `QueueModule`'s native consumer)\n * - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on\n * the underlying Hono app\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * export default {\n * fetch: app.fetch,\n * scheduled: app.scheduled.bind(app),\n * queue: app.queue.bind(app),\n * };\n * ```\n *\n * @example\n * ```ts\n * // Serve OpenAPI docs alongside your routes\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule);\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> JSON document\n * // GET /scalar -> Scalar UI (loads from CDN)\n * ```\n */\nexport class CloudflareApplication {\n readonly #app: VelaApplication;\n /** Scheduled triggers in flight; close() aborts their signals and awaits them. */\n readonly #scheduled = new Map<Promise<void>, AbortController>();\n\n constructor(\n app: VelaApplication,\n readonly env: VelaEnv,\n ) {\n this.#app = app;\n this.get = app.get.bind(app);\n }\n\n readonly fetch = async (\n request: Request,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ): Promise<Response> => {\n assertCloudflareEnvironment(this.env, env);\n return this.#app.fetch(request, env, ctx);\n };\n\n getHonoApp(): ReturnType<VelaApplication['getHonoApp']> {\n return this.#app.getHonoApp();\n }\n\n /**\n * Resolve a provider from the application's DI container (delegates to\n * `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,\n * which finishes the HTTP surface outside the DI request pipeline.\n *\n * @example\n * ```ts\n * const app = await createCloudflareApp(AppModule, { env });\n * const auth = app.get(BetterAuthService);\n * ```\n */\n readonly get: VelaApplication['get'];\n\n get entrypoints(): VelaApplication['entrypoints'] {\n return this.#app.entrypoints;\n }\n\n /**\n * The application's DI container (delegates to `VelaApplication.getContainer`),\n * for dispatch seams that take it with `entrypoints`, such as\n * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.\n */\n getContainer(): ReturnType<VelaApplication['getContainer']> {\n return this.#app.getContainer();\n }\n\n /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */\n enableCors(options?: CorsOptions): this {\n this.#app.enableCors(options);\n return this;\n }\n\n /**\n * Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the\n * underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,\n * so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when\n * opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from\n * a CDN at runtime, nothing is bundled server-side.\n *\n * @example\n * ```ts\n * import { createOpenApiDocument } from '@velajs/vela/openapi';\n *\n * const app = await createCloudflareApp(AppModule, { env });\n * const document = createOpenApiDocument(AppModule, {\n * info: { title: 'My API', version: '1.0.0' },\n * });\n * app.mountOpenApi({ document, ui: 'scalar' });\n * // GET /openapi.json -> { openapi: '3.1.0', ... }\n * // GET /scalar -> Scalar UI HTML\n * ```\n */\n mountOpenApi(options: MountOpenApiOptions): this {\n this.#app.mountOpenApi(options);\n return this;\n }\n\n /**\n * Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose\n * expression is exactly `event.cron` (the trigger string is compared as\n * delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch\n * primitive every runtime shares. Each job receives only its\n * `ScheduleInvocation`, runs in a fresh invocation scope seeded with\n * {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`\n * dispatch. The trigger settles after every matching job and its managed\n * work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.\n */\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n _ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n assertCloudflareEnvironment(this.env, env);\n const jobs = this.#app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .filter((entry) => entry.meta.expression === event.cron);\n if (jobs.length === 0) return;\n\n const controller = new AbortController();\n const scheduledTime = event.scheduledTime ?? Date.now();\n // Shared by every matching job, so none of them can alter what another sees.\n const invocation: ScheduleInvocation = Object.freeze({\n kind: 'cron' as const,\n expression: event.cron,\n scheduledTime,\n signal: controller.signal,\n });\n const trigger = cloudflareScheduledEvent(event, scheduledTime);\n const container = this.#app.getContainer();\n const running = settleEntrypoints(\n jobs.map((entry) =>\n invokeScheduledJob(container, entry, invocation, {\n seed: (scope) => scope.setRequestInstance(CLOUDFLARE_SCHEDULED_EVENT, trigger),\n }),\n ),\n );\n this.#scheduled.set(running, controller);\n try {\n await running;\n } finally {\n this.#scheduled.delete(running);\n }\n }\n\n /**\n * Run one queue consumer inside a fresh request scope, through the shared\n * guard → interceptor pipeline (components declared with\n * `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or\n * method). HTTP-global components deliberately do NOT apply — an HTTP auth\n * guard has no business rejecting a queue batch. Unclaimed errors are\n * reported once (`QueueModule`'s consumer reports its own) and rethrow so\n * the platform's retry semantics stay intact.\n */\n private async dispatchEntrypoint(\n ep: Entrypoint,\n payload: unknown,\n env: VelaEnv,\n platformContext: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n const targetClass = ep.token;\n if (typeof targetClass !== 'function') throw new Error('Entrypoint token must be a class.');\n if (ep.methodName === undefined) throw new Error('Entrypoint must declare a handler method.');\n const methodName = ep.methodName;\n const reportContext = {\n edge: 'queue' as const,\n source: `${targetClass.name}.${String(methodName)}`,\n };\n let reported: { error: unknown } | undefined;\n // A self-reporting handler's own rejection was already reported.\n let delegated: { error: unknown } | undefined;\n try {\n await runInEntrypointScope(this.#app.getContainer(), async (scope, lifetime) => {\n const moduleId = getEntrypointModuleId(scope, ep);\n const context = buildEntrypointExecutionContext(\n ep.kind,\n targetClass,\n methodName,\n payload,\n moduleId,\n scope,\n );\n const invocationContext = {\n waitUntil(promise: Promise<unknown>): void {\n lifetime.waitUntil(promise);\n platformContext.waitUntil(promise);\n },\n };\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', targetClass, methodName, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync(\n 'guard',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n targetClass,\n methodName,\n scope,\n moduleId,\n );\n await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: async () => [payload, env, invocationContext],\n invoke: async (args) => {\n const instance = await resolveEntrypoint(scope, ep);\n if (typeof instance !== 'object' || instance === null) {\n throw new Error('Entrypoint must resolve to an object.');\n }\n try {\n return await invoke(instance, methodName, args);\n } catch (error) {\n if (SELF_REPORTING_KINDS.has(ep.kind)) delegated = { error };\n throw error;\n }\n },\n });\n } catch (error) {\n if (delegated?.error !== error) {\n resolveErrorReporter(scope).report(error, reportContext);\n }\n for (const filter of filters) {\n if (shouldFilterCatch(filter, error)) {\n // Filters run closest-first; this is the framework catch hook.\n // eslint-disable-next-line no-await-in-loop, promise/valid-params\n await filter.catch(error, context);\n return;\n }\n }\n reported = { error };\n throw error;\n }\n });\n } catch (error) {\n // Managed completion happens after the handler's filter boundary. Report\n // a new completion failure without reporting an already-observed handler\n // failure twice; preserve both errors in the rejected invocation.\n if (!reported || reported.error !== error) {\n const completionError =\n reported && error instanceof AggregateError && error.errors[0] === reported.error\n ? error.errors[1]\n : error;\n resolveErrorReporter(this.#app.getContainer()).report(completionError, reportContext);\n }\n throw error;\n }\n }\n\n /**\n * Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read\n * from `app.entrypoints` claim a batch by its physical queue name and\n * receive it whole. A batch no handler claims goes to `QueueModule`'s native\n * consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which\n * routes each job by its logical queue. Each dispatch runs inside a fresh\n * request-scoped child (request-scoped providers rebuild per batch — no\n * boot-time captives). A batch nothing claims rejects: resolving would let\n * Cloudflare acknowledge every message implicitly.\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 assertCloudflareEnvironment(this.env, env);\n const raw = this.#app.entrypoints\n .ofKind('cf:queue')\n .filter((ep) => entrypointString(ep.meta, 'queueName') === batch.queue);\n if (raw.length > 0) this.warnRawJobs(batch);\n const handlers = raw.length > 0 ? raw : this.#app.entrypoints.ofKind('cf:queue:module');\n\n if (handlers.length === 0) {\n throw new Error(\n `No consumer claims queue '${batch.queue}'. Add @QueueConsumer('${batch.queue}') to a ` +\n `provider, or deliver it through QueueModule.forRoot({ driver: cloudflareQueues() }) ` +\n `with a QueueModule.forFeature([]) for each queue it carries. The batch is rejected ` +\n `unacknowledged, so Cloudflare retries it and then routes it to the configured ` +\n `dead-letter queue.`,\n );\n }\n\n await settleEntrypoints(handlers.map((ep) => this.dispatchEntrypoint(ep, batch, env, ctx)));\n }\n\n /**\n * A raw `@QueueConsumer` owns its physical queue's batches and must not carry\n * jobs of a queue registered with `QueueModule`: those reach their\n * `@Processor` only if the raw handler dispatches them itself, while\n * `cloudflareQueues()` delivers registered queues. Warn once per physical and\n * logical queue (unless diagnostics are silent); the raw consumer still\n * receives and settles the batch.\n */\n private warnRawJobs(batch: { queue: string; messages: readonly unknown[] }): void {\n if (this.#app.getContainer().getDiagnostics() === 'silent') return;\n const registered = new Set(\n this.#app.entrypoints\n .ofKind('queue:registration')\n .map((entry) =>\n typeof entry.meta === 'object' && entry.meta !== null\n ? Reflect.get(entry.meta, 'name')\n : undefined,\n ),\n );\n if (registered.size === 0) return;\n for (const message of batch.messages) {\n const body =\n typeof message === 'object' && message !== null ? Reflect.get(message, 'body') : undefined;\n const queue = envelopeQueue(body);\n if (queue === undefined || !registered.has(queue)) continue;\n const warning =\n `[vela] @QueueConsumer('${batch.queue}') received jobs of registered queue '${queue}'. ` +\n `The raw consumer owns '${batch.queue}' and must not carry jobs of registered queues: ` +\n `they reach @Processor('${queue}') only if the raw handler dispatches them itself. ` +\n `Deliver '${queue}' through cloudflareQueues() instead: send it to a physical queue ` +\n `that no @QueueConsumer claims.`;\n if (warnedRawJobs.has(warning)) continue;\n warnedRawJobs.add(warning);\n console.warn(warning);\n }\n }\n\n /**\n * Abort the signals of scheduled jobs still running, wait for them and their\n * managed work to settle, then close the application.\n */\n async close(signal?: string): Promise<void> {\n for (const controller of this.#scheduled.values()) controller.abort();\n await Promise.allSettled(this.#scheduled.keys());\n return this.#app.close(signal);\n }\n}\n"],"mappings":";;;;AAgCA,SAAS,OAAO,UAAkB,YAA6B,MAA0B;CAEvF,MAAM,SAAkB,QAAQ,IAAI,UAAU,UAAU;CACxD,IAAI,OAAO,WA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AK,MAAM,WAAW,MAAM,UAAU;GAGpC,MAAM,QAAQ,cADZ,OAAO,YAAY,YAAY,YAAY,OAAO,QAAQ,IAAI,SAAS,MAAM,IAAI,KAAA,CACnD;GAChC,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,IAAI,KAAK,GAAG;GACnD,MAAM,UACJ,0BAA0B,MAAM,MAAM,wCAAwC,MAAM,4BAC1D,MAAM,MAAM,yEACZ,MAAM,8DACpB,MAAM;GAEpB,IAAI,cAAc,IAAI,OAAO,GAAG;GAChC,cAAc,IAAI,OAAO;GACzB,QAAQ,KAAK,OAAO;EACtB;CACF;;;;;CAMA,MAAM,MAAM,QAAgC;EAC1C,KAAK,MAAM,cAAc,KAAK,WAAW,OAAO,GAAG,WAAW,MAAM;EACpE,MAAM,QAAQ,WAAW,KAAK,WAAW,KAAK,CAAC;EAC/C,OAAO,KAAK,KAAK,MAAM,MAAM;CAC/B;AACF"}
|
|
@@ -25,7 +25,7 @@ function assertQueueConsumerOwnership(entrypoints) {
|
|
|
25
25
|
const pinned = new Set(entrypoints.ofKind("cf:queue:module").flatMap((entry) => readStrings(entry.meta, "consumers")));
|
|
26
26
|
for (const entry of entrypoints.ofKind("cf:queue")) {
|
|
27
27
|
const [queue] = readStrings(entry.meta, "queueName");
|
|
28
|
-
if (queue !== void 0 && pinned.has(queue)) throw new Error(`Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a QueueModule.
|
|
28
|
+
if (queue !== void 0 && pinned.has(queue)) throw new Error(`Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a QueueModule.forFeature([{ consumer: '${queue}' }]) both claim it. Keep one owner.`);
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
@@ -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,IAAI,KAAK,GACzC,MAAM,IAAI,MACR,2CAA2C,MAAM,qBAAqB,MAAM,kDAChC,MAAM,oCACpD;CAEJ;AACF;;;;;;;;;;;;AAaA,SAAgB,kBAAkB,SAA2C;CAC3E,MAAM,EAAE,QAAQ;CAChB,OAAO;EACL,MAAM;EACN,mBAAmB,CACjB,OAAO,SAAS,SAAS;GACvB,4BAA4B,KAAK,QAAQ,GAAG;GAC5C,MAAM,KAAK;EACb,CACF;EACA,sBACG,EAAE,WACF,YACC,QAAQ,QAAQ,IAAI,MAAM,SAAS,GAAG,CAAC;EAG3C,cAAc,MAAM,EAAE,IAAI,OAAO,kBAAkB,KAAK;EACxD,qBAAqB,cAAc;GACjC,2BAA2B,WAAW,KAAK;IACzC,WAAW,yBAAyB,GAAG;IACvC,MAAM,mBAAmB,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C,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,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,IAAI,KAAK,GACzC,MAAM,IAAI,MACR,2CAA2C,MAAM,qBAAqB,MAAM,gDAClC,MAAM,qCAClD;CAEJ;AACF;;;;;;;;;;;;AAaA,SAAgB,kBAAkB,SAA2C;CAC3E,MAAM,EAAE,QAAQ;CAChB,OAAO;EACL,MAAM;EACN,mBAAmB,CACjB,OAAO,SAAS,SAAS;GACvB,4BAA4B,KAAK,QAAQ,GAAG;GAC5C,MAAM,KAAK;EACb,CACF;EACA,sBACG,EAAE,WAC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G;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"}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,12 +2,11 @@ import "./vela-env-DFvyoNT3.js";
|
|
|
2
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
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, FlagEvaluationDetails } 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
|
|
@@ -138,6 +137,57 @@ export declare function kvCacheInvalidation(ref: {
|
|
|
138
137
|
binding: string;
|
|
139
138
|
}): EnvFactory<CacheInvalidationStore>;
|
|
140
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
|
|
141
191
|
//#region src/services/flagship-flag.driver.d.ts
|
|
142
192
|
/**
|
|
143
193
|
* The subset of a Cloudflare **Flagship** binding this driver evaluates against
|
|
@@ -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.
|
|
106
|
-
if (registration.binding === void 0) throw new Error(`Queue '${name}' has no producer binding. Register it with QueueModule.
|
|
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.
|
|
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,KAAK,WAAW,KAAK;EAClC,IAAI,OAAO,KAAM,OAAO;EACxB,IAAI,OAAO,IAAM,QAAQ;OACpB,IAAI,SAAS,MAAQ,SAAS,IAAM,QAAQ;OAC5C,IAAI,OAAO,KAAM,QAAQ;OACzB,IAAI,OAAO,MAAO,QAAQ;OAC1B,IAAI,QAAQ,SAAU,QAAQ,OAAQ,QAAQ;OAC9C,QAAQ;CACf;CACA,OAAO,KAAK,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,KAAK,UAAU,CAAC;AAClE;AAEA,SAAS,QAAQ,OAAgB,MAA2B;CAC1D,QAAQ,OAAO,OAAf;EACE,KAAK,UACH,OAAO,YAAY,KAAK;EAC1B,KAAK,UACH,OAAO,KAAK,IAAI,OAAO,KAAK,CAAC,CAAC,QAAQ,CAAC;EACzC,KAAK,UACH,OAAO,OAAO,KAAK,CAAC,CAAC,SAAS;EAChC,KAAK,WACH,OAAO;EACT,KAAK,UACH;EACF,SACE,OAAO;CACX;CACA,IAAI,UAAU,MAAM,OAAO;CAE3B,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CACd,IAAI,QAAQ;CACZ,IAAI,YAAY,OAAO,KAAK,KAAK,iBAAiB,a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AAI,MAAM,0BAA0B,MAAM,MAAM,mBACrD,QAAQ,OAAO,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,EAC9D;EAEF,MAAM,WAAW,eAAe,OAAO;EAGvC,KAAI,MADiB,SAAS,KAAK,SAAS,OAAO,EAAA,EACvC,YAAY,GAAG,MAAM,IAAI,MAAM,cAAc,IAAI,KAAK,kBAAkB;EACpF,IAAI,SAAS,YAAY,CAAC,CAAC,YAAY,aAAa,SAAS,QAAQ,IAAI;CAC3E,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAEF,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;CACtC,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,gCAAgC;AAC1F"}
|
|
1
|
+
{"version":3,"file":"cloudflare-queues.js","names":[],"sources":["../../src/queue/cloudflare-queues.ts"],"sourcesContent":["import { observeMessage, parseQueueJob, QueueBatchError } from '@velajs/vela/queue';\nimport { resolveBinding } from '@velajs/vela/module-kit';\nimport { QUEUE_PRODUCER } from '../bindings';\nimport type {\n AddJobOptions,\n QueueDispatchFn,\n QueueDispatchResult,\n QueueDriver,\n QueueDriverContext,\n QueueDriverFactory,\n QueueEnqueueRequest,\n QueueJob,\n QueueMessageLike,\n} from '@velajs/vela/queue';\n\n/** The native producer surface the driver uses: a Wrangler `queues.producers` binding. */\nexport interface CloudflareQueueProducer {\n // Both older void-returning bindings and current metric-returning bindings work.\n send(message: QueueJob, options?: QueueSendOptions): Promise<unknown>;\n sendBatch?(messages: Iterable<MessageSendRequest<QueueJob>>): Promise<unknown>;\n}\n\n/** The Cloudflare Queues send limits `addBulk` is chunked to (bytes are decimal kilobytes). */\nexport const QUEUE_SEND_LIMITS = Object.freeze({\n /** Messages per `sendBatch` call. */\n messages: 100,\n /** Estimated bytes per `sendBatch` call. */\n batchBytes: 256_000,\n /** Estimated bytes per message. */\n messageBytes: 128_000,\n});\n\n/** Allowance for the platform's per-message framing on top of the body estimate. */\nconst MESSAGE_MARGIN_BYTES = 256;\nconst MAX_DELAY_MS = 86_400_000;\n\n/**\n * A string's size as JSON (UTF-8, quoted, escaped) or as V8 serializes it\n * (one byte per character, two for a string holding any character above\n * U+00FF), whichever is larger.\n */\nfunction stringBytes(text: string): number {\n let json = 2;\n let wide = false;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n if (code > 0xff) wide = true;\n if (code < 0x20) json += 6;\n else if (code === 0x22 || code === 0x5c) json += 2;\n else if (code < 0x80) json += 1;\n else if (code < 0x800) json += 2;\n else if (code >= 0xd800 && code <= 0xdfff) json += 2;\n else json += 3;\n }\n return Math.max(json, (wide ? text.length * 2 : text.length) + 5);\n}\n\nfunction measure(value: unknown, seen: Set<object>): number {\n switch (typeof value) {\n case 'string':\n return stringBytes(value);\n case 'number':\n return Math.max(String(value).length, 9);\n case 'bigint':\n return String(value).length + 9;\n case 'boolean':\n return 5;\n case 'object':\n break;\n default:\n return 9;\n }\n if (value === null) return 4;\n // V8 serializes a repeated reference as a back-reference.\n if (seen.has(value)) return 9;\n seen.add(value);\n let bytes = 2;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n bytes += value.byteLength + 9;\n } else if (value instanceof Date) {\n bytes += 26;\n } else if (value instanceof Map) {\n for (const [key, item] of value) bytes += measure(key, seen) + measure(item, seen) + 2;\n } else if (value instanceof Set) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else if (Array.isArray(value)) {\n for (const item of value) bytes += measure(item, seen) + 1;\n } else {\n for (const key of Object.keys(value)) {\n bytes += stringBytes(key) + measure(Reflect.get(value, key), seen) + 2;\n }\n }\n return bytes;\n}\n\n/**\n * A conservative size estimate of one native queue message: the larger of the\n * body's JSON and V8 sizes, plus a per-message margin.\n */\nexport function estimateQueueMessageBytes(body: unknown): number {\n return measure(body, new Set()) + MESSAGE_MARGIN_BYTES;\n}\n\nfunction delaySeconds(options: AddJobOptions | undefined): number | undefined {\n const delayMs = options?.delayMs;\n if (delayMs === undefined) return undefined;\n if (!Number.isFinite(delayMs) || delayMs < 0 || delayMs > MAX_DELAY_MS) {\n throw new RangeError('Queue delayMs must be between 0 and 86400000.');\n }\n return Math.ceil(delayMs / 1000);\n}\n\nfunction nativeBatch(payload: unknown): { queue: string; messages: QueueMessageLike[] } {\n if (\n typeof payload !== 'object' ||\n payload === null ||\n !('queue' in payload) ||\n typeof payload.queue !== 'string' ||\n !('messages' in payload) ||\n !Array.isArray(payload.messages)\n )\n throw new TypeError('Invalid native queue batch.');\n const messages: QueueMessageLike[] = [];\n for (const message of payload.messages as unknown[]) {\n if (\n typeof message !== 'object' ||\n message === null ||\n !('body' in message) ||\n !('ack' in message) ||\n typeof message.ack !== 'function' ||\n !('retry' in message) ||\n typeof message.retry !== 'function' ||\n !('id' in message) ||\n typeof message.id !== 'string' ||\n !('timestamp' in message) ||\n !(message.timestamp instanceof Date) ||\n !('attempts' in message) ||\n typeof message.attempts !== 'number'\n )\n throw new TypeError('Invalid native queue message.');\n messages.push(message as QueueMessageLike);\n }\n return { queue: payload.queue, messages };\n}\n\ninterface PreparedMessage {\n readonly id: string;\n readonly queue: string;\n readonly bytes: number;\n readonly request: MessageSendRequest<QueueJob>;\n}\n\n/** Split in order: a new call starts at 100 messages, at the byte budget, or at another queue. */\nfunction chunk(messages: readonly PreparedMessage[]): PreparedMessage[][] {\n const chunks: PreparedMessage[][] = [];\n let current: PreparedMessage[] = [];\n let bytes = 0;\n for (const message of messages) {\n if (\n current.length > 0 &&\n (current.length === QUEUE_SEND_LIMITS.messages ||\n bytes + message.bytes > QUEUE_SEND_LIMITS.batchBytes ||\n current[0]!.queue !== message.queue)\n ) {\n chunks.push(current);\n current = [];\n bytes = 0;\n }\n current.push(message);\n bytes += message.bytes;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\nfunction createDriver({ env, queues }: QueueDriverContext): QueueDriver {\n // Physical queue -> the logical queues registrations pin to it.\n const pins = new Map<string, string[]>();\n for (const queue of queues.all()) {\n for (const physical of queue.consumers) {\n pins.set(physical, [...(pins.get(physical) ?? []), queue.name]);\n }\n }\n\n // Resolved on every send from this application's ENV, never cached.\n const producerFor = (name: string): CloudflareQueueProducer => {\n const registration = queues.get(name);\n if (!registration) {\n throw new Error(\n `Queue '${name}' is not registered. Add QueueModule.forFeature([{ name: '${name}', ` +\n `binding }]) to the module that produces it.`,\n );\n }\n if (registration.binding === undefined) {\n throw new Error(\n `Queue '${name}' has no producer binding. Register it with ` +\n `QueueModule.forFeature([{ name: '${name}', binding: 'YOUR_QUEUE' }]), where the ` +\n `binding is a queues.producers[].binding of this Worker.`,\n );\n }\n try {\n return resolveBinding(env, { binding: registration.binding }, QUEUE_PRODUCER);\n } catch (error) {\n throw new Error(\n `Queue '${name}' cannot send: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n };\n\n return {\n kind: 'cloudflare',\n entrypoints: [{ kind: 'cf:queue:module', meta: { consumers: [...pins.keys()] } }],\n\n async consume(payload: unknown, dispatch: QueueDispatchFn): Promise<void> {\n const batch = nativeBatch(payload);\n const pinned = pins.get(batch.queue);\n await consumeQueueBatch(\n batch,\n (job) => {\n // A pinned queue is consumed only from the physical queues it names.\n const expected = queues.get(job.queue)?.consumers ?? [];\n if (expected.length > 0 && !expected.includes(batch.queue)) {\n throw new Error(\n `Queue '${job.queue}' is consumed from ` +\n `${expected.map((queue) => `'${queue}'`).join(', ')}, not '${batch.queue}'.`,\n );\n }\n return dispatch(job);\n },\n pinned ? { queues: pinned } : {},\n );\n },\n\n async enqueue(job: QueueJob, options?: AddJobOptions): Promise<void> {\n const delay = delaySeconds(options);\n await producerFor(job.queue).send(\n parseQueueJob(job),\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n },\n\n async enqueueBatch(requests: readonly QueueEnqueueRequest[]): Promise<void> {\n // Validate every job and resolve every binding before the first send.\n const messages = requests.map(({ job, options }): PreparedMessage => {\n const body = parseQueueJob(job);\n const bytes = estimateQueueMessageBytes(body);\n if (bytes > QUEUE_SEND_LIMITS.messageBytes) {\n throw new RangeError(\n `Queue job '${job.id}' is an estimated ${bytes} bytes, over the ` +\n `${QUEUE_SEND_LIMITS.messageBytes}-byte Cloudflare message limit. Store large ` +\n `payloads elsewhere (for example in R2) and enqueue a reference.`,\n );\n }\n const delay = delaySeconds(options);\n return {\n id: job.id,\n queue: job.queue,\n bytes,\n request: delay === undefined ? { body } : { body, delaySeconds: delay },\n };\n });\n const producers = new Map<string, CloudflareQueueProducer>();\n for (const { queue } of messages) {\n if (!producers.has(queue)) producers.set(queue, producerFor(queue));\n }\n const accepted: string[] = [];\n for (const part of chunk(messages)) {\n const producer = producers.get(part[0]!.queue)!;\n try {\n if (typeof producer.sendBatch === 'function') {\n // eslint-disable-next-line no-await-in-loop\n await producer.sendBatch(part.map(({ request }) => request));\n accepted.push(...part.map(({ id }) => id));\n } else {\n for (const { id, request } of part) {\n const delay = request.delaySeconds;\n // eslint-disable-next-line no-await-in-loop\n await producer.send(\n request.body,\n delay === undefined ? undefined : { delaySeconds: delay },\n );\n accepted.push(id);\n }\n }\n } catch (error) {\n throw new QueueBatchError(\n accepted,\n messages.slice(accepted.length).map(({ id }) => id),\n error,\n );\n }\n }\n },\n };\n}\n\n/**\n * The Cloudflare Queues driver for `QueueModule`:\n *\n * ```ts\n * QueueModule.forRoot({ driver: cloudflareQueues() })\n * QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])\n * ```\n *\n * Each application gets its own driver. Producing reads the registered binding\n * from that application's `ENV` when a job is added and awaits the native\n * send; `addBulk` uses `sendBatch`, chunked to {@link QUEUE_SEND_LIMITS}.\n * Consuming is native too: the Worker's `queue()` handler routes every batch\n * that no `@QueueConsumer` claims through `QueueModule`, one message at a time,\n * by each job's logical `queue`, with the module's dispatch policy (signed\n * dispatch included). A registration's `consumer` pins its queue to that\n * physical queue: the queue's jobs are accepted only from it, and it only\n * carries the queues pinned to it. A message that is not a job envelope,\n * belongs to an unregistered queue, or fails stays unacknowledged, so\n * Cloudflare retries it and then dead-letters it.\n */\nexport function cloudflareQueues(): QueueDriverFactory {\n return (context) => createDriver(context);\n}\n\nexport interface ConsumeQueueBatchOptions {\n /**\n * Accept only jobs of these logical queues; any other message fails and is\n * retried. By default every job envelope is accepted.\n */\n readonly queues?: readonly string[];\n}\n\n/**\n * Settle native messages one job at a time. Attempts come from the host.\n * Process every message; ack successful/unsettled deliveries, then rethrow any\n * failures so the host retries the unsettled remainder. Explicit settlement wins.\n * The callback must await all work that should determine delivery success.\n */\nexport async function consumeQueueBatch(\n batch: { readonly queue: string; readonly messages: readonly QueueMessageLike[] },\n dispatch: (job: QueueJob, message: QueueMessageLike) => Promise<QueueDispatchResult | void>,\n options: ConsumeQueueBatchOptions = {},\n): Promise<void> {\n const errors: unknown[] = [];\n for (const message of batch.messages) {\n try {\n const job = parseQueueJob(message.body, message.attempts);\n if (options.queues && !options.queues.includes(job.queue)) {\n throw new Error(\n `Queue '${job.queue}' is not consumed from '${batch.queue}', which accepts ` +\n `${options.queues.map((queue) => `'${queue}'`).join(', ')}.`,\n );\n }\n const observed = observeMessage(message);\n // eslint-disable-next-line no-await-in-loop\n const result = await dispatch(job, observed.message);\n if (result?.handled === 0) throw new Error(`Queue job '${job.name}' has no handler.`);\n if (observed.disposition().outcome === 'unsettled') observed.message.ack();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Queue batch deliveries failed.');\n}\n"],"mappings":";;;;;AAuBA,MAAa,oBAAoB,OAAO,OAAO;;CAE7C,UAAU;;CAEV,YAAY;;CAEZ,cAAc;AAChB,CAAC;;AAGD,MAAM,uBAAuB;AAC7B,MAAM,eAAe;;;;;;AAOrB,SAAS,YAAY,MAAsB;CACzC,IAAI,OAAO;CACX,IAAI,OAAO;CACX,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,MAAM,OAAO,K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AAe,QAAQ,gCAAgC;AAC1F"}
|
package/dist/queues.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ interface CloudflareQueueProducer {
|
|
|
11
11
|
*
|
|
12
12
|
* ```ts
|
|
13
13
|
* QueueModule.forRoot({ driver: cloudflareQueues() })
|
|
14
|
-
* QueueModule.
|
|
14
|
+
* QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])
|
|
15
15
|
* ```
|
|
16
16
|
*
|
|
17
17
|
* Each application gets its own driver. Producing reads the registered binding
|
|
@@ -6,7 +6,7 @@ import { r2Driver } from "@velajs/storage/drivers/r2";
|
|
|
6
6
|
* application's `ENV` by name:
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
|
-
* StorageModule.
|
|
9
|
+
* StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) })
|
|
10
10
|
* ```
|
|
11
11
|
*
|
|
12
12
|
* `StorageModule` builds the driver on the first storage operation of each
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.
|
|
1
|
+
{"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) })\n * ```\n *\n * `StorageModule` builds the driver on the first storage operation of each\n * application, so a static module graph serves every environment and boot\n * touches no binding. A missing or mistyped binding fails that operation with\n * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot\n * presign uploads; serve downloads through `publicBaseUrl` or the module's\n * `http: { download: 'proxy' }` controller.\n */\nexport function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>> {\n const { binding, ...driver } = options;\n const bucket = r2({ binding });\n return (env) => r2Driver({ ...driver, bucket: bucket(env) });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAgB,UAAU,SAAgE;CACxF,MAAM,EAAE,SAAS,GAAG,WAAW;CAC/B,MAAM,SAAS,GAAG,EAAE,QAAQ,CAAC;CAC7B,QAAQ,QAAQ,SAAS;EAAE,GAAG;EAAQ,QAAQ,OAAO,GAAG;CAAE,CAAC;AAC7D"}
|
package/dist/storage.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {
|
|
|
13
13
|
* application's `ENV` by name:
|
|
14
14
|
*
|
|
15
15
|
* ```ts
|
|
16
|
-
* StorageModule.
|
|
16
|
+
* StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) })
|
|
17
17
|
* ```
|
|
18
18
|
*
|
|
19
19
|
* `StorageModule` builds the driver on the first storage operation of each
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { NonRetryableError } from "cloudflare:workflows";
|
|
2
|
+
import { convertNonRetryableError } from "@velajs/workflow";
|
|
3
|
+
//#region src/workflow/portable-workflow-step.ts
|
|
4
|
+
function duration(value) {
|
|
5
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
|
|
6
|
+
if (typeof value === "string" && /^\d+(?:\.\d+)? (?:second|minute|hour|day|week|month|year)s?$/.test(value)) return value;
|
|
7
|
+
throw new NonRetryableError("Invalid Workflow duration.");
|
|
8
|
+
}
|
|
9
|
+
function config(value) {
|
|
10
|
+
if (value.retries && (!Number.isInteger(value.retries.limit) || value.retries.limit < 0)) throw new NonRetryableError("Workflow retries.limit must be a nonnegative integer.");
|
|
11
|
+
return {
|
|
12
|
+
...value.timeout !== void 0 ? { timeout: duration(value.timeout) } : {},
|
|
13
|
+
...value.retries ? { retries: {
|
|
14
|
+
...value.retries,
|
|
15
|
+
delay: duration(value.retries.delay ?? 1e4)
|
|
16
|
+
} } : {}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/** Translate at callback boundaries, before the engine decides whether a failure should retry. */
|
|
20
|
+
function portableWorkflowStep(native) {
|
|
21
|
+
async function run(name, second, third, fourth) {
|
|
22
|
+
const callback = typeof second === "function" ? second : third;
|
|
23
|
+
if (typeof callback !== "function") throw new TypeError("Workflow step.do requires a callback.");
|
|
24
|
+
const declaredRollback = typeof second === "function" ? third : fourth;
|
|
25
|
+
const rollback = typeof declaredRollback === "object" ? declaredRollback : void 0;
|
|
26
|
+
const forward = async (context) => {
|
|
27
|
+
try {
|
|
28
|
+
return await callback(context);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
return convertNonRetryableError(error, NonRetryableError);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
let rollbackOptions;
|
|
34
|
+
if (rollback?.rollback) {
|
|
35
|
+
const undo = rollback.rollback;
|
|
36
|
+
rollbackOptions = {
|
|
37
|
+
rollback: async (context) => {
|
|
38
|
+
try {
|
|
39
|
+
await undo(context);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
convertNonRetryableError(error, NonRetryableError);
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
...rollback.rollbackConfig ? { rollbackConfig: config(rollback.rollbackConfig) } : {}
|
|
45
|
+
};
|
|
46
|
+
} else if (rollback?.rollbackConfig) throw new NonRetryableError("Workflow rollbackConfig requires a rollback handler.");
|
|
47
|
+
return typeof second === "function" ? native.do(name, forward, rollbackOptions) : native.do(name, config(second), forward, rollbackOptions);
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
do: run,
|
|
51
|
+
sleep: (name, value) => native.sleep(name, duration(value)),
|
|
52
|
+
sleepUntil: (name, timestamp) => native.sleepUntil(name, timestamp),
|
|
53
|
+
waitForEvent: (name, options) => native.waitForEvent(name, {
|
|
54
|
+
type: options.type,
|
|
55
|
+
...options.timeout !== void 0 ? { timeout: duration(options.timeout) } : {}
|
|
56
|
+
})
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
export { portableWorkflowStep };
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=portable-workflow-step.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"portable-workflow-step.js","names":[],"sources":["../../src/workflow/portable-workflow-step.ts"],"sourcesContent":["import type { WorkflowSleepDuration, WorkflowStep, WorkflowStepConfig } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\nimport {\n convertNonRetryableError,\n type WorkflowStepConfigLike,\n type WorkflowStepContextLike,\n type WorkflowStepLike,\n type WorkflowStepRollbackOptionsLike,\n} from '@velajs/workflow';\n\nfunction duration(value: string | number): WorkflowSleepDuration {\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value;\n if (\n typeof value === 'string' &&\n /^\\d+(?:\\.\\d+)? (?:second|minute|hour|day|week|month|year)s?$/.test(value)\n )\n return value as WorkflowSleepDuration;\n throw new NonRetryableError('Invalid Workflow duration.');\n}\n\nfunction config(value: WorkflowStepConfigLike): WorkflowStepConfigLike & WorkflowStepConfig {\n if (value.retries && (!Number.isInteger(value.retries.limit) || value.retries.limit < 0))\n throw new NonRetryableError('Workflow retries.limit must be a nonnegative integer.');\n return {\n ...(value.timeout !== undefined ? { timeout: duration(value.timeout) } : {}),\n ...(value.retries\n ? {\n retries: {\n ...value.retries,\n // Cloudflare's default delay is ten seconds. The portable contract permits omission.\n delay: duration(value.retries.delay ?? 10_000),\n },\n }\n : {}),\n };\n}\n\n/** Translate at callback boundaries, before the engine decides whether a failure should retry. */\nexport function portableWorkflowStep(native: WorkflowStep): WorkflowStepLike {\n // Portable result types are unconstrained. Native checkpoint serialization remains\n // authoritative and rejects unsupported values; only this call boundary erases that constraint.\n async function run<T>(\n name: string,\n second: WorkflowStepConfigLike | ((context: WorkflowStepContextLike) => Promise<T>),\n third?: ((context: WorkflowStepContextLike) => Promise<T>) | WorkflowStepRollbackOptionsLike<T>,\n fourth?: WorkflowStepRollbackOptionsLike<T>,\n ): Promise<T> {\n const callback = typeof second === 'function' ? second : third;\n if (typeof callback !== 'function')\n throw new TypeError('Workflow step.do requires a callback.');\n const declaredRollback = typeof second === 'function' ? third : fourth;\n const rollback = typeof declaredRollback === 'object' ? declaredRollback : undefined;\n const forward = async (context: WorkflowStepContextLike): Promise<T> => {\n try {\n // The engine validates checkpoint serialization and rejects unsupported results.\n return await callback(context);\n } catch (error) {\n return convertNonRetryableError(error, NonRetryableError);\n }\n };\n let rollbackOptions: WorkflowStepRollbackOptionsLike<T> | undefined;\n if (rollback?.rollback) {\n const undo = rollback.rollback;\n rollbackOptions = {\n rollback: async (context) => {\n try {\n await undo(context);\n } catch (error) {\n convertNonRetryableError(error, NonRetryableError);\n }\n },\n ...(rollback.rollbackConfig ? { rollbackConfig: config(rollback.rollbackConfig) } : {}),\n };\n } else if (rollback?.rollbackConfig) {\n throw new NonRetryableError('Workflow rollbackConfig requires a rollback handler.');\n }\n return typeof second === 'function'\n ? (native.do as WorkflowStepLike['do'])(name, forward, rollbackOptions)\n : (native.do as WorkflowStepLike['do'])(name, config(second), forward, rollbackOptions);\n }\n\n return {\n do: run,\n sleep: (name, value) => native.sleep(name, duration(value)),\n sleepUntil: (name, timestamp) => native.sleepUntil(name, timestamp),\n waitForEvent: (name, options) =>\n native.waitForEvent(name, {\n type: options.type,\n ...(options.timeout !== undefined ? { timeout: duration(options.timeout) } : {}),\n }),\n };\n}\n"],"mappings":";;;AAUA,SAAS,SAAS,OAA+C;CAC/D,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,GAAG,OAAO;CAC9E,IACE,OAAO,UAAU,YACjB,+DAA+D,KAAK,KAAK,GAEzE,OAAO;CACT,MAAM,IAAI,kBAAkB,4BAA4B;AAC1D;AAEA,SAAS,OAAO,OAA4E;CAC1F,IAAI,MAAM,YAAY,CAAC,OAAO,UAAU,MAAM,QAAQ,KAAK,KAAK,MAAM,QAAQ,QAAQ,IACpF,MAAM,IAAI,kBAAkB,uDAAuD;CACrF,OAAO;EACL,GAAI,MAAM,YAAY,KAAA,IAAY,EAAE,SAAS,SAAS,MAAM,OAAO,EAAE,IAAI,CAAC;EAC1E,GAAI,MAAM,UACN,EACE,SAAS;GACP,GAAG,MAAM;GAET,OAAO,SAAS,MAAM,QAAQ,SAAS,GAAM;EAC/C,EACF,IACA,CAAC;CACP;AACF;;AAGA,SAAgB,qBAAqB,QAAwC;CAG3E,eAAe,IACb,MACA,QACA,OACA,QACY;EACZ,MAAM,WAAW,OAAO,WAAW,aAAa,SAAS;EACzD,IAAI,OAAO,aAAa,YACtB,MAAM,IAAI,UAAU,uCAAuC;EAC7D,MAAM,mBAAmB,OAAO,WAAW,aAAa,QAAQ;EAChE,MAAM,WAAW,OAAO,qBAAqB,WAAW,mBAAmB,KAAA;EAC3E,MAAM,UAAU,OAAO,YAAiD;GACtE,IAAI;IAEF,OAAO,MAAM,SAAS,OAAO;GAC/B,SAAS,OAAO;IACd,OAAO,yBAAyB,OAAO,iBAAiB;GAC1D;EACF;EACA,IAAI;EACJ,IAAI,UAAU,UAAU;GACtB,MAAM,OAAO,SAAS;GACtB,kBAAkB;IAChB,UAAU,OAAO,YAAY;KAC3B,IAAI;MACF,MAAM,KAAK,OAAO;KACpB,SAAS,OAAO;MACd,yBAAyB,OAAO,iBAAiB;KACnD;IACF;IACA,GAAI,SAAS,iBAAiB,EAAE,gBAAgB,OAAO,SAAS,cAAc,EAAE,IAAI,CAAC;GACvF;EACF,OAAO,IAAI,UAAU,gBACnB,MAAM,IAAI,kBAAkB,sDAAsD;EAEpF,OAAO,OAAO,WAAW,aACpB,OAAO,GAA8B,MAAM,SAAS,eAAe,IACnE,OAAO,GAA8B,MAAM,OAAO,MAAM,GAAG,SAAS,eAAe;CAC1F;CAEA,OAAO;EACL,IAAI;EACJ,QAAQ,MAAM,UAAU,OAAO,MAAM,MAAM,SAAS,KAAK,CAAC;EAC1D,aAAa,MAAM,cAAc,OAAO,WAAW,MAAM,SAAS;EAClE,eAAe,MAAM,YACnB,OAAO,aAAa,MAAM;GACxB,MAAM,QAAQ;GACd,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,SAAS,QAAQ,OAAO,EAAE,IAAI,CAAC;EAChF,CAAC;CACL;AACF"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
|
|
2
|
+
import { VelaWorkflow } from "./vela-workflow.js";
|
|
3
|
+
import { portableWorkflowStep } from "./portable-workflow-step.js";
|
|
4
|
+
import __decorateMetadata from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js";
|
|
5
|
+
import __decorateParam from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js";
|
|
6
|
+
import { ENV, Inject, Injectable, ModuleRef, Scope } from "@velajs/vela";
|
|
7
|
+
import { SchemaValidationError, isValidationSchema, parseSchemaAsync } from "@velajs/vela/validation";
|
|
8
|
+
import { NonRetryableError } from "cloudflare:workflows";
|
|
9
|
+
import { convertNonRetryableError, createWorkflowRunContext, isWorkflowDefinition } from "@velajs/workflow";
|
|
10
|
+
//#region src/workflow/vela-workflow-definition.ts
|
|
11
|
+
function isEnvironment(value) {
|
|
12
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Run a portable workflow or compiled agent through Vela's native Workflow host.
|
|
16
|
+
* Export a named subclass and use that name in Wrangler's `class_name`.
|
|
17
|
+
* The deployed `event.workflowName` labels logs; no export name or binding is inferred.
|
|
18
|
+
*/
|
|
19
|
+
function VelaWorkflowDefinition(app, options) {
|
|
20
|
+
if (!isValidationSchema(options.params)) throw new TypeError("VelaWorkflowDefinition params requires a validation schema.");
|
|
21
|
+
if (!Array.isArray(options.inject) || typeof options.useFactory !== "function") throw new TypeError("VelaWorkflowDefinition requires inject and useFactory.");
|
|
22
|
+
const { params: schema, useFactory } = options;
|
|
23
|
+
const inject = [...options.inject];
|
|
24
|
+
let PortableWorkflowHost = class PortableWorkflowHost {
|
|
25
|
+
modules;
|
|
26
|
+
env;
|
|
27
|
+
constructor(modules, env) {
|
|
28
|
+
this.modules = modules;
|
|
29
|
+
this.env = env;
|
|
30
|
+
}
|
|
31
|
+
async run(event, step) {
|
|
32
|
+
try {
|
|
33
|
+
const env = this.env;
|
|
34
|
+
if (!isEnvironment(env)) throw new TypeError("Workflow environment must be an object.");
|
|
35
|
+
const resolved = await Promise.all(inject.map((token) => this.modules.resolve(token)));
|
|
36
|
+
const runtime = await useFactory(...resolved);
|
|
37
|
+
if (!runtime || !isWorkflowDefinition(runtime.definition) || typeof runtime.definition.handler !== "function" || typeof runtime.run !== "function") throw new TypeError("Workflow factory must return { definition, run }.");
|
|
38
|
+
return await runtime.definition.handler(createWorkflowRunContext({
|
|
39
|
+
env,
|
|
40
|
+
event,
|
|
41
|
+
exportName: event.workflowName,
|
|
42
|
+
run: runtime.run,
|
|
43
|
+
step: portableWorkflowStep(step),
|
|
44
|
+
nonRetryableErrorClass: NonRetryableError
|
|
45
|
+
}));
|
|
46
|
+
} catch (error) {
|
|
47
|
+
return convertNonRetryableError(error, NonRetryableError);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
PortableWorkflowHost = __decorate([
|
|
52
|
+
Injectable({ scope: Scope.REQUEST }),
|
|
53
|
+
__decorateParam(0, Inject(ModuleRef)),
|
|
54
|
+
__decorateParam(1, Inject(ENV)),
|
|
55
|
+
__decorateMetadata("design:paramtypes", [typeof ModuleRef === "undefined" ? Object : ModuleRef, Object])
|
|
56
|
+
], PortableWorkflowHost);
|
|
57
|
+
const NativeWorkflow = VelaWorkflow(app, PortableWorkflowHost);
|
|
58
|
+
class ValidatedWorkflow extends NativeWorkflow {
|
|
59
|
+
async run(event, step) {
|
|
60
|
+
let params;
|
|
61
|
+
try {
|
|
62
|
+
params = await parseSchemaAsync(schema, event.payload);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof SchemaValidationError) throw new NonRetryableError("Workflow trigger parameters failed validation.");
|
|
65
|
+
return convertNonRetryableError(error, NonRetryableError);
|
|
66
|
+
}
|
|
67
|
+
return super.run({
|
|
68
|
+
...event,
|
|
69
|
+
payload: params
|
|
70
|
+
}, step);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return ValidatedWorkflow;
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
export { VelaWorkflowDefinition };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=vela-workflow-definition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vela-workflow-definition.js","names":[],"sources":["../../src/workflow/vela-workflow-definition.ts"],"sourcesContent":["import type { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\nimport { ENV, Inject, Injectable, ModuleRef, Scope, type Token, type VelaEnv } from '@velajs/vela';\nimport type { InferTokens } from '@velajs/vela/module-kit';\nimport {\n isValidationSchema,\n parseSchemaAsync,\n SchemaValidationError,\n type SchemaInput,\n type SchemaOutput,\n type ValidationSchema,\n} from '@velajs/vela/validation';\nimport {\n convertNonRetryableError,\n createWorkflowRunContext,\n isWorkflowDefinition,\n type WorkflowDefinition,\n type WorkflowRunFunction,\n} from '@velajs/workflow';\nimport type { CloudflareApp } from '../cloudflare-factory';\nimport { VelaWorkflow } from './vela-workflow';\nimport { portableWorkflowStep } from './portable-workflow-step';\n\nfunction isEnvironment(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Dependencies of one portable run. Dispatch authority is supplied explicitly by the application. */\nexport interface WorkflowRuntime<Params, Output> {\n /** A definition may accept a wider input; its handler must accept every validated output. */\n readonly definition: Omit<WorkflowDefinition<Params, Output>, '__params'>;\n readonly run: WorkflowRunFunction;\n}\n\nexport interface VelaWorkflowDefinitionOptions<\n S extends ValidationSchema,\n Inject extends readonly Token[],\n Output,\n> {\n /** Validate native trigger data before resolving dependencies or calling the factory. */\n readonly params: S;\n readonly inject: Inject;\n /** Called once per native run, including replay, in that run's execution scope. */\n readonly useFactory: (\n ...dependencies: InferTokens<Inject>\n ) => WorkflowRuntime<SchemaOutput<S>, Output> | Promise<WorkflowRuntime<SchemaOutput<S>, Output>>;\n}\n\n/** Bindings take schema inputs; the portable definition receives schema outputs. */\nexport type VelaWorkflowDefinitionClass<Params, Output> = new (\n ctx: ExecutionContext,\n env: VelaEnv,\n) => Omit<WorkflowEntrypoint<VelaEnv, Params>, 'run'> & {\n run(event: Readonly<WorkflowEvent<Params>>, step: WorkflowStep): Promise<Output>;\n};\n\n/**\n * Run a portable workflow or compiled agent through Vela's native Workflow host.\n * Export a named subclass and use that name in Wrangler's `class_name`.\n * The deployed `event.workflowName` labels logs; no export name or binding is inferred.\n */\nexport function VelaWorkflowDefinition<\n S extends ValidationSchema,\n const Inject extends readonly Token[],\n Output,\n>(\n app: CloudflareApp,\n options: VelaWorkflowDefinitionOptions<S, Inject, Output>,\n): VelaWorkflowDefinitionClass<SchemaInput<S>, Output> {\n if (!isValidationSchema(options.params))\n throw new TypeError('VelaWorkflowDefinition params requires a validation schema.');\n if (!Array.isArray(options.inject) || typeof options.useFactory !== 'function')\n throw new TypeError('VelaWorkflowDefinition requires inject and useFactory.');\n const { params: schema, useFactory } = options;\n const inject = [...options.inject];\n\n @Injectable({ scope: Scope.REQUEST })\n class PortableWorkflowHost {\n constructor(\n @Inject(ModuleRef) private readonly modules: ModuleRef,\n @Inject(ENV) private readonly env: VelaEnv,\n ) {}\n\n async run(\n event: Readonly<WorkflowEvent<SchemaOutput<S>>>,\n step: WorkflowStep,\n ): Promise<Output> {\n try {\n const env = this.env;\n if (!isEnvironment(env)) throw new TypeError('Workflow environment must be an object.');\n const resolved = await Promise.all(inject.map((token) => this.modules.resolve(token)));\n // Each position resolves its corresponding token; Promise.all erases the tuple mapping.\n const runtime = await useFactory(...(resolved as InferTokens<Inject>));\n if (\n !runtime ||\n !isWorkflowDefinition(runtime.definition) ||\n typeof runtime.definition.handler !== 'function' ||\n typeof runtime.run !== 'function'\n )\n throw new TypeError('Workflow factory must return { definition, run }.');\n return await runtime.definition.handler(\n createWorkflowRunContext({\n env,\n event,\n exportName: event.workflowName,\n run: runtime.run,\n step: portableWorkflowStep(step),\n nonRetryableErrorClass: NonRetryableError,\n }),\n );\n } catch (error) {\n return convertNonRetryableError(error, NonRetryableError);\n }\n }\n }\n\n const NativeWorkflow = VelaWorkflow(app, PortableWorkflowHost);\n // Validate before the native host boots the application. Bootstrap eagerly\n // creates singleton providers, which may themselves be factory dependencies.\n class ValidatedWorkflow extends NativeWorkflow {\n override async run(\n event: Readonly<WorkflowEvent<unknown>>,\n step: WorkflowStep,\n ): Promise<Awaited<Output>> {\n let params: SchemaOutput<S>;\n try {\n params = await parseSchemaAsync(schema, event.payload);\n } catch (error) {\n if (error instanceof SchemaValidationError)\n throw new NonRetryableError('Workflow trigger parameters failed validation.');\n return convertNonRetryableError(error,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EAAE,OAAO,MAAM,QAAQ,CAAC;EAG/B,gBAAA,GAAA,OAAO,SAAS,CAAA;EAChB,gBAAA,GAAA,OAAO,GAAG,CAAA;;;CAoCf,MAAM,iBAAiB,aAAa,KAAK,oBAAoB;CAG7D,MAAM,0BAA0B,eAAe;EAC7C,MAAe,IACb,OACA,MAC0B;GAC1B,IAAI;GACJ,IAAI;IACF,SAAS,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GACvD,SAAS,OAAO;IACd,IAAI,iBAAiB,uBACnB,MAAM,IAAI,kBAAkB,gDAAgD;IAC9E,OAAO,yBAAyB,OAAO,iBAAiB;GAC1D;GACA,OAAO,MAAM,IAAI;IAAE,GAAG;IAAO,SAAS;GAAO,GAAG,IAAI;EACtD;CACF;CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import { a as CloudflareApp } from "./cloudflare-factory-DM9CBvNH.js";
|
|
3
|
+
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from "cloudflare:workers";
|
|
4
|
+
import { Token, VelaEnv } from "@velajs/vela";
|
|
5
|
+
import { InferTokens } from "@velajs/vela/module-kit";
|
|
6
|
+
import { SchemaInput, SchemaOutput, ValidationSchema } from "@velajs/vela/validation";
|
|
7
|
+
import { WorkflowDefinition, WorkflowRunFunction } from "@velajs/workflow";
|
|
8
|
+
//#region src/workflow/vela-workflow-definition.d.ts
|
|
9
|
+
/** Dependencies of one portable run. Dispatch authority is supplied explicitly by the application. */
|
|
10
|
+
interface WorkflowRuntime<Params, Output> {
|
|
11
|
+
/** A definition may accept a wider input; its handler must accept every validated output. */
|
|
12
|
+
readonly definition: Omit<WorkflowDefinition<Params, Output>, '__params'>;
|
|
13
|
+
readonly run: WorkflowRunFunction;
|
|
14
|
+
}
|
|
15
|
+
interface VelaWorkflowDefinitionOptions<S extends ValidationSchema, Inject extends readonly Token[], Output> {
|
|
16
|
+
/** Validate native trigger data before resolving dependencies or calling the factory. */
|
|
17
|
+
readonly params: S;
|
|
18
|
+
readonly inject: Inject;
|
|
19
|
+
/** Called once per native run, including replay, in that run's execution scope. */
|
|
20
|
+
readonly useFactory: (...dependencies: InferTokens<Inject>) => WorkflowRuntime<SchemaOutput<S>, Output> | Promise<WorkflowRuntime<SchemaOutput<S>, Output>>;
|
|
21
|
+
}
|
|
22
|
+
/** Bindings take schema inputs; the portable definition receives schema outputs. */
|
|
23
|
+
type VelaWorkflowDefinitionClass<Params, Output> = new (ctx: ExecutionContext, env: VelaEnv) => Omit<WorkflowEntrypoint<VelaEnv, Params>, 'run'> & {
|
|
24
|
+
run(event: Readonly<WorkflowEvent<Params>>, step: WorkflowStep): Promise<Output>;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Run a portable workflow or compiled agent through Vela's native Workflow host.
|
|
28
|
+
* Export a named subclass and use that name in Wrangler's `class_name`.
|
|
29
|
+
* The deployed `event.workflowName` labels logs; no export name or binding is inferred.
|
|
30
|
+
*/
|
|
31
|
+
export declare function VelaWorkflowDefinition<S extends ValidationSchema, const Inject extends readonly Token[], Output>(app: CloudflareApp, options: VelaWorkflowDefinitionOptions<S, Inject, Output>): VelaWorkflowDefinitionClass<SchemaInput<S>, Output>;
|
|
32
|
+
//#endregion
|
|
33
|
+
export type { VelaWorkflowDefinitionClass, VelaWorkflowDefinitionOptions, WorkflowRuntime };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velajs/cloudflare",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.35.0",
|
|
4
4
|
"description": "Cloudflare Workers integration for Vela framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -83,6 +83,10 @@
|
|
|
83
83
|
"./workflows": {
|
|
84
84
|
"types": "./dist/workflows.d.ts",
|
|
85
85
|
"import": "./dist/workflows.js"
|
|
86
|
+
},
|
|
87
|
+
"./workflow-definitions": {
|
|
88
|
+
"types": "./dist/workflow-definitions.d.ts",
|
|
89
|
+
"import": "./dist/workflow-definitions.js"
|
|
86
90
|
}
|
|
87
91
|
},
|
|
88
92
|
"publishConfig": {
|
|
@@ -102,21 +106,27 @@
|
|
|
102
106
|
"typescript": "7.0.2",
|
|
103
107
|
"unplugin-swc": "1.5.9",
|
|
104
108
|
"vitest": "4.1.11",
|
|
105
|
-
"zod": "
|
|
106
|
-
"@velajs/
|
|
107
|
-
"@velajs/
|
|
108
|
-
"@velajs/
|
|
109
|
-
"@velajs/
|
|
109
|
+
"zod": "4.4.3",
|
|
110
|
+
"@velajs/agent": "1.31.0",
|
|
111
|
+
"@velajs/storage": "1.34.0",
|
|
112
|
+
"@velajs/feature-flags": "1.33.0",
|
|
113
|
+
"@velajs/testing": "1.34.0",
|
|
114
|
+
"@velajs/vela": "1.34.0",
|
|
115
|
+
"@velajs/workflow": "1.1.0"
|
|
110
116
|
},
|
|
111
117
|
"peerDependencies": {
|
|
112
118
|
"@cloudflare/workers-types": ">=4",
|
|
113
119
|
"hono": ">=4",
|
|
114
|
-
"@velajs/feature-flags": "^1.
|
|
115
|
-
"@velajs/
|
|
116
|
-
"@velajs/
|
|
117
|
-
"@velajs/
|
|
120
|
+
"@velajs/feature-flags": "^1.33.0",
|
|
121
|
+
"@velajs/testing": "^1.34.0",
|
|
122
|
+
"@velajs/storage": "^1.34.0",
|
|
123
|
+
"@velajs/workflow": "^1.1.0",
|
|
124
|
+
"@velajs/vela": "^1.34.0"
|
|
118
125
|
},
|
|
119
126
|
"peerDependenciesMeta": {
|
|
127
|
+
"@velajs/workflow": {
|
|
128
|
+
"optional": true
|
|
129
|
+
},
|
|
120
130
|
"@velajs/feature-flags": {
|
|
121
131
|
"optional": true
|
|
122
132
|
},
|