@velajs/cloudflare 1.31.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +154 -10
  3. package/dist/bindings.js +17 -1
  4. package/dist/bindings.js.map +1 -1
  5. package/dist/{cloudflare-factory-eGiet0mg.d.ts → cloudflare-application-CXDy9C1R.d.ts} +9 -98
  6. package/dist/cloudflare-application.js +8 -0
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +153 -20
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/durable-object/boot.js +76 -0
  12. package/dist/durable-object/boot.js.map +1 -0
  13. package/dist/durable-object/host-dispatch.js +134 -0
  14. package/dist/durable-object/host-dispatch.js.map +1 -0
  15. package/dist/durable-object/host-methods.js +47 -0
  16. package/dist/durable-object/host-methods.js.map +1 -0
  17. package/dist/durable-object/tokens.js +17 -0
  18. package/dist/durable-object/tokens.js.map +1 -0
  19. package/dist/durable-object/vela-durable-object.js +121 -0
  20. package/dist/durable-object/vela-durable-object.js.map +1 -0
  21. package/dist/durable-objects.d.ts +131 -9
  22. package/dist/durable-objects.js +3 -1
  23. package/dist/email/email-dispatch.js +65 -0
  24. package/dist/email/email-dispatch.js.map +1 -0
  25. package/dist/email/on-email.js +57 -0
  26. package/dist/email/on-email.js.map +1 -0
  27. package/dist/email.d.ts +51 -0
  28. package/dist/email.js +3 -0
  29. package/dist/entrypoint/vela-entrypoint.js +160 -0
  30. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  31. package/dist/entrypoints.d.ts +93 -0
  32. package/dist/entrypoints.js +2 -0
  33. package/dist/host/host-invoker.js +276 -0
  34. package/dist/host/host-invoker.js.map +1 -0
  35. package/dist/host/host-members.js +73 -0
  36. package/dist/host/host-members.js.map +1 -0
  37. package/dist/host-members-DECj_4yz.d.ts +13 -0
  38. package/dist/index.d.ts +74 -13
  39. package/dist/index.js +4 -3
  40. package/dist/root-module.js +19 -0
  41. package/dist/root-module.js.map +1 -0
  42. package/dist/rpc/entrypoint-error.js +145 -0
  43. package/dist/rpc/entrypoint-error.js.map +1 -0
  44. package/dist/services/kv-cache.store.js +4 -4
  45. package/dist/services/kv-cache.store.js.map +1 -1
  46. package/dist/tail/on-tail.js +46 -0
  47. package/dist/tail/on-tail.js.map +1 -0
  48. package/dist/tail/tail-dispatch.js +67 -0
  49. package/dist/tail/tail-dispatch.js.map +1 -0
  50. package/dist/tail.d.ts +39 -0
  51. package/dist/tail.js +2 -0
  52. package/dist/testing.d.ts +55 -3
  53. package/dist/testing.js +78 -1
  54. package/dist/testing.js.map +1 -1
  55. package/dist/websocket/binding-gateways.js +1 -1
  56. package/dist/websocket/binding-gateways.js.map +1 -1
  57. package/dist/websocket/do-bootstrap.js +40 -37
  58. package/dist/websocket/do-bootstrap.js.map +1 -1
  59. package/dist/websocket/websocket.durable-object.js +37 -8
  60. package/dist/websocket/websocket.durable-object.js.map +1 -1
  61. package/dist/worker-events.js +49 -0
  62. package/dist/worker-events.js.map +1 -0
  63. package/dist/workflow/vela-workflow.js +104 -0
  64. package/dist/workflow/vela-workflow.js.map +1 -0
  65. package/dist/workflows.d.ts +82 -0
  66. package/dist/workflows.js +2 -0
  67. package/package.json +23 -7
  68. package/dist/root-module-C23bUwt_.d.ts +0 -11
