@velajs/cloudflare 1.30.0 → 1.32.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 +174 -0
- package/README.md +407 -77
- package/dist/bindings.js +93 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
- package/dist/cloudflare-application.js +15 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
- package/dist/cloudflare-factory.js +227 -38
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-object/boot.js +76 -0
- package/dist/durable-object/boot.js.map +1 -0
- package/dist/durable-object/host-dispatch.js +134 -0
- package/dist/durable-object/host-dispatch.js.map +1 -0
- package/dist/durable-object/host-methods.js +47 -0
- package/dist/durable-object/host-methods.js.map +1 -0
- package/dist/durable-object/tokens.js +17 -0
- package/dist/durable-object/tokens.js.map +1 -0
- package/dist/durable-object/vela-durable-object.js +121 -0
- package/dist/durable-object/vela-durable-object.js.map +1 -0
- package/dist/durable-objects.d.ts +136 -10
- package/dist/durable-objects.js +3 -1
- package/dist/email/email-dispatch.js +65 -0
- package/dist/email/email-dispatch.js.map +1 -0
- package/dist/email/on-email.js +57 -0
- package/dist/email/on-email.js.map +1 -0
- package/dist/email.d.ts +51 -0
- package/dist/email.js +3 -0
- package/dist/entrypoint/vela-entrypoint.js +160 -0
- package/dist/entrypoint/vela-entrypoint.js.map +1 -0
- package/dist/entrypoints.d.ts +93 -0
- package/dist/entrypoints.js +2 -0
- package/dist/host/host-invoker.js +276 -0
- package/dist/host/host-invoker.js.map +1 -0
- package/dist/host/host-members.js +73 -0
- package/dist/host/host-members.js.map +1 -0
- package/dist/host-members-DECj_4yz.d.ts +13 -0
- package/dist/index.d.ts +211 -445
- package/dist/index.js +8 -13
- package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +7 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
- package/dist/root-module.js +19 -0
- package/dist/root-module.js.map +1 -0
- package/dist/rpc/entrypoint-error.js +145 -0
- package/dist/rpc/entrypoint-error.js.map +1 -0
- package/dist/schedule-diagnostics.js +8 -15
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/services/kv-cache.store.js +33 -7
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/storage/r2-storage.js +30 -0
- package/dist/storage/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.js +2 -0
- package/dist/tail/on-tail.js +46 -0
- package/dist/tail/on-tail.js.map +1 -0
- package/dist/tail/tail-dispatch.js +67 -0
- package/dist/tail/tail-dispatch.js.map +1 -0
- package/dist/tail.d.ts +39 -0
- package/dist/tail.js +2 -0
- package/dist/testing.d.ts +148 -0
- package/dist/testing.js +188 -0
- package/dist/testing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +3 -1
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +64 -40
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/do-live.js +49 -90
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-state.js.map +1 -1
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +11 -1
- package/dist/websocket/room-id.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +51 -18
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- package/dist/worker-events.js +49 -0
- package/dist/worker-events.js.map +1 -0
- package/dist/workflow/vela-workflow.js +104 -0
- package/dist/workflow/vela-workflow.js.map +1 -0
- package/dist/workflows.d.ts +82 -0
- package/dist/workflows.js +2 -0
- package/package.json +39 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
- package/dist/storage/r2-storage.driver.js +0 -67
- package/dist/storage/r2-storage.driver.js.map +0 -1
- package/dist/storage/storage-key-claim.js +0 -74
- package/dist/storage/storage-key-claim.js.map +0 -1
- package/dist/storage/storage-manager.service.js +0 -38
- package/dist/storage/storage-manager.service.js.map +0 -1
- package/dist/storage/storage.controller.js +0 -64
- package/dist/storage/storage.controller.js.map +0 -1
- package/dist/storage/storage.module.js +0 -25
- package/dist/storage/storage.module.js.map +0 -1
- package/dist/storage/storage.service.js +0 -64
- package/dist/storage/storage.service.js.map +0 -1
- package/dist/storage/storage.tokens.js +0 -7
- package/dist/storage/storage.tokens.js.map +0 -1
- package/dist/websocket/broadcast.js +0 -32
- package/dist/websocket/broadcast.js.map +0 -1
- package/dist/websocket/cloudflare-websocket.module.js +0 -25
- package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
- package/dist/websocket/websocket-routing.js +0 -133
- package/dist/websocket/websocket-routing.js.map +0 -1
- package/dist/websocket/ws-server-holder.js +0 -38
- package/dist/websocket/ws-server-holder.js.map +0 -1
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { assertCloudflareEnvironment, registerCloudflareEnvironment } from "./environment.js";
|
|
1
|
+
import { assertCloudflareEnvironment } from "./environment.js";
|
|
3
2
|
import { registerScheduledEventSeed } from "./scheduled-event.js";
|
|
4
3
|
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
4
|
+
import { registerCloudflarePlatform } from "./platform.js";
|
|
5
5
|
import { reportCloudflareScheduleDiagnostics } from "./schedule-diagnostics.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { reportUnservedGateways } from "./websocket/binding-gateways.js";
|
|
7
|
+
import { workerWebSocketTransport } from "./websocket/worker-transport.js";
|
|
8
|
+
import { workerLivePlatform } from "./websocket/live-driver.js";
|
|
9
|
+
import { defineWorkerEvents } from "./worker-events.js";
|
|
10
|
+
import { withRootProviders } from "./root-module.js";
|
|
8
11
|
import { VelaFactory } from "@velajs/vela";
|
|
9
12
|
//#region src/cloudflare-factory.ts
|
|
10
13
|
function readStrings(meta, property) {
|
|
@@ -28,9 +31,13 @@ function assertQueueConsumerOwnership(entrypoints) {
|
|
|
28
31
|
/**
|
|
29
32
|
* Bind an application to one environment: seeded as the global ENV before
|
|
30
33
|
* provider factories and lifecycle hooks, and asserted on every request. The
|
|
31
|
-
* adapter also
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
+
* adapter also registers the Worker's platform wiring: `WebSocketModule`
|
|
35
|
+
* forwards each authenticated gateway upgrade to the room's Durable Object,
|
|
36
|
+
* and `LiveModule` sends invalidations there. It supplies the
|
|
37
|
+
* `InternalDispatcher` transport, so signed queue and schedule dispatch
|
|
38
|
+
* re-enter this application's routes, and reports, through the diagnostics
|
|
39
|
+
* policy, schedule declarations a cron trigger cannot honor and binding-backed
|
|
40
|
+
* gateways without `WebSocketModule`.
|
|
34
41
|
*/
|
|
35
42
|
function cloudflareAdapter(options) {
|
|
36
43
|
const { env } = options;
|
|
@@ -41,57 +48,217 @@ function cloudflareAdapter(options) {
|
|
|
41
48
|
await next();
|
|
42
49
|
}],
|
|
43
50
|
invocationTransport: ({ app }) => (request) => Promise.resolve(app.fetch(request, env)),
|
|
44
|
-
getClientIp: (c) =>
|
|
51
|
+
getClientIp: (c) => c.req.header("cf-connecting-ip") ?? null,
|
|
45
52
|
configureContainer: (container) => {
|
|
46
|
-
|
|
53
|
+
registerCloudflarePlatform(container, env, {
|
|
54
|
+
websocket: workerWebSocketTransport(env),
|
|
55
|
+
live: workerLivePlatform(env, container)
|
|
56
|
+
});
|
|
47
57
|
registerScheduledEventSeed(container);
|
|
48
58
|
},
|
|
49
|
-
onBootstrap:
|
|
59
|
+
onBootstrap: ({ app, container, discovery }) => {
|
|
50
60
|
assertQueueConsumerOwnership(app.entrypoints);
|
|
51
61
|
reportCloudflareScheduleDiagnostics(container, app.entrypoints);
|
|
52
|
-
|
|
62
|
+
reportUnservedGateways(container, discovery);
|
|
53
63
|
}
|
|
54
64
|
};
|
|
55
65
|
}
|
|
56
66
|
/**
|
|
67
|
+
* The `VelaFactory.create()` options an application for `options.env` is built
|
|
68
|
+
* with: that environment (seeded as ENV and sent by test clients as `c.env`),
|
|
69
|
+
* the Cloudflare adapter bound to it, then any further adapters.
|
|
70
|
+
*/
|
|
71
|
+
function cloudflareCreateOptions(options) {
|
|
72
|
+
return {
|
|
73
|
+
env: options.env,
|
|
74
|
+
globalPrefix: options.globalPrefix,
|
|
75
|
+
globalPrefixOptions: options.globalPrefixOptions,
|
|
76
|
+
versioning: options.versioning,
|
|
77
|
+
security: options.security,
|
|
78
|
+
cors: options.cors,
|
|
79
|
+
adapters: [cloudflareAdapter(options), ...options.adapters ?? []]
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
57
83
|
* Build an application for one native Workers environment. Call inside a platform event.
|
|
58
84
|
* The root is static: a module class or a `DynamicModule` declared at module scope.
|
|
59
85
|
* Read bindings in providers (`@InjectEnv()`) and module factories
|
|
60
86
|
* (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
|
|
61
87
|
*/
|
|
62
88
|
async function createCloudflareApp(rootModule, options) {
|
|
63
|
-
const velaApp = await VelaFactory.create(rootModule,
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
89
|
+
const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));
|
|
90
|
+
return new CloudflareApplication(velaApp, options.env);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Run a Worker's `configure` hook on the application built for `env`, as
|
|
94
|
+
* `createCloudflareWorker()` does before any event reaches it: a throw or a
|
|
95
|
+
* returned promise closes the application and fails the construction.
|
|
96
|
+
*/
|
|
97
|
+
async function configureCloudflareApplication(app, env, configure) {
|
|
98
|
+
if (!configure) return app;
|
|
99
|
+
try {
|
|
100
|
+
const result = configure(app, env);
|
|
101
|
+
if (result instanceof Promise) {
|
|
102
|
+
result.catch(() => {});
|
|
103
|
+
throw new TypeError("createCloudflareWorker configure must finish synchronously: it runs before any event reaches the application, so read bindings and perform I/O in providers.");
|
|
104
|
+
}
|
|
105
|
+
} catch (error) {
|
|
106
|
+
await app.close().catch(() => {});
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
72
109
|
return app;
|
|
73
110
|
}
|
|
74
111
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
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')`.
|
|
78
115
|
*/
|
|
79
|
-
|
|
116
|
+
const CLOUDFLARE_WORKER = Symbol.for("vela.cloudflare.worker");
|
|
117
|
+
/**
|
|
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')`.
|
|
122
|
+
*/
|
|
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 = {}) {
|
|
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
|
+
};
|
|
80
223
|
const applications = /* @__PURE__ */ new WeakMap();
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
224
|
+
const build = async (env) => configureCloudflareApplication(await createCloudflareApp(workerRoot(), {
|
|
225
|
+
...appOptions,
|
|
226
|
+
env
|
|
227
|
+
}), env, configure);
|
|
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
|
+
}
|
|
244
|
+
};
|
|
245
|
+
const { application } = state;
|
|
246
|
+
const descriptor = {
|
|
247
|
+
rootModule,
|
|
248
|
+
options,
|
|
249
|
+
durableObjects,
|
|
250
|
+
workflows,
|
|
251
|
+
entrypoints,
|
|
252
|
+
createOptions: (env) => cloudflareCreateOptions({
|
|
253
|
+
...appOptions,
|
|
254
|
+
env
|
|
255
|
+
}),
|
|
256
|
+
createApplication: (env) => VelaFactory.create(workerRoot(), cloudflareCreateOptions({
|
|
257
|
+
...appOptions,
|
|
86
258
|
env
|
|
87
|
-
})
|
|
88
|
-
applications.set(env, pending);
|
|
89
|
-
pending.catch(() => {
|
|
90
|
-
if (applications.get(env) === pending) applications.delete(env);
|
|
91
|
-
});
|
|
92
|
-
return pending;
|
|
259
|
+
}))
|
|
93
260
|
};
|
|
94
|
-
|
|
261
|
+
const worker = {
|
|
95
262
|
async fetch(request, env, ctx) {
|
|
96
263
|
return (await application(env)).fetch(request, env, ctx);
|
|
97
264
|
},
|
|
@@ -100,10 +267,32 @@ function createCloudflareWorker(rootModule, options = {}) {
|
|
|
100
267
|
},
|
|
101
268
|
async queue(batch, env, ctx) {
|
|
102
269
|
return (await application(env)).queue(batch, env, ctx);
|
|
103
|
-
}
|
|
270
|
+
},
|
|
271
|
+
[CLOUDFLARE_WORKER]: descriptor
|
|
104
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;
|
|
105
294
|
}
|
|
106
295
|
//#endregion
|
|
107
|
-
export { cloudflareAdapter, createCloudflareApp, createCloudflareWorker };
|
|
296
|
+
export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, cloudflareApplication, cloudflareCreateOptions, configureCloudflareApplication, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, registerDurableObject, registerEntrypoint, registerWorkflow };
|
|
108
297
|
|
|
109
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 { getConnInfo } from 'hono/cloudflare-workers';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n VelaApplication,\n VelaEnv,\n VelaMiddlewareHandler,\n VelaSecurityOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment, registerCloudflareEnvironment } from './environment';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { warnWorkerLocalLive } from './websocket/do-live';\nimport { registerWebSocketRoutes } from './websocket/websocket-routing';\nimport type { CloudflareRoot } from './root-module';\n\nexport interface CloudflareWorkerOptions {\n globalPrefix?: string;\n security?: VelaSecurityOptions;\n /** Build request middleware from the same native environment DI receives as ENV. */\n middleware?: (env: VelaEnv) => VelaMiddlewareHandler[];\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareWorkerOptions {\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 supplies the `InternalDispatcher` transport, so signed queue and\n * schedule dispatch re-enter this application's routes, and reports schedule\n * declarations a cron trigger cannot honor through the diagnostics policy.\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 getClientIp: (c) => getConnInfo(c).remote.address ?? null,\n configureContainer: (container) => {\n registerCloudflareEnvironment(container, env);\n registerScheduledEventSeed(container);\n },\n onBootstrap: async ({ app, container }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n await warnWorkerLocalLive(container);\n },\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, {\n globalPrefix: options.globalPrefix,\n security: options.security,\n middleware: options.middleware?.(options.env),\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n });\n const app = new CloudflareApplication(velaApp, options.env);\n app.scanInstances(velaApp.getInstances());\n registerWebSocketRoutes(app.getHonoApp(), app.getWsGatewayRoutes(), velaApp.getContainer());\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity. Concurrent cold\n * events share construction; failed construction is evicted so the next event\n * can retry. Weak keys stop this cache from retaining a replaced environment.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n) {\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const application = (env: VelaEnv): Promise<CloudflareApplication> => {\n const existing = applications.get(env);\n if (existing) return existing;\n const pending = createCloudflareApp(rootModule, { ...options, 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 return {\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 };\n}\n"],"mappings":";;;;;;;;;AAgCA,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;;;;;;;;AASA,SAAgB,kBAAkB,SAA2C;CAC3E,MAAM,EAAE,QAAQ;CAChB,OAAO;EACL,MAAM;EACN,mBAAmB,CACjB,OAAO,SAAS,SAAS;GACvB,4BAA4B,KAAK,QAAQ,GAAG;GAC5C,MAAM,KAAK;EACb,CACF;EACA,sBACG,EAAE,WACF,YACC,QAAQ,QAAQ,IAAI,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e;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;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare-factory.js","names":[],"sources":["../src/cloudflare-factory.ts"],"sourcesContent":["import type { ExecutionContext } from 'hono';\nimport { VelaFactory } from '@velajs/vela';\nimport type {\n CorsOptions,\n GlobalPrefixOptions,\n Type,\n VelaApplication,\n VelaCreateOptions,\n VelaEnv,\n VelaSecurityOptions,\n VersioningOptions,\n} from '@velajs/vela';\nimport type { RuntimeAdapter } from '@velajs/vela/module-kit';\nimport { CloudflareApplication } from './cloudflare-application';\nimport { assertCloudflareEnvironment } from './environment';\nimport { registerCloudflarePlatform } from './platform';\nimport { reportCloudflareScheduleDiagnostics } from './schedule-diagnostics';\nimport { registerScheduledEventSeed, type ScheduledEvent } from './scheduled-event';\nimport { reportUnservedGateways } from './websocket/binding-gateways';\nimport { workerLivePlatform } from './websocket/live-driver';\nimport { workerWebSocketTransport } from './websocket/worker-transport';\nimport { defineWorkerEvents } from './worker-events';\nimport { withRootProviders, type CloudflareRoot } from './root-module';\n\nexport interface CloudflareAppOptions {\n globalPrefix?: string;\n /** Routes served without the global prefix (`{ exclude }`). */\n globalPrefixOptions?: GlobalPrefixOptions;\n /** URI versioning: the version segment prefix (default `'v'`). */\n versioning?: VersioningOptions;\n security?: VelaSecurityOptions;\n /** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */\n cors?: CorsOptions | boolean;\n /** Further runtime adapters, composed after the Cloudflare adapter for each application. */\n adapters?: RuntimeAdapter[];\n}\n\nexport interface CloudflareWorkerOptions extends CloudflareAppOptions {\n /**\n * Finish each application's HTTP surface, such as extra Hono routes, once per\n * environment. It runs after the application is built and before any event,\n * including concurrent cold events, reaches it; a throw fails that\n * construction, and the next event retries. It must be synchronous and do no\n * I/O (a returned promise fails the construction): read bindings in\n * providers. Request middleware belongs in modules (`configure(consumer)`),\n * which can inject `ENV`.\n */\n configure?(app: CloudflareApplication, env: VelaEnv): void;\n}\n\nexport interface CreateCloudflareAppOptions extends CloudflareAppOptions {\n /** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */\n env: VelaEnv;\n}\n\nfunction readStrings(meta: unknown, property: string): string[] {\n const value: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, property) : undefined;\n if (typeof value === 'string') return [value];\n if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return value;\n throw new TypeError(`Invalid queue consumer metadata: ${property}.`);\n}\n\n/**\n * `@QueueConsumer` handlers own their physical queue. A `QueueModule`\n * registration that pins the same physical queue with `consumer` would never\n * see its batches, so bootstrap rejects the overlap.\n */\nfunction assertQueueConsumerOwnership(entrypoints: VelaApplication['entrypoints']): void {\n const pinned = new Set(\n entrypoints.ofKind('cf:queue:module').flatMap((entry) => readStrings(entry.meta, 'consumers')),\n );\n for (const entry of entrypoints.ofKind('cf:queue')) {\n const [queue] = readStrings(entry.meta, 'queueName');\n if (queue !== undefined && pinned.has(queue)) {\n throw new Error(\n `Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a ` +\n `QueueModule.registerQueue({ consumer: '${queue}' }) both claim it. Keep one owner.`,\n );\n }\n }\n}\n\n/**\n * Bind an application to one environment: seeded as the global ENV before\n * provider factories and lifecycle hooks, and asserted on every request. The\n * adapter also registers the Worker's platform wiring: `WebSocketModule`\n * forwards each authenticated gateway upgrade to the room's Durable Object,\n * and `LiveModule` sends invalidations there. It supplies the\n * `InternalDispatcher` transport, so signed queue and schedule dispatch\n * re-enter this application's routes, and reports, through the diagnostics\n * policy, schedule declarations a cron trigger cannot honor and binding-backed\n * gateways without `WebSocketModule`.\n */\nexport function cloudflareAdapter(options: { env: VelaEnv }): RuntimeAdapter {\n const { env } = options;\n return {\n name: 'cloudflare',\n requestMiddleware: [\n async (context, next) => {\n assertCloudflareEnvironment(env, context.env);\n await next();\n },\n ],\n invocationTransport:\n ({ app }) =>\n (request) =>\n Promise.resolve(app.fetch(request, env)),\n // Cloudflare attests the client address in this header. Read directly:\n // hono/cloudflare-workers would also load its WebSocket upgrade helper.\n getClientIp: (c) => c.req.header('cf-connecting-ip') ?? null,\n configureContainer: (container) => {\n registerCloudflarePlatform(container, env, {\n websocket: workerWebSocketTransport(env),\n live: workerLivePlatform(env, container),\n });\n registerScheduledEventSeed(container);\n },\n onBootstrap: ({ app, container, discovery }) => {\n assertQueueConsumerOwnership(app.entrypoints);\n reportCloudflareScheduleDiagnostics(container, app.entrypoints);\n reportUnservedGateways(container, discovery);\n },\n };\n}\n\n/**\n * The `VelaFactory.create()` options an application for `options.env` is built\n * with: that environment (seeded as ENV and sent by test clients as `c.env`),\n * the Cloudflare adapter bound to it, then any further adapters.\n */\nexport function cloudflareCreateOptions(options: CreateCloudflareAppOptions): VelaCreateOptions {\n return {\n env: options.env,\n globalPrefix: options.globalPrefix,\n globalPrefixOptions: options.globalPrefixOptions,\n versioning: options.versioning,\n security: options.security,\n cors: options.cors,\n adapters: [cloudflareAdapter(options), ...(options.adapters ?? [])],\n };\n}\n\n/**\n * Build an application for one native Workers environment. Call inside a platform event.\n * The root is static: a module class or a `DynamicModule` declared at module scope.\n * Read bindings in providers (`@InjectEnv()`) and module factories\n * (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.\n */\nexport async function createCloudflareApp(\n rootModule: CloudflareRoot,\n options: CreateCloudflareAppOptions,\n): Promise<CloudflareApplication> {\n const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));\n return new CloudflareApplication(velaApp, options.env);\n}\n\n/**\n * Run a Worker's `configure` hook on the application built for `env`, as\n * `createCloudflareWorker()` does before any event reaches it: a throw or a\n * returned promise closes the application and fails the construction.\n */\nexport async function configureCloudflareApplication(\n app: CloudflareApplication,\n env: VelaEnv,\n configure: CloudflareWorkerOptions['configure'],\n): Promise<CloudflareApplication> {\n if (!configure) return app;\n try {\n const result: unknown = configure(app, env);\n if (result instanceof Promise) {\n // Observe the rejected work; the construction fails either way.\n result.catch(() => {});\n throw new TypeError(\n 'createCloudflareWorker configure must finish synchronously: it runs before any ' +\n 'event reaches the application, so read bindings and perform I/O in providers.',\n );\n }\n } catch (error) {\n await app.close().catch(() => {});\n throw error;\n }\n return app;\n}\n\n/**\n * The well-known key under which a Worker entry (`defineCloudflareApp().worker`\n * or `createCloudflareWorker()`) carries its {@link CloudflareWorkerDescriptor}:\n * `Symbol.for('vela.cloudflare.worker')`.\n */\nexport const CLOUDFLARE_WORKER: unique symbol = Symbol.for('vela.cloudflare.worker');\n\n/**\n * The well-known static key under which a Durable Object class that\n * `VelaDurableObject()` or `VelaWebSocketDurableObject()` returns (and every\n * class extending it) carries its {@link CloudflareDurableObjectDescriptor}:\n * `Symbol.for('vela.cloudflare.durableObject')`.\n */\nexport const CLOUDFLARE_DURABLE_OBJECT: unique symbol = Symbol.for('vela.cloudflare.durableObject');\n\n/**\n * The well-known static key under which a Workflow class that `VelaWorkflow()`\n * returns (and every class extending it) carries its\n * {@link CloudflareWorkflowDescriptor}: `Symbol.for('vela.cloudflare.workflow')`.\n */\nexport const CLOUDFLARE_WORKFLOW: unique symbol = Symbol.for('vela.cloudflare.workflow');\n\n/**\n * The well-known static key under which a service entrypoint class that\n * `VelaEntrypoint()` returns (and every class extending it) carries its\n * {@link CloudflareEntrypointDescriptor}: `Symbol.for('vela.cloudflare.entrypoint')`.\n */\nexport const CLOUDFLARE_ENTRYPOINT: unique symbol = Symbol.for('vela.cloudflare.entrypoint');\n\n/** What a Vela Durable Object class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareDurableObjectDescriptor {\n /**\n * `host`: `VelaDurableObject(root, Host, { rpc })`, whose RPC methods are\n * the host methods `rpc` names.\n * `websocket`: `VelaWebSocketDurableObject(root)`, a gateway room's sockets.\n */\n readonly kind: 'host' | 'websocket';\n readonly rootModule: CloudflareRoot;\n /** The host class of a `host` Durable Object. */\n readonly host?: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class the factory returned: an exported Durable Object class extends it. */\n readonly durableObject: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela Workflow class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareWorkflowDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose `run(event, step)` each Workflow run calls. */\n readonly host: Type;\n /** The class `VelaWorkflow()` returned: an exported Workflow class extends it. */\n readonly workflow: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Vela service entrypoint class is built from, for tools such as `vela cf sync`. */\nexport interface CloudflareEntrypointDescriptor {\n readonly rootModule: CloudflareRoot;\n /** The host class whose methods `methods` names. */\n readonly host: Type;\n /** The RPC methods the class exposes. */\n readonly methods: readonly string[];\n /** The class `VelaEntrypoint()` returned: an exported entrypoint class extends it. */\n readonly entrypoint: abstract new (...args: never[]) => unknown;\n}\n\n/** What a Worker entry is built from, for tools that load it outside a platform event. */\nexport interface CloudflareWorkerDescriptor {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Durable Object classes defined from the same {@link CloudflareApp}\n * (`VelaDurableObject(app, Host)`, `VelaWebSocketDurableObject(app)`), in\n * definition order; empty for `createCloudflareWorker()`.\n */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from the app (`VelaWorkflow(app, Host)`), in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /**\n * The service entrypoint classes defined from the app\n * (`VelaEntrypoint(app, Host, { rpc })`), in definition order.\n */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n /** The `VelaFactory.create()` options the Worker builds its application with for `env`. */\n createOptions(env: VelaEnv): VelaCreateOptions;\n /**\n * `VelaFactory.create()` of the Worker's root (the root module, with the\n * hosts of the app's Workflow and service entrypoint classes among its\n * providers) and `createOptions(env)`: the application without its Worker\n * handlers or the `configure` hook, which receives the Workers application.\n */\n createApplication(env: VelaEnv): Promise<VelaApplication>;\n}\n\n/** The exported handlers of a Worker entry (`defineCloudflareApp().worker`, `createCloudflareWorker()`). */\nexport interface CloudflareWorker {\n fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;\n scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void>;\n /**\n * The Email Workers handler, present once a module imports `OnEmail` from\n * `@velajs/cloudflare/email`: it runs the application's `@OnEmail()`\n * handlers, and rejects a message none of them accepts.\n */\n readonly email?: (\n message: ForwardableEmailMessage,\n env: VelaEnv,\n ctx?: ExecutionContext,\n ) => Promise<void>;\n /**\n * The Tail Workers handler, present once a module imports `OnTail` from\n * `@velajs/cloudflare/tail`: it runs the application's `@OnTail()` handlers\n * and never rejects, even when the application fails to start (the error is\n * logged to the console, and the next batch retries).\n */\n readonly tail?: (events: TraceItem[], env: VelaEnv, ctx?: ExecutionContext) => Promise<void>;\n /**\n * Symbol-keyed, so the platform, which reads string-keyed handlers, ignores\n * it; enumerable, so `{ ...worker, email }` keeps it for the CLI.\n */\n readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;\n}\n\n/**\n * One Cloudflare application: a static root module and its options, shared\n * by the Worker's default export and every Durable Object, Workflow and\n * service entrypoint class defined from it. Create it once, at module scope\n * of the Worker entry, with {@link defineCloudflareApp}.\n */\nexport interface CloudflareApp {\n readonly rootModule: CloudflareRoot;\n readonly options: CloudflareWorkerOptions;\n /**\n * The Worker's handlers (`export default app.worker`): one application per\n * environment identity, built on the first event and shared by concurrent\n * cold events, the app's Workflows and its service entrypoints.\n */\n readonly worker: CloudflareWorker;\n /** The Durable Object classes defined from this app, in definition order. */\n readonly durableObjects: readonly CloudflareDurableObjectDescriptor[];\n /** The Workflow classes defined from this app, in definition order. */\n readonly workflows: readonly CloudflareWorkflowDescriptor[];\n /** The service entrypoint classes defined from this app, in definition order. */\n readonly entrypoints: readonly CloudflareEntrypointDescriptor[];\n}\n\n/** What an app definition records beyond its public members. */\ninterface AppState {\n readonly durableObjects: CloudflareDurableObjectDescriptor[];\n readonly workflows: CloudflareWorkflowDescriptor[];\n readonly entrypoints: CloudflareEntrypointDescriptor[];\n readonly application: (env: VelaEnv) => Promise<CloudflareApplication>;\n /** Whether the Worker started building an application: its providers are then fixed. */\n started: boolean;\n}\n\nconst states = new WeakMap<object, AppState>();\n\n/** Whether `value` is an app {@link defineCloudflareApp} returned. */\nexport function isCloudflareApp(value: unknown): value is CloudflareApp {\n return typeof value === 'object' && value !== null && states.has(value);\n}\n\nfunction stateOf(app: unknown, factory: string): AppState {\n const state = typeof app === 'object' && app !== null ? states.get(app) : undefined;\n if (state === undefined) {\n throw new TypeError(\n `${factory}() takes the app from defineCloudflareApp(AppModule, options), whose Worker ` +\n 'application it runs in: define the app once and pass it.',\n );\n }\n return state;\n}\n\n/**\n * @internal Record a Durable Object class defined from `app`, so the Worker\n * descriptor lists it. The `@velajs/cloudflare/durable-objects` factories call\n * it at class definition.\n */\nexport function registerDurableObject(\n app: CloudflareApp,\n descriptor: CloudflareDurableObjectDescriptor,\n): void {\n states.get(app)?.durableObjects.push(descriptor);\n}\n\n/** Hosts join the Worker's root providers, so they must be declared before it is built. */\nfunction assertNotStarted(state: AppState, factory: string, host: Type): void {\n if (!state.started) return;\n throw new Error(\n `${factory}(app, ${host.name}) was called after the app started building its Worker ` +\n 'application, whose providers are then fixed: define Workflow and service entrypoint ' +\n 'classes at module scope, in the module that defines the app.',\n );\n}\n\n/**\n * @internal Record a Workflow class defined from `app`: its host joins the\n * Worker application's root providers, and the Worker descriptor lists it.\n * `VelaWorkflow()` calls it at class definition; `app` is validated here.\n */\nexport function registerWorkflow(app: unknown, descriptor: CloudflareWorkflowDescriptor): void {\n const state = stateOf(app, 'VelaWorkflow');\n assertNotStarted(state, 'VelaWorkflow', descriptor.host);\n state.workflows.push(descriptor);\n}\n\n/**\n * @internal Record a service entrypoint class defined from `app`: its host\n * joins the Worker application's root providers, and the Worker descriptor\n * lists it. `VelaEntrypoint()` calls it at class definition; `app` is\n * validated here.\n */\nexport function registerEntrypoint(app: unknown, descriptor: CloudflareEntrypointDescriptor): void {\n const state = stateOf(app, 'VelaEntrypoint');\n assertNotStarted(state, 'VelaEntrypoint', descriptor.host);\n state.entrypoints.push(descriptor);\n}\n\n/**\n * @internal The Worker's application for `env`: the one its handlers use,\n * built on first use for each environment identity and shared by concurrent\n * events, so the app's Workflows and service entrypoints run in it too.\n */\nexport function cloudflareApplication(\n app: CloudflareApp,\n env: VelaEnv,\n): Promise<CloudflareApplication> {\n return stateOf(app, 'cloudflareApplication').application(env);\n}\n\n/**\n * Define one Cloudflare application from a static root module (a module class\n * or a `DynamicModule`) and its options. The Worker entry exports its Worker\n * and the Durable Object, Workflow and service entrypoint classes defined from\n * it, which share the root and the options: runtime `adapters` configure every\n * application and Durable Object context the app builds.\n *\n * ```ts\n * import { defineCloudflareApp } from '@velajs/cloudflare';\n * import { VelaDurableObject } from '@velajs/cloudflare/durable-objects';\n *\n * const app = defineCloudflareApp(AppModule, { globalPrefix: '/api' });\n * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}\n * export default app.worker;\n * ```\n *\n * The Worker builds one application per environment identity. The app's\n * Workflows (`VelaWorkflow`) and service entrypoints (`VelaEntrypoint`) run in\n * that application, with their hosts added to the root module's providers;\n * each Durable Object instance boots its own application context. Declare the\n * classes in the module that defines the app: a class file importing the app\n * from the Worker entry would run before the entry defined it. Keep them in\n * the entry, or define the app in a module of its own that the entry and the\n * class files import. `createCloudflareWorker` is\n * `defineCloudflareApp(rootModule, options).worker`.\n */\nexport function defineCloudflareApp(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareApp {\n const { configure, ...appOptions } = options;\n const durableObjects: CloudflareDurableObjectDescriptor[] = [];\n const workflows: CloudflareWorkflowDescriptor[] = [];\n const entrypoints: CloudflareEntrypointDescriptor[] = [];\n // The Worker's root: the root module, with the hosts of the Workflow and\n // service entrypoint classes among its providers.\n const workerRoot = (): CloudflareRoot => {\n const hosts = [...new Set([...workflows, ...entrypoints].map(({ host }) => host))];\n return hosts.length === 0 ? rootModule : withRootProviders(rootModule, hosts);\n };\n // Weak keys stop this cache from retaining a replaced environment.\n const applications = new WeakMap<VelaEnv, Promise<CloudflareApplication>>();\n const build = async (env: VelaEnv): Promise<CloudflareApplication> =>\n configureCloudflareApplication(\n await createCloudflareApp(workerRoot(), { ...appOptions, env }),\n env,\n configure,\n );\n const state: AppState = {\n durableObjects,\n workflows,\n entrypoints,\n started: false,\n // Concurrent cold events share construction, including `configure`; a\n // failed construction is evicted so the next event can retry.\n application: (env) => {\n const existing = applications.get(env);\n if (existing) return existing;\n state.started = true;\n const pending = build(env);\n applications.set(env, pending);\n void pending.catch(() => {\n if (applications.get(env) === pending) applications.delete(env);\n });\n return pending;\n },\n };\n const { application } = state;\n const descriptor: CloudflareWorkerDescriptor = {\n rootModule,\n options,\n durableObjects,\n workflows,\n entrypoints,\n createOptions: (env) => cloudflareCreateOptions({ ...appOptions, env }),\n createApplication: (env) =>\n VelaFactory.create(workerRoot(), cloudflareCreateOptions({ ...appOptions, env })),\n };\n const worker: CloudflareWorker = {\n async fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response> {\n return (await application(env)).fetch(request, env, ctx);\n },\n async scheduled(\n event: ScheduledEvent,\n env: VelaEnv,\n ctx?: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).scheduled(event, env, ctx);\n },\n async queue(\n batch: { queue: string; messages: readonly unknown[] },\n env: VelaEnv,\n ctx: { waitUntil: (promise: Promise<unknown>) => void },\n ): Promise<void> {\n return (await application(env)).queue(batch, env, ctx);\n },\n [CLOUDFLARE_WORKER]: descriptor,\n };\n // `email` and `tail` appear once a module imports their decorators.\n defineWorkerEvents(worker, application);\n const app: CloudflareApp = {\n rootModule,\n options,\n worker,\n durableObjects,\n workflows,\n entrypoints,\n };\n states.set(app, state);\n return app;\n}\n\n/**\n * Worker entrypoint with one bootstrap per environment identity: the Worker of\n * `defineCloudflareApp(rootModule, options)`. Concurrent cold events share\n * construction, including `configure`; failed construction is evicted so the\n * next event can retry. Define the app with {@link defineCloudflareApp} when the\n * entry also exports Durable Object classes built from it.\n */\nexport function createCloudflareWorker(\n rootModule: CloudflareRoot,\n options: CloudflareWorkerOptions = {},\n): CloudflareWorker {\n return defineCloudflareApp(rootModule, options).worker;\n}\n"],"mappings":";;;;;;;;;;;;AAuDA,SAAS,YAAY,MAAe,UAA4B;CAC9D,MAAM,QACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC5E,IAAI,OAAO,UAAU,UAAU,OAAO,CAAC,KAAK;CAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,GAAG,OAAO;CACpF,MAAM,IAAI,UAAU,oCAAoC,SAAS,EAAE;AACrE;;;;;;AAOA,SAAS,6BAA6B,aAAmD;CACvF,MAAM,SAAS,IAAI,IACjB,YAAY,OAAO,iBAAiB,CAAC,CAAC,SAAS,UAAU,YAAY,MAAM,MAAM,WAAW,CAAC,CAC/F;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,UAAU,GAAG;EAClD,MAAM,CAAC,SAAS,YAAY,MAAM,MAAM,WAAW;EACnD,IAAI,UAAU,KAAA,KAAa,OAAO,IAAI,KAAK,GACzC,MAAM,IAAI,MACR,2CAA2C,MAAM,qBAAqB,MAAM,kDAChC,MAAM,oCACpD;CAEJ;AACF;;;;;;;;;;;;AAaA,SAAgB,kBAAkB,SAA2C;CAC3E,MAAM,EAAE,QAAQ;CAChB,OAAO;E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G,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,18 @@
|
|
|
1
|
+
//#region src/diagnostics.ts
|
|
2
|
+
const reported = /* @__PURE__ */ new Set();
|
|
3
|
+
/**
|
|
4
|
+
* Report through the application's diagnostics policy: `'throw'` fails the
|
|
5
|
+
* caller, `'log'` warns once per message in this isolate, `'silent'` skips.
|
|
6
|
+
*/
|
|
7
|
+
function reportDiagnostic(container, message) {
|
|
8
|
+
const mode = container.getDiagnostics();
|
|
9
|
+
if (mode === "silent") return;
|
|
10
|
+
if (mode === "throw") throw new Error(message);
|
|
11
|
+
if (reported.has(message)) return;
|
|
12
|
+
reported.add(message);
|
|
13
|
+
console.warn(message);
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
export { reportDiagnostic };
|
|
17
|
+
|
|
18
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["import type { Container } from '@velajs/vela/module-kit';\n\nconst reported = new Set<string>();\n\n/**\n * Report through the application's diagnostics policy: `'throw'` fails the\n * caller, `'log'` warns once per message in this isolate, `'silent'` skips.\n */\nexport function reportDiagnostic(container: Container, message: string): void {\n const mode = container.getDiagnostics();\n if (mode === 'silent') return;\n if (mode === 'throw') throw new Error(message);\n if (reported.has(message)) return;\n reported.add(message);\n console.warn(message);\n}\n"],"mappings":";AAEA,MAAM,2BAAW,IAAI,IAAY;;;;;AAMjC,SAAgB,iBAAiB,WAAsB,SAAuB;CAC5E,MAAM,OAAO,UAAU,eAAe;CACtC,IAAI,SAAS,UAAU;CACvB,IAAI,SAAS,SAAS,MAAM,IAAI,MAAM,OAAO;CAC7C,IAAI,SAAS,IAAI,OAAO,GAAG;CAC3B,SAAS,IAAI,OAAO;CACpB,QAAQ,KAAK,OAAO;AACtB"}
|
|
@@ -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,kBAAkB,MAAM,CAAC,IAAI,CAAC;AACvC;;;;;;;AAQA,SAAgB,2BACd,MACA,SACiC;CACjC,MAAM,EAAE,KAAK,UAAU;CACvB,MAAM,WACJ,QAAQ,cACN,eAA8C;EAC9C,WAAW,yBAAyB,GAAG;EACvC,MAAM,mBAAmB,KAAK,SAAS;CACzC;CACF,OAAO,YAAY,yBAAyB,MAAM,EAChD,oBAAoB,OAAO,cAAc;EACvC,2BAA2B,WAAW,KAAK,SAAS,SAAS,CAAC;EAC9D,IAAI,OAAO;GACT,UAAU,SAAS,eAAe,UAAU,EAAE,UAAU,MAAM,CAAC,CAAC;GAChE,UAAU,SAAS,eAAe,YAAY,EAAE,UAAU,MAAM,QAAQ,CAAC,CAAC;GAC1E,UAAU,SAAS,eAAe,OAAO,EAAE,UAAU,MAAM,GAAG,CAAC,CAAC;GAChE,UAAU,gBAAgB,QAAQ;GAClC,UAAU,gBAAgB,UAAU;GACpC,UAAU,gBAAgB,KAAK;EACjC;EACA,KAAK,MAAM,WAAW,QAAQ,YAAY,CAAC,GAGzC,MAAM,QAAQ,qBAAqB,SAAS;CAEhD,EACF,CAAC;AACH;;;;;;;;AASA,SAAgB,mBACd,OACA,MACA,MACY;CACZ,MAAM,QAAQ,MAAM,sBAAsB,YAAY;EACpD,IAAI;GACF,OAAO,MAAM,KAAK;EACpB,SAAS,OAAO;GACd,QAAQ,MAAM,yBAAyB,KAAK,oBAAoB,KAAK;GACrE,MAAM,wBAAwB;EAChC;CACF,CAAC;CAED,MAAM,YAAY,CAAC,CAAC;CACpB,OAAO;AACT"}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { internalEntrypointError, renderEntrypointResponse } from "../rpc/entrypoint-error.js";
|
|
2
|
+
import { createDurableObjectContext, withDurableObjectHost } from "./boot.js";
|
|
3
|
+
import { HostInvoker, callRpcMethod, catchWith, claimingFilter, hostModuleId, platformSettlement } from "../host/host-invoker.js";
|
|
4
|
+
import { getErrorStatus } from "@velajs/vela";
|
|
5
|
+
import { trackResponseStream } from "@velajs/vela/module-kit";
|
|
6
|
+
//#region src/durable-object/host-dispatch.ts
|
|
7
|
+
const fetchSettlement = {
|
|
8
|
+
success(value) {
|
|
9
|
+
if (!(value instanceof Response)) throw new TypeError("A Durable Object host fetch() must return a Response.");
|
|
10
|
+
return value;
|
|
11
|
+
},
|
|
12
|
+
async failure(error, failure) {
|
|
13
|
+
const filter = claimingFilter(failure.filters, error);
|
|
14
|
+
let current = error;
|
|
15
|
+
if (filter) {
|
|
16
|
+
const caught = await catchWith(filter, error, failure);
|
|
17
|
+
if (caught.handled) {
|
|
18
|
+
if (caught.value instanceof Response) return caught.value;
|
|
19
|
+
if (caught.value !== void 0) return Response.json(caught.value, { status: getErrorStatus(error) });
|
|
20
|
+
} else current = caught.error;
|
|
21
|
+
}
|
|
22
|
+
return renderEntrypointResponse(current, failure.reporter, failure.context);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const alarmSettlement = platformSettlement(true);
|
|
26
|
+
const webSocketSettlement = platformSettlement(false);
|
|
27
|
+
/**
|
|
28
|
+
* Runs the invocations of one Durable Object instance's host: each RPC call
|
|
29
|
+
* and event in a fresh execution scope (request-scoped providers are built
|
|
30
|
+
* per invocation) through the host's scoped guards, pipes (RPC arguments
|
|
31
|
+
* only), interceptors and exception filters. Application-wide `APP_*`
|
|
32
|
+
* components do not apply: an object's callers are other Workers and the
|
|
33
|
+
* platform, with no HTTP request. Failures are reported first; an RPC call
|
|
34
|
+
* rejects with an `EntrypointError`, a `fetch()` renders a JSON error
|
|
35
|
+
* response, and alarms and WebSocket events rethrow for the platform.
|
|
36
|
+
*/
|
|
37
|
+
var DurableObjectHostDispatcher = class {
|
|
38
|
+
context;
|
|
39
|
+
#invoker;
|
|
40
|
+
#methods;
|
|
41
|
+
constructor(context, host, moduleId, members, waitUntil) {
|
|
42
|
+
this.context = context;
|
|
43
|
+
this.#invoker = new HostInvoker({
|
|
44
|
+
container: context.getContainer(),
|
|
45
|
+
host,
|
|
46
|
+
moduleId,
|
|
47
|
+
edge: "durable-object",
|
|
48
|
+
waitUntil
|
|
49
|
+
});
|
|
50
|
+
this.#methods = new Set(members.methods);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Call the host's RPC method `method`. It rejects only with an
|
|
54
|
+
* `EntrypointError`, also when the invocation fails before its pipeline
|
|
55
|
+
* renders the error.
|
|
56
|
+
*/
|
|
57
|
+
call(method, args) {
|
|
58
|
+
return callRpcMethod(this.#invoker, this.#methods, method, args);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Serve the host's `fetch()`; any failure becomes a JSON error response. A
|
|
62
|
+
* streamed body keeps the invocation's scope (its request-scoped providers
|
|
63
|
+
* and managed work) open until it is sent.
|
|
64
|
+
*/
|
|
65
|
+
async fetch(request) {
|
|
66
|
+
try {
|
|
67
|
+
return await this.#invoker.invoke({
|
|
68
|
+
kind: "cf:do:fetch",
|
|
69
|
+
method: "fetch",
|
|
70
|
+
args: [request],
|
|
71
|
+
settlement: fetchSettlement,
|
|
72
|
+
transmit: (response) => this.#transmit(request, response)
|
|
73
|
+
});
|
|
74
|
+
} catch (error) {
|
|
75
|
+
this.#invoker.reportOutside(error, this.#invoker.report("cf:do:fetch", "fetch"));
|
|
76
|
+
const failure = internalEntrypointError();
|
|
77
|
+
return Response.json({ error: {
|
|
78
|
+
code: failure.code,
|
|
79
|
+
message: failure.message
|
|
80
|
+
} }, { status: failure.status });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async alarm(info) {
|
|
84
|
+
await this.#invoker.invoke({
|
|
85
|
+
kind: "cf:do:alarm",
|
|
86
|
+
method: "alarm",
|
|
87
|
+
args: info === void 0 ? [] : [info],
|
|
88
|
+
settlement: alarmSettlement
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
async webSocket(handler, args) {
|
|
92
|
+
await this.#invoker.invoke({
|
|
93
|
+
kind: "cf:do:websocket",
|
|
94
|
+
method: handler,
|
|
95
|
+
args,
|
|
96
|
+
settlement: webSocketSettlement
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* How a `fetch()` response is sent: a streamed body keeps the scope open
|
|
101
|
+
* until it was read, failed or was cancelled, and the object's `waitUntil`
|
|
102
|
+
* holds that completion. A HEAD response sends no body, so its body is
|
|
103
|
+
* cancelled before the scope finishes. A WebSocket upgrade (101) and a
|
|
104
|
+
* bodyless response need nothing.
|
|
105
|
+
*/
|
|
106
|
+
#transmit(request, response) {
|
|
107
|
+
if (response.body === null || response.status === 101) return void 0;
|
|
108
|
+
if (request.method === "HEAD") return {
|
|
109
|
+
value: new Response(null, response),
|
|
110
|
+
sent: response.body.cancel(),
|
|
111
|
+
background: false
|
|
112
|
+
};
|
|
113
|
+
const stream = trackResponseStream(response.body);
|
|
114
|
+
return {
|
|
115
|
+
value: new Response(stream.body, response),
|
|
116
|
+
sent: stream.done,
|
|
117
|
+
background: true
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Boot one Durable Object instance's application context from `root` with
|
|
123
|
+
* `host` added to the root module's providers, and return its dispatcher,
|
|
124
|
+
* which serves `members`.
|
|
125
|
+
*/
|
|
126
|
+
async function createDurableObjectHost(root, host, options, members) {
|
|
127
|
+
const context = await createDurableObjectContext(withDurableObjectHost(root, host), options);
|
|
128
|
+
const rootClass = typeof root === "function" ? root : root.module;
|
|
129
|
+
return new DurableObjectHostDispatcher(context, host, hostModuleId(context.getContainer(), host, rootClass), members, options.waitUntil);
|
|
130
|
+
}
|
|
131
|
+
//#endregion
|
|
132
|
+
export { DurableObjectHostDispatcher, createDurableObjectHost };
|
|
133
|
+
|
|
134
|
+
//# sourceMappingURL=host-dispatch.js.map
|