@velajs/cloudflare 1.34.0 → 1.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +48 -9
- package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorate.js +1 -2
- package/dist/_virtual/_@oxc-project_runtime@0.160.0/helpers/esm/decorateMetadata.js +5 -0
- package/dist/_virtual/_@oxc-project_runtime@0.160.0/helpers/esm/decorateParam.js +7 -0
- package/dist/bindings.js +1 -2
- package/dist/{cloudflare-application-Dsscb3Mo.d.ts → cloudflare-application-Zw9th_-h.d.ts} +2 -7
- package/dist/cloudflare-application.js +3 -4
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/{cloudflare-factory-DM9CBvNH.d.ts → cloudflare-factory-Ab6XoKqO.d.ts} +5 -9
- package/dist/cloudflare-factory.js +6 -7
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/decorators/queue-consumer.js +1 -2
- package/dist/diagnostics.js +1 -2
- package/dist/durable-object/boot.js +5 -6
- package/dist/durable-object/host-dispatch.js +4 -5
- package/dist/durable-object/host-dispatch.js.map +1 -1
- package/dist/durable-object/host-methods.js +1 -2
- package/dist/durable-object/tokens.js +1 -2
- package/dist/durable-object/vela-durable-object.js +3 -4
- package/dist/durable-objects.d.ts +7 -19
- package/dist/durable-objects.js +1 -1
- package/dist/email/email-dispatch.js +1 -2
- package/dist/email/on-email.js +2 -3
- package/dist/email.d.ts +2 -6
- package/dist/email.js +1 -1
- package/dist/entrypoint/vela-entrypoint.js +4 -5
- package/dist/entrypoints.d.ts +3 -5
- package/dist/entrypoints.js +1 -2
- package/dist/environment.js +1 -2
- package/dist/host/host-invoker.js +2 -3
- package/dist/host/host-invoker.js.map +1 -1
- package/dist/host/host-members.js +1 -2
- package/dist/{host-members-DECj_4yz.d.ts → host-members-bKCWuJP2.d.ts} +0 -2
- package/dist/index.d.ts +99 -38
- package/dist/index.js +6 -5
- package/dist/nonce/durable-object-nonce.store.js +1 -2
- package/dist/nonce/nonce-validation.js +1 -2
- package/dist/nonce/nonce.durable-object.js +2 -3
- package/dist/nonce/nonce.durable-object.js.map +1 -1
- package/dist/{nonce.durable-object-Bg1e0BMD.d.ts → nonce.durable-object-Csuy3U9e.d.ts} +0 -4
- package/dist/pipelines.d.ts +1 -3
- package/dist/pipelines.js +1 -2
- package/dist/platform.js +2 -3
- package/dist/queue/cloudflare-queues.js +6 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/queue-events/consume.js +1 -2
- package/dist/queue-events/consume.js.map +1 -1
- package/dist/queue-events.d.ts +1 -2
- package/dist/queue-events.js +1 -2
- package/dist/queues.d.ts +2 -4
- package/dist/queues.js +1 -2
- package/dist/rate-limit/cloudflare-rate-limit.store.js +1 -2
- package/dist/rate-limit/d1-throttler.store.js +96 -0
- package/dist/rate-limit/d1-throttler.store.js.map +1 -0
- package/dist/root-module.js +1 -2
- package/dist/rpc/entrypoint-error.js +1 -2
- package/dist/rpc/entrypoint-error.js.map +1 -1
- package/dist/schedule-diagnostics.js +2 -3
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/scheduled-event.js +1 -2
- package/dist/services/flagship-flag.driver.js +1 -2
- package/dist/services/flagship-flag.driver.js.map +1 -1
- package/dist/services/kv-cache.store.js +1 -2
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/services/kv-flag.driver.js +1 -2
- package/dist/services/kv-flag.driver.js.map +1 -1
- package/dist/storage/r2-storage.js +3 -4
- package/dist/storage/r2-storage.js.map +1 -1
- package/dist/storage.d.ts +2 -4
- package/dist/storage.js +1 -2
- package/dist/tail/on-tail.js +2 -3
- package/dist/tail/tail-dispatch.js +2 -3
- package/dist/tail.d.ts +2 -6
- package/dist/tail.js +1 -2
- package/dist/testing.d.ts +5 -5
- package/dist/testing.js +6 -6
- package/dist/testing.js.map +1 -1
- package/dist/tracing.d.ts +1 -3
- package/dist/tracing.js +3 -4
- package/dist/{vela-env-DFvyoNT3.d.ts → vela-env-5graXefc.d.ts} +0 -1
- package/dist/websocket/binding-gateways.js +2 -3
- package/dist/websocket/cf-room-registry.js +2 -3
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/cf-ws-client.js +2 -3
- package/dist/websocket/cf-ws-client.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +5 -6
- package/dist/websocket/do-live.js +4 -5
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-pitr.js +1 -2
- package/dist/websocket/do-pitr.js.map +1 -1
- package/dist/websocket/do-state.js +1 -2
- package/dist/websocket/do-websocket-host.js +3 -4
- package/dist/websocket/do-websocket-host.js.map +1 -1
- package/dist/websocket/live-driver.js +3 -4
- package/dist/websocket/live-driver.js.map +1 -1
- package/dist/websocket/room-id.js +1 -2
- package/dist/websocket/websocket.durable-object.js +5 -6
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +3 -4
- package/dist/websocket/ws-attachment.js +1 -2
- package/dist/worker-events.js +1 -2
- package/dist/workflow/portable-workflow-step.js +61 -0
- package/dist/workflow/portable-workflow-step.js.map +1 -0
- package/dist/workflow/vela-workflow-definition.js +77 -0
- package/dist/workflow/vela-workflow-definition.js.map +1 -0
- package/dist/workflow/vela-workflow.js +2 -3
- package/dist/workflow-definitions.d.ts +31 -0
- package/dist/workflow-definitions.js +1 -0
- package/dist/workflows.d.ts +2 -4
- package/dist/workflows.js +1 -2
- package/package.json +31 -21
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,54 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.36.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 0202d0f: Count rate limits exactly on D1 and count failures. `d1ThrottlerStore({ binding })` from `@velajs/cloudflare` is a `ThrottlerModule` store that counts each request with one atomic D1 upsert, so every isolate and location shares one fixed-window counter per key, with windows of any length and `@Throttle()` overrides. `d1ThrottlerMigration()` returns its table, and ended windows are pruned in small batches or through `prune()`.
|
|
8
|
+
|
|
9
|
+
`FailureCounter` from `@velajs/vela/throttler` counts failed attempts instead of requests (`check`, `fail`, `clear`) on any store that reads and resets counters; `ThrottlerStore` gains an optional `get(key)`, which the memory store implements. Generated projects pin the new core and Cloudflare versions.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 0f9490f: Update runtime dependencies to their current releases: Hono 4.13.23, Zod 4.6.7, `@cfworker/json-schema` 4.1.8, Cedar 4.15.0, jose 6.2.19, the MCP SDK 1.32.2, oxc-parser 0.161 and the TanStack Query, Router, Virtual and Table 9 packages behind Studio.
|
|
14
|
+
|
|
15
|
+
`@velajs/graphql` accepts graphql 17 and graphql-yoga 6 alongside graphql 16.14.2+ and graphql-yoga 5.24.1+, and depends on `@graphql-tools/utils` 13. Applications on graphql 16 and Yoga 5 need no change.
|
|
16
|
+
|
|
17
|
+
The Yoga driver hands Yoga the runtime's native stream classes, which Yoga 6 needs to enforce its request body limit.
|
|
18
|
+
|
|
19
|
+
`@velajs/cli` recognizes the Wrangler 4.171 binding sections `analytics`, `k2`, `oidc_tokens` and `realtimekit` in `vela add binding`, `cf sync` and `deploy check`. Generated projects pin Vitest 5.1.2, `@cloudflare/vitest-plugin` 1.10.3, `@cloudflare/vite-plugin` 1.72.1, Wrangler 4.171.0, Vite 8.4.1, Workers types 5.20261203.1, Hono 4.13.23 and Zod 4.6.7.
|
|
20
|
+
|
|
21
|
+
Zod 4.6 describes a union of primitive types, including a nullable primitive, as one JSON Schema `type` array (`["string", "null"]`) instead of `anyOf`. OpenAPI 3.1 documents and generated clients accept both forms.
|
|
22
|
+
|
|
23
|
+
`emailMessage()` from `@velajs/cloudflare/testing` sets the new `canBeForwarded` field of `ForwardableEmailMessage` (`true` unless the `canBeForwarded` option says otherwise). Test doubles written by hand against Workers types 5.20261203.1 or later need that field too.
|
|
24
|
+
- Updated dependencies [0202d0f]
|
|
25
|
+
- Updated dependencies [0f9490f]
|
|
26
|
+
- Updated dependencies [1e90154]
|
|
27
|
+
- @velajs/vela@1.37.0
|
|
28
|
+
- @velajs/feature-flags@1.33.0
|
|
29
|
+
- @velajs/storage@1.34.0
|
|
30
|
+
- @velajs/testing@1.34.0
|
|
31
|
+
|
|
32
|
+
## 1.35.0
|
|
33
|
+
|
|
34
|
+
### Minor Changes
|
|
35
|
+
|
|
36
|
+
- 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.
|
|
37
|
+
|
|
38
|
+
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.
|
|
39
|
+
|
|
40
|
+
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.
|
|
41
|
+
|
|
42
|
+
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.
|
|
43
|
+
|
|
44
|
+
### Patch Changes
|
|
45
|
+
|
|
46
|
+
- Updated dependencies [9a00506]
|
|
47
|
+
- @velajs/vela@1.34.0
|
|
48
|
+
- @velajs/storage@1.34.0
|
|
49
|
+
- @velajs/feature-flags@1.33.0
|
|
50
|
+
- @velajs/testing@1.34.0
|
|
51
|
+
|
|
3
52
|
## 1.34.0
|
|
4
53
|
|
|
5
54
|
### 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`
|
|
@@ -663,8 +680,8 @@ methods. `secretsStoreSecret` returns a native `SecretsStoreSecret` handle; call
|
|
|
663
680
|
they do not read secrets, evaluate flags, cache results, create resources or prove
|
|
664
681
|
remote availability. Native method errors and local-development behavior are
|
|
665
682
|
unchanged. Use current generated Wrangler types or Workers types containing
|
|
666
|
-
these native interfaces (validated with Wrangler 4.
|
|
667
|
-
5.
|
|
683
|
+
these native interfaces (validated with Wrangler 4.171.0 and Workers types
|
|
684
|
+
5.20261203.1).
|
|
668
685
|
|
|
669
686
|
```ts
|
|
670
687
|
import { flagship, secretsStoreSecret } from '@velajs/cloudflare';
|
|
@@ -719,9 +736,31 @@ counters, so responses carry no `X-RateLimit-Remaining`, and no reset time, so
|
|
|
719
736
|
|
|
720
737
|
Workers Rate Limiting counts per Cloudflare location, and its counters are
|
|
721
738
|
eventually consistent: limits are approximate, not a global or exact quota. A
|
|
722
|
-
client spread across locations can exceed them.
|
|
723
|
-
|
|
724
|
-
|
|
739
|
+
client spread across locations can exceed them.
|
|
740
|
+
|
|
741
|
+
For exact limits, windows of any length and `FailureCounter`, count in D1:
|
|
742
|
+
|
|
743
|
+
```ts
|
|
744
|
+
import { d1ThrottlerStore } from '@velajs/cloudflare';
|
|
745
|
+
|
|
746
|
+
ThrottlerModule.forRoot({
|
|
747
|
+
throttlers: [{ name: 'forms', ttl: 10 * 60_000, limit: 20 }],
|
|
748
|
+
storage: d1ThrottlerStore({ binding: 'DB' }), // table: 'vela_rate_limits'
|
|
749
|
+
});
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
Each counted request is one `INSERT … ON CONFLICT … RETURNING` statement, which
|
|
753
|
+
D1 runs atomically on the database's primary: every isolate and location shares
|
|
754
|
+
one exact fixed-window counter per key, and `@Throttle()` overrides work. That
|
|
755
|
+
is one D1 write per counted request, plus the round trip to the primary, so use
|
|
756
|
+
it where exactness matters (sign-in, codes, forms) rather than on every route.
|
|
757
|
+
Create the table in a migration from `d1ThrottlerMigration({ table? })`, which
|
|
758
|
+
returns the `CREATE TABLE` and expiry-index statements. About one count in 100
|
|
759
|
+
also deletes up to `pruneBatch` (default 100) ended windows; set `pruneBatch: 0`
|
|
760
|
+
and call the store's `prune()` from a scheduled job instead if you prefer. The
|
|
761
|
+
store reads and resets counters, so `FailureCounter` from
|
|
762
|
+
`@velajs/vela/throttler` can count failed sign-ins on it (see
|
|
763
|
+
[security](../../docs/security.md#counting-failures)).
|
|
725
764
|
|
|
726
765
|
## R2 storage and caches
|
|
727
766
|
|
|
@@ -733,7 +772,7 @@ is the one file-storage module. Its native R2 driver comes from the
|
|
|
733
772
|
import { StorageModule } from '@velajs/storage';
|
|
734
773
|
import { r2Storage } from '@velajs/cloudflare/storage';
|
|
735
774
|
|
|
736
|
-
StorageModule.
|
|
775
|
+
StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) });
|
|
737
776
|
```
|
|
738
777
|
|
|
739
778
|
The bucket is read from each application's `ENV` on its first storage
|
|
@@ -828,7 +867,7 @@ it('processes a created todo', async () => {
|
|
|
828
867
|
- `scheduled(cron, { scheduledTime? })` fires a cron trigger with
|
|
829
868
|
`createScheduledController()`, and rejects when no `@Cron` job declares `cron`.
|
|
830
869
|
- `email(message)` and `tail(events)` deliver to the `@OnEmail()` and
|
|
831
|
-
`@OnTail()` handlers. `emailMessage({ from, to, subject?, text?, headers?, raw? })`
|
|
870
|
+
`@OnTail()` handlers. `emailMessage({ from, to, subject?, text?, headers?, raw?, canBeForwarded? })`
|
|
832
871
|
builds a `ForwardableEmailMessage` that records `setReject()`, `forward()` and
|
|
833
872
|
`reply()` (`rejectReason`, `forwards`, `replies`); `traceItem(overrides?)`
|
|
834
873
|
builds a `TraceItem`.
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
// \0@oxc-project+runtime@0.160.0/helpers/esm/decorate.js
|
|
2
2
|
function __decorate(decorators, target, key, desc) {
|
|
3
3
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
4
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
5
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
6
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
7
|
}
|
|
8
|
-
//#endregion
|
|
9
8
|
export { __decorate as default };
|
package/dist/bindings.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineBinding } from "@velajs/vela/module-kit";
|
|
2
|
-
|
|
2
|
+
// src/bindings.ts
|
|
3
3
|
/** Whether a value exposes every named operation as a function. */
|
|
4
4
|
function hasOperations(value, operations) {
|
|
5
5
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -111,7 +111,6 @@ const SECRETS_STORE_SECRET = {
|
|
|
111
111
|
accepts: (value) => hasOperations(value, ["get"])
|
|
112
112
|
};
|
|
113
113
|
const secretsStoreSecret = /* @__PURE__ */ defineBinding(SECRETS_STORE_SECRET);
|
|
114
|
-
//#endregion
|
|
115
114
|
export { D1_DATABASE, DURABLE_OBJECT_NAMESPACE, FLAGSHIP, KV_NAMESPACE, QUEUE_PRODUCER, R2_BUCKET, RATE_LIMITER, SECRETS_STORE_SECRET, d1, durableObject, flagship, kv, queue, r2, rateLimit, secretsStoreSecret, workflow };
|
|
116
115
|
|
|
117
116
|
//# sourceMappingURL=bindings.js.map
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
+
import { ExecutionContext } from "hono";
|
|
1
2
|
import { CorsOptions, InjectionToken, VelaApplication, VelaEnv } from "@velajs/vela";
|
|
2
|
-
import "@velajs/vela/module-kit";
|
|
3
|
-
import { ExecutionContext as ExecutionContext$1 } from "hono";
|
|
4
|
-
//#region src/scheduled-event.d.ts
|
|
5
3
|
/**
|
|
6
4
|
* The event a Worker's `scheduled()` export receives. The native
|
|
7
5
|
* `ScheduledController` satisfies it; direct calls (tests, scripts) may omit
|
|
@@ -53,8 +51,6 @@ interface CloudflareScheduledEvent {
|
|
|
53
51
|
* ```
|
|
54
52
|
*/
|
|
55
53
|
declare const CLOUDFLARE_SCHEDULED_EVENT: InjectionToken<CloudflareScheduledEvent>;
|
|
56
|
-
//#endregion
|
|
57
|
-
//#region src/cloudflare-application.d.ts
|
|
58
54
|
/**
|
|
59
55
|
* Options accepted by {@link CloudflareApplication.mountOpenApi}.
|
|
60
56
|
*
|
|
@@ -97,7 +93,7 @@ declare class CloudflareApplication {
|
|
|
97
93
|
#private;
|
|
98
94
|
readonly env: VelaEnv;
|
|
99
95
|
constructor(app: VelaApplication, env: VelaEnv);
|
|
100
|
-
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext
|
|
96
|
+
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
|
|
101
97
|
getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
|
|
102
98
|
/**
|
|
103
99
|
* Resolve a provider from the application's DI container (delegates to
|
|
@@ -195,5 +191,4 @@ declare class CloudflareApplication {
|
|
|
195
191
|
*/
|
|
196
192
|
close(signal?: string): Promise<void>;
|
|
197
193
|
}
|
|
198
|
-
//#endregion
|
|
199
194
|
export { ScheduledEvent as a, CloudflareScheduledEvent as i, MountOpenApiOptions as n, CLOUDFLARE_SCHEDULED_EVENT as r, CloudflareApplication as t };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { PipelineRunner, buildEntrypointExecutionContext, getEntrypointModuleId, invokeScheduledJob, parseCronMetadata, resolveEntrypoint, resolveErrorReporter, resolveScopedComponentsAsync, runInEntrypointScope, shouldFilterCatch } from "@velajs/vela/module-kit";
|
|
1
2
|
import { assertCloudflareEnvironment } from "./environment.js";
|
|
2
3
|
import { CLOUDFLARE_SCHEDULED_EVENT, cloudflareScheduledEvent } from "./scheduled-event.js";
|
|
3
|
-
|
|
4
|
-
//#region src/cloudflare-application.ts
|
|
4
|
+
// src/cloudflare-application.ts
|
|
5
5
|
function invoke(instance, methodName, args) {
|
|
6
6
|
const method = Reflect.get(instance, methodName);
|
|
7
7
|
if (typeof method !== "function") throw new Error(`Method '${String(methodName)}' is not a function on ${instance.constructor.name}`);
|
|
@@ -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
|
/**
|
|
@@ -284,7 +284,6 @@ var CloudflareApplication = class {
|
|
|
284
284
|
return this.#app.close(signal);
|
|
285
285
|
}
|
|
286
286
|
};
|
|
287
|
-
//#endregion
|
|
288
287
|
export { CloudflareApplication };
|
|
289
288
|
|
|
290
289
|
//# sourceMappingURL=cloudflare-application.js.map
|
|
@@ -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.allS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CAAC,CAC5B,KAAK,UACJ,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,OAC7C,QAAQ,IAAI,MAAM,MAAM,MAAM,IAC9B,KAAA,CACN,CACJ;EACA,IAAI,WAAW,SAAS,GAAG;EAC3B,KAAK,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"}
|
|
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,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,IAAI,CAAC,iBAAiB,CAAC;AAExD,MAAM,gCAAgB,IAAI,IAAY;;AAGtC,SAAS,cAAc,MAAmC;CACxD,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,OAAO,KAAA;CACtD,MAAM,QAAiB,QAAQ,IAAI,MAAM,OAAO;CAChD,IACE,OAAO,UAAU,YACjB,OAAO,QAAQ,IAAI,MAAM,IAAI,MAAM,YACnC,OAAO,QAAQ,IAAI,MAAM,MAAM,MAAM,YACrC,EAAE,UAAU,OAEZ;CAEF,OAAO;AACT;;AAGA,eAAe,kBAAkB,MAA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MACR,6BAA6B,MAAM,MAAM,yBAAyB,MAAM,MAAM,gRAKhF;EAGF,MAAM,kBAAkB,SAAS,KAAK,OAAO,KAAK,mBAAmB,IAAI,OAAO,KAAK,GAAG,CAAC,CAAC;CAC5F;;;;;;;;;CAUQ,YAAY,OAA8D;EAChF,IAAI,KAAK,KAAK,aAAa,CAAC,CAAC,eAAe,MAAM,UAAU;EAC5D,MAAM,aAAa,IAAI,IACrB,KAAK,KAAK,YACP,OAAO,oBAAoB,CAAC,CAC5B,KAAK,UACJ,OAAO,MAAM,SAAS,YAAY,MAAM,SAAS,OAC7C,QAAQ,IAAI,MAAM,MAAM,MAAM,IAC9B,KAAA,CACN,CACJ;EACA,IAAI,WAAW,SAAS,GAAG;EAC3B,KAAK,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"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ExecutionContext } from "hono";
|
|
2
2
|
import { CorsOptions, DynamicModule, GlobalPrefixOptions, Type, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
|
|
3
3
|
import { RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
4
|
-
import {
|
|
5
|
-
//#region src/root-module.d.ts
|
|
4
|
+
import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-Zw9th_-h.js";
|
|
6
5
|
/**
|
|
7
6
|
* The root a Worker or Durable Object is built from: a module class or a
|
|
8
7
|
* `DynamicModule`, declared once at module scope. Configuration that needs
|
|
@@ -10,8 +9,6 @@ import { ExecutionContext as ExecutionContext$1 } from "hono";
|
|
|
10
9
|
* factories, which run for each application with that application's ENV.
|
|
11
10
|
*/
|
|
12
11
|
type CloudflareRoot = Type | DynamicModule;
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region src/cloudflare-factory.d.ts
|
|
15
12
|
interface CloudflareAppOptions {
|
|
16
13
|
globalPrefix?: string;
|
|
17
14
|
/** Routes served without the global prefix (`{ exclude }`). */
|
|
@@ -149,7 +146,7 @@ interface CloudflareWorkerDescriptor {
|
|
|
149
146
|
}
|
|
150
147
|
/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */
|
|
151
148
|
interface CloudflareWorker {
|
|
152
|
-
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext
|
|
149
|
+
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
|
|
153
150
|
scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
|
|
154
151
|
waitUntil: (promise: Promise<unknown>) => void;
|
|
155
152
|
}): Promise<void>;
|
|
@@ -164,14 +161,14 @@ interface CloudflareWorker {
|
|
|
164
161
|
* `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`
|
|
165
162
|
* handlers, and rejects a message none of them accepts.
|
|
166
163
|
*/
|
|
167
|
-
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext
|
|
164
|
+
readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
168
165
|
/**
|
|
169
166
|
* The Tail Workers handler, present once a module imports `OnTail` from
|
|
170
167
|
* `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers
|
|
171
168
|
* and never rejects, even when the application fails to start (the error is
|
|
172
169
|
* logged to the console, and the next batch retries).
|
|
173
170
|
*/
|
|
174
|
-
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext
|
|
171
|
+
readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
|
|
175
172
|
/**
|
|
176
173
|
* Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
|
|
177
174
|
* it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
|
|
@@ -237,5 +234,4 @@ declare function defineCloudflareApp(rootModule: CloudflareRoot, options?: Cloud
|
|
|
237
234
|
* entry also exports Durable Object classes built from it.
|
|
238
235
|
*/
|
|
239
236
|
declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareWorker;
|
|
240
|
-
//#endregion
|
|
241
237
|
export { defineCloudflareApp as _, CloudflareApp as a, CloudflareEntrypointDescriptor as c, CloudflareWorkerOptions as d, CloudflareWorkflowDescriptor as f, createCloudflareWorker as g, createCloudflareApp as h, CLOUDFLARE_WORKFLOW as i, CloudflareWorker as l, cloudflareAdapter as m, CLOUDFLARE_ENTRYPOINT as n, CloudflareAppOptions as o, CreateCloudflareAppOptions as p, CLOUDFLARE_WORKER as r, CloudflareDurableObjectDescriptor as s, CLOUDFLARE_DURABLE_OBJECT as t, CloudflareWorkerDescriptor as u, isCloudflareApp as v, CloudflareRoot as y };
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { registerScheduledEventSeed } from "./scheduled-event.js";
|
|
1
|
+
import { VelaFactory } from "@velajs/vela";
|
|
3
2
|
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
3
|
+
import { assertCloudflareEnvironment } from "./environment.js";
|
|
4
4
|
import { registerCloudflarePlatform } from "./platform.js";
|
|
5
5
|
import { reportCloudflareScheduleDiagnostics } from "./schedule-diagnostics.js";
|
|
6
|
+
import { registerScheduledEventSeed } from "./scheduled-event.js";
|
|
6
7
|
import { reportUnservedGateways } from "./websocket/binding-gateways.js";
|
|
7
|
-
import { workerWebSocketTransport } from "./websocket/worker-transport.js";
|
|
8
8
|
import { workerLivePlatform } from "./websocket/live-driver.js";
|
|
9
|
+
import { workerWebSocketTransport } from "./websocket/worker-transport.js";
|
|
9
10
|
import { defineWorkerEvents } from "./worker-events.js";
|
|
10
11
|
import { withRootProviders } from "./root-module.js";
|
|
11
|
-
|
|
12
|
-
//#region src/cloudflare-factory.ts
|
|
12
|
+
// src/cloudflare-factory.ts
|
|
13
13
|
function readStrings(meta, property) {
|
|
14
14
|
const value = typeof meta === "object" && meta !== null ? Reflect.get(meta, property) : void 0;
|
|
15
15
|
if (typeof value === "string") return [value];
|
|
@@ -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
|
/**
|
|
@@ -292,7 +292,6 @@ function defineCloudflareApp(rootModule, options = {}) {
|
|
|
292
292
|
function createCloudflareWorker(rootModule, options = {}) {
|
|
293
293
|
return defineCloudflareApp(rootModule, options).worker;
|
|
294
294
|
}
|
|
295
|
-
//#endregion
|
|
296
295
|
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, cloudflareApplication, cloudflareCreateOptions, configureCloudflareApplication, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, registerDurableObject, registerEntrypoint, registerWorkflow };
|
|
297
296
|
|
|
298
297
|
//# sourceMappingURL=cloudflare-factory.js.map
|
|
@@ -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,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MAAM,SAAS,KAAK,GAAG;EACzD;EACA,MAAM,UACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,UAAU,OAAO,KAAK,GAAG;EAC3D;EACA,MAAM,MACJ,OACA,KACA,KACe;GACf,QAAQ,MAAM,YAAY,GAAG,EAAA,CAAG,MAAM,OAAO,KAAK,GAAG;EACvD;GACC,oBAAoB;CACvB;CAEA,mBAAmB,QAAQ,WAAW;CACtC,MAAM,MAAqB;EACzB;EACA;EACA;EACA;EACA;EACA;CACF;CACA,OAAO,IAAI,KAAK,KAAK;CACrB,OAAO;AACT;;;;;;;;AASA,SAAgB,uBACd,YACA,UAAmC,CAAC,GAClB;CAClB,OAAO,oBAAoB,YAAY,OAAO,CAAC,CAAC;AAClD"}
|
|
1
|
+
{"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n CorsOptions,\n GlobalPrefixOptions,\n Type,\n VelaApplication,\n VelaCreateOptions,\n VelaEnv,\n VelaSecurityOptions,\n VersioningOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment } from './environment';\nimport { registerCloudflarePlatform } from './platform';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { reportUnservedGateways } from './websocket/binding-gateways';\nimport { workerLivePlatform } from './websocket/live-driver';\nimport { workerWebSocketTransport } from './websocket/worker-transport';\nimport { defineWorkerEvents } from './worker-events';\nimport { withRootProviders, type CloudflareRoot } from './root-module';\n\nexport interface CloudflareAppOptions {\n globalPrefix?: string;\n /** Routes served without the global prefix (`{ exclude }`). */\n globalPrefixOptions?: GlobalPrefixOptions;\n /** URI versioning: the version segment prefix (default `'v'`). */\n versioning?: VersioningOptions;\n security?: VelaSecurityOptions;\n /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */\n cors?: CorsOptions | boolean;\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CloudflareWorkerOptions extends CloudflareAppOptions {\n /**\n * Finish each application's HTTP surface, such as extra Hono routes, once per\n * environment. It runs after the application is built and before any event,\n * including concurrent cold events, reaches it; a throw fails that\n * construction, and the next event retries. It must be synchronous and do no\n * I/O (a returned promise fails the construction): read bindings in\n * providers. Request middleware belongs in modules (`configure(consumer)`),\n * which can inject `ENV`.\n */\n configure?(app: CloudflareApplication, env: VelaEnv): void;\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareAppOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.forFeature([{ consumer: '${queue}' }]) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also registers the Worker's platform wiring: `WebSocketModule`\n * forwards each authenticated gateway upgrade to the room's Durable Object,\n * and `LiveModule` sends invalidations there. It supplies the\n * `InternalDispatcher` transport, so signed queue and schedule dispatch\n * re-enter this application's routes, and reports, through the diagnostics\n * policy, schedule declarations a cron trigger cannot honor and binding-backed\n * gateways without `WebSocketModule`.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n // Cloudflare attests the client address in this header. Read directly:\n // hono/cloudflare-workers would also load its WebSocket upgrade helper.\n getClientIp: (c) => c.req.header('cf-connecting-ip') ?? null,\n configureContainer: (container) => {\n registerCloudflarePlatform(container, env, {\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n });\n registerScheduledEventSeed(container);\n },\n onBootstrap: ({ app, container, discovery }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n reportUnservedGateways(container, discovery);\n },\n };\n}\n\n/**\n * The `VelaFactory.create()` options an application for `options.env` is built\n * with: that environment (seeded as ENV and sent by test clients as `c.env`),\n * the Cloudflare adapter bound to it, then any further adapters.\n */\nexport function cloudflareCreateOptions(options: CreateCloudflareAppOptions): VelaCreateOptions {\n return {\n env: options.env,\n globalPrefix: options.globalPrefix,\n globalPrefixOptions: options.globalPrefixOptions,\n versioning: options.versioning,\n security: options.security,\n cors: options.cors,\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));\n return new CloudflareApplication(velaApp, options.env);\n}\n\n/**\n * Run a Worker's `configure` hook on the application built for `env`, as\n * `createCloudflareWorker()` does before any event reaches it: a throw or a\n * returned promise closes the application and fails the construction.\n */\nexport async function configureCloudflareApplication(\n app: CloudflareApplication,\n env: VelaEnv,\n configure: CloudflareWorkerOptions['configure'],\n): Promise<CloudflareApplication> {\n if (!configure) return app;\n try {\n const result: unknown = configure(app, env);\n if (result instanceof Promise) {\n // Observe the rejected work; the construction fails either way.\n result.catch(() => {});\n throw new TypeError(\n 'createCloudflareWorker configure must finish synchronously: it runs before any ' +\n 'event reaches the application, so read bindings and perform I/O in providers.',\n );\n }\n } catch (error) {\n await app.close().catch(() => {});\n throw error;\n }\n return app;\n}\n\n/**\n * The well-known key under which a Worker entry (`defineCloudflareApp().worker`\n * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:\n * `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\n\n/**\n * The well-known static key under which a Durable Object class that\n * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every\n * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:\n * `Symbol.for('vela.cloudflare.durableObject')`.\n */\nexport const CLOUDFLARE_DURABLE_OBJECT: unique symbol = Symbol.for('vela.cloudflare.durableObject');\n\n/**\n * The well-known static key under which a Workflow class that `VelaWorkflow()`\n * returns (and every class extending it) carries its\n * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.\n */\nexport const CLOUDFLARE_WORKFLOW: unique symbol = Symbol.for('vela.cloudflare.workflow');\n\n/**\n * The well-known static key under which a service entrypoint class that\n * `VelaEntrypoint()` returns (and every class extending it) carries its\n * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.\n */\nexport const CLOUDFLARE_ENTRYPOINT: unique symbol = Symbol.for('vela.cloudflare.entrypoint');\n\n/** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareDurableObjectDescriptor {\n /**\n * `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are\n * the host methods `rpc` names.\n * `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.\n */\n readonly kind: 'host' | 'websocket';\n readonly rootModule: CloudflareRoot;\n /** The host class of a `host` Durable Object. */\n readonly host?: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class the factory returned: an exported Durable Object class extends it. */\n readonly durableObject: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareWorkflowDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose `run(event, step)` each Workflow run calls. */\n readonly host: Type;\n /** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */\n readonly workflow: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareEntrypointDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose methods `methods` names. */\n readonly host: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */\n readonly entrypoint: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Worker entry is built from, for tools that load it outside a platform event. */\nexport interface CloudflareWorkerDescriptor {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Durable Object classes defined from the same {@link CloudflareApp}\n * (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in\n * definition order; empty for `createCloudflareWorker()`.\n */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /**\n * The service entrypoint classes defined from the app\n * (`VelaEntrypoint(app, Host, { rpc })`), in definition order.\n */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create()` of the Worker's root (the root module, with the\n * hosts of the app's Workflow and service entrypoint classes among its\n * providers) and `createOptions(env)`: the application without its Worker\n * handlers or the `configure` hook, which receives the Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */\nexport interface CloudflareWorker {\n fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;\n scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n /**\n * The Email Workers handler, present once a module imports `OnEmail` from\n * `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`\n * handlers, and rejects a message none of them accepts.\n */\n readonly email?: (\n message: ForwardableEmailMessage,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ) => Promise<void>;\n /**\n * The Tail Workers handler, present once a module imports `OnTail` from\n * `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers\n * and never rejects, even when the application fails to start (the error is\n * logged to the console, and the next batch retries).\n */\n readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;\n /**\n * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores\n * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.\n */\n readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;\n}\n\n/**\n * One Cloudflare application: a static root module and its options, shared\n * by the Worker's default export and every Durable Object, Workflow and\n * service entrypoint class defined from it. Create it once, at module scope\n * of the Worker entry, with {@link defineCloudflareApp}.\n */\nexport interface CloudflareApp {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Worker's handlers (`export default app.worker`): one application per\n * environment identity, built on the first event and shared by concurrent\n * cold events, the app's Workflows and its service entrypoints.\n */\n readonly worker: CloudflareWorker;\n /** The Durable Object classes defined from this app, in definition order. */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from this app, in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /** The service entrypoint classes defined from this app, in definition order. */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n}\n\n/** What an app definition records beyond its public members. */\ninterface AppState {\n readonly durableObjects: CloudflareDurableObjectDescriptor[];\n readonly workflows: CloudflareWorkflowDescriptor[];\n readonly entrypoints: CloudflareEntrypointDescriptor[];\n readonly application: (env: VelaEnv) => Promise<CloudflareApplication>;\n /** Whether the Worker started building an application: its providers are then fixed. */\n started: boolean;\n}\n\nconst states = new WeakMap<object, AppState>();\n\n/** Whether `value` is an app {@link defineCloudflareApp} returned. */\nexport function isCloudflareApp(value: unknown): value is CloudflareApp {\n return typeof value === 'object' && value !== null && states.has(value);\n}\n\nfunction stateOf(app: unknown, factory: string): AppState {\n const state = typeof app === 'object' && app !== null ? states.get(app) : undefined;\n if (state === undefined) {\n throw new TypeError(\n `${factory}() takes the app from defineCloudflareApp(AppModule, options), whose Worker ` +\n 'application it runs in: define the app once and pass it.',\n );\n }\n return state;\n}\n\n/**\n * @internal Record a Durable Object class defined from `app`, so the Worker\n * descriptor lists it. The `@velajs/cloudflare/durable-objects` factories call\n * it at class definition.\n */\nexport function registerDurableObject(\n app: CloudflareApp,\n descriptor: CloudflareDurableObjectDescriptor,\n): void {\n states.get(app)?.durableObjects.push(descriptor);\n}\n\n/** Hosts join the Worker's root providers, so they must be declared before it is built. */\nfunction assertNotStarted(state: AppState, factory: string, host: Type): void {\n if (!state.started) return;\n throw new Error(\n `${factory}(app, ${host.name}) was called after the app started building its Worker ` +\n 'application, whose providers are then fixed: define Workflow and service entrypoint ' +\n 'classes at module scope, in the module that defines the app.',\n );\n}\n\n/**\n * @internal Record a Workflow class defined from `app`: its host joins the\n * Worker application's root providers, and the Worker descriptor lists it.\n * `VelaWorkflow()` calls it at class definition; `app` is validated here.\n */\nexport function registerWorkflow(app: unknown, descriptor: CloudflareWorkflowDescriptor): void {\n const state = stateOf(app, 'VelaWorkflow');\n assertNotStarted(state, 'VelaWorkflow', descriptor.host);\n state.workflows.push(descriptor);\n}\n\n/**\n * @internal Record a service entrypoint class defined from `app`: its host\n * joins the Worker application's root providers, and the Worker descriptor\n * lists it. `VelaEntrypoint()` calls it at class definition; `app` is\n * validated here.\n */\nexport function registerEntrypoint(app: unknown, descriptor: CloudflareEntrypointDescriptor): void {\n const state = stateOf(app, 'VelaEntrypoint');\n assertNotStarted(state, 'VelaEntrypoint', descriptor.host);\n state.entrypoints.push(descriptor);\n}\n\n/**\n * @internal The Worker's application for `env`: the one its handlers use,\n * built on first use for each environment identity and shared by concurrent\n * events, so the app's Workflows and service entrypoints run in it too.\n */\nexport function cloudflareApplication(\n app: CloudflareApp,\n env: VelaEnv,\n): Promise<CloudflareApplication> {\n return stateOf(app, 'cloudflareApplication').application(env);\n}\n\n/**\n * Define one Cloudflare application from a static root module (a module class\n * or a `DynamicModule`) and its options. The Worker entry exports its Worker\n * and the Durable Object, Workflow and service entrypoint classes defined from\n * it, which share the root and the options: runtime `adapters` configure every\n * application and Durable Object context the app builds.\n *\n * ```ts\n * import { defineCloudflareApp } from '@velajs/cloudflare';\n * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';\n *\n * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });\n * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}\n * export default app.worker;\n * ```\n *\n * The Worker builds one application per environment identity. The app's\n * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in\n * that application, with their hosts added to the root module's providers;\n * each Durable Object instance boots its own application context. Declare the\n * classes in the module that defines the app: a class file importing the app\n * from the Worker entry would run before the entry defined it. Keep them in\n * the entry, or define the app in a module of its own that the entry and the\n * class files import. `createCloudflareWorker` is\n * `defineCloudflareApp(rootModule, options).worker`.\n */\nexport function defineCloudflareApp(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareApp {\n const { configure, ...appOptions } = options;\n const durableObjects: CloudflareDurableObjectDescriptor[] = [];\n const workflows: CloudflareWorkflowDescriptor[] = [];\n const entrypoints: CloudflareEntrypointDescriptor[] = [];\n // The Worker's root: the root module, with the hosts of the Workflow and\n // service entrypoint classes among its providers.\n const workerRoot = (): CloudflareRoot => {\n const hosts = [...new Set([...workflows, ...entrypoints].map(({ host }) => host))];\n return hosts.length === 0 ? rootModule : withRootProviders(rootModule, hosts);\n };\n // Weak keys stop this cache from retaining a replaced environment.\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(workerRoot(), { ...appOptions, env }),\n env,\n configure,\n );\n const state: AppState = {\n durableObjects,\n workflows,\n entrypoints,\n started: false,\n // Concurrent cold events share construction, including `configure`; a\n // failed construction is evicted so the next event can retry.\n application: (env) => {\n const existing = applications.get(env);\n if (existing) return existing;\n state.started = true;\n const pending = build(env);\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n },\n };\n const { application } = state;\n const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n durableObjects,\n workflows,\n entrypoints,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(workerRoot(), cloudflareCreateOptions({ ...appOptions, env })),\n };\n const worker: CloudflareWorker = {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\n },\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).queue(batch, env, ctx);\n },\n [CLOUDFLARE_WORKER]: descriptor,\n };\n // `email` and `tail` appear once a module imports their decorators.\n defineWorkerEvents(worker, application);\n const app: CloudflareApp = {\n rootModule,\n options,\n worker,\n durableObjects,\n workflows,\n entrypoints,\n };\n states.set(app, state);\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity: the Worker of\n * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share\n * construction, including `configure`; failed construction is evicted so the\n * next event can retry. Define the app with {@link defineCloudflareApp} when the\n * entry also exports Durable Object classes built from it.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n return defineCloudflareApp(rootModule, options).worker;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,CAAC,SAAS,UAAU,YAAY,MAAM,MAAM,WAAW,CAAC,CAC/F;CACA,KAAK,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