package/CHANGELOG.md CHANGED
@@ -1,5 +1,90 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.33.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b7d0725: Remove obsolete contracts and backward-compatibility paths.
8
+
9
+ Validation now requires Standard Schema or DTO descriptors. Decorated events require event definitions and use EventDispatcher; EventEmitter.emit always settles every matching callback. Remove token-only discovery, instance-based schedule views, ownerless entrypoints, disposed-container reuse, unmanaged scope finalization, and the `(.*)` middleware alias. Queue driver bind returns cleanup and enqueue after inline disposal rejects. Configure HTTP body caps through security.body.maxBytes.
10
+
11
+ WebSocket clients must report admission with trySendRaw. Tiered caches require expiry-aware read/write methods; KV entries without expiry metadata miss. Aggregate specs use only aggregations, the default CRUD adapter can be undefined, and Studio discovers resources registered through Crud. Remove the Studio path alias, the mail envelope argument overload, the AI embedding resolver fallback, and the obsolete contentHash export.
12
+
13
+ Storage encryption rejects invalid ciphertext; compression requires format metadata and a metadata-capable store.
14
+
15
+ Update adapters, examples, tests, API snapshots and migration documentation to the current contracts.
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies [b7d0725]
20
+ - Updated dependencies [b7d0725]
21
+ - @velajs/vela@1.33.0
22
+ - @velajs/testing@1.33.0
23
+ - @velajs/storage@1.33.0
24
+ - @velajs/feature-flags@1.31.0
25
+
26
+ ## 1.32.0
27
+
28
+ ### Minor Changes
29
+
30
+ - 0dccc7f: Durable Objects are Vela entrypoints. `defineCloudflareApp(AppModule, options)` defines one application: its `worker` is the Worker's default export, and the Durable Object classes defined from it share its root module and options. `VelaDurableObject(app, Host, { rpc })` from `@velajs/cloudflare/durable-objects` returns a Durable Object class whose JS-RPC methods are the host methods `rpc` names:
31
+
32
+ ```ts
33
+ const app = defineCloudflareApp(AppModule);
34
+ export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
35
+ export default app.worker;
36
+ // await env.COUNTER.getByName('orders').increment(1)
37
+ ```
38
+
39
+ - Each instance boots one application context with `VelaFactory.createApplicationContext`, in its constructor under `blockConcurrencyWhile`. The host, an `@Injectable()`, is added to the root module's providers. The context injects the object's `ENV` and the new `DO_STATE`, `DO_STORAGE` and `DO_ID` tokens, and the app's runtime adapters configure its container (`configureContainer`) as they do the Worker's. Their other hooks (`onBootstrap`, `onRoutesBuilt`, `invocationTransport`, `getClientIp`, `requestMiddleware`) do not run in the object, which serves no HTTP routes. `VelaDurableObject(AppModule, Host, { rpc })` takes a bare root instead. A class uses the app when it is defined, so declare it in the module that defines the app: in the Worker entry, or beside an app defined in a module of its own that the entry imports.
40
+ - The RPC surface is explicit: exactly the host methods `rpc` names are RPC methods, and a `DurableObjectNamespace<Counter>` stub exposes exactly their signatures. No other method is reachable over RPC, even from plain JavaScript naming it on a stub: not an unlisted public method, a TypeScript `private` or `protected` helper, a lifecycle hook or the container's `dispose()` hook. Without `rpc`, the object serves only its event handlers. `rpc` is typed to the host's public methods (`DurableObjectRpcMethod<Host>`); when the class is defined, a name that is not a prototype method of the host (an accessor, or an instance field such as an arrow function), a hook (`onModuleInit`, ..., `dispose`, `collectEntrypoints`), an event handler, or `ctx`, `env`, `connect`, `dup`, `id`, `name` or `then` (which the class or its stubs own) throws, and so does a host whose prototype defines `then()`, since every instance would be a thenable and resolving it would hang. A host's `fetch`, `alarm`, `webSocketMessage`, `webSocketClose` and `webSocketError` become the object's handlers.
41
+ - Each RPC call and event runs in its own execution scope, so request-scoped providers are built per call, through the host's scoped guards, pipes (RPC arguments only), interceptors and filters. A `fetch()` response with a streamed body keeps its scope open, as the HTTP edge does, until the body is read, fails or is cancelled, under the object's `waitUntil`. Application-wide `APP_GUARD`, `APP_INTERCEPTOR`, `APP_PIPE` and `APP_FILTER` components do not apply; failures still reach the application's `ExceptionHandler`. `ExecutionContext.getType()` is `'rpc'`, `'cf:do:fetch'`, `'cf:do:alarm'` or `'cf:do:websocket'`, and `getPayload()` is the arguments.
42
+ - Failures are reported first. An RPC call rejects only with an `EntrypointError` (`EntrypointError`, `isEntrypointError()` and `EntrypointErrorInit` are exported from `@velajs/cloudflare`; service entrypoints share it). It carries what HTTP sends for the error, with server bodies redacted: its `status`, `code` and `message`, and its `details` below 500. A 4xx `HttpException` keeps its code, message and details, a branded `VelaError` keeps its code and message at any status, as over HTTP, and an unknown error becomes `500 internal`. Unlike HTTP, a branded `VelaError` with a 5xx status loses its details, and a 4xx `HttpException` constructed with an object response, which HTTP sends as it is, keeps only its status (code `error`, message `Entrypoint request failed`) unless that object is a canonical `{ error: { code, message, details } }` body. No stack frame, cause or other property of the original error crosses the RPC boundary. `isEntrypointError()` recognizes the plain `Error` workerd delivers to the caller. workerd keeps those properties across RPC only from `compatibility_date` 2026-04-21 or with the `enhanced_error_serialization` flag; on an older date the caller receives an `Error` whose message is `EntrypointError: <message>`, without its status, code or details. An `EntrypointError` a host rethrows, such as another object's failure, keeps its code, message and details for a client fault and only its status for a server fault, and a failure outside the pipeline is reported and becomes `500 internal`. `fetch()` renders the JSON error body; alarms and WebSocket events rethrow for the platform. A context that fails to start resets the object, and waiting callers receive only a redacted `500`.
43
+ - The Worker descriptor lists the Durable Object classes defined from the app (`durableObjects`), and each class carries a `CloudflareDurableObjectDescriptor` under the static `CLOUDFLARE_DURABLE_OBJECT` key, so tools know what each exported class serves. `isCloudflareApp()` recognizes an app definition.
44
+ - `createCloudflareWorker(AppModule, options)` is `defineCloudflareApp(AppModule, options).worker`.
45
+ - `CloudflareApp` types an app definition. `@velajs/cloudflare/durable-objects` exports `DurableObjectRoot`, `VelaDurableObjectOptions`, `VelaDurableObjectClass`, `DurableObjectRpc`, `DurableObjectRpcMethod`, and `DurableObjectExecutionContext`, the `ExecutionContext` that guards, interceptors and filters receive around an invocation, whose `getType()` values are `DurableObjectInvocationKind`.
46
+ - The host code lives in `@velajs/cloudflare/durable-objects`, and the Workflow, service entrypoint, email and tail code in their own subpaths: the minimal `createCloudflareWorker()` Worker (one controller, bundled by Wrangler with `--minify`) bundles none of it. It measures 163,895 bytes raw and 55,713 bytes gzipped in this release, against 155,636 and 52,363 for 1.31.0 (mostly the core's route contracts and application context, then the app definition and the Worker's optional `email` and `tail` handlers), within its unchanged ceiling.
47
+
48
+ **Behavior change:** `VelaWebSocketDurableObject(root)` boots through the same application context as `VelaDurableObject`, and also accepts the app from `defineCloudflareApp`, whose runtime adapters then configure its container (`configureContainer`). Its context injects `DO_STATE`, `DO_STORAGE` and `DO_ID`. When its application fails to start, a waiting caller receives a redacted `EntrypointError` (`500 internal`) instead of the startup error, which the object logs. An application that does not import `WebSocketModule` now fails after its lifecycle hooks ran, and its context is disposed.
49
+ - 8f3d0a6: Workflows, service entrypoints, email and tail are Vela entrypoints. Their classes are defined from the app of `defineCloudflareApp(AppModule, options)`, like Durable Objects, and run in the Worker's own application for the event's environment: the one the Worker's `fetch`, `queue` and `scheduled` handlers use, with its singletons, runtime adapters and `ENV`. Their hosts are added to the root module's providers. Application-wide `APP_GUARD`, `APP_INTERCEPTOR`, `APP_PIPE` and `APP_FILTER` components do not apply to Workflow runs, service entrypoint calls, or email and tail handlers, as for Durable Objects: their callers are the platform and other Workers, not HTTP requests. Declare guards on the host or handler class or method.
50
+
51
+ ```ts
52
+ const app = defineCloudflareApp(AppModule);
53
+ export class SignupWorkflow extends VelaWorkflow(app, SignupHost) {}
54
+ export class Billing extends VelaEntrypoint(app, BillingHost, { rpc: ['charge'] }) {}
55
+ export default app.worker;
56
+ ```
57
+
58
+ - **Workflows.** `VelaWorkflow(app, Host)` from the new `@velajs/cloudflare/workflows` subpath returns a `WorkflowEntrypoint` class whose `run(event, step)` calls the `run` method of `Host`, an `@Injectable()`. The engine's `event` and `step` pass through untouched, so `step.do`, `step.sleep` and `step.waitForEvent` keep their retry and replay semantics. Each run executes in its own execution scope (request-scoped providers per run) through the host's scoped guards, interceptors and filters, with `ExecutionContext.getType()` `'cf:workflow'` and `getPayload()` the event. A failure is reported (`edge: 'workflow'`) and rethrown as it is, so the engine honors `NonRetryableError`; a scoped filter that catches it settles the run with what it returns. The engine's own interruptions, an `Error` whose message starts with `Aborting engine:` that a step rejects with when the instance is paused, restarted or terminated, pass through as they are: they are not reported and no filter sees them, so a paused instance stays paused and can resume. The class type takes the params from the host's `run(event)`, so `wrangler types` types the binding (`Workflow<Readonly<SignupParams>>`), and `WorkflowParams<T>` reads them from a Workflow class or host. `workflow<Params>({ binding })`, a new binding reference of the root entry, creates and reads instances by binding name.
59
+ - **Service entrypoints.** `VelaEntrypoint(app, Host, { rpc })` from the new `@velajs/cloudflare/entrypoints` subpath returns a `WorkerEntrypoint` class whose JS-RPC methods are exactly the host methods `rpc` names, typed on a `Service<typeof Billing>` binding; nothing else is reachable over RPC. `ctx`, `env`, `dup`, `then`, the lifecycle hooks and the `WorkerEntrypoint` handlers (`fetch`, `connect`, `email`, `queue`, `scheduled`, `tail`, `tailStream`, `test`, `trace`) are rejected when the class is defined. Each call runs in its own execution scope through the host's scoped guards, pipes (the arguments), interceptors and filters (`getType()` `'rpc'`), with the caller's `ctx.props` injectable as the request-scoped `ENTRYPOINT_PROPS` token (`{}` when the caller attached none). Failures are reported (`edge: 'rpc'`) and reject only with an `EntrypointError`; a call to an application that fails to start rejects with a redacted `500`.
60
+ - **Email and tail.** `@OnEmail({ to? })` from the new `@velajs/cloudflare/email` subpath and `@OnTail()` from the new `@velajs/cloudflare/tail` subpath make provider methods Email Workers and Tail Workers handlers (entrypoint kinds `cf:email` and `cf:tail`); importing them gives the Worker (`app.worker`, `createCloudflareWorker()`) its `email` and `tail` handlers. An email goes to the handlers whose `to` lists its envelope recipient, compared without regard to case, else to those without `to`; each receives the native `ForwardableEmailMessage` in its own execution scope through its scoped guards, interceptors and filters. A message no handler accepts is rejected with `setReject(UNCLAIMED_EMAIL_REASON)` instead of dropped, and handler failures are reported (`edge: 'email'`) and rethrown unless a scoped filter handles them. Every `@OnTail()` handler receives every `TraceItem[]` batch; its failures are reported (`edge: 'tail'`) and never thrown into the platform's loop. When the application fails to start, the `tail` handler logs the error to the console and resolves, and the next batch retries.
61
+ - **Hosts.** A host whose prototype defines `then()`, as a method or an accessor, is rejected when a Workflow or service entrypoint class is defined from it, as for a Durable Object: every instance would be a thenable, and resolving the host would hang.
62
+ - **Descriptors.** The Worker descriptor and the app list the Workflow and service entrypoint classes defined from the app (`workflows`, `entrypoints`), and each class carries a `CloudflareWorkflowDescriptor` or `CloudflareEntrypointDescriptor` under the new static `CLOUDFLARE_WORKFLOW` or `CLOUDFLARE_ENTRYPOINT` key. The descriptor's `createApplication(env)` includes their hosts. A Workflow or service entrypoint class defined after the app started building its Worker application throws.
63
+ - **Testing.** `createTestingWorker()` drives `email(message)` and `tail(events)`. `emailMessage({ from, to, subject?, text?, headers?, raw? })` builds a `ForwardableEmailMessage` that records `setReject()`, `forward()` and `reply()` (`rejectReason`, `forwards`, `replies`), and `traceItem(overrides?)` builds a `TraceItem`.
64
+ - `CloudflareApplication.getContainer()` returns the application's container, for dispatch seams that take it with `entrypoints`.
65
+ - Types: `@velajs/cloudflare/workflows` exports `VelaWorkflowClass`, `WorkflowHost`, `WorkflowOutput`, `WorkflowParams` and `WorkflowExecutionContext`; `@velajs/cloudflare/entrypoints` exports `EntrypointRpc`, `EntrypointRpcMethod`, `VelaEntrypointClass`, `VelaEntrypointOptions` and `EntrypointRpcExecutionContext`; `@velajs/cloudflare/email` exports `OnEmailOptions`, `OnEmailDecorator` and `EmailExecutionContext`; `@velajs/cloudflare/tail` exports `OnTailDecorator` and `TailExecutionContext`; and `@velajs/cloudflare/testing` exports `TestingEmailMessage` and `TestingEmailInit`. Each `*ExecutionContext` is the `ExecutionContext` that guards, interceptors and filters receive around that kind of invocation.
66
+ - The new subpaths stay out of the minimal `createCloudflareWorker()` Worker.
67
+
68
+ ### Patch Changes
69
+
70
+ - Updated dependencies [9dea818]
71
+ - Updated dependencies [524e422]
72
+ - Updated dependencies [a7d0912]
73
+ - Updated dependencies [04e7ac5]
74
+ - Updated dependencies [ff98301]
75
+ - Updated dependencies [38ab1e5]
76
+ - Updated dependencies [ef18e04]
77
+ - Updated dependencies [38ab1e5]
78
+ - Updated dependencies [586be4f]
79
+ - Updated dependencies [9c1bd0b]
80
+ - Updated dependencies [e412fc8]
81
+ - Updated dependencies [bcdf5e3]
82
+ - Updated dependencies [d5a8c60]
83
+ - @velajs/vela@1.32.0
84
+ - @velajs/storage@1.32.0
85
+ - @velajs/testing@1.32.0
86
+ - @velajs/feature-flags@1.31.0
87
+
3
88
  ## 1.31.0
