@velajs/cloudflare 1.31.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +154 -10
  3. package/dist/bindings.js +17 -1
  4. package/dist/bindings.js.map +1 -1
  5. package/dist/{cloudflare-factory-eGiet0mg.d.ts → cloudflare-application-CXDy9C1R.d.ts} +9 -98
  6. package/dist/cloudflare-application.js +8 -0
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +153 -20
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/durable-object/boot.js +76 -0
  12. package/dist/durable-object/boot.js.map +1 -0
  13. package/dist/durable-object/host-dispatch.js +134 -0
  14. package/dist/durable-object/host-dispatch.js.map +1 -0
  15. package/dist/durable-object/host-methods.js +47 -0
  16. package/dist/durable-object/host-methods.js.map +1 -0
  17. package/dist/durable-object/tokens.js +17 -0
  18. package/dist/durable-object/tokens.js.map +1 -0
  19. package/dist/durable-object/vela-durable-object.js +121 -0
  20. package/dist/durable-object/vela-durable-object.js.map +1 -0
  21. package/dist/durable-objects.d.ts +131 -9
  22. package/dist/durable-objects.js +3 -1
  23. package/dist/email/email-dispatch.js +65 -0
  24. package/dist/email/email-dispatch.js.map +1 -0
  25. package/dist/email/on-email.js +57 -0
  26. package/dist/email/on-email.js.map +1 -0
  27. package/dist/email.d.ts +51 -0
  28. package/dist/email.js +3 -0
  29. package/dist/entrypoint/vela-entrypoint.js +160 -0
  30. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  31. package/dist/entrypoints.d.ts +93 -0
  32. package/dist/entrypoints.js +2 -0
  33. package/dist/host/host-invoker.js +276 -0
  34. package/dist/host/host-invoker.js.map +1 -0
  35. package/dist/host/host-members.js +73 -0
  36. package/dist/host/host-members.js.map +1 -0
  37. package/dist/host-members-DECj_4yz.d.ts +13 -0
  38. package/dist/index.d.ts +74 -13
  39. package/dist/index.js +4 -3
  40. package/dist/root-module.js +19 -0
  41. package/dist/root-module.js.map +1 -0
  42. package/dist/rpc/entrypoint-error.js +145 -0
  43. package/dist/rpc/entrypoint-error.js.map +1 -0
  44. package/dist/services/kv-cache.store.js +4 -4
  45. package/dist/services/kv-cache.store.js.map +1 -1
  46. package/dist/tail/on-tail.js +46 -0
  47. package/dist/tail/on-tail.js.map +1 -0
  48. package/dist/tail/tail-dispatch.js +67 -0
  49. package/dist/tail/tail-dispatch.js.map +1 -0
  50. package/dist/tail.d.ts +39 -0
  51. package/dist/tail.js +2 -0
  52. package/dist/testing.d.ts +55 -3
  53. package/dist/testing.js +78 -1
  54. package/dist/testing.js.map +1 -1
  55. package/dist/websocket/binding-gateways.js +1 -1
  56. package/dist/websocket/binding-gateways.js.map +1 -1
  57. package/dist/websocket/do-bootstrap.js +40 -37
  58. package/dist/websocket/do-bootstrap.js.map +1 -1
  59. package/dist/websocket/websocket.durable-object.js +37 -8
  60. package/dist/websocket/websocket.durable-object.js.map +1 -1
  61. package/dist/worker-events.js +49 -0
  62. package/dist/worker-events.js.map +1 -0
  63. package/dist/workflow/vela-workflow.js +104 -0
  64. package/dist/workflow/vela-workflow.js.map +1 -0
  65. package/dist/workflows.d.ts +82 -0
  66. package/dist/workflows.js +2 -0
  67. package/package.json +23 -7
  68. package/dist/root-module-C23bUwt_.d.ts +0 -11
