@velajs/cloudflare 1.29.0 → 1.31.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 +136 -0
- package/README.md +262 -75
- package/dist/bindings.js +77 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application.js +282 -0
- package/dist/cloudflare-application.js.map +1 -0
- package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
- package/dist/cloudflare-factory.js +165 -0
- package/dist/cloudflare-factory.js.map +1 -0
- package/dist/decorators/queue-consumer.js +39 -0
- package/dist/decorators/queue-consumer.js.map +1 -0
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-objects.d.ts +8 -5
- package/dist/durable-objects.js +2 -524
- package/dist/environment.js +19 -0
- package/dist/environment.js.map +1 -0
- package/dist/index.d.ts +163 -456
- package/dist/index.js +15 -1276
- package/dist/nonce/durable-object-nonce.store.js +33 -0
- package/dist/nonce/durable-object-nonce.store.js.map +1 -0
- package/dist/nonce/nonce-validation.js +18 -0
- package/dist/nonce/nonce-validation.js.map +1 -0
- package/dist/nonce/nonce.durable-object.js +54 -0
- package/dist/nonce/nonce.durable-object.js.map +1 -0
- package/dist/{nonce.durable-object-Df4CZi-0.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -12
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +215 -0
- package/dist/queue/cloudflare-queues.js.map +1 -0
- package/dist/queues.d.ts +1 -2
- package/dist/queues.js +1 -214
- package/dist/rate-limit/cloudflare-rate-limit.store.js +79 -0
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -0
- package/dist/root-module-C23bUwt_.d.ts +11 -0
- package/dist/schedule-diagnostics.js +44 -0
- package/dist/schedule-diagnostics.js.map +1 -0
- package/dist/scheduled-event.js +68 -0
- package/dist/scheduled-event.js.map +1 -0
- package/dist/services/flagship-flag.driver.js +52 -0
- package/dist/services/flagship-flag.driver.js.map +1 -0
- package/dist/services/kv-cache.store.js +108 -0
- package/dist/services/kv-cache.store.js.map +1 -0
- package/dist/services/kv-flag.driver.js +62 -0
- package/dist/services/kv-flag.driver.js.map +1 -0
- 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/testing.d.ts +96 -0
- package/dist/testing.js +111 -0
- package/dist/testing.js.map +1 -0
- package/dist/vela-env-DFvyoNT3.d.ts +1 -2
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +139 -0
- package/dist/websocket/cf-room-registry.js.map +1 -0
- package/dist/websocket/cf-ws-client.js +94 -0
- package/dist/websocket/cf-ws-client.js.map +1 -0
- package/dist/websocket/do-bootstrap.js +77 -0
- package/dist/websocket/do-bootstrap.js.map +1 -0
- package/dist/websocket/do-live.js +143 -0
- package/dist/websocket/do-live.js.map +1 -0
- package/dist/websocket/do-pitr.js +81 -0
- package/dist/websocket/do-pitr.js.map +1 -0
- package/dist/websocket/do-state.js +7 -0
- package/dist/websocket/do-state.js.map +1 -0
- package/dist/websocket/do-websocket-host.js +169 -0
- package/dist/websocket/do-websocket-host.js.map +1 -0
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +37 -0
- package/dist/websocket/room-id.js.map +1 -0
- package/dist/websocket/websocket.durable-object.js +142 -0
- package/dist/websocket/websocket.durable-object.js.map +1 -0
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- package/dist/websocket/ws-attachment.js +79 -0
- package/dist/websocket/ws-attachment.js.map +1 -0
- package/package.json +26 -7
- package/dist/durable-objects.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/nonce-validation-Dy8z05A9.js +0 -522
- package/dist/nonce-validation-Dy8z05A9.js.map +0 -1
- package/dist/queues.js.map +0 -1
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
|
|
2
|
+
import { CorsOptions, GlobalPrefixOptions, InjectionToken, VelaApplication, VelaCreateOptions, VelaEnv, VelaSecurityOptions, VersioningOptions } from "@velajs/vela";
|
|
3
|
+
import { ExecutionContext } from "hono";
|
|
4
|
+
import { RuntimeAdapter } from "@velajs/vela/module-kit";
|
|
5
|
+
//#region src/scheduled-event.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The event a Worker's `scheduled()` export receives. The native
|
|
8
|
+
* `ScheduledController` satisfies it; direct calls (tests, scripts) may omit
|
|
9
|
+
* `scheduledTime`, which then defaults to the current time, and `noRetry`.
|
|
10
|
+
*/
|
|
11
|
+
interface ScheduledEvent {
|
|
12
|
+
readonly cron: string;
|
|
13
|
+
readonly scheduledTime?: number;
|
|
14
|
+
noRetry?(): void;
|
|
15
|
+
}
|
|
16
|
+
/** The Cloudflare trigger behind the current scheduled invocation. */
|
|
17
|
+
interface CloudflareScheduledEvent {
|
|
18
|
+
/** The trigger's exact cron string; it equals the invocation's `expression`. */
|
|
19
|
+
readonly cron: string;
|
|
20
|
+
/** The platform's scheduled time in Unix milliseconds. */
|
|
21
|
+
readonly scheduledTime: number;
|
|
22
|
+
/**
|
|
23
|
+
* Ask Cloudflare not to retry this trigger if the invocation fails. Already
|
|
24
|
+
* bound to the native controller, so it can be passed around or destructured.
|
|
25
|
+
* A no-op for direct calls that supplied no controller.
|
|
26
|
+
*/
|
|
27
|
+
readonly noRetry: () => void;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Request-scoped Cloudflare view of the scheduled trigger, seeded into each
|
|
31
|
+
* `@Cron` job's invocation scope by the Cloudflare adapter. Inject it where a
|
|
32
|
+
* job needs platform controls such as `noRetry()`; the job's argument stays
|
|
33
|
+
* the portable `ScheduleInvocation`. It resolves only inside a scheduled
|
|
34
|
+
* invocation; resolving it anywhere else throws. A cron job fired on demand
|
|
35
|
+
* (Studio's run-now) receives a synthetic event: `cron` is the job's
|
|
36
|
+
* expression and `noRetry()` does nothing.
|
|
37
|
+
*
|
|
38
|
+
* The token provides itself as request-scoped in every container, so a class
|
|
39
|
+
* that injects it is request-scoped wherever the graph boots (a Worker, a
|
|
40
|
+
* Durable Object, the CLI or a testing module) and is built only for an
|
|
41
|
+
* invocation, never at bootstrap.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* @Injectable({ scope: Scope.REQUEST })
|
|
46
|
+
* class Reports {
|
|
47
|
+
* constructor(@Inject(CLOUDFLARE_SCHEDULED_EVENT) private readonly trigger: CloudflareScheduledEvent) {}
|
|
48
|
+
*
|
|
49
|
+
* @Cron('0 3 * * *', { dialect: 'cloudflare' })
|
|
50
|
+
* async nightly(tick: CronInvocation) {
|
|
51
|
+
* if (!(await this.upstreamAvailable(tick.signal))) this.trigger.noRetry();
|
|
52
|
+
* }
|
|
53
|
+
* }
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
declare const CLOUDFLARE_SCHEDULED_EVENT: InjectionToken<CloudflareScheduledEvent>;
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/cloudflare-application.d.ts
|
|
59
|
+
/**
|
|
60
|
+
* Options accepted by {@link CloudflareApplication.mountOpenApi}.
|
|
61
|
+
*
|
|
62
|
+
* Re-exposes vela's `MountOpenApiOptions` type — derived structurally from
|
|
63
|
+
* the underlying `VelaApplication.mountOpenApi` signature so consumers don't
|
|
64
|
+
* have to reach into vela's internal subpaths to type the argument.
|
|
65
|
+
*/
|
|
66
|
+
type MountOpenApiOptions = Parameters<VelaApplication['mountOpenApi']>[0];
|
|
67
|
+
/**
|
|
68
|
+
* Wraps VelaApplication with Cloudflare-specific handlers:
|
|
69
|
+
* - `fetch` — HTTP request handler (from Hono)
|
|
70
|
+
* - `scheduled` — Cron trigger handler (runs the `@Cron()` jobs whose
|
|
71
|
+
* expression is the trigger's exact string)
|
|
72
|
+
* - `queue` — Queue consumer handler (`@QueueConsumer()` by physical queue,
|
|
73
|
+
* then `QueueModule`'s native consumer)
|
|
74
|
+
* - `mountOpenApi` — Serve an OpenAPI document (and optional Scalar UI) on
|
|
75
|
+
* the underlying Hono app
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
80
|
+
* export default {
|
|
81
|
+
* fetch: app.fetch,
|
|
82
|
+
* scheduled: app.scheduled.bind(app),
|
|
83
|
+
* queue: app.queue.bind(app),
|
|
84
|
+
* };
|
|
85
|
+
* ```
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* // Serve OpenAPI docs alongside your routes
|
|
90
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
91
|
+
* const document = createOpenApiDocument(AppModule);
|
|
92
|
+
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
93
|
+
* // GET /openapi.json -> JSON document
|
|
94
|
+
* // GET /scalar -> Scalar UI (loads from CDN)
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
declare class CloudflareApplication {
|
|
98
|
+
#private;
|
|
99
|
+
readonly env: VelaEnv;
|
|
100
|
+
constructor(app: VelaApplication, env: VelaEnv);
|
|
101
|
+
readonly fetch: (request: Request, env: VelaEnv, ctx?: ExecutionContext) => Promise<Response>;
|
|
102
|
+
getHonoApp(): ReturnType<VelaApplication['getHonoApp']>;
|
|
103
|
+
/**
|
|
104
|
+
* Resolve a provider from the application's DI container (delegates to
|
|
105
|
+
* `VelaApplication.get`). Handy in `createCloudflareWorker({ configure })`,
|
|
106
|
+
* which finishes the HTTP surface outside the DI request pipeline.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
111
|
+
* const auth = app.get(BetterAuthService);
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
readonly get: VelaApplication['get'];
|
|
115
|
+
get entrypoints(): VelaApplication['entrypoints'];
|
|
116
|
+
/** Enable CORS for every route, as `VelaApplication.enableCors()`; no rebuild needed. */
|
|
117
|
+
enableCors(options?: CorsOptions): this;
|
|
118
|
+
/**
|
|
119
|
+
* Serve a pre-built OpenAPI document (and optionally a Scalar UI) on the
|
|
120
|
+
* underlying Hono app. Delegates verbatim to `VelaApplication.mountOpenApi`,
|
|
121
|
+
* so the JSON endpoint defaults to `/openapi.json` and the Scalar UI (when
|
|
122
|
+
* opted in) defaults to `/scalar`. Edge-safe — the UI HTML loads Scalar from
|
|
123
|
+
* a CDN at runtime, nothing is bundled server-side.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { createOpenApiDocument } from '@velajs/vela/openapi';
|
|
128
|
+
*
|
|
129
|
+
* const app = await createCloudflareApp(AppModule, { env });
|
|
130
|
+
* const document = createOpenApiDocument(AppModule, {
|
|
131
|
+
* info: { title: 'My API', version: '1.0.0' },
|
|
132
|
+
* });
|
|
133
|
+
* app.mountOpenApi({ document, ui: 'scalar' });
|
|
134
|
+
* // GET /openapi.json -> { openapi: '3.1.0', ... }
|
|
135
|
+
* // GET /scalar -> Scalar UI HTML
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
mountOpenApi(options: MountOpenApiOptions): this;
|
|
139
|
+
/**
|
|
140
|
+
* Handle a Cloudflare cron trigger. Runs every core `@Cron()` job whose
|
|
141
|
+
* expression is exactly `event.cron` (the trigger string is compared as
|
|
142
|
+
* delivered, never re-evaluated) through `invokeScheduledJob`, the dispatch
|
|
143
|
+
* primitive every runtime shares. Each job receives only its
|
|
144
|
+
* `ScheduleInvocation`, runs in a fresh invocation scope seeded with
|
|
145
|
+
* {@link CLOUDFLARE_SCHEDULED_EVENT}, and honors signed `ScheduleModule`
|
|
146
|
+
* dispatch. The trigger settles after every matching job and its managed
|
|
147
|
+
* work (`EXECUTION_LIFETIME.waitUntil`/`defer`) settle; failures reject it.
|
|
148
|
+
*/
|
|
149
|
+
scheduled(event: ScheduledEvent, env: VelaEnv, _ctx?: {
|
|
150
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
151
|
+
}): Promise<void>;
|
|
152
|
+
/**
|
|
153
|
+
* Run one queue consumer inside a fresh request scope, through the shared
|
|
154
|
+
* guard → interceptor pipeline (components declared with
|
|
155
|
+
* `@UseGuards`/`@UseInterceptors`/`@UseFilters` on the consumer class or
|
|
156
|
+
* method). HTTP-global components deliberately do NOT apply — an HTTP auth
|
|
157
|
+
* guard has no business rejecting a queue batch. Unclaimed errors are
|
|
158
|
+
* reported once (`QueueModule`'s consumer reports its own) and rethrow so
|
|
159
|
+
* the platform's retry semantics stay intact.
|
|
160
|
+
*/
|
|
161
|
+
private dispatchEntrypoint;
|
|
162
|
+
/**
|
|
163
|
+
* Handle Cloudflare Queue consumer events. `@QueueConsumer()` handlers read
|
|
164
|
+
* from `app.entrypoints` claim a batch by its physical queue name and
|
|
165
|
+
* receive it whole. A batch no handler claims goes to `QueueModule`'s native
|
|
166
|
+
* consumer (`cloudflareQueues()` from `@velajs/cloudflare/queues`), which
|
|
167
|
+
* routes each job by its logical queue. Each dispatch runs inside a fresh
|
|
168
|
+
* request-scoped child (request-scoped providers rebuild per batch — no
|
|
169
|
+
* boot-time captives). A batch nothing claims rejects: resolving would let
|
|
170
|
+
* Cloudflare acknowledge every message implicitly.
|
|
171
|
+
*/
|
|
172
|
+
queue(batch: {
|
|
173
|
+
queue: string;
|
|
174
|
+
messages: readonly unknown[];
|
|
175
|
+
}, env: VelaEnv, ctx: {
|
|
176
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
177
|
+
}): Promise<void>;
|
|
178
|
+
/**
|
|
179
|
+
* A raw `@QueueConsumer` owns its physical queue's batches and must not carry
|
|
180
|
+
* jobs of a queue registered with `QueueModule`: those reach their
|
|
181
|
+
* `@Processor` only if the raw handler dispatches them itself, while
|
|
182
|
+
* `cloudflareQueues()` delivers registered queues. Warn once per physical and
|
|
183
|
+
* logical queue (unless diagnostics are silent); the raw consumer still
|
|
184
|
+
* receives and settles the batch.
|
|
185
|
+
*/
|
|
186
|
+
private warnRawJobs;
|
|
187
|
+
/**
|
|
188
|
+
* Abort the signals of scheduled jobs still running, wait for them and their
|
|
189
|
+
* managed work to settle, then close the application.
|
|
190
|
+
*/
|
|
191
|
+
close(signal?: string): Promise<void>;
|
|
192
|
+
}
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region src/cloudflare-factory.d.ts
|
|
195
|
+
interface CloudflareAppOptions {
|
|
196
|
+
globalPrefix?: string;
|
|
197
|
+
/** Routes served without the global prefix (`{ exclude }`). */
|
|
198
|
+
globalPrefixOptions?: GlobalPrefixOptions;
|
|
199
|
+
/** URI versioning: the version segment prefix (default `'v'`). */
|
|
200
|
+
versioning?: VersioningOptions;
|
|
201
|
+
security?: VelaSecurityOptions;
|
|
202
|
+
/** Enable CORS for every route: `true` or `CorsOptions`, as `app.enableCors()` takes. */
|
|
203
|
+
cors?: CorsOptions | boolean;
|
|
204
|
+
/** Further runtime adapters, composed after the Cloudflare adapter for each application. */
|
|
205
|
+
adapters?: RuntimeAdapter[];
|
|
206
|
+
}
|
|
207
|
+
interface CloudflareWorkerOptions extends CloudflareAppOptions {
|
|
208
|
+
/**
|
|
209
|
+
* Finish each application's HTTP surface, such as extra Hono routes, once per
|
|
210
|
+
* environment. It runs after the application is built and before any event,
|
|
211
|
+
* including concurrent cold events, reaches it; a throw fails that
|
|
212
|
+
* construction, and the next event retries. It must be synchronous and do no
|
|
213
|
+
* I/O (a returned promise fails the construction): read bindings in
|
|
214
|
+
* providers. Request middleware belongs in modules (`configure(consumer)`),
|
|
215
|
+
* which can inject `ENV`.
|
|
216
|
+
*/
|
|
217
|
+
configure?(app: CloudflareApplication, env: VelaEnv): void;
|
|
218
|
+
}
|
|
219
|
+
interface CreateCloudflareAppOptions extends CloudflareAppOptions {
|
|
220
|
+
/** Supply the platform environment inside fetch/queue/scheduled or a DO constructor. */
|
|
221
|
+
env: VelaEnv;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Bind an application to one environment: seeded as the global ENV before
|
|
225
|
+
* provider factories and lifecycle hooks, and asserted on every request. The
|
|
226
|
+
* adapter also registers the Worker's platform wiring: `WebSocketModule`
|
|
227
|
+
* forwards each authenticated gateway upgrade to the room's Durable Object,
|
|
228
|
+
* and `LiveModule` sends invalidations there. It supplies the
|
|
229
|
+
* `InternalDispatcher` transport, so signed queue and schedule dispatch
|
|
230
|
+
* re-enter this application's routes, and reports, through the diagnostics
|
|
231
|
+
* policy, schedule declarations a cron trigger cannot honor and binding-backed
|
|
232
|
+
* gateways without `WebSocketModule`.
|
|
233
|
+
*/
|
|
234
|
+
declare function cloudflareAdapter(options: {
|
|
235
|
+
env: VelaEnv;
|
|
236
|
+
}): RuntimeAdapter;
|
|
237
|
+
/**
|
|
238
|
+
* Build an application for one native Workers environment. Call inside a platform event.
|
|
239
|
+
* The root is static: a module class or a `DynamicModule` declared at module scope.
|
|
240
|
+
* Read bindings in providers (`@InjectEnv()`) and module factories
|
|
241
|
+
* (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
|
|
242
|
+
*/
|
|
243
|
+
declare function createCloudflareApp(rootModule: CloudflareRoot, options: CreateCloudflareAppOptions): Promise<CloudflareApplication>;
|
|
244
|
+
/**
|
|
245
|
+
* The well-known key under which a `createCloudflareWorker()` entry carries
|
|
246
|
+
* its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.
|
|
247
|
+
*/
|
|
248
|
+
declare const CLOUDFLARE_WORKER: unique symbol;
|
|
249
|
+
/** What a Worker entry is built from, for tools that load it outside a platform event. */
|
|
250
|
+
interface CloudflareWorkerDescriptor {
|
|
251
|
+
readonly rootModule: CloudflareRoot;
|
|
252
|
+
readonly options: CloudflareWorkerOptions;
|
|
253
|
+
/** The `VelaFactory.create()` options the Worker builds its application with for `env`. */
|
|
254
|
+
createOptions(env: VelaEnv): VelaCreateOptions;
|
|
255
|
+
/**
|
|
256
|
+
* `VelaFactory.create(rootModule, createOptions(env))`: the application
|
|
257
|
+
* without its Worker handlers or the `configure` hook, which receives the
|
|
258
|
+
* Workers application.
|
|
259
|
+
*/
|
|
260
|
+
createApplication(env: VelaEnv): Promise<VelaApplication>;
|
|
261
|
+
}
|
|
262
|
+
/** The exported handlers of a `createCloudflareWorker()` entry. */
|
|
263
|
+
interface CloudflareWorker {
|
|
264
|
+
fetch(request: Request, env: VelaEnv, ctx: ExecutionContext): Promise<Response>;
|
|
265
|
+
scheduled(event: ScheduledEvent, env: VelaEnv, ctx?: {
|
|
266
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
267
|
+
}): Promise<void>;
|
|
268
|
+
queue(batch: {
|
|
269
|
+
queue: string;
|
|
270
|
+
messages: readonly unknown[];
|
|
271
|
+
}, env: VelaEnv, ctx: {
|
|
272
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
273
|
+
}): Promise<void>;
|
|
274
|
+
/**
|
|
275
|
+
* Symbol-keyed, so the platform, which reads string-keyed handlers, ignores
|
|
276
|
+
* it; enumerable, so `{ ...worker, email }` keeps it for the CLI.
|
|
277
|
+
*/
|
|
278
|
+
readonly [CLOUDFLARE_WORKER]: CloudflareWorkerDescriptor;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Worker entrypoint with one bootstrap per environment identity. Concurrent cold
|
|
282
|
+
* events share construction, including `configure`; failed construction is
|
|
283
|
+
* evicted so the next event can retry. Weak keys stop this cache from
|
|
284
|
+
* retaining a replaced environment.
|
|
285
|
+
*/
|
|
286
|
+
declare function createCloudflareWorker(rootModule: CloudflareRoot, options?: CloudflareWorkerOptions): CloudflareWorker;
|
|
287
|
+
//#endregion
|
|
288
|
+
export { CloudflareWorkerOptions as a, createCloudflareApp as c, MountOpenApiOptions as d, CLOUDFLARE_SCHEDULED_EVENT as f, CloudflareWorkerDescriptor as i, createCloudflareWorker as l, ScheduledEvent as m, CloudflareAppOptions as n, CreateCloudflareAppOptions as o, CloudflareScheduledEvent as p, CloudflareWorker as r, cloudflareAdapter as s, CLOUDFLARE_WORKER as t, CloudflareApplication as u };
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { assertCloudflareEnvironment } from "./environment.js";
|
|
2
|
+
import { registerScheduledEventSeed } from "./scheduled-event.js";
|
|
3
|
+
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
4
|
+
import { registerCloudflarePlatform } from "./platform.js";
|
|
5
|
+
import { reportCloudflareScheduleDiagnostics } from "./schedule-diagnostics.js";
|
|
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 { VelaFactory } from "@velajs/vela";
|
|
10
|
+
//#region src/cloudflare-factory.ts
|
|
11
|
+
function readStrings(meta, property) {
|
|
12
|
+
const value = typeof meta === "object" && meta !== null ? Reflect.get(meta, property) : void 0;
|
|
13
|
+
if (typeof value === "string") return [value];
|
|
14
|
+
if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
|
|
15
|
+
throw new TypeError(`Invalid queue consumer metadata: ${property}.`);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* `@QueueConsumer` handlers own their physical queue. A `QueueModule`
|
|
19
|
+
* registration that pins the same physical queue with `consumer` would never
|
|
20
|
+
* see its batches, so bootstrap rejects the overlap.
|
|
21
|
+
*/
|
|
22
|
+
function assertQueueConsumerOwnership(entrypoints) {
|
|
23
|
+
const pinned = new Set(entrypoints.ofKind("cf:queue:module").flatMap((entry) => readStrings(entry.meta, "consumers")));
|
|
24
|
+
for (const entry of entrypoints.ofKind("cf:queue")) {
|
|
25
|
+
const [queue] = readStrings(entry.meta, "queueName");
|
|
26
|
+
if (queue !== void 0 && pinned.has(queue)) throw new Error(`Ambiguous consumer ownership for queue '${queue}': @QueueConsumer('${queue}') and a QueueModule.registerQueue({ consumer: '${queue}' }) both claim it. Keep one owner.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Bind an application to one environment: seeded as the global ENV before
|
|
31
|
+
* provider factories and lifecycle hooks, and asserted on every request. The
|
|
32
|
+
* adapter also registers the Worker's platform wiring: `WebSocketModule`
|
|
33
|
+
* forwards each authenticated gateway upgrade to the room's Durable Object,
|
|
34
|
+
* and `LiveModule` sends invalidations there. It supplies the
|
|
35
|
+
* `InternalDispatcher` transport, so signed queue and schedule dispatch
|
|
36
|
+
* re-enter this application's routes, and reports, through the diagnostics
|
|
37
|
+
* policy, schedule declarations a cron trigger cannot honor and binding-backed
|
|
38
|
+
* gateways without `WebSocketModule`.
|
|
39
|
+
*/
|
|
40
|
+
function cloudflareAdapter(options) {
|
|
41
|
+
const { env } = options;
|
|
42
|
+
return {
|
|
43
|
+
name: "cloudflare",
|
|
44
|
+
requestMiddleware: [async (context, next) => {
|
|
45
|
+
assertCloudflareEnvironment(env, context.env);
|
|
46
|
+
await next();
|
|
47
|
+
}],
|
|
48
|
+
invocationTransport: ({ app }) => (request) => Promise.resolve(app.fetch(request, env)),
|
|
49
|
+
getClientIp: (c) => c.req.header("cf-connecting-ip") ?? null,
|
|
50
|
+
configureContainer: (container) => {
|
|
51
|
+
registerCloudflarePlatform(container, env, {
|
|
52
|
+
websocket: workerWebSocketTransport(env),
|
|
53
|
+
live: workerLivePlatform(env, container)
|
|
54
|
+
});
|
|
55
|
+
registerScheduledEventSeed(container);
|
|
56
|
+
},
|
|
57
|
+
onBootstrap: ({ app, container, discovery }) => {
|
|
58
|
+
assertQueueConsumerOwnership(app.entrypoints);
|
|
59
|
+
reportCloudflareScheduleDiagnostics(container, app.entrypoints);
|
|
60
|
+
reportUnservedGateways(container, discovery);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The `VelaFactory.create()` options an application for `options.env` is built
|
|
66
|
+
* with: that environment (seeded as ENV and sent by test clients as `c.env`),
|
|
67
|
+
* the Cloudflare adapter bound to it, then any further adapters.
|
|
68
|
+
*/
|
|
69
|
+
function cloudflareCreateOptions(options) {
|
|
70
|
+
return {
|
|
71
|
+
env: options.env,
|
|
72
|
+
globalPrefix: options.globalPrefix,
|
|
73
|
+
globalPrefixOptions: options.globalPrefixOptions,
|
|
74
|
+
versioning: options.versioning,
|
|
75
|
+
security: options.security,
|
|
76
|
+
cors: options.cors,
|
|
77
|
+
adapters: [cloudflareAdapter(options), ...options.adapters ?? []]
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Build an application for one native Workers environment. Call inside a platform event.
|
|
82
|
+
* The root is static: a module class or a `DynamicModule` declared at module scope.
|
|
83
|
+
* Read bindings in providers (`@InjectEnv()`) and module factories
|
|
84
|
+
* (`forRootAsync({ inject: [ENV], useFactory })`), which run for each application.
|
|
85
|
+
*/
|
|
86
|
+
async function createCloudflareApp(rootModule, options) {
|
|
87
|
+
const velaApp = await VelaFactory.create(rootModule, cloudflareCreateOptions(options));
|
|
88
|
+
return new CloudflareApplication(velaApp, options.env);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Run a Worker's `configure` hook on the application built for `env`, as
|
|
92
|
+
* `createCloudflareWorker()` does before any event reaches it: a throw or a
|
|
93
|
+
* returned promise closes the application and fails the construction.
|
|
94
|
+
*/
|
|
95
|
+
async function configureCloudflareApplication(app, env, configure) {
|
|
96
|
+
if (!configure) return app;
|
|
97
|
+
try {
|
|
98
|
+
const result = configure(app, env);
|
|
99
|
+
if (result instanceof Promise) {
|
|
100
|
+
result.catch(() => {});
|
|
101
|
+
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.");
|
|
102
|
+
}
|
|
103
|
+
} catch (error) {
|
|
104
|
+
await app.close().catch(() => {});
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
return app;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The well-known key under which a `createCloudflareWorker()` entry carries
|
|
111
|
+
* its {@link CloudflareWorkerDescriptor}: `Symbol.for('vela.cloudflare.worker')`.
|
|
112
|
+
*/
|
|
113
|
+
const CLOUDFLARE_WORKER = Symbol.for("vela.cloudflare.worker");
|
|
114
|
+
/**
|
|
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.
|
|
119
|
+
*/
|
|
120
|
+
function createCloudflareWorker(rootModule, options = {}) {
|
|
121
|
+
const { configure, ...appOptions } = options;
|
|
122
|
+
const applications = /* @__PURE__ */ new WeakMap();
|
|
123
|
+
const build = async (env) => configureCloudflareApplication(await createCloudflareApp(rootModule, {
|
|
124
|
+
...appOptions,
|
|
125
|
+
env
|
|
126
|
+
}), 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;
|
|
136
|
+
};
|
|
137
|
+
const descriptor = {
|
|
138
|
+
rootModule,
|
|
139
|
+
options,
|
|
140
|
+
createOptions: (env) => cloudflareCreateOptions({
|
|
141
|
+
...appOptions,
|
|
142
|
+
env
|
|
143
|
+
}),
|
|
144
|
+
createApplication: (env) => VelaFactory.create(rootModule, cloudflareCreateOptions({
|
|
145
|
+
...appOptions,
|
|
146
|
+
env
|
|
147
|
+
}))
|
|
148
|
+
};
|
|
149
|
+
return {
|
|
150
|
+
async fetch(request, env, ctx) {
|
|
151
|
+
return (await application(env)).fetch(request, env, ctx);
|
|
152
|
+
},
|
|
153
|
+
async scheduled(event, env, ctx) {
|
|
154
|
+
return (await application(env)).scheduled(event, env, ctx);
|
|
155
|
+
},
|
|
156
|
+
async queue(batch, env, ctx) {
|
|
157
|
+
return (await application(env)).queue(batch, env, ctx);
|
|
158
|
+
},
|
|
159
|
+
[CLOUDFLARE_WORKER]: descriptor
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
export { CLOUDFLARE_WORKER, cloudflareAdapter, cloudflareCreateOptions, configureCloudflareApplication, createCloudflareApp, createCloudflareWorker };
|
|
164
|
+
|
|
165
|
+
//# sourceMappingURL=cloudflare-factory.js.map
|
|
@@ -0,0 +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":"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"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { defineMetadata, getMetadata, registerEntrypointKind } from "@velajs/vela/module-kit";
|
|
2
|
+
//#region src/decorators/queue-consumer.ts
|
|
3
|
+
const QUEUE_CONSUMER_METADATA_KEY = "cloudflare:queue-consumer";
|
|
4
|
+
registerEntrypointKind({
|
|
5
|
+
kind: "cf:queue",
|
|
6
|
+
metaKey: QUEUE_CONSUMER_METADATA_KEY,
|
|
7
|
+
level: "method"
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Marks a method as a queue consumer handler.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* @Injectable()
|
|
15
|
+
* class WorkerService {
|
|
16
|
+
* @QueueConsumer('email-queue')
|
|
17
|
+
* async processEmails(batch: MessageBatch) {
|
|
18
|
+
* for (const msg of batch.messages) {
|
|
19
|
+
* console.log('Processing:', msg.body);
|
|
20
|
+
* msg.ack();
|
|
21
|
+
* }
|
|
22
|
+
* }
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
function QueueConsumer(queueName) {
|
|
27
|
+
return (target, propertyKey, _descriptor) => {
|
|
28
|
+
const existing = getMetadata(QUEUE_CONSUMER_METADATA_KEY, target.constructor) ?? [];
|
|
29
|
+
existing.push({
|
|
30
|
+
queueName,
|
|
31
|
+
methodName: String(propertyKey)
|
|
32
|
+
});
|
|
33
|
+
defineMetadata(QUEUE_CONSUMER_METADATA_KEY, existing, target.constructor);
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { QueueConsumer };
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=queue-consumer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queue-consumer.js","names":[],"sources":["../../src/decorators/queue-consumer.ts"],"sourcesContent":["import { defineMetadata, getMetadata, registerEntrypointKind } from '@velajs/vela/module-kit';\n\nconst QUEUE_CONSUMER_METADATA_KEY = 'cloudflare:queue-consumer';\n\n// Open entrypoint kind: any adapter can enumerate queue consumers via\n// `app.entrypoints.ofKind('cf:queue')` — declared here, next to the decorator,\n// with zero vela-core involvement.\nregisterEntrypointKind({ kind: 'cf:queue', metaKey: QUEUE_CONSUMER_METADATA_KEY, level: 'method' });\n\nexport interface QueueConsumerMetadata {\n queueName: string;\n methodName: string;\n}\n\n/**\n * Marks a method as a queue consumer handler.\n *\n * @example\n * ```ts\n * @Injectable()\n * class WorkerService {\n * @QueueConsumer('email-queue')\n * async processEmails(batch: MessageBatch) {\n * for (const msg of batch.messages) {\n * console.log('Processing:', msg.body);\n * msg.ack();\n * }\n * }\n * }\n * ```\n */\nexport function QueueConsumer(queueName: string): MethodDecorator {\n return (target: object, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const existing: QueueConsumerMetadata[] =\n (getMetadata(QUEUE_CONSUMER_METADATA_KEY, target.constructor) as QueueConsumerMetadata[]) ??\n [];\n existing.push({ queueName, methodName: String(propertyKey) });\n defineMetadata(QUEUE_CONSUMER_METADATA_KEY, existing, target.constructor);\n };\n}\n\nexport function getQueueConsumerMetadata(target: object): QueueConsumerMetadata[] {\n const ctor = target.constructor ?? target;\n return (getMetadata(QUEUE_CONSUMER_METADATA_KEY, ctor) as QueueConsumerMetadata[]) ?? [];\n}\n"],"mappings":";;AAEA,MAAM,8BAA8B;AAKpC,uBAAuB;CAAE,MAAM;CAAY,SAAS;CAA6B,OAAO;AAAS,CAAC;;;;;;;;;;;;;;;;;;AAwBlG,SAAgB,cAAc,WAAoC;CAChE,QAAQ,QAAgB,aAA8B,gBAAoC;EACxF,MAAM,WACH,YAAY,6BAA6B,OAAO,WAAW,KAC5D,CAAC;EACH,SAAS,KAAK;GAAE;GAAW,YAAY,OAAO,WAAW;EAAE,CAAC;EAC5D,eAAe,6BAA6B,UAAU,OAAO,WAAW;CAC1E;AACF"}
|
|
@@ -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"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import {
|
|
2
|
+
import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
|
|
3
|
+
import { l as VelaDoPitrRpc, t as VelaNonceDurableObject } from "./nonce.durable-object-Bg1e0BMD.js";
|
|
4
|
+
import { DurableObject } from "cloudflare:workers";
|
|
3
5
|
import { VelaEnv } from "@velajs/vela";
|
|
4
6
|
import { BroadcastCommand } from "@velajs/vela/websocket";
|
|
5
7
|
import { CommitStamp, InvalidationCommand, LiveInspection } from "@velajs/vela/live";
|
|
6
|
-
import { DurableObject } from "cloudflare:workers";
|
|
7
8
|
//#region src/websocket/websocket.durable-object.d.ts
|
|
8
9
|
/**
|
|
9
10
|
* Base class for the WebSocket Durable Object. The user exports a named subclass
|
|
@@ -16,7 +17,10 @@ import { DurableObject } from "cloudflare:workers";
|
|
|
16
17
|
*
|
|
17
18
|
* It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
|
|
18
19
|
* bridge DO hibernation) and forwards every event into the runtime-agnostic
|
|
19
|
-
* `WsDispatcher` via {@link DoWebSocketHost}. The
|
|
20
|
+
* `WsDispatcher` via {@link DoWebSocketHost}. The application imports the core
|
|
21
|
+
* `WebSocketModule.forRoot()`: this object registers the platform that binds
|
|
22
|
+
* its server to these sockets, delivers live invalidations locally and keeps
|
|
23
|
+
* the live cursor log in its SQLite storage. The DO's `env` is the
|
|
20
24
|
* application's ENV, as in the Worker.
|
|
21
25
|
*/
|
|
22
26
|
export declare function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (ctx: DurableObjectState, env: VelaEnv) => DurableObject<VelaEnv> & VelaDoPitrRpc & {
|
|
@@ -25,5 +29,4 @@ export declare function VelaWebSocketDurableObject(rootModule: CloudflareRoot):
|
|
|
25
29
|
inspectLive(): Promise<LiveInspection>;
|
|
26
30
|
};
|
|
27
31
|
//#endregion
|
|
28
|
-
export { VelaNonceDurableObject };
|
|
29
|
-
//# sourceMappingURL=durable-objects.d.ts.map
|
|
32
|
+
export { VelaNonceDurableObject };
|