4
89
 
5
90
  ### Minor Changes
package/README.md CHANGED
@@ -40,11 +40,16 @@ class AppModule {}
40
40
  export default createCloudflareWorker(AppModule);
41
41
  ```
42
42
 
43
- The worker exposes `fetch`, `queue`, and `scheduled`, and carries a
43
+ The worker exposes `fetch`, `queue`, and `scheduled`, plus `email` and `tail`
44
+ once a module imports `@OnEmail()` or `@OnTail()` (see
45
+ [Service entrypoints, email and tail](#service-entrypoints-email-and-tail)), and carries a
44
46
  descriptor under the symbol key `CLOUDFLARE_WORKER`
45
47
  (`Symbol.for('vela.cloudflare.worker')`), which the platform ignores and which
46
48
  an entry adding handlers keeps (`export default { ...worker, email }`): the
47
- root module, the options, and
49
+ root module, the options, the Durable Object, Workflow and service entrypoint
50
+ classes defined from the same app (each class also carries its descriptor
51
+ under `CLOUDFLARE_DURABLE_OBJECT`, `CLOUDFLARE_WORKFLOW` or
52
+ `CLOUDFLARE_ENTRYPOINT`), and
48
53
  `createOptions(env)`/`createApplication(env)`, which build the application
49
54
  exactly as the Worker does, short of the `configure(app, env)` hook, which
50
55
  receives the Workers application. `@velajs/cli` loads the Worker entry and builds its
@@ -57,7 +62,12 @@ drivers. A failed construction is evicted and the next event retries.
57
62
 
58
63
  The root is static: a module class, or a `DynamicModule` such as
59
64
  `AppModule.forRoot(...)`, declared once at module scope. `createCloudflareWorker`,
60
- `createCloudflareApp` and `VelaWebSocketDurableObject` all take the same root.
65
+ `createCloudflareApp`, `VelaDurableObject` and `VelaWebSocketDurableObject` all
66
+ take the same root. An entry that exports Durable Object classes defines the app
67
+ once with `defineCloudflareApp(AppModule, options)`: its `worker` is the default
68
+ export, and the classes built from the app share its root, and its runtime
69
+ adapters configure their containers (`configureContainer`) (see [Durable Object hosts](#durable-object-hosts)); `createCloudflareWorker` is
70
+ `defineCloudflareApp(...).worker`.
61
71
  When module configuration needs bindings, read them where each application is
62
72
  built, from its own `ENV`:
63
73
 
@@ -353,7 +363,7 @@ Use the native Durable Object entrypoint only in your Worker entry file:
353
363
  import { Module } from '@velajs/vela';
354
364
  import { LiveModule } from '@velajs/vela/live';
355
365
  import { WebSocketModule } from '@velajs/vela/websocket';
356
- import { createCloudflareWorker } from '@velajs/cloudflare';
366
+ import { defineCloudflareApp } from '@velajs/cloudflare';
357
367
  import { VelaWebSocketDurableObject } from '@velajs/cloudflare/durable-objects';
358
368
 
359
369
  @Module({
@@ -363,8 +373,9 @@ import { VelaWebSocketDurableObject } from '@velajs/cloudflare/durable-objects';
363
373
  })
364
374
  class RoomModule {}
365
375
 
366
- export class Room extends VelaWebSocketDurableObject(RoomModule) {}
367
- export default createCloudflareWorker(RoomModule);
376
+ const app = defineCloudflareApp(RoomModule);
377
+ export class Room extends VelaWebSocketDurableObject(app) {}
378
+ export default app.worker;
368
379
  ```