@@ -0,0 +1,241 @@
1
+ import { a as ScheduledEvent, t as CloudflareApplication } from "./cloudflare-application-CXDy9C1R.js";
2
+ import { CorsOptions, DynamicModule, GlobalPrefixOptions, Type, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
3
+ import { RuntimeAdapter } from "@velajs/vela/module-kit";
4
+ import { ExecutionContext } from "hono";
5
+ //#region src/root-module.d.ts
6
+ /**
7
+ * The root a Worker or Durable Object is built from: a module class or a
8
+ * `DynamicModule`, declared once at module scope. Configuration that needs
9
+ * bindings belongs in providers and `forRootAsync({ inject: [ENV] })`
10
+ * factories, which run for each application with that application's ENV.
11
+ */
12
+ type CloudflareRoot = Type | DynamicModule;
13
+ //#endregion
14
+ //#region src/cloudflare-factory.d.ts
15
+ interface CloudflareAppOptions {
16
+ globalPrefix?: string;
17
+ /** Routes served without the global prefix (`{ exclude }`). */
18
+ globalPrefixOptions?: GlobalPrefixOptions;
19
+ /** URI versioning: the version segment prefix (default `'v'`). */
20
+ versioning?: VersioningOptions;
21
+ security?: VelaSecurityOptions;
22
+ /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */
23
+ cors?: CorsOptions | boolean;
24
+ /** Further runtime adapters, composed after the Cloudflare adapter for each application. */
25
+ adapters?: RuntimeAdapter[];
26
+ }
27
+ interface CloudflareWorkerOptions extends CloudflareAppOptions {
28
+ /**
29
+ * Finish each application's HTTP surface, such as extra Hono routes, once per
30
+ * environment. It runs after the application is built and before any event,
31
+ * including concurrent cold events, reaches it; a throw fails that
32
+ * construction, and the next event retries. It must be synchronous and do no
33
+ * I/O (a returned promise fails the construction): read bindings in
34
+ * providers. Request middleware belongs in modules (`configure(consumer)`),
35
+ * which can inject `ENV`.
36
+ */
37
+ configure?(app: CloudflareApplication, env: VelaEnv): void;
38
+ }
39
+ interface CreateCloudflareAppOptions extends CloudflareAppOptions {
40
+ /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
41
+ env: VelaEnv;
42
+ }
43
+ /**
44
+ * Bind an application to one environment: seeded as the global ENV before
45
+ * provider factories and lifecycle hooks, and asserted on every request. The
46
+ * adapter also registers the Worker's platform wiring: `WebSocketModule`
47
+ * forwards each authenticated gateway upgrade to the room's Durable Object,
48
+ * and `LiveModule` sends invalidations there. It supplies the
49
+ * `InternalDispatcher` transport, so signed queue and schedule dispatch
50
+ * re-enter this application's routes, and reports, through the diagnostics
51
+ * policy, schedule declarations a cron trigger cannot honor and binding-backed
52
+ * gateways without `WebSocketModule`.
53
+ */
54
+ declare function cloudflareAdapter(options: {
55
+ env: VelaEnv;
56
+ }): RuntimeAdapter;
57
+ /**
58
+ * Build an application for one native Workers environment. Call inside a platform event.
59
+ * The root is static: a module class or a `DynamicModule` declared at module scope.
60
+ * Read bindings in providers (`@InjectEnv()`) and module factories
61
+ * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
62
+ */
63
+ declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
64
+ /**
65
+ * The well-known key under which a Worker entry (`defineCloudflareApp().worker`
66
+ * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:
67
+ * `Symbol.for('vela.cloudflare.worker')`.
68
+ */
69
+ declare const CLOUDFLARE_WORKER: unique symbol;
70
+ /**
71
+ * The well-known static key under which a Durable Object class that
72
+ * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every
73
+ * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:
74
+ * `Symbol.for('vela.cloudflare.durableObject')`.
75
+ */
76
+ declare const CLOUDFLARE_DURABLE_OBJECT: unique symbol;
77
+ /**
78
+ * The well-known static key under which a Workflow class that `VelaWorkflow()`
79
+ * returns (and every class extending it) carries its
80
+ * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.
81
+ */
82
+ declare const CLOUDFLARE_WORKFLOW: unique symbol;
83
+ /**
84
+ * The well-known static key under which a service entrypoint class that
85
+ * `VelaEntrypoint()` returns (and every class extending it) carries its
86
+ * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.
87
+ */
88
+ declare const CLOUDFLARE_ENTRYPOINT: unique symbol;
89
+ /** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */
90
+ interface CloudflareDurableObjectDescriptor {
91
+ /**
92
+ * `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are
93
+ * the host methods `rpc` names.
94
+ * `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.
95
+ */
96
+ readonly kind: 'host' | 'websocket';
97
+ readonly rootModule: CloudflareRoot;
98
+ /** The host class of a `host` Durable Object. */
99
+ readonly host?: Type;
100
+ /** The RPC methods the class exposes. */
101
+ readonly methods: readonly string[];
102
+ /** The class the factory returned: an exported Durable Object class extends it. */
103
+ readonly durableObject: abstract new (...args: never[]) => unknown;
104
+ }
105
+ /** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */
106
+ interface CloudflareWorkflowDescriptor {
107
+ readonly rootModule: CloudflareRoot;
108
+ /** The host class whose `run(event, step)` each Workflow run calls. */
109
+ readonly host: Type;
110
+ /** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */
111
+ readonly workflow: abstract new (...args: never[]) => unknown;
112
+ }
113
+ /** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */
114
+ interface CloudflareEntrypointDescriptor {
115
+ readonly rootModule: CloudflareRoot;
116
+ /** The host class whose methods `methods` names. */
117
+ readonly host: Type;
118
+ /** The RPC methods the class exposes. */
119
+ readonly methods: readonly string[];
120
+ /** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */
121
+ readonly entrypoint: abstract new (...args: never[]) => unknown;
122
+ }
123
+ /** What a Worker entry is built from, for tools that load it outside a platform event. */
124
+ interface CloudflareWorkerDescriptor {
125
+ readonly rootModule: CloudflareRoot;
126
+ readonly options: CloudflareWorkerOptions;
127
+ /**
128
+ * The Durable Object classes defined from the same {@link CloudflareApp}
129
+ * (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in
130
+ * definition order; empty for `createCloudflareWorker()`.
131
+ */
132
+ readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];
133
+ /** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */
134
+ readonly workflows: readonly CloudflareWorkflowDescriptor[];
135
+ /**
136
+ * The service entrypoint classes defined from the app
137
+ * (`VelaEntrypoint(app, Host, { rpc })`), in definition order.
138
+ */
139
+ readonly entrypoints: readonly CloudflareEntrypointDescriptor[];
140
+ /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */
141
+ createOptions(env: VelaEnv): VelaCreateOptions;
142
+ /**
143
+ * `VelaFactory.create()` of the Worker's root (the root module, with the
144
+ * hosts of the app's Workflow and service entrypoint classes among its
145
+ * providers) and `createOptions(env)`: the application without its Worker
146
+ * handlers or the `configure` hook, which receives the Workers application.
147
+ */
148
+ createApplication(env: VelaEnv): Promise<VelaApplication>;
149
+ }
150
+ /** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */
151
+ interface CloudflareWorker {
152
+ fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
153
+ scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
154
+ waitUntil: (promise: Promise<unknown>) => void;
155
+ }): Promise<void>;
156
+ queue(batch: {
157
+ queue: string;
158
+ messages: readonly unknown[];
159
+ }, env: VelaEnv, ctx: {
160
+ waitUntil: (promise: Promise<unknown>) => void;
161
+ }): Promise<void>;
162
+ /**
163
+ * The Email Workers handler, present once a module imports `OnEmail` from
164
+ * `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`
165
+ * handlers, and rejects a message none of them accepts.
166
+ */
167
+ readonly email?: (message: ForwardableEmailMessage, env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
168
+ /**
169
+ * The Tail Workers handler, present once a module imports `OnTail` from
170
+ * `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers
171
+ * and never rejects, even when the application fails to start (the error is
172
+ * logged to the console, and the next batch retries).
173
+ */
174
+ readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;
175
+ /**
176
+ * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
177
+ * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
178
+ */
179
+ readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;
180
+ }
181
+ /**
182
+ * One Cloudflare application: a static root module and its options, shared
183
+ * by the Worker's default export and every Durable Object, Workflow and
184
+ * service entrypoint class defined from it. Create it once, at module scope
185
+ * of the Worker entry, with {@link defineCloudflareApp}.
186
+ */
187
+ interface CloudflareApp {
188
+ readonly rootModule: CloudflareRoot;
189
+ readonly options: CloudflareWorkerOptions;
190
+ /**
191
+ * The Worker's handlers (`export default app.worker`): one application per
192
+ * environment identity, built on the first event and shared by concurrent
193
+ * cold events, the app's Workflows and its service entrypoints.
194
+ */
195
+ readonly worker: CloudflareWorker;
196
+ /** The Durable Object classes defined from this app, in definition order. */
197
+ readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];
198
+ /** The Workflow classes defined from this app, in definition order. */
199
+ readonly workflows: readonly CloudflareWorkflowDescriptor[];
200
+ /** The service entrypoint classes defined from this app, in definition order. */
201
+ readonly entrypoints: readonly CloudflareEntrypointDescriptor[];
202
+ }
203
+ /** Whether `value` is an app {@link defineCloudflareApp} returned. */
204
+ declare function isCloudflareApp(value: unknown): value is CloudflareApp;
205
+ /**
206
+ * Define one Cloudflare application from a static root module (a module class
207
+ * or a `DynamicModule`) and its options. The Worker entry exports its Worker
208
+ * and the Durable Object, Workflow and service entrypoint classes defined from
209
+ * it, which share the root and the options: runtime `adapters` configure every
210
+ * application and Durable Object context the app builds.
211
+ *
212
+ * ```ts
213
+ * import { defineCloudflareApp } from '@velajs/cloudflare';
214
+ * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';
215
+ *
216
+ * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });
217
+ * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
218
+ * export default app.worker;
219
+ * ```
220
+ *
221
+ * The Worker builds one application per environment identity. The app's
222
+ * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in
223
+ * that application, with their hosts added to the root module's providers;
224
+ * each Durable Object instance boots its own application context. Declare the
225
+ * classes in the module that defines the app: a class file importing the app
226
+ * from the Worker entry would run before the entry defined it. Keep them in
227
+ * the entry, or define the app in a module of its own that the entry and the
228
+ * class files import. `createCloudflareWorker` is
229
+ * `defineCloudflareApp(rootModule, options).worker`.
230
+ */
231
+ declare function defineCloudflareApp(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareApp;
232
+ /**
233
+ * Worker entrypoint with one bootstrap per environment identity: the Worker of
234
+ * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share
235
+ * construction, including `configure`; failed construction is evicted so the
236
+ * next event can retry. Define the app with {@link defineCloudflareApp} when the
237
+ * entry also exports Durable Object classes built from it.
238
+ */
239
+ declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareWorker;
240
+ //#endregion
241
+ 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 };
@@ -6,6 +6,8 @@ import { reportCloudflareScheduleDiagnostics } from "./schedule-diagnostics.js";
6
6
  import { reportUnservedGateways } from "./websocket/binding-gateways.js";