369
380
 
370
381
  `cloudflareAdapter` registers the platform as the global `WS_TRANSPORT` and
@@ -427,10 +438,136 @@ package. `VelaNonceDurableObject` is exported from `/durable-objects`; its
427
438
  The root package contains no runtime `cloudflare:workers` import and can be
428
439
  loaded by Node tooling. Native classes belong to `/durable-objects`.
429
440
 
441
+ ## Durable Object hosts
442
+
443
+ `VelaDurableObject(app, Host)` from `/durable-objects` returns a Durable Object
444
+ class whose instances each boot one application context from the app's root
445
+ (`VelaFactory.createApplicationContext`, under `blockConcurrencyWhile`), with
446
+ `Host`, an `@Injectable()`, added to the root module's providers. The host
447
+ methods the `rpc` option names become the class's JS-RPC methods, typed on the
448
+ binding; no other method, TypeScript `private` helpers included, is reachable
449
+ over RPC. Its `fetch`, `alarm` and WebSocket handlers become the object's:
450
+
451
+ ```ts
452
+ import { Inject, Injectable } from '@velajs/vela';
453
+ import { DO_STORAGE, VelaDurableObject } from '@velajs/cloudflare/durable-objects';
454
+
455
+ @Injectable()
456
+ export class CounterHost {
457
+ constructor(@Inject(DO_STORAGE) private readonly storage: DurableObjectStorage) {}
458
+
459
+ async increment(by: number): Promise<number> {
460
+ const value = ((await this.storage.get<number>('value')) ?? 0) + by;
461
+ await this.storage.put('value', value);
462
+ return value;
463
+ }
464
+ }
465
+
466
+ export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
467
+ // Anywhere with the COUNTER binding: await env.COUNTER.getByName('orders').increment(1)
468
+ ```
469
+
470
+ The context injects `ENV`, `DO_STATE`, `DO_STORAGE` and `DO_ID`. Each call and
471
+ event runs in its own execution scope (request-scoped providers per call)
472
+ through the host's scoped guards, pipes, interceptors and filters, with an
473
+ `ExecutionContext` of type `rpc` (or `cf:do:fetch`, `cf:do:alarm`,
474
+ `cf:do:websocket`); a streamed `fetch()` body keeps its scope open until it is
475
+ sent. Failures are reported first; an RPC call rejects only with an
476
+ `EntrypointError` (`status`, `code`, `message`, and `details` for a client
477
+ fault), which `isEntrypointError()` from the root entry recognizes on the
478
+ caller's side from `compatibility_date` 2026-04-21 (or with
479
+ `enhanced_error_serialization`). A host whose prototype defines `then()` is
480
+ rejected when the class is defined. See
481
+ [Durable Objects](../../docs/durable-objects.md).
482
+
483
+ ## Workflows
484
+
485
+ `VelaWorkflow(app, Host)` from `@velajs/cloudflare/workflows` returns a
486
+ `WorkflowEntrypoint` class whose `run(event, step)` is the `run` method of an
487
+ `@Injectable()` host, resolved in the Worker's application for the run's
488
+ environment (the one the Worker's handlers use), with the host added to the
489
+ root module's providers:
490
+
491
+ ```ts
492
+ import { Injectable } from '@velajs/vela';
493
+ import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
494
+ import { VelaWorkflow } from '@velajs/cloudflare/workflows';
495
+
496
+ @Injectable()
497
+ export class SignupHost {
498
+ constructor(private readonly users: UsersService) {}
499
+
500
+ async run(event: WorkflowEvent<{ email: string }>, step: WorkflowStep) {
501
+ const userId = await step.do(
502
+ 'create user',
503
+ async (): Promise<string> => this.users.create(event.payload.email),
504
+ );
505
+ await step.sleep('grace period', '1 day');
506
+ return { userId };
507
+ }
508
+ }
509
+
510
+ export class SignupWorkflow extends VelaWorkflow(app, SignupHost) {}
511
+ // Worker code: await env.SIGNUP_WORKFLOW.create({ params: { email } })
512
+ ```
513
+
514
+ `event` and `step` pass through untouched, so step retries and replays keep
515
+ their semantics. Each run gets its own execution scope (request-scoped
516
+ providers per run) and runs the host's scoped guards, interceptors and filters
517
+ (`getType()` `'cf:workflow'`). A failure is reported (`edge: 'workflow'`) and
518
+ rethrown as it is, so the engine honors `NonRetryableError`. The engine's own
519
+ interruptions (`Aborting engine: ...` when an instance is paused, restarted or
520
+ terminated) pass through unreported and unfiltered. The typed
521
+ `workflow<Params>({ binding })` reference (root entry) creates and reads
522
+ instances from module options and helpers; `WorkflowParams<T>` reads a
523
+ Workflow's params from its class or host. See
524
+ [Workflows](../../docs/workflows.md).
525
+
526
+ ## Service entrypoints, email and tail
527
+
528
+ `VelaEntrypoint(app, Host, { rpc })` from `@velajs/cloudflare/entrypoints`
529
+ returns a `WorkerEntrypoint` class whose JS-RPC methods are the host methods
530
+ `rpc` names, typed on a `Service<typeof Billing>` binding. Each call runs in the
531
+ Worker's application through the host's scoped guards, pipes, interceptors and
532
+ filters (`getType()` `'rpc'`), with the caller's `ctx.props` injectable as
533
+ `ENTRYPOINT_PROPS`; failures are reported (`edge: 'rpc'`) and reject only with
534
+ an `EntrypointError`:
535
+
536
+ ```ts
537
+ import { Inject, Injectable } from '@velajs/vela';
538
+ import { ENTRYPOINT_PROPS, VelaEntrypoint } from '@velajs/cloudflare/entrypoints';
539
+
540
+ @Injectable()
541
+ export class BillingHost {
542
+ constructor(@Inject(ENTRYPOINT_PROPS) private readonly props: unknown) {}
543
+
544
+ async charge(customerId: string, cents: number): Promise<{ invoiceId: string }> {
545
+ return { invoiceId: `${customerId}-${cents}` };
546
+ }
547
+ }
548
+
549
+ export class Billing extends VelaEntrypoint(app, BillingHost, { rpc: ['charge'] }) {}
550
+ // Another Worker: services: [{ binding: 'BILLING', service: 'billing', entrypoint: 'Billing' }]
551
+ // await env.BILLING.charge('customer-1', 500)
552
+ ```
553
+
554
+ `fetch`, `connect`, `then`, `ctx`, `env`, `dup`, hooks and the
555
+ `WorkerEntrypoint` handlers are never RPC methods.
556
+
557
+ `@OnEmail({ to? })` from `@velajs/cloudflare/email` and `@OnTail()` from
558
+ `@velajs/cloudflare/tail` make provider methods the Worker's Email Workers and
559
+ Tail Workers handlers (entrypoint kinds `cf:email` and `cf:tail`); importing
560
+ them gives `app.worker` its `email` and `tail` handlers. An email goes to the
561
+ handlers whose `to` lists its envelope recipient, else to those without `to`,
562
+ and a message no handler accepts is rejected with `setReject()`. Tail handler
563
+ failures are reported and never thrown into the platform's loop; an
564
+ application that fails to start is logged to the console instead. See
565
+ [Service entrypoints, email and tail](../../docs/entrypoints.md).
566
+
430
567
  ## Bindings by name
431
568
 
432
569
  Module options name a binding instead of holding it. `kv`, `r2`, `d1`,
433
- `queue`, `durableObject` and `rateLimit` each take `{ binding }`, the name
570
+ `queue`, `durableObject`, `rateLimit` and `workflow` each take `{ binding }`, the name
434
571
  declared in the Wrangler configuration, and read nothing when declared: calling
435
572
  the reference with an application's `ENV` returns the typed native binding, or
436
573
  fails naming the binding and the Wrangler key that declares it
@@ -510,9 +647,11 @@ is not declared fails the operation with an error naming it and
510
647
  `kv_namespaces`; the cache treats that as a miss and sends the error to the
511
648
  application's error reporter (edge `'cache'`).
512
649
 
513
- `KVCacheStore` and `KVCacheInvalidationStore` take a namespace or a function
514
- returning one, for composition such as
515
- `store: (env) => new TieredCacheStore([new MemoryCacheStore(), new KVCacheStore(env.CACHE)])`.
650
+ `kvCache({ binding })` is a function of `ENV`, so a tier composes it without
651
+ reading `ENV` directly:
652
+ `store: (env) => new TieredCacheStore([new MemoryCacheStore(), kvCache({ binding: 'CACHE' })(env)])`.
653
+ `KVCacheStore` and `KVCacheInvalidationStore` also take a namespace or a
654
+ function returning one.
516
655
  Construct `KvFlagDriver` with a native namespace: `new KvFlagDriver(env.CACHE)`.
517
656
  Cache reads and object-valued flag reads return `unknown`; validate them with an
518
657
  application parser (`cache.scope(scope).getParsed(key, parser)`).
@@ -575,6 +714,11 @@ it('processes a created todo', async () => {
575
714
  builds the envelope `QueueClient.add()` sends.
576
715
  - `scheduled(cron, { scheduledTime? })` fires a cron trigger with
577
716
  `createScheduledController()`, and rejects when no `@Cron` job declares `cron`.
717
+ - `email(message)` and `tail(events)` deliver to the `@OnEmail()` and
718
+ `@OnTail()` handlers. `emailMessage({ from, to, subject?, text?, headers?, raw? })`
719
+ builds a `ForwardableEmailMessage` that records `setReject()`, `forward()` and
720
+ `reply()` (`rejectReason`, `forwards`, `replies`); `traceItem(overrides?)`
721
+ builds a `TraceItem`.
578
722
  - `close()` cancels response bodies a test never read, waits for background
579
723
  work (`waitUntil`) and closes the application.
580
724
 
package/dist/bindings.js CHANGED
@@ -71,7 +71,23 @@ const RATE_LIMITER = {
71
71
  accepts: (value) => hasOperations(value, ["limit"])
72
72
  };
73
73
  const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);
74
+ /**
75
+ * A reference to a Workflow binding declared under `workflows`, whose
76
+ * instances take `Params`: for a class from `VelaWorkflow()`,
77
+ * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.
78
+ * Called with an application's ENV, it returns the native binding typed with
79
+ * those params: `await signups(env).create({ params: { email } })`. The
80
+ * runtime checks that the binding is a Workflow; its params are what the
81
+ * Workflow class declares.
82
+ */
83
+ function workflow(ref) {
84
+ return defineBinding({
85
+ name: "Workflow",
86
+ configKey: "workflows",
87
+ accepts: (value) => hasOperations(value, ["create", "get"])
88
+ })(ref);
89
+ }
74
90
  //#endregion
75
- export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, d1, durableObject, kv, queue, r2, rateLimit };
91
+ export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, d1, durableObject, kv, queue, r2, rateLimit, workflow };
76
92
 
77
93
  //# sourceMappingURL=bindings.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import { defineBinding, type BindingKind } from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n"],"mappings":";;;AAGA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY"}
1
+ {"version":3,"file":"bindings.js","names":[],"sources":["../src/bindings.ts"],"sourcesContent":["import {\n defineBinding,\n type Binding,\n type BindingKind,\n type BindingRef,\n} from '@velajs/vela/module-kit';\n\n/** Whether a value exposes every named operation as a function. */\nfunction hasOperations(value: unknown, operations: readonly string[]): boolean {\n if (typeof value !== 'object' || value === null) return false;\n return operations.every((operation) => typeof Reflect.get(value, operation) === 'function');\n}\n\n/**\n * Name-based Workers binding factories. Each takes `{ binding }`, the name\n * declared in the Wrangler configuration, and returns a reference that reads\n * and validates the native binding from an application's `ENV` when called.\n * Declaring one reads no environment, so references belong in static module\n * options: `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\n\n/** A KV namespace declared under `kv_namespaces`. */\nexport const KV_NAMESPACE: BindingKind<KVNamespace> = {\n name: 'KV namespace',\n configKey: 'kv_namespaces',\n accepts: (value): value is KVNamespace =>\n hasOperations(value, ['get', 'put', 'delete', 'list', 'getWithMetadata']),\n};\nexport const kv = /* @__PURE__ */ defineBinding(KV_NAMESPACE);\n\n/** An R2 bucket declared under `r2_buckets`. */\nexport const R2_BUCKET: BindingKind<R2Bucket> = {\n name: 'R2 bucket',\n configKey: 'r2_buckets',\n accepts: (value): value is R2Bucket =>\n hasOperations(value, ['get', 'put', 'head', 'delete', 'list', 'createMultipartUpload']),\n};\nexport const r2 = /* @__PURE__ */ defineBinding(R2_BUCKET);\n\n/** A D1 database declared under `d1_databases`. */\nexport const D1_DATABASE: BindingKind<D1Database> = {\n name: 'D1 database',\n configKey: 'd1_databases',\n accepts: (value): value is D1Database => hasOperations(value, ['prepare', 'batch', 'exec']),\n};\nexport const d1 = /* @__PURE__ */ defineBinding(D1_DATABASE);\n\n/** A queue producer declared under `queues.producers`. */\nexport const QUEUE_PRODUCER: BindingKind<Queue> = {\n name: 'queue producer',\n configKey: 'queues.producers',\n accepts: (value): value is Queue => hasOperations(value, ['send']),\n};\nexport const queue = /* @__PURE__ */ defineBinding(QUEUE_PRODUCER);\n\n/** A Durable Object namespace declared under `durable_objects.bindings`. */\nexport const DURABLE_OBJECT_NAMESPACE: BindingKind<DurableObjectNamespace> = {\n name: 'Durable Object namespace',\n configKey: 'durable_objects.bindings',\n accepts: (value): value is DurableObjectNamespace => hasOperations(value, ['idFromName', 'get']),\n};\nexport const durableObject = /* @__PURE__ */ defineBinding(DURABLE_OBJECT_NAMESPACE);\n\n/** A Workers Rate Limiting binding declared under `ratelimits`. */\nexport const RATE_LIMITER: BindingKind<RateLimit> = {\n name: 'rate limiter',\n configKey: 'ratelimits',\n accepts: (value): value is RateLimit => hasOperations(value, ['limit']),\n};\nexport const rateLimit = /* @__PURE__ */ defineBinding(RATE_LIMITER);\n\n/**\n * A reference to a Workflow binding declared under `workflows`, whose\n * instances take `Params`: for a class from `VelaWorkflow()`,\n * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.\n * Called with an application's ENV, it returns the native binding typed with\n * those params: `await signups(env).create({ params: { email } })`. The\n * runtime checks that the binding is a Workflow; its params are what the\n * Workflow class declares.\n */\nexport function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>> {\n return defineBinding<Workflow<Params>>({\n name: 'Workflow',\n configKey: 'workflows',\n accepts: (value): value is Workflow<Params> => hasOperations(value, ['create', 'get']),\n })(ref);\n}\n"],"mappings":";;;AAQA,SAAS,cAAc,OAAgB,YAAwC;CAC7E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,WAAW,OAAO,cAAc,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM,UAAU;AAC5F;;;;;;;;;AAWA,MAAa,eAAyC;CACpD,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAU;EAAQ;CAAiB,CAAC;AAC5E;AACA,MAAa,KAAqB,8BAAc,YAAY;;AAG5D,MAAa,YAAmC;CAC9C,MAAM;CACN,WAAW;CACX,UAAU,UACR,cAAc,OAAO;EAAC;EAAO;EAAO;EAAQ;EAAU;EAAQ;CAAuB,CAAC;AAC1F;AACA,MAAa,KAAqB,8BAAc,SAAS;;AAGzD,MAAa,cAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA+B,cAAc,OAAO;EAAC;EAAW;EAAS;CAAM,CAAC;AAC5F;AACA,MAAa,KAAqB,8BAAc,WAAW;;AAG3D,MAAa,iBAAqC;CAChD,MAAM;CACN,WAAW;CACX,UAAU,UAA0B,cAAc,OAAO,CAAC,MAAM,CAAC;AACnE;AACA,MAAa,QAAwB,8BAAc,cAAc;;AAGjE,MAAa,2BAAgE;CAC3E,MAAM;CACN,WAAW;CACX,UAAU,UAA2C,cAAc,OAAO,CAAC,cAAc,KAAK,CAAC;AACjG;AACA,MAAa,gBAAgC,8BAAc,wBAAwB;;AAGnF,MAAa,eAAuC;CAClD,MAAM;CACN,WAAW;CACX,UAAU,UAA8B,cAAc,OAAO,CAAC,OAAO,CAAC;AACxE;AACA,MAAa,YAA4B,8BAAc,YAAY;;;;;;;;;;AAWnE,SAAgB,SAA2B,KAA4C;CACrF,OAAO,cAAgC;EACrC,MAAM;EACN,WAAW;EACX,UAAU,UAAqC,cAAc,OAAO,CAAC,UAAU,KAAK,CAAC;CACvF,CAAC,CAAC,CAAC,GAAG;AACR"}
@@ -1,7 +1,6 @@
1
- import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
2
- import { CorsOptions, GlobalPrefixOptions, InjectionToken, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
1
+ import { CorsOptions, InjectionToken, VelaApplication, VelaEnv } from "@velajs/vela";
2
+ import "@velajs/vela/module-kit";
3
3
  import { ExecutionContext } from "hono";
4
- import { RuntimeAdapter } from "@velajs/vela/module-kit";
5
4
  //#region src/scheduled-event.d.ts
6
5
  /**
7
6
  * The event a Worker's `scheduled()` export receives. The native
@@ -113,6 +112,12 @@ declare class CloudflareApplication {
113
112
  */
114
113
  readonly get: VelaApplication['get'];
115
114
  get entrypoints(): VelaApplication['entrypoints'];
115
+ /**
116
+ * The application's DI container (delegates to `VelaApplication.getContainer`),
117
+ * for dispatch seams that take it with `entrypoints`, such as
118
+ * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.
119
+ */
120
+ getContainer(): ReturnType<VelaApplication['getContainer']>;
116
121
  /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
117
122
  enableCors(options?: CorsOptions): this;
118
123
  /**
@@ -191,98 +196,4 @@ declare class CloudflareApplication {
191
196
  close(signal?: string): Promise<void>;
192
197
  }
193
198
  //#endregion
194
- //#region src/cloudflare-factory.d.ts
195
- interface CloudflareAppOptions {
196
- globalPrefix?: string;
197
- /** Routes served without the global prefix (`{ exclude }`). */
198
- globalPrefixOptions?: GlobalPrefixOptions;
199
- /** URI versioning: the version segment prefix (default `'v'`). */
200
- versioning?: VersioningOptions;
201
- security?: VelaSecurityOptions;
202
- /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */
203
- cors?: CorsOptions | boolean;
204
- /** Further runtime adapters, composed after the Cloudflare adapter for each application. */
205
- adapters?: RuntimeAdapter[];
206
- }
207
- interface CloudflareWorkerOptions extends CloudflareAppOptions {
208
- /**
209
- * Finish each application's HTTP surface, such as extra Hono routes, once per
210
- * environment. It runs after the application is built and before any event,
211
- * including concurrent cold events, reaches it; a throw fails that
212
- * construction, and the next event retries. It must be synchronous and do no
213
- * I/O (a returned promise fails the construction): read bindings in
214
- * providers. Request middleware belongs in modules (`configure(consumer)`),
215
- * which can inject `ENV`.
216
- */
217
- configure?(app: CloudflareApplication, env: VelaEnv): void;
218
- }
219
- interface CreateCloudflareAppOptions extends CloudflareAppOptions {
220
- /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
221
- env: VelaEnv;
222
- }
223
- /**
224
- * Bind an application to one environment: seeded as the global ENV before
225
- * provider factories and lifecycle hooks, and asserted on every request. The
226
- * adapter also registers the Worker's platform wiring: `WebSocketModule`
227
- * forwards each authenticated gateway upgrade to the room's Durable Object,
228
- * and `LiveModule` sends invalidations there. It supplies the
229
- * `InternalDispatcher` transport, so signed queue and schedule dispatch
230
- * re-enter this application's routes, and reports, through the diagnostics
231
- * policy, schedule declarations a cron trigger cannot honor and binding-backed
232
- * gateways without `WebSocketModule`.
233
- */
234
- declare function cloudflareAdapter(options: {
235
- env: VelaEnv;
236
- }): RuntimeAdapter;
237
- /**
238
- * Build an application for one native Workers environment. Call inside a platform event.
239
- * The root is static: a module class or a `DynamicModule` declared at module scope.
240
- * Read bindings in providers (`@InjectEnv()`) and module factories
241
- * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
242
- */
243
- declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
244
- /**
245
- * The well-known key under which a `createCloudflareWorker()` entry carries
246
- * its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.
247
- */
248
- declare const CLOUDFLARE_WORKER: unique symbol;
249
- /** What a Worker entry is built from, for tools that load it outside a platform event. */
250
- interface CloudflareWorkerDescriptor {
251
- readonly rootModule: CloudflareRoot;
252
- readonly options: CloudflareWorkerOptions;
253
- /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */
254
- createOptions(env: VelaEnv): VelaCreateOptions;
255
- /**
256
- * `VelaFactory.create(rootModule, createOptions(env))`: the application
257
- * without its Worker handlers or the `configure` hook, which receives the
258
- * Workers application.
259
- */
260
- createApplication(env: VelaEnv): Promise<VelaApplication>;
261
- }
262
- /** The exported handlers of a `createCloudflareWorker()` entry. */
263
- interface CloudflareWorker {
264
- fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
265
- scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
266
- waitUntil: (promise: Promise<unknown>) => void;
267
- }): Promise<void>;
268
- queue(batch: {
269
- queue: string;
270
- messages: readonly unknown[];
271
- }, env: VelaEnv, ctx: {
272
- waitUntil: (promise: Promise<unknown>) => void;
273
- }): Promise<void>;
274
- /**
275
- * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
276
- * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
277
- */
278
- readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;
279
- }
280
- /**
281
- * Worker entrypoint with one bootstrap per environment identity. Concurrent cold
282
- * events share construction, including `configure`; failed construction is
283
- * evicted so the next event can retry. Weak keys stop this cache from
284
- * retaining a replaced environment.
285
- */
286
- declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareWorker;
287
- //#endregion
288
- export { CloudflareWorkerOptions as a, createCloudflareApp as c, MountOpenApiOptions as d, CLOUDFLARE_SCHEDULED_EVENT as f, CloudflareWorkerDescriptor as i, createCloudflareWorker as l, ScheduledEvent as m, CloudflareAppOptions as n, CreateCloudflareAppOptions as o, CloudflareScheduledEvent as p, CloudflareWorker as r, cloudflareAdapter as s, CLOUDFLARE_WORKER as t, CloudflareApplication as u };
199
+ export { ScheduledEvent as a, CloudflareScheduledEvent as i, MountOpenApiOptions as n, CLOUDFLARE_SCHEDULED_EVENT as r, CloudflareApplication as t };
@@ -95,6 +95,14 @@ var CloudflareApplication = class {
95
95
  get entrypoints() {
96
96
  return this.#app.entrypoints;
97
97
  }
98
+ /**
99
+ * The application's DI container (delegates to `VelaApplication.getContainer`),
100
+ * for dispatch seams that take it with `entrypoints`, such as
101
+ * `dispatchInboundEmail(app.getContainer(), app.entrypoints, email)`.
102
+ */
103
+ getContainer() {
104
+ return this.#app.getContainer();
105
+ }
98
106
  /** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
99
107
  enableCors(options) {
100
108
  this.#app.enableCors(options);
@@ -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 /** 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,UACnB,MAAM,IAAI,MAAM,gCAAgC,SAAS,mBAAmB;CAC9E,OAAO;AACT;;;;;;AAOA,MAAM,uCAAuB,IAAI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O,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.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,U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