7
7
  import { workerWebSocketTransport } from "./websocket/worker-transport.js";
8
8
  import { workerLivePlatform } from "./websocket/live-driver.js";
9
+ import { defineWorkerEvents } from "./worker-events.js";
10
+ import { withRootProviders } from "./root-module.js";
9
11
  import { VelaFactory } from "@velajs/vela";
10
12
  //#region src/cloudflare-factory.ts
11
13
  function readStrings(meta, property) {
@@ -107,46 +109,156 @@ async function configureCloudflareApplication(app, env, configure) {
107
109
  return app;
108
110
  }
109
111
  /**
110
- * The well-known key under which a `createCloudflareWorker()` entry carries
111
- * its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.
112
+ * The well-known key under which a Worker entry (`defineCloudflareApp().worker`
113
+ * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:
114
+ * `Symbol.for('vela.cloudflare.worker')`.
112
115
  */
113
116
  const CLOUDFLARE_WORKER = Symbol.for("vela.cloudflare.worker");
114
117
  /**
115
- * Worker entrypoint with one bootstrap per environment identity. Concurrent cold
116
- * events share construction, including `configure`; failed construction is
117
- * evicted so the next event can retry. Weak keys stop this cache from
118
- * retaining a replaced environment.
118
+ * The well-known static key under which a Durable Object class that
119
+ * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every
120
+ * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:
121
+ * `Symbol.for('vela.cloudflare.durableObject')`.
119
122
  */
120
- function createCloudflareWorker(rootModule, options = {}) {
123
+ const CLOUDFLARE_DURABLE_OBJECT = Symbol.for("vela.cloudflare.durableObject");
124
+ /**
125
+ * The well-known static key under which a Workflow class that `VelaWorkflow()`
126
+ * returns (and every class extending it) carries its
127
+ * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.
128
+ */
129
+ const CLOUDFLARE_WORKFLOW = Symbol.for("vela.cloudflare.workflow");
130
+ /**
131
+ * The well-known static key under which a service entrypoint class that
132
+ * `VelaEntrypoint()` returns (and every class extending it) carries its
133
+ * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.
134
+ */
135
+ const CLOUDFLARE_ENTRYPOINT = Symbol.for("vela.cloudflare.entrypoint");
136
+ const states = /* @__PURE__ */ new WeakMap();
137
+ /** Whether `value` is an app {@link defineCloudflareApp} returned. */
138
+ function isCloudflareApp(value) {
139
+ return typeof value === "object" && value !== null && states.has(value);
140
+ }
141
+ function stateOf(app, factory) {
142
+ const state = typeof app === "object" && app !== null ? states.get(app) : void 0;
143
+ if (state === void 0) throw new TypeError(`${factory}() takes the app from defineCloudflareApp(AppModule, options), whose Worker application it runs in: define the app once and pass it.`);
144
+ return state;
145
+ }
146
+ /**
147
+ * @internal Record a Durable Object class defined from `app`, so the Worker
148
+ * descriptor lists it. The `@velajs/cloudflare/durable-objects` factories call
149
+ * it at class definition.
150
+ */
151
+ function registerDurableObject(app, descriptor) {
152
+ states.get(app)?.durableObjects.push(descriptor);
153
+ }
154
+ /** Hosts join the Worker's root providers, so they must be declared before it is built. */
155
+ function assertNotStarted(state, factory, host) {
156
+ if (!state.started) return;
157
+ throw new Error(`${factory}(app, ${host.name}) was called after the app started building its Worker application, whose providers are then fixed: define Workflow and service entrypoint classes at module scope, in the module that defines the app.`);
158
+ }
159
+ /**
160
+ * @internal Record a Workflow class defined from `app`: its host joins the
161
+ * Worker application's root providers, and the Worker descriptor lists it.
162
+ * `VelaWorkflow()` calls it at class definition; `app` is validated here.
163
+ */
164
+ function registerWorkflow(app, descriptor) {
165
+ const state = stateOf(app, "VelaWorkflow");
166
+ assertNotStarted(state, "VelaWorkflow", descriptor.host);
167
+ state.workflows.push(descriptor);
168
+ }
169
+ /**
170
+ * @internal Record a service entrypoint class defined from `app`: its host
171
+ * joins the Worker application's root providers, and the Worker descriptor
172
+ * lists it. `VelaEntrypoint()` calls it at class definition; `app` is
173
+ * validated here.
174
+ */
175
+ function registerEntrypoint(app, descriptor) {
176
+ const state = stateOf(app, "VelaEntrypoint");
177
+ assertNotStarted(state, "VelaEntrypoint", descriptor.host);
178
+ state.entrypoints.push(descriptor);
179
+ }
180
+ /**
181
+ * @internal The Worker's application for `env`: the one its handlers use,
182
+ * built on first use for each environment identity and shared by concurrent
183
+ * events, so the app's Workflows and service entrypoints run in it too.
184
+ */
185
+ function cloudflareApplication(app, env) {
186
+ return stateOf(app, "cloudflareApplication").application(env);
187
+ }
188
+ /**
189
+ * Define one Cloudflare application from a static root module (a module class
190
+ * or a `DynamicModule`) and its options. The Worker entry exports its Worker
191
+ * and the Durable Object, Workflow and service entrypoint classes defined from
192
+ * it, which share the root and the options: runtime `adapters` configure every
193
+ * application and Durable Object context the app builds.
194
+ *
195
+ * ```ts
196
+ * import { defineCloudflareApp } from '@velajs/cloudflare';
197
+ * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';
198
+ *
199
+ * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });
200
+ * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
201
+ * export default app.worker;
202
+ * ```
203
+ *
204
+ * The Worker builds one application per environment identity. The app's
205
+ * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in
206
+ * that application, with their hosts added to the root module's providers;
207
+ * each Durable Object instance boots its own application context. Declare the
208
+ * classes in the module that defines the app: a class file importing the app
209
+ * from the Worker entry would run before the entry defined it. Keep them in
210
+ * the entry, or define the app in a module of its own that the entry and the
211
+ * class files import. `createCloudflareWorker` is
212
+ * `defineCloudflareApp(rootModule, options).worker`.
213
+ */
214
+ function defineCloudflareApp(rootModule, options = {}) {
121
215
  const { configure, ...appOptions } = options;
216
+ const durableObjects = [];
217
+ const workflows = [];
218
+ const entrypoints = [];
219
+ const workerRoot = () => {
220
+ const hosts = [...new Set([...workflows, ...entrypoints].map(({ host }) => host))];
221
+ return hosts.length === 0 ? rootModule : withRootProviders(rootModule, hosts);
222
+ };
122
223
  const applications = /* @__PURE__ */ new WeakMap();
123
- const build = async (env) => configureCloudflareApplication(await createCloudflareApp(rootModule, {
224
+ const build = async (env) => configureCloudflareApplication(await createCloudflareApp(workerRoot(), {
124
225
  ...appOptions,
125
226
  env
126
227
  }), env, configure);
127
- const application = (env) => {
128
- const existing = applications.get(env);
129
- if (existing) return existing;
130
- const pending = build(env);
131
- applications.set(env, pending);
132
- pending.catch(() => {
133
- if (applications.get(env) === pending) applications.delete(env);
134
- });
135
- return pending;
228
+ const state = {
229
+ durableObjects,
230
+ workflows,
231
+ entrypoints,
232
+ started: false,
233
+ application: (env) => {
234
+ const existing = applications.get(env);
235
+ if (existing) return existing;
236
+ state.started = true;
237
+ const pending = build(env);
238
+ applications.set(env, pending);
239
+ pending.catch(() => {
240
+ if (applications.get(env) === pending) applications.delete(env);
241
+ });
242
+ return pending;
243
+ }
136
244
  };
245
+ const { application } = state;
137
246
  const descriptor = {
138
247
  rootModule,
139
248
  options,
249
+ durableObjects,
250
+ workflows,
251
+ entrypoints,
140
252
  createOptions: (env) => cloudflareCreateOptions({
141
253
  ...appOptions,
142
254
  env
143
255
  }),
144
- createApplication: (env) => VelaFactory.create(rootModule, cloudflareCreateOptions({
256
+ createApplication: (env) => VelaFactory.create(workerRoot(), cloudflareCreateOptions({
145
257
  ...appOptions,
146
258
  env
147
259
  }))
148
260
  };
149
- return {
261
+ const worker = {
150
262
  async fetch(request, env, ctx) {
151
263
  return (await application(env)).fetch(request, env, ctx);
152
264
  },
@@ -158,8 +270,29 @@ function createCloudflareWorker(rootModule, options = {}) {
158
270
  },
159
271
  [CLOUDFLARE_WORKER]: descriptor
160
272
  };
273
+ defineWorkerEvents(worker, application);
274
+ const app = {
275
+ rootModule,
276
+ options,
277
+ worker,
278
+ durableObjects,
279
+ workflows,
280
+ entrypoints
281
+ };
282
+ states.set(app, state);
283
+ return app;
284
+ }
285
+ /**
286
+ * Worker entrypoint with one bootstrap per environment identity: the Worker of
287
+ * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share
288
+ * construction, including `configure`; failed construction is evicted so the
289
+ * next event can retry. Define the app with {@link defineCloudflareApp} when the
290
+ * entry also exports Durable Object classes built from it.
291
+ */
292
+ function createCloudflareWorker(rootModule, options = {}) {
293
+ return defineCloudflareApp(rootModule, options).worker;
161
294
  }
162
295
  //#endregion
163
- export { CLOUDFLARE_WORKER, cloudflareAdapter, cloudflareCreateOptions, configureCloudflareApplication, createCloudflareApp, createCloudflareWorker };
296
+ export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, cloudflareApplication, cloudflareCreateOptions, configureCloudflareApplication, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, registerDurableObject, registerEntrypoint, registerWorkflow };
164
297
 
165
298
  //# 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 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 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 `createCloudflareWorker()` entry carries\n * its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\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 /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create(rootModule, createOptions(env))`: the application\n * without its Worker handlers or the `configure` hook, which receives the\n * Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a `createCloudflareWorker()` entry. */\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 * 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 * Worker entrypoint with one bootstrap per environment identity. Concurrent cold\n * events share construction, including `configure`; failed construction is\n * evicted so the next event can retry. Weak keys stop this cache from\n * retaining a replaced environment.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n const { configure, ...appOptions } = options;\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(rootModule, { ...appOptions, env }),\n env,\n configure,\n );\n const application = (env: VelaEnv): Promise<CloudflareApplication> => {\n const existing = applications.get(env);\n if (existing) return existing;\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 const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(rootModule, 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 return worker;\n}\n"],"mappings":";;;;;;;;;;AAqDA,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;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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;CAEX;AACd"}
1
+ {"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n CorsOptions,\n GlobalPrefixOptions,\n Type,\n VelaApplication,\n VelaCreateOptions,\n VelaEnv,\n VelaSecurityOptions,\n VersioningOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment } from './environment';\nimport { registerCloudflarePlatform } from './platform';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { reportUnservedGateways } from './websocket/binding-gateways';\nimport { workerLivePlatform } from './websocket/live-driver';\nimport { workerWebSocketTransport } from './websocket/worker-transport';\nimport { defineWorkerEvents } from './worker-events';\nimport { withRootProviders, type CloudflareRoot } from './root-module';\n\nexport interface CloudflareAppOptions {\n globalPrefix?: string;\n /** Routes served without the global prefix (`{ exclude }`). */\n globalPrefixOptions?: GlobalPrefixOptions;\n /** URI versioning: the version segment prefix (default `'v'`). */\n versioning?: VersioningOptions;\n security?: VelaSecurityOptions;\n /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */\n cors?: CorsOptions | boolean;\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CloudflareWorkerOptions extends CloudflareAppOptions {\n /**\n * Finish each application's HTTP surface, such as extra Hono routes, once per\n * environment. It runs after the application is built and before any event,\n * including concurrent cold events, reaches it; a throw fails that\n * construction, and the next event retries. It must be synchronous and do no\n * I/O (a returned promise fails the construction): read bindings in\n * providers. Request middleware belongs in modules (`configure(consumer)`),\n * which can inject `ENV`.\n */\n configure?(app: CloudflareApplication, env: VelaEnv): void;\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareAppOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.registerQueue({ consumer: '${queue}' }) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also registers the Worker's platform wiring: `WebSocketModule`\n * forwards each authenticated gateway upgrade to the room's Durable Object,\n * and `LiveModule` sends invalidations there. It supplies the\n * `InternalDispatcher` transport, so signed queue and schedule dispatch\n * re-enter this application's routes, and reports, through the diagnostics\n * policy, schedule declarations a cron trigger cannot honor and binding-backed\n * gateways without `WebSocketModule`.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n // Cloudflare attests the client address in this header. Read directly:\n // hono/cloudflare-workers would also load its WebSocket upgrade helper.\n getClientIp: (c) => c.req.header('cf-connecting-ip') ?? null,\n configureContainer: (container) => {\n registerCloudflarePlatform(container, env, {\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n });\n registerScheduledEventSeed(container);\n },\n onBootstrap: ({ app, container, discovery }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n reportUnservedGateways(container, discovery);\n },\n };\n}\n\n/**\n * The `VelaFactory.create()` options an application for `options.env` is built\n * with: that environment (seeded as ENV and sent by test clients as `c.env`),\n * the Cloudflare adapter bound to it, then any further adapters.\n */\nexport function cloudflareCreateOptions(options: CreateCloudflareAppOptions): VelaCreateOptions {\n return {\n env: options.env,\n globalPrefix: options.globalPrefix,\n globalPrefixOptions: options.globalPrefixOptions,\n versioning: options.versioning,\n security: options.security,\n cors: options.cors,\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));\n return new CloudflareApplication(velaApp, options.env);\n}\n\n/**\n * Run a Worker's `configure` hook on the application built for `env`, as\n * `createCloudflareWorker()` does before any event reaches it: a throw or a\n * returned promise closes the application and fails the construction.\n */\nexport async function configureCloudflareApplication(\n app: CloudflareApplication,\n env: VelaEnv,\n configure: CloudflareWorkerOptions['configure'],\n): Promise<CloudflareApplication> {\n if (!configure) return app;\n try {\n const result: unknown = configure(app, env);\n if (result instanceof Promise) {\n // Observe the rejected work; the construction fails either way.\n result.catch(() => {});\n throw new TypeError(\n 'createCloudflareWorker configure must finish synchronously: it runs before any ' +\n 'event reaches the application, so read bindings and perform I/O in providers.',\n );\n }\n } catch (error) {\n await app.close().catch(() => {});\n throw error;\n }\n return app;\n}\n\n/**\n * The well-known key under which a Worker entry (`defineCloudflareApp().worker`\n * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:\n * `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\n\n/**\n * The well-known static key under which a Durable Object class that\n * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every\n * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:\n * `Symbol.for('vela.cloudflare.durableObject')`.\n */\nexport const CLOUDFLARE_DURABLE_OBJECT: unique symbol = Symbol.for('vela.cloudflare.durableObject');\n\n/**\n * The well-known static key under which a Workflow class that `VelaWorkflow()`\n * returns (and every class extending it) carries its\n * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.\n */\nexport const CLOUDFLARE_WORKFLOW: unique symbol = Symbol.for('vela.cloudflare.workflow');\n\n/**\n * The well-known static key under which a service entrypoint class that\n * `VelaEntrypoint()` returns (and every class extending it) carries its\n * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.\n */\nexport const CLOUDFLARE_ENTRYPOINT: unique symbol = Symbol.for('vela.cloudflare.entrypoint');\n\n/** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareDurableObjectDescriptor {\n /**\n * `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are\n * the host methods `rpc` names.\n * `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.\n */\n readonly kind: 'host' | 'websocket';\n readonly rootModule: CloudflareRoot;\n /** The host class of a `host` Durable Object. */\n readonly host?: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class the factory returned: an exported Durable Object class extends it. */\n readonly durableObject: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareWorkflowDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose `run(event, step)` each Workflow run calls. */\n readonly host: Type;\n /** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */\n readonly workflow: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareEntrypointDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose methods `methods` names. */\n readonly host: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */\n readonly entrypoint: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Worker entry is built from, for tools that load it outside a platform event. */\nexport interface CloudflareWorkerDescriptor {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Durable Object classes defined from the same {@link CloudflareApp}\n * (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in\n * definition order; empty for `createCloudflareWorker()`.\n */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /**\n * The service entrypoint classes defined from the app\n * (`VelaEntrypoint(app, Host, { rpc })`), in definition order.\n */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create()` of the Worker's root (the root module, with the\n * hosts of the app's Workflow and service entrypoint classes among its\n * providers) and `createOptions(env)`: the application without its Worker\n * handlers or the `configure` hook, which receives the Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */\nexport interface CloudflareWorker {\n fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;\n scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n /**\n * The Email Workers handler, present once a module imports `OnEmail` from\n * `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`\n * handlers, and rejects a message none of them accepts.\n */\n readonly email?: (\n message: ForwardableEmailMessage,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ) => Promise<void>;\n /**\n * The Tail Workers handler, present once a module imports `OnTail` from\n * `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers\n * and never rejects, even when the application fails to start (the error is\n * logged to the console, and the next batch retries).\n */\n readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;\n /**\n * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores\n * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.\n */\n readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;\n}\n\n/**\n * One Cloudflare application: a static root module and its options, shared\n * by the Worker's default export and every Durable Object, Workflow and\n * service entrypoint class defined from it. Create it once, at module scope\n * of the Worker entry, with {@link defineCloudflareApp}.\n */\nexport interface CloudflareApp {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Worker's handlers (`export default app.worker`): one application per\n * environment identity, built on the first event and shared by concurrent\n * cold events, the app's Workflows and its service entrypoints.\n */\n readonly worker: CloudflareWorker;\n /** The Durable Object classes defined from this app, in definition order. */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from this app, in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /** The service entrypoint classes defined from this app, in definition order. */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n}\n\n/** What an app definition records beyond its public members. */\ninterface AppState {\n readonly durableObjects: CloudflareDurableObjectDescriptor[];\n readonly workflows: CloudflareWorkflowDescriptor[];\n readonly entrypoints: CloudflareEntrypointDescriptor[];\n readonly application: (env: VelaEnv) => Promise<CloudflareApplication>;\n /** Whether the Worker started building an application: its providers are then fixed. */\n started: boolean;\n}\n\nconst states = new WeakMap<object, AppState>();\n\n/** Whether `value` is an app {@link defineCloudflareApp} returned. */\nexport function isCloudflareApp(value: unknown): value is CloudflareApp {\n return typeof value === 'object' && value !== null && states.has(value);\n}\n\nfunction stateOf(app: unknown, factory: string): AppState {\n const state = typeof app === 'object' && app !== null ? states.get(app) : undefined;\n if (state === undefined) {\n throw new TypeError(\n `${factory}() takes the app from defineCloudflareApp(AppModule, options), whose Worker ` +\n 'application it runs in: define the app once and pass it.',\n );\n }\n return state;\n}\n\n/**\n * @internal Record a Durable Object class defined from `app`, so the Worker\n * descriptor lists it. The `@velajs/cloudflare/durable-objects` factories call\n * it at class definition.\n */\nexport function registerDurableObject(\n app: CloudflareApp,\n descriptor: CloudflareDurableObjectDescriptor,\n): void {\n states.get(app)?.durableObjects.push(descriptor);\n}\n\n/** Hosts join the Worker's root providers, so they must be declared before it is built. */\nfunction assertNotStarted(state: AppState, factory: string, host: Type): void {\n if (!state.started) return;\n throw new Error(\n `${factory}(app, ${host.name}) was called after the app started building its Worker ` +\n 'application, whose providers are then fixed: define Workflow and service entrypoint ' +\n 'classes at module scope, in the module that defines the app.',\n );\n}\n\n/**\n * @internal Record a Workflow class defined from `app`: its host joins the\n * Worker application's root providers, and the Worker descriptor lists it.\n * `VelaWorkflow()` calls it at class definition; `app` is validated here.\n */\nexport function registerWorkflow(app: unknown, descriptor: CloudflareWorkflowDescriptor): void {\n const state = stateOf(app, 'VelaWorkflow');\n assertNotStarted(state, 'VelaWorkflow', descriptor.host);\n state.workflows.push(descriptor);\n}\n\n/**\n * @internal Record a service entrypoint class defined from `app`: its host\n * joins the Worker application's root providers, and the Worker descriptor\n * lists it. `VelaEntrypoint()` calls it at class definition; `app` is\n * validated here.\n */\nexport function registerEntrypoint(app: unknown, descriptor: CloudflareEntrypointDescriptor): void {\n const state = stateOf(app, 'VelaEntrypoint');\n assertNotStarted(state, 'VelaEntrypoint', descriptor.host);\n state.entrypoints.push(descriptor);\n}\n\n/**\n * @internal The Worker's application for `env`: the one its handlers use,\n * built on first use for each environment identity and shared by concurrent\n * events, so the app's Workflows and service entrypoints run in it too.\n */\nexport function cloudflareApplication(\n app: CloudflareApp,\n env: VelaEnv,\n): Promise<CloudflareApplication> {\n return stateOf(app, 'cloudflareApplication').application(env);\n}\n\n/**\n * Define one Cloudflare application from a static root module (a module class\n * or a `DynamicModule`) and its options. The Worker entry exports its Worker\n * and the Durable Object, Workflow and service entrypoint classes defined from\n * it, which share the root and the options: runtime `adapters` configure every\n * application and Durable Object context the app builds.\n *\n * ```ts\n * import { defineCloudflareApp } from '@velajs/cloudflare';\n * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';\n *\n * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });\n * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}\n * export default app.worker;\n * ```\n *\n * The Worker builds one application per environment identity. The app's\n * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in\n * that application, with their hosts added to the root module's providers;\n * each Durable Object instance boots its own application context. Declare the\n * classes in the module that defines the app: a class file importing the app\n * from the Worker entry would run before the entry defined it. Keep them in\n * the entry, or define the app in a module of its own that the entry and the\n * class files import. `createCloudflareWorker` is\n * `defineCloudflareApp(rootModule, options).worker`.\n */\nexport function defineCloudflareApp(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareApp {\n const { configure, ...appOptions } = options;\n const durableObjects: CloudflareDurableObjectDescriptor[] = [];\n const workflows: CloudflareWorkflowDescriptor[] = [];\n const entrypoints: CloudflareEntrypointDescriptor[] = [];\n // The Worker's root: the root module, with the hosts of the Workflow and\n // service entrypoint classes among its providers.\n const workerRoot = (): CloudflareRoot => {\n const hosts = [...new Set([...workflows, ...entrypoints].map(({ host }) => host))];\n return hosts.length === 0 ? rootModule : withRootProviders(rootModule, hosts);\n };\n // Weak keys stop this cache from retaining a replaced environment.\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(workerRoot(), { ...appOptions, env }),\n env,\n configure,\n );\n const state: AppState = {\n durableObjects,\n workflows,\n entrypoints,\n started: false,\n // Concurrent cold events share construction, including `configure`; a\n // failed construction is evicted so the next event can retry.\n application: (env) => {\n const existing = applications.get(env);\n if (existing) return existing;\n state.started = true;\n const pending = build(env);\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n },\n };\n const { application } = state;\n const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n durableObjects,\n workflows,\n entrypoints,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(workerRoot(), cloudflareCreateOptions({ ...appOptions, env })),\n };\n const worker: CloudflareWorker = {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\n },\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).queue(batch, env, ctx);\n },\n [CLOUDFLARE_WORKER]: descriptor,\n };\n // `email` and `tail` appear once a module imports their decorators.\n defineWorkerEvents(worker, application);\n const app: CloudflareApp = {\n rootModule,\n options,\n worker,\n durableObjects,\n workflows,\n entrypoints,\n };\n states.set(app, state);\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity: the Worker of\n * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share\n * construction, including `configure`; failed construction is evicted so the\n * next event can retry. Define the app with {@link defineCloudflareApp} when the\n * entry also exports Durable Object classes built from it.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n return defineCloudflareApp(rootModule, options).worker;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,CAAC,SAAS,UAAU,YAAY,MAAM,MAAM,WAAW,CAAC,CAC/F;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,UAAU,GAAG;EAClD,MAAM,CAAC,SAAS,YAAY,MAAM,MAAM,WAAW;EACnD,IAAI,UAAU,KAAA,KAAa,OAAO,IAAI,KAAK,GACzC,MAAM,IAAI,MACR,2CAA2C,MAAM,qBAAqB,MAAM,kDAChC,MAAM,oCACpD;CAEJ;AACF;;;;;;;;;;;;AAaA,SAAgB,k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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"}
@@ -0,0 +1,76 @@
1
+ import { registerCloudflarePlatform } from "../platform.js";
2
+ import { workerWebSocketTransport } from "../websocket/worker-transport.js";
3
+ import { workerLivePlatform } from "../websocket/live-driver.js";
4
+ import { withRootProviders } from "../root-module.js";
5
+ import { isCloudflareApp } from "../cloudflare-factory.js";
6
+ import { internalEntrypointError } from "../rpc/entrypoint-error.js";
7
+ import { DO_ID, DO_STATE, DO_STORAGE } from "./tokens.js";
8
+ import { VelaFactory, defineProvider } from "@velajs/vela";
9
+ //#region src/durable-object/boot.ts
10
+ /** @internal */
11
+ function durableObjectDefinition(root) {
12
+ if (isCloudflareApp(root)) return {
13
+ rootModule: root.rootModule,
14
+ adapters: root.options.adapters ?? [],
15
+ app: root
16
+ };
17
+ return {
18
+ rootModule: root,
19
+ adapters: []
20
+ };
21
+ }
22
+ /**
23
+ * @internal The root a host Durable Object boots: `root` with `host` added to
24
+ * its own providers, so the host injects what the root module can see.
25
+ */
26
+ function withDurableObjectHost(root, host) {
27
+ return withRootProviders(root, [host]);
28
+ }
29
+ /**
30
+ * @internal Boot the application context of one Durable Object instance with
31
+ * the production bootstrap (`VelaFactory.createApplicationContext`): no HTTP
32
+ * routes, its environment seeded as `ENV`, its platform and its native state
33
+ * registered before any provider constructs, then the runtime adapters.
34
+ */
35
+ function createDurableObjectContext(root, options) {
36
+ const { env, state } = options;
37
+ const platform = options.platform ?? ((container) => ({
38
+ websocket: workerWebSocketTransport(env),
39
+ live: workerLivePlatform(env, container)
40
+ }));
41
+ return VelaFactory.createApplicationContext(root, { configureContainer: async (container) => {
42
+ registerCloudflarePlatform(container, env, platform(container));
43
+ if (state) {
44
+ container.register(defineProvider(DO_STATE, { useValue: state }));
45
+ container.register(defineProvider(DO_STORAGE, { useValue: state.storage }));
46
+ container.register(defineProvider(DO_ID, { useValue: state.id }));
47
+ container.markGlobalToken(DO_STATE);
48
+ container.markGlobalToken(DO_STORAGE);
49
+ container.markGlobalToken(DO_ID);
50
+ }
51
+ for (const adapter of options.adapters ?? []) await adapter.configureContainer?.(container);
52
+ } });
53
+ }
54
+ /**
55
+ * @internal Boot a Durable Object instance under `blockConcurrencyWhile`, so
56
+ * no event runs before it is ready. A failure is logged, and resets the
57
+ * object (the next event boots it again); workerd hands the callback's
58
+ * rejection to every waiting caller, so they receive only a redacted
59
+ * `EntrypointError`, never the startup error itself.
60
+ */
61
+ function startDurableObject(state, name, boot) {
62
+ const ready = state.blockConcurrencyWhile(async () => {
63
+ try {
64
+ return await boot();
65
+ } catch (error) {
66
+ console.error(`[vela] Durable Object ${name} failed to start:`, error);
67
+ throw internalEntrypointError();
68
+ }
69
+ });
70
+ ready.catch(() => {});
71
+ return ready;
72
+ }
73
+ //#endregion
74
+ export { createDurableObjectContext, durableObjectDefinition, startDurableObject, withDurableObjectHost };
75
+
76
+ //# sourceMappingURL=boot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"boot.js","names":[],"sources":["../../src/durable-object/boot.ts"],"sourcesContent":["import { VelaFactory, defineProvider } from '@velajs/vela';\nimport type { DynamicModule, Type, VelaApplicationContext, VelaEnv } from '@velajs/vela';\nimport type { Container, RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { isCloudflareApp, type CloudflareApp } from '../cloudflare-factory';\nimport { registerCloudflarePlatform, type CloudflarePlatform } from '../platform';\nimport { withRootProviders, type CloudflareRoot } from '../root-module';\nimport { workerLivePlatform } from '../websocket/live-driver';\nimport { workerWebSocketTransport } from '../websocket/worker-transport';\nimport { internalEntrypointError } from '../rpc/entrypoint-error';\nimport { DO_ID, DO_STATE, DO_STORAGE } from './tokens';\n\n/**\n * What a Durable Object class is built from: a static root module (a module\n * class or a `DynamicModule`), or an app from `defineCloudflareApp`, whose\n * root and runtime adapters the object shares with the Worker.\n */\nexport type DurableObjectRoot = CloudflareRoot | CloudflareApp;\n\n/** @internal The root, adapters and app a Durable Object class is defined from. */\nexport interface DurableObjectDefinition {\n readonly rootModule: CloudflareRoot;\n readonly adapters: readonly RuntimeAdapter[];\n readonly app?: CloudflareApp;\n}\n\n/** @internal */\nexport function durableObjectDefinition(root: DurableObjectRoot): DurableObjectDefinition {\n if (isCloudflareApp(root)) {\n return { rootModule: root.rootModule, adapters: root.options.adapters ?? [], app: root };\n }\n return { rootModule: root, adapters: [] };\n}\n\n/** @internal Options of {@link createDurableObjectContext}. */\nexport interface DurableObjectContextOptions {\n readonly env: VelaEnv;\n /** Runtime adapters whose `configureContainer` runs in the object, after its platform. */\n readonly adapters?: readonly RuntimeAdapter[];\n /** This object's native state, injected as `DO_STATE`, `DO_STORAGE` and `DO_ID`. */\n readonly state?: DurableObjectState;\n /**\n * How the application reaches WebSocket rooms and live invalidation from\n * this object. Defaults to the Worker's: pushes and invalidations go to each\n * gateway room's Durable Object through its binding.\n */\n readonly platform?: (container: Container) => CloudflarePlatform;\n}\n\n/**\n * @internal The root a host Durable Object boots: `root` with `host` added to\n * its own providers, so the host injects what the root module can see.\n */\nexport function withDurableObjectHost(root: CloudflareRoot, host: Type): DynamicModule {\n return withRootProviders(root, [host]);\n}\n\n/**\n * @internal Boot the application context of one Durable Object instance with\n * the production bootstrap (`VelaFactory.createApplicationContext`): no HTTP\n * routes, its environment seeded as `ENV`, its platform and its native state\n * registered before any provider constructs, then the runtime adapters.\n */\nexport function createDurableObjectContext(\n root: CloudflareRoot,\n options: DurableObjectContextOptions,\n): Promise<VelaApplicationContext> {\n const { env, state } = options;\n const platform =\n options.platform ??\n ((container: Container): CloudflarePlatform => ({\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n }));\n return VelaFactory.createApplicationContext(root, {\n configureContainer: async (container) => {\n registerCloudflarePlatform(container, env, platform(container));\n if (state) {\n container.register(defineProvider(DO_STATE, { useValue: state }));\n container.register(defineProvider(DO_STORAGE, { useValue: state.storage }));\n container.register(defineProvider(DO_ID, { useValue: state.id }));\n container.markGlobalToken(DO_STATE);\n container.markGlobalToken(DO_STORAGE);\n container.markGlobalToken(DO_ID);\n }\n for (const adapter of options.adapters ?? []) {\n // Adapters configure the container in order, as for the Worker.\n // eslint-disable-next-line no-await-in-loop\n await adapter.configureContainer?.(container);\n }\n },\n });\n}\n\n/**\n * @internal Boot a Durable Object instance under `blockConcurrencyWhile`, so\n * no event runs before it is ready. A failure is logged, and resets the\n * object (the next event boots it again); workerd hands the callback's\n * rejection to every waiting caller, so they receive only a redacted\n * `EntrypointError`, never the startup error itself.\n */\nexport function startDurableObject<T>(\n state: Pick<DurableObjectState, 'blockConcurrencyWhile'>,\n name: string,\n boot: () => Promise<T>,\n): Promise<T> {\n const ready = state.blockConcurrencyWhile(async () => {\n try {\n return await boot();\n } catch (error) {\n console.error(`[vela] Durable Object ${name} failed to start:`, error);\n throw internalEntrypointError();\n }\n });\n // Every handler awaits it; this observes a failure no handler has awaited yet.\n ready.catch(() => {});\n return ready;\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAgB,wBAAwB,MAAkD;CACxF,IAAI,gBAAgB,IAAI,GACtB,OAAO;EAAE,YAAY,KAAK;EAAY,UAAU,KAAK,QAAQ,YAAY,CAAC;EAAG,KAAK;CAAK;CAEzF,OAAO;EAAE,YAAY;EAAM,UAAU,CAAC;CAAE;AAC1C;;;;;AAqBA,SAAgB,sBAAsB,MAAsB,MAA2B;CACrF,OAAO,kB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