@velajs/cloudflare 1.31.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +154 -10
  3. package/dist/bindings.js +17 -1
  4. package/dist/bindings.js.map +1 -1
  5. package/dist/{cloudflare-factory-eGiet0mg.d.ts → cloudflare-application-CXDy9C1R.d.ts} +9 -98
  6. package/dist/cloudflare-application.js +8 -0
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +153 -20
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/durable-object/boot.js +76 -0
  12. package/dist/durable-object/boot.js.map +1 -0
  13. package/dist/durable-object/host-dispatch.js +134 -0
  14. package/dist/durable-object/host-dispatch.js.map +1 -0
  15. package/dist/durable-object/host-methods.js +47 -0
  16. package/dist/durable-object/host-methods.js.map +1 -0
  17. package/dist/durable-object/tokens.js +17 -0
  18. package/dist/durable-object/tokens.js.map +1 -0
  19. package/dist/durable-object/vela-durable-object.js +121 -0
  20. package/dist/durable-object/vela-durable-object.js.map +1 -0
  21. package/dist/durable-objects.d.ts +131 -9
  22. package/dist/durable-objects.js +3 -1
  23. package/dist/email/email-dispatch.js +65 -0
  24. package/dist/email/email-dispatch.js.map +1 -0
  25. package/dist/email/on-email.js +57 -0
  26. package/dist/email/on-email.js.map +1 -0
  27. package/dist/email.d.ts +51 -0
  28. package/dist/email.js +3 -0
  29. package/dist/entrypoint/vela-entrypoint.js +160 -0
  30. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  31. package/dist/entrypoints.d.ts +93 -0
  32. package/dist/entrypoints.js +2 -0
  33. package/dist/host/host-invoker.js +276 -0
  34. package/dist/host/host-invoker.js.map +1 -0
  35. package/dist/host/host-members.js +73 -0
  36. package/dist/host/host-members.js.map +1 -0
  37. package/dist/host-members-DECj_4yz.d.ts +13 -0
  38. package/dist/index.d.ts +74 -13
  39. package/dist/index.js +4 -3
  40. package/dist/root-module.js +19 -0
  41. package/dist/root-module.js.map +1 -0
  42. package/dist/rpc/entrypoint-error.js +145 -0
  43. package/dist/rpc/entrypoint-error.js.map +1 -0
  44. package/dist/services/kv-cache.store.js +4 -4
  45. package/dist/services/kv-cache.store.js.map +1 -1
  46. package/dist/tail/on-tail.js +46 -0
  47. package/dist/tail/on-tail.js.map +1 -0
  48. package/dist/tail/tail-dispatch.js +67 -0
  49. package/dist/tail/tail-dispatch.js.map +1 -0
  50. package/dist/tail.d.ts +39 -0
  51. package/dist/tail.js +2 -0
  52. package/dist/testing.d.ts +55 -3
  53. package/dist/testing.js +78 -1
  54. package/dist/testing.js.map +1 -1
  55. package/dist/websocket/binding-gateways.js +1 -1
  56. package/dist/websocket/binding-gateways.js.map +1 -1
  57. package/dist/websocket/do-bootstrap.js +40 -37
  58. package/dist/websocket/do-bootstrap.js.map +1 -1
  59. package/dist/websocket/websocket.durable-object.js +37 -8
  60. package/dist/websocket/websocket.durable-object.js.map +1 -1
  61. package/dist/worker-events.js +49 -0
  62. package/dist/worker-events.js.map +1 -0
  63. package/dist/workflow/vela-workflow.js +104 -0
  64. package/dist/workflow/vela-workflow.js.map +1 -0
  65. package/dist/workflows.d.ts +82 -0
  66. package/dist/workflows.js +2 -0
  67. package/package.json +23 -7
  68. package/dist/root-module-C23bUwt_.d.ts +0 -11
@@ -0,0 +1,276 @@
1
+ import { EntrypointError, internalEntrypointError, renderEntrypointError } from "../rpc/entrypoint-error.js";
2
+ import { PipelineRunner, buildEntrypointExecutionContext, createExecutionScope, getEntrypointModuleId, getMetadata, resolveErrorReporter, resolveScopedComponentsAsync, shouldFilterCatch } from "@velajs/vela/module-kit";
3
+ //#region src/host/host-invoker.ts
4
+ /** The first scoped filter (closest first) that catches `error`. */
5
+ function claimingFilter(filters, error) {
6
+ return filters.find((filter) => shouldFilterCatch(filter, error));
7
+ }
8
+ /** A filter that throws replaces the error; its own throw is reported too. */
9
+ async function catchWith(filter, error, { context, reporter, report }) {
10
+ try {
11
+ return {
12
+ handled: true,
13
+ value: await filter.catch(error, context)
14
+ };
15
+ } catch (replacement) {
16
+ if (replacement !== error) reporter.report(replacement, {
17
+ ...report,
18
+ note: "exception filter threw"
19
+ });
20
+ return {
21
+ handled: false,
22
+ error: replacement
23
+ };
24
+ }
25
+ }
26
+ /**
27
+ * A JS-RPC call: a claiming filter may recover with a result (returning
28
+ * nothing keeps the failure); otherwise the call rejects with the rendered
29
+ * {@link EntrypointError}.
30
+ */
31
+ const rpcSettlement = {
32
+ success: (value) => value,
33
+ async failure(error, failure) {
34
+ const filter = claimingFilter(failure.filters, error);
35
+ let current = error;
36
+ if (filter) {
37
+ const caught = await catchWith(filter, error, failure);
38
+ if (caught.handled && caught.value !== void 0) return caught.value;
39
+ if (!caught.handled) current = caught.error;
40
+ }
41
+ throw renderEntrypointError(current, failure.reporter, failure.context);
42
+ }
43
+ };
44
+ /**
45
+ * A platform event: a claiming filter handles the failure (a value it returns
46
+ * becomes the result); otherwise the platform sees the error.
47
+ */
48
+ function platformSettlement(completionFails) {
49
+ return {
50
+ completionFails,
51
+ success: (value) => value,
52
+ async failure(error, failure) {
53
+ const filter = claimingFilter(failure.filters, error);
54
+ if (!filter) throw error;
55
+ const caught = await catchWith(filter, error, failure);
56
+ if (!caught.handled) throw caught.error;
57
+ return caught.value;
58
+ }
59
+ };
60
+ }
61
+ /**
62
+ * An event whose failures must never reach the platform, such as a tail
63
+ * event: the failure was reported, and a claiming filter still runs.
64
+ */
65
+ const observedSettlement = {
66
+ success: () => void 0,
67
+ async failure(error, failure) {
68
+ const filter = claimingFilter(failure.filters, error);
69
+ if (filter) await catchWith(filter, error, failure);
70
+ }
71
+ };
72
+ /**
73
+ * Runs invocations of one host's methods: each in a fresh execution scope
74
+ * (request-scoped providers are built per invocation) through the host's
75
+ * scoped guards, pipes (when asked), interceptors and exception filters.
76
+ * Application-wide `APP_*` components do not apply: the callers are other
77
+ * Workers and the platform, with no HTTP request. Failures are reported
78
+ * first, then settled the way the invocation's kind requires.
79
+ */
80
+ var HostInvoker = class {
81
+ #container;
82
+ #host;
83
+ #moduleId;
84
+ #edge;
85
+ #waitUntil;
86
+ constructor(options) {
87
+ this.#container = options.container;
88
+ this.#host = options.host;
89
+ this.#moduleId = options.moduleId;
90
+ this.#edge = options.edge;
91
+ this.#waitUntil = options.waitUntil;
92
+ }
93
+ /** The report context of an invocation of `method`. */
94
+ report(kind, method) {
95
+ return {
96
+ edge: this.#edge,
97
+ source: `${this.#host.name}.${String(method)}`,
98
+ kind
99
+ };
100
+ }
101
+ /** Report through the application, or the console when its reporter cannot be built. */
102
+ reportOutside(error, report) {
103
+ try {
104
+ resolveErrorReporter(this.#container).report(error, report);
105
+ } catch {
106
+ console.error(`[vela] ${report.edge} error in ${report.source ?? "an entrypoint"}:`, error);
107
+ }
108
+ }
109
+ async invoke(invocation) {
110
+ const root = this.#container;
111
+ const report = this.report(invocation.kind, invocation.method);
112
+ const scope = createExecutionScope(root);
113
+ let outcome;
114
+ try {
115
+ invocation.seed?.(scope.container);
116
+ outcome = {
117
+ ok: true,
118
+ value: await this.#run(scope.container, invocation, report)
119
+ };
120
+ } catch (error) {
121
+ outcome = {
122
+ ok: false,
123
+ error
124
+ };
125
+ }
126
+ let transmission;
127
+ try {
128
+ transmission = outcome.ok ? invocation.transmit?.(outcome.value) : void 0;
129
+ } catch (error) {
130
+ outcome = {
131
+ ok: false,
132
+ error
133
+ };
134
+ }
135
+ if (transmission?.background) {
136
+ this.#finishLater(scope, transmission.sent, report);
137
+ return transmission.value;
138
+ }
139
+ try {
140
+ await scope.finish(transmission?.sent);
141
+ } catch (completion) {
142
+ this.reportOutside(completion, {
143
+ ...report,
144
+ note: "managed work failed after the invocation"
145
+ });
146
+ if (invocation.settlement.completionFails && outcome.ok) outcome = {
147
+ ok: false,
148
+ error: completion
149
+ };
150
+ }
151
+ if (!outcome.ok) throw outcome.error;
152
+ return transmission ? transmission.value : outcome.value;
153
+ }
154
+ /** Finish `scope` after `boundary` settles, reporting a failure; the platform waits for it. */
155
+ #finishLater(scope, boundary, report) {
156
+ const completion = scope.finish(boundary).catch((error) => {
157
+ this.reportOutside(error, {
158
+ ...report,
159
+ note: "managed work failed after the response"
160
+ });
161
+ });
162
+ this.#waitUntil?.(completion);
163
+ }
164
+ async #run(scope, invocation, report) {
165
+ const host = this.#host;
166
+ const moduleId = this.#moduleId;
167
+ const { kind, method, args, settlement } = invocation;
168
+ const context = buildEntrypointExecutionContext(kind, host, method, "payload" in invocation ? invocation.payload : args, moduleId, scope);
169
+ const reporter = resolveErrorReporter(scope);
170
+ let filters = [];
171
+ try {
172
+ filters = (await resolveScopedComponentsAsync("filter", host, method, scope, moduleId)).toReversed();
173
+ const guards = await resolveScopedComponentsAsync("guard", host, method, scope, moduleId);
174
+ const interceptors = await resolveScopedComponentsAsync("interceptor", host, method, scope, moduleId);
175
+ const value = await PipelineRunner.run({
176
+ context,
177
+ guards,
178
+ interceptors,
179
+ resolveArgs: () => invocation.pipes ? this.#transformArguments(scope, method, args) : Promise.resolve([...args]),
180
+ invoke: async (resolved) => {
181
+ const instance = await scope.resolveAsync(host, moduleId);
182
+ if (typeof instance !== "object" || instance === null) throw new TypeError(`${host.name} did not resolve to an object.`);
183
+ const handler = Reflect.get(instance, method);
184
+ if (typeof handler !== "function") throw new TypeError(`${host.name}.${String(method)} is not a method.`);
185
+ return Reflect.apply(handler, instance, resolved);
186
+ }
187
+ });
188
+ return settlement.success(value);
189
+ } catch (error) {
190
+ if (invocation.passthrough?.(error) === true) throw error;
191
+ reporter.report(error, report);
192
+ return settlement.failure(error, {
193
+ filters,
194
+ context,
195
+ reporter,
196
+ report
197
+ });
198
+ }
199
+ }
200
+ /** Scoped pipes transform each argument, typed by the method's parameter metadata. */
201
+ async #transformArguments(scope, method, args) {
202
+ const pipes = await resolveScopedComponentsAsync("pipe", this.#host, method, scope, this.#moduleId);
203
+ if (pipes.length === 0) return [...args];
204
+ const types = getMetadata("design:paramtypes", this.#host.prototype, method);
205
+ const transformed = [];
206
+ for (const [index, argument] of args.entries()) {
207
+ const metadata = {
208
+ type: "custom",
209
+ metatype: types?.[index]
210
+ };
211
+ let value = argument;
212
+ for (const pipe of pipes) value = await (pipe.transformAsync ? pipe.transformAsync(value, metadata) : pipe.transform(value, metadata));
213
+ transformed.push(value);
214
+ }
215
+ return transformed;
216
+ }
217
+ };
218
+ /**
219
+ * Call the RPC method `method` of a host through `invoker`. It rejects only
220
+ * with an {@link EntrypointError}: a method `methods` does not list answers
221
+ * `404 not_found`, and a failure outside the pipeline is reported and becomes
222
+ * `500 internal`.
223
+ */
224
+ async function callRpcMethod(invoker, methods, method, args, seed) {
225
+ if (!methods.has(method)) throw new EntrypointError({
226
+ status: 404,
227
+ code: "not_found",
228
+ message: "Unknown RPC method"
229
+ });
230
+ try {
231
+ return await invoker.invoke({
232
+ kind: "rpc",
233
+ method,
234
+ args,
235
+ settlement: rpcSettlement,
236
+ pipes: true,
237
+ seed
238
+ });
239
+ } catch (error) {
240
+ if (error instanceof EntrypointError) throw error;
241
+ invoker.reportOutside(error, invoker.report("rpc", method));
242
+ throw internalEntrypointError();
243
+ }
244
+ }
245
+ /**
246
+ * An invoker of a decorated method entrypoint (`@OnEmail()`, `@OnTail()`):
247
+ * its class, resolved in the module that registered it.
248
+ */
249
+ function entrypointInvoker(container, entrypoint, edge) {
250
+ const { token } = entrypoint;
251
+ if (typeof token !== "function") throw new TypeError("Entrypoint token must be a class.");
252
+ return new HostInvoker({
253
+ container,
254
+ host: token,
255
+ moduleId: getEntrypointModuleId(container, entrypoint),
256
+ edge
257
+ });
258
+ }
259
+ /** Wait for every invocation, even when one fails before its siblings; then fail with them. */
260
+ async function settleInvocations(work) {
261
+ const errors = (await Promise.allSettled(work)).flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
262
+ if (errors.length === 1) throw errors[0];
263
+ if (errors.length > 1) throw new AggregateError(errors, "Multiple entrypoint handlers failed.");
264
+ }
265
+ /**
266
+ * The module a host added to the root module's providers is resolved in: the
267
+ * root's registration when there are several.
268
+ */
269
+ function hostModuleId(container, host, rootClass) {
270
+ const owners = container.getOwnerModuleIds(host);
271
+ return owners.find((owner) => container.getModuleScope(owner)?.moduleClass === rootClass) ?? owners[0];
272
+ }
273
+ //#endregion
274
+ export { HostInvoker, callRpcMethod, catchWith, claimingFilter, entrypointInvoker, hostModuleId, observedSettlement, platformSettlement, rpcSettlement, settleInvocations };
275
+
276
+ //# sourceMappingURL=host-invoker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-invoker.js","names":[],"sources":["../../src/host/host-invoker.ts"],"sourcesContent":["/* eslint-disable no-await-in-loop -- Pipes and exception filters keep their declared order. */\nimport type { ErrorReportContext, ExceptionFilter, Type } from '@velajs/vela';\nimport {\n PipelineRunner,\n buildEntrypointExecutionContext,\n createExecutionScope,\n getEntrypointModuleId,\n getMetadata,\n resolveErrorReporter,\n resolveScopedComponentsAsync,\n shouldFilterCatch,\n type Container,\n type Entrypoint,\n type EntrypointExecutionContext,\n type ErrorReporter,\n type ExecutionScope,\n} from '@velajs/vela/module-kit';\nimport {\n EntrypointError,\n internalEntrypointError,\n renderEntrypointError,\n} from '../rpc/entrypoint-error';\n\n/** What a failed invocation hands its settlement, after the failure was reported. */\nexport interface InvocationFailure {\n readonly filters: readonly ExceptionFilter[];\n readonly context: EntrypointExecutionContext;\n readonly reporter: ErrorReporter;\n readonly report: ErrorReportContext;\n}\n\n/** How an invocation's result is sent after its handler returned. */\nexport interface Transmission<T> {\n /** What the invocation returns in place of the handler's result. */\n readonly value: T;\n /** Settles once the result was sent, failed or was cancelled. */\n readonly sent: Promise<unknown>;\n /** Finish the scope after the invocation returns, rather than before. */\n readonly background: boolean;\n}\n\n/** How one kind of invocation ends: its result, and what a failure becomes. */\nexport interface Settlement<T> {\n success(value: unknown): T;\n failure(error: unknown, failure: InvocationFailure): Promise<T>;\n /** Managed work that fails after a successful handler fails the invocation. */\n readonly completionFails?: boolean;\n}\n\n/** The first scoped filter (closest first) that catches `error`. */\nexport function claimingFilter(\n filters: readonly ExceptionFilter[],\n error: unknown,\n): ExceptionFilter | undefined {\n return filters.find((filter) => shouldFilterCatch(filter, error));\n}\n\n/** A filter that throws replaces the error; its own throw is reported too. */\nexport async function catchWith(\n filter: ExceptionFilter,\n error: unknown,\n { context, reporter, report }: InvocationFailure,\n): Promise<{ handled: true; value: unknown } | { handled: false; error: unknown }> {\n try {\n // eslint-disable-next-line promise/valid-params -- The Vela ExceptionFilter hook.\n return { handled: true, value: await filter.catch(error, context) };\n } catch (replacement) {\n if (replacement !== error) {\n reporter.report(replacement, { ...report, note: 'exception filter threw' });\n }\n return { handled: false, error: replacement };\n }\n}\n\n/**\n * A JS-RPC call: a claiming filter may recover with a result (returning\n * nothing keeps the failure); otherwise the call rejects with the rendered\n * {@link EntrypointError}.\n */\nexport const rpcSettlement: Settlement<unknown> = {\n success: (value) => value,\n async failure(error, failure) {\n const filter = claimingFilter(failure.filters, error);\n let current = error;\n if (filter) {\n const caught = await catchWith(filter, error, failure);\n if (caught.handled && caught.value !== undefined) return caught.value;\n if (!caught.handled) current = caught.error;\n }\n throw renderEntrypointError(current, failure.reporter, failure.context);\n },\n};\n\n/**\n * A platform event: a claiming filter handles the failure (a value it returns\n * becomes the result); otherwise the platform sees the error.\n */\nexport function platformSettlement(completionFails: boolean): Settlement<unknown> {\n return {\n completionFails,\n success: (value) => value,\n async failure(error, failure) {\n const filter = claimingFilter(failure.filters, error);\n if (!filter) throw error;\n const caught = await catchWith(filter, error, failure);\n if (!caught.handled) throw caught.error;\n return caught.value;\n },\n };\n}\n\n/**\n * An event whose failures must never reach the platform, such as a tail\n * event: the failure was reported, and a claiming filter still runs.\n */\nexport const observedSettlement: Settlement<void> = {\n success: () => undefined,\n async failure(error, failure) {\n const filter = claimingFilter(failure.filters, error);\n if (filter) await catchWith(filter, error, failure);\n },\n};\n\n/** One invocation of a host method. */\nexport interface HostInvocation<T> {\n /** `ExecutionContext.getType()`: `'rpc'`, `'cf:workflow'`, ... */\n readonly kind: string;\n readonly method: string | symbol;\n readonly args: readonly unknown[];\n /** `ExecutionContext.getPayload()`; the arguments by default. */\n readonly payload?: unknown;\n readonly settlement: Settlement<T>;\n /** Transform each argument through the scoped pipes (RPC arguments). */\n readonly pipes?: boolean;\n /** Seed request-scoped values, such as the caller's props, into the invocation scope. */\n readonly seed?: (scope: Container) => void;\n /** How a successful result is sent, such as a streamed response body. */\n readonly transmit?: (value: T) => Transmission<T> | undefined;\n /**\n * Whether `error` is the platform steering the invocation rather than a\n * failure of it, such as the Workflows engine pausing a run: it is rethrown\n * as it is, never reported or handed to an exception filter.\n */\n readonly passthrough?: (error: unknown) => boolean;\n}\n\n/** What a {@link HostInvoker} runs its invocations against. */\nexport interface HostInvokerOptions {\n /** The application container each invocation scope is a child of. */\n readonly container: Container;\n /** The class whose method each invocation calls, resolved in the invocation scope. */\n readonly host: Type;\n /** The module the host is resolved in, and its scoped components. */\n readonly moduleId: string | undefined;\n /** The `ErrorReportContext.edge` failures are reported on. */\n readonly edge: ErrorReportContext['edge'];\n /** Keeps the platform object alive for work that outlives an invocation. */\n readonly waitUntil?: (promise: Promise<unknown>) => void;\n}\n\n/**\n * Runs invocations of one host's methods: each in a fresh execution scope\n * (request-scoped providers are built per invocation) through the host's\n * scoped guards, pipes (when asked), interceptors and exception filters.\n * Application-wide `APP_*` components do not apply: the callers are other\n * Workers and the platform, with no HTTP request. Failures are reported\n * first, then settled the way the invocation's kind requires.\n */\nexport class HostInvoker {\n readonly #container: Container;\n readonly #host: Type;\n readonly #moduleId: string | undefined;\n readonly #edge: ErrorReportContext['edge'];\n readonly #waitUntil: ((promise: Promise<unknown>) => void) | undefined;\n\n constructor(options: HostInvokerOptions) {\n this.#container = options.container;\n this.#host = options.host;\n this.#moduleId = options.moduleId;\n this.#edge = options.edge;\n this.#waitUntil = options.waitUntil;\n }\n\n /** The report context of an invocation of `method`. */\n report(kind: string, method: string | symbol): ErrorReportContext {\n return { edge: this.#edge, source: `${this.#host.name}.${String(method)}`, kind };\n }\n\n /** Report through the application, or the console when its reporter cannot be built. */\n reportOutside(error: unknown, report: ErrorReportContext): void {\n try {\n resolveErrorReporter(this.#container).report(error, report);\n } catch {\n console.error(`[vela] ${report.edge} error in ${report.source ?? 'an entrypoint'}:`, error);\n }\n }\n\n async invoke<T>(invocation: HostInvocation<T>): Promise<T> {\n const root = this.#container;\n const report = this.report(invocation.kind, invocation.method);\n const scope = createExecutionScope(root);\n let outcome: { ok: true; value: T } | { ok: false; error: unknown };\n try {\n invocation.seed?.(scope.container);\n outcome = { ok: true, value: await this.#run(scope.container, invocation, report) };\n } catch (error) {\n outcome = { ok: false, error };\n }\n let transmission: Transmission<T> | undefined;\n try {\n transmission = outcome.ok ? invocation.transmit?.(outcome.value) : undefined;\n } catch (error) {\n // Such as a body another reader locked: the scope still finishes.\n outcome = { ok: false, error };\n }\n if (transmission?.background) {\n // The scope outlives the invocation until its result is sent.\n this.#finishLater(scope, transmission.sent, report);\n return transmission.value;\n }\n try {\n // Request-scoped providers and managed work (`EXECUTION_LIFETIME`)\n // settle before the invocation does.\n await scope.finish(transmission?.sent);\n } catch (completion) {\n this.reportOutside(completion, {\n ...report,\n note: 'managed work failed after the invocation',\n });\n if (invocation.settlement.completionFails && outcome.ok) {\n outcome = { ok: false, error: completion };\n }\n }\n if (!outcome.ok) throw outcome.error;\n return transmission ? transmission.value : outcome.value;\n }\n\n /** Finish `scope` after `boundary` settles, reporting a failure; the platform waits for it. */\n #finishLater(\n scope: ExecutionScope,\n boundary: Promise<unknown>,\n report: ErrorReportContext,\n ): void {\n const completion = scope.finish(boundary).catch((error: unknown) => {\n this.reportOutside(error, { ...report, note: 'managed work failed after the response' });\n });\n this.#waitUntil?.(completion);\n }\n\n async #run<T>(\n scope: Container,\n invocation: HostInvocation<T>,\n report: ErrorReportContext,\n ): Promise<T> {\n const host = this.#host;\n const moduleId = this.#moduleId;\n const { kind, method, args, settlement } = invocation;\n const context = buildEntrypointExecutionContext(\n kind,\n host,\n method,\n 'payload' in invocation ? invocation.payload : args,\n moduleId,\n scope,\n );\n const reporter = resolveErrorReporter(scope);\n let filters: ExceptionFilter[] = [];\n try {\n filters = (\n await resolveScopedComponentsAsync('filter', host, method, scope, moduleId)\n ).toReversed();\n const guards = await resolveScopedComponentsAsync('guard', host, method, scope, moduleId);\n const interceptors = await resolveScopedComponentsAsync(\n 'interceptor',\n host,\n method,\n scope,\n moduleId,\n );\n const value = await PipelineRunner.run({\n context,\n guards,\n interceptors,\n resolveArgs: () =>\n invocation.pipes\n ? this.#transformArguments(scope, method, args)\n : Promise.resolve([...args]),\n invoke: async (resolved) => {\n const instance: unknown = await scope.resolveAsync(host, moduleId);\n if (typeof instance !== 'object' || instance === null) {\n throw new TypeError(`${host.name} did not resolve to an object.`);\n }\n const handler: unknown = Reflect.get(instance, method);\n if (typeof handler !== 'function') {\n throw new TypeError(`${host.name}.${String(method)} is not a method.`);\n }\n return Reflect.apply(handler, instance, resolved);\n },\n });\n return settlement.success(value);\n } catch (error) {\n if (invocation.passthrough?.(error) === true) throw error;\n reporter.report(error, report);\n return settlement.failure(error, { filters, context, reporter, report });\n }\n }\n\n /** Scoped pipes transform each argument, typed by the method's parameter metadata. */\n async #transformArguments(\n scope: Container,\n method: string | symbol,\n args: readonly unknown[],\n ): Promise<unknown[]> {\n const pipes = await resolveScopedComponentsAsync(\n 'pipe',\n this.#host,\n method,\n scope,\n this.#moduleId,\n );\n if (pipes.length === 0) return [...args];\n const types = getMetadata<unknown[]>('design:paramtypes', this.#host.prototype, method);\n const transformed: unknown[] = [];\n for (const [index, argument] of args.entries()) {\n const metadata = { type: 'custom', metatype: types?.[index] };\n let value = argument;\n for (const pipe of pipes) {\n value = await (pipe.transformAsync\n ? pipe.transformAsync(value, metadata)\n : pipe.transform(value, metadata));\n }\n transformed.push(value);\n }\n return transformed;\n }\n}\n\n/**\n * Call the RPC method `method` of a host through `invoker`. It rejects only\n * with an {@link EntrypointError}: a method `methods` does not list answers\n * `404 not_found`, and a failure outside the pipeline is reported and becomes\n * `500 internal`.\n */\nexport async function callRpcMethod(\n invoker: HostInvoker,\n methods: ReadonlySet<string>,\n method: string,\n args: readonly unknown[],\n seed?: (scope: Container) => void,\n): Promise<unknown> {\n if (!methods.has(method)) {\n throw new EntrypointError({ status: 404, code: 'not_found', message: 'Unknown RPC method' });\n }\n try {\n return await invoker.invoke({\n kind: 'rpc',\n method,\n args,\n settlement: rpcSettlement,\n pipes: true,\n seed,\n });\n } catch (error) {\n if (error instanceof EntrypointError) throw error;\n invoker.reportOutside(error, invoker.report('rpc', method));\n throw internalEntrypointError();\n }\n}\n\n/**\n * An invoker of a decorated method entrypoint (`@OnEmail()`, `@OnTail()`):\n * its class, resolved in the module that registered it.\n */\nexport function entrypointInvoker(\n container: Container,\n entrypoint: Entrypoint,\n edge: ErrorReportContext['edge'],\n): HostInvoker {\n const { token } = entrypoint;\n if (typeof token !== 'function') throw new TypeError('Entrypoint token must be a class.');\n return new HostInvoker({\n container,\n host: token,\n moduleId: getEntrypointModuleId(container, entrypoint),\n edge,\n });\n}\n\n/** Wait for every invocation, even when one fails before its siblings; then fail with them. */\nexport async function settleInvocations(work: readonly Promise<unknown>[]): Promise<void> {\n const outcomes = await Promise.allSettled(work);\n const errors = outcomes.flatMap((outcome) =>\n outcome.status === 'rejected' ? [outcome.reason] : [],\n );\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Multiple entrypoint handlers failed.');\n}\n\n/**\n * The module a host added to the root module's providers is resolved in: the\n * root's registration when there are several.\n */\nexport function hostModuleId(\n container: Container,\n host: Type,\n rootClass: Type,\n): string | undefined {\n const owners = container.getOwnerModuleIds(host);\n return (\n owners.find((owner) => container.getModuleScope(owner)?.moduleClass === rootClass) ?? owners[0]\n );\n}\n"],"mappings":";;;;AAkDA,SAAgB,eACd,SACA,OAC6B;C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AO,MAAM,CAAC;EAC1D,MAAM,wBAAwB;CAChC;AACF;;;;;AAMA,SAAgB,kBACd,WACA,YACA,MACa;CACb,MAAM,EAAE,UAAU;CAClB,IAAI,OAAO,UAAU,YAAY,MAAM,IAAI,UAAU,mCAAmC;CACxF,OAAO,IAAI,YAAY;EACrB;EACA,MAAM;EACN,UAAU,sBAAsB,WAAW,UAAU;EACrD;CACF,CAAC;AACH;;AAGA,eAAsB,kBAAkB,MAAkD;CAExF,MAAM,UAAS,MADQ,QAAQ,WAAW,IAAI,EAAA,CACtB,SAAS,YAC/B,QAAQ,WAAW,aAAa,CAAC,QAAQ,MAAM,IAAI,CAAC,CACtD;CACA,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;CACtC,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,sCAAsC;AAChG;;;;;AAMA,SAAgB,aACd,WACA,MACA,WACoB;CACpB,MAAM,SAAS,UAAU,kBAAkB,IAAI;CAC/C,OACE,OAAO,MAAM,UAAU,UAAU,eAAe,KAAK,CAAC,EAAE,gBAAgB,SAAS,KAAK,OAAO;AAEjG"}
@@ -0,0 +1,73 @@
1
+ //#region src/host/host-members.ts
2
+ /**
3
+ * Methods the application context calls on providers: lifecycle hooks, the
4
+ * container's `dispose()` disposal hook and the entrypoint contributor hook.
5
+ * Never RPC methods.
6
+ */
7
+ const HOOKS = /* @__PURE__ */ new Set([
8
+ "constructor",
9
+ "onModuleInit",
10
+ "onApplicationBootstrap",
11
+ "onModuleDestroy",
12
+ "beforeApplicationShutdown",
13
+ "onApplicationShutdown",
14
+ "dispose",
15
+ "collectEntrypoints"
16
+ ]);
17
+ /** The nearest declaration of `name` on the prototype chain of `host`, below `Object.prototype`. */
18
+ function prototypeMember(host, name) {
19
+ for (let prototype = host.prototype; typeof prototype === "object" && prototype !== null && prototype !== Object.prototype; prototype = Object.getPrototypeOf(prototype)) {
20
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
21
+ if (descriptor) return descriptor;
22
+ }
23
+ }
24
+ /** Whether `host` declares the prototype method `name` (not an accessor or an instance field). */
25
+ function hasPrototypeMethod(host, name) {
26
+ return typeof prototypeMember(host, name)?.value === "function";
27
+ }
28
+ /**
29
+ * Reject a host whose prototype chain defines `then`, as a method or an
30
+ * accessor: an instance would be a thenable, so awaiting the resolved host
31
+ * would call it instead of producing the instance, and the invocation would
32
+ * hang. Checked when the class is defined, without constructing the host.
33
+ */
34
+ function assertNotThenable(host) {
35
+ if (prototypeMember(host, "then") === void 0) return;
36
+ throw new TypeError(`${host.name} defines then(), which makes every instance a thenable: resolving the host would call it instead of returning the instance, and each invocation would hang. Rename the method.`);
37
+ }
38
+ /** Why `name` cannot be an RPC method of `host`, or undefined when it can. */
39
+ function rpcNameProblem(host, name, surface) {
40
+ if (typeof name !== "string") return `${host.name}: an rpc entry must be a method name, not ${String(name)}.`;
41
+ if (surface.reserved.has(name)) return `${host.name}.${name}() cannot be a ${surface.label} RPC method: '${name}' is reserved by the ${surface.label} class or its stubs. Rename the method.`;
42
+ if (HOOKS.has(name)) return `${host.name}.${name}() cannot be a ${surface.label} RPC method: the application context calls it (a lifecycle, disposal or entrypoint hook).`;
43
+ if (surface.handlers.includes(name)) return `${host.name}.${name}() is the ${surface.label} ${name} handler, which the platform calls: leave it out of the rpc list.`;
44
+ if (!hasPrototypeMethod(host, name)) return `${host.name} has no prototype method ${name}(): list methods declared in the class body, not accessors or instance fields such as arrow functions.`;
45
+ }
46
+ /**
47
+ * The members of `host` its entrypoint class exposes: the RPC methods `rpc`
48
+ * names, and the event handlers of `surface` it implements. Each `rpc` entry
49
+ * must name a string-keyed method on the host's prototype chain (below
50
+ * `Object.prototype`); a hook, an event handler, a reserved name, an accessor
51
+ * or an instance field throws, and so does a host defining `then`. Nothing
52
+ * else is an RPC method, TypeScript `private` and `protected` methods
53
+ * included. Read at class definition, without constructing the host.
54
+ */
55
+ function hostMembers(host, rpc, surface) {
56
+ assertNotThenable(host);
57
+ const names = rpc ?? [];
58
+ if (!Array.isArray(names)) throw new TypeError(`${host.name}: the rpc option must be an array of method names.`);
59
+ const methods = [];
60
+ for (const name of names) {
61
+ const problem = rpcNameProblem(host, name, surface);
62
+ if (problem !== void 0) throw new TypeError(problem);
63
+ if (!methods.includes(name)) methods.push(name);
64
+ }
65
+ return {
66
+ methods,
67
+ handlers: surface.handlers.filter((name) => hasPrototypeMethod(host, name))
68
+ };
69
+ }
70
+ //#endregion
71
+ export { assertNotThenable, hasPrototypeMethod, hostMembers, prototypeMember };
72
+
73
+ //# sourceMappingURL=host-members.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-members.js","names":[],"sources":["../../src/host/host-members.ts"],"sourcesContent":["/**\n * Methods the application context calls on providers: lifecycle hooks, the\n * container's `dispose()` disposal hook and the entrypoint contributor hook.\n * Never RPC methods.\n */\nconst HOOKS = new Set([\n 'constructor',\n 'onModuleInit',\n 'onApplicationBootstrap',\n 'onModuleDestroy',\n 'beforeApplicationShutdown',\n 'onApplicationShutdown',\n 'dispose',\n 'collectEntrypoints',\n]);\n\n/** Host members the application context calls, which are never RPC methods. */\nexport type HostHookName =\n | 'onModuleInit'\n | 'onApplicationBootstrap'\n | 'onModuleDestroy'\n | 'beforeApplicationShutdown'\n | 'onApplicationShutdown'\n | 'dispose'\n | 'collectEntrypoints';\n\n/**\n * The names a host's `rpc` list may take: its public methods, less the\n * `Excluded` names. TypeScript `private` and `protected` methods are not\n * among them.\n */\nexport type RpcMethodOf<Host, Excluded extends string> = {\n [K in keyof Host]: K extends string\n ? K extends Excluded | HostHookName\n ? never\n : Host[K] extends (...args: never[]) => unknown\n ? K\n : never\n : never;\n}[keyof Host];\n\n/** The RPC methods `Method` of `Host`, asynchronous, as the entrypoint's stubs call them. */\nexport type RpcMethods<Host, Method extends keyof Host> = {\n [K in Method]: Host[K] extends (...args: infer Args) => infer Result\n ? (...args: Args) => Promise<Awaited<Result>>\n : never;\n};\n\n/** @internal A class whose prototype methods a host exposes. */\nexport type HostClass = abstract new (...args: never[]) => unknown;\n\n/** The nearest declaration of `name` on the prototype chain of `host`, below `Object.prototype`. */\nexport function prototypeMember(host: HostClass, name: string): PropertyDescriptor | undefined {\n for (\n let prototype: unknown = host.prototype;\n typeof prototype === 'object' && prototype !== null && prototype !== Object.prototype;\n prototype = Object.getPrototypeOf(prototype)\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n if (descriptor) return descriptor;\n }\n return undefined;\n}\n\n/** Whether `host` declares the prototype method `name` (not an accessor or an instance field). */\nexport function hasPrototypeMethod(host: HostClass, name: string): boolean {\n return typeof prototypeMember(host, name)?.value === 'function';\n}\n\n/**\n * Reject a host whose prototype chain defines `then`, as a method or an\n * accessor: an instance would be a thenable, so awaiting the resolved host\n * would call it instead of producing the instance, and the invocation would\n * hang. Checked when the class is defined, without constructing the host.\n */\nexport function assertNotThenable(host: HostClass): void {\n if (prototypeMember(host, 'then') === undefined) return;\n throw new TypeError(\n `${host.name} defines then(), which makes every instance a thenable: resolving the host ` +\n 'would call it instead of returning the instance, and each invocation would hang. ' +\n 'Rename the method.',\n );\n}\n\n/** How one kind of host names its RPC restrictions in messages. */\nexport interface RpcSurface<Handler extends string> {\n /** What the class is, as messages name it: `'Durable Object'`, `'service entrypoint'`. */\n readonly label: string;\n /** Names the class or its stubs own, which no RPC method may take. */\n readonly reserved: ReadonlySet<string>;\n /** Event handlers the platform calls on the class, in the order the class defines them. */\n readonly handlers: readonly Handler[];\n}\n\n/** What a host class contributes to its entrypoint class. */\nexport interface HostMembers<Handler extends string> {\n /** RPC methods: the host methods its `rpc` list names. */\n readonly methods: readonly string[];\n /** Event handlers the host implements, in the surface's handler order. */\n readonly handlers: readonly Handler[];\n}\n\n/** Why `name` cannot be an RPC method of `host`, or undefined when it can. */\nfunction rpcNameProblem<Handler extends string>(\n host: HostClass,\n name: unknown,\n surface: RpcSurface<Handler>,\n): string | undefined {\n if (typeof name !== 'string') {\n return `${host.name}: an rpc entry must be a method name, not ${String(name)}.`;\n }\n if (surface.reserved.has(name)) {\n return (\n `${host.name}.${name}() cannot be a ${surface.label} RPC method: '${name}' is reserved ` +\n `by the ${surface.label} class or its stubs. Rename the method.`\n );\n }\n if (HOOKS.has(name)) {\n return (\n `${host.name}.${name}() cannot be a ${surface.label} RPC method: the application ` +\n 'context calls it (a lifecycle, disposal or entrypoint hook).'\n );\n }\n if ((surface.handlers as readonly string[]).includes(name)) {\n return (\n `${host.name}.${name}() is the ${surface.label} ${name} handler, which the platform ` +\n 'calls: leave it out of the rpc list.'\n );\n }\n if (!hasPrototypeMethod(host, name)) {\n return (\n `${host.name} has no prototype method ${name}(): list methods declared in the class ` +\n 'body, not accessors or instance fields such as arrow functions.'\n );\n }\n return undefined;\n}\n\n/**\n * The members of `host` its entrypoint class exposes: the RPC methods `rpc`\n * names, and the event handlers of `surface` it implements. Each `rpc` entry\n * must name a string-keyed method on the host's prototype chain (below\n * `Object.prototype`); a hook, an event handler, a reserved name, an accessor\n * or an instance field throws, and so does a host defining `then`. Nothing\n * else is an RPC method, TypeScript `private` and `protected` methods\n * included. Read at class definition, without constructing the host.\n */\nexport function hostMembers<Handler extends string>(\n host: HostClass,\n rpc: readonly string[] | undefined,\n surface: RpcSurface<Handler>,\n): { methods: string[]; handlers: Handler[] } {\n assertNotThenable(host);\n const names = rpc ?? [];\n if (!Array.isArray(names)) {\n throw new TypeError(`${host.name}: the rpc option must be an array of method names.`);\n }\n const methods: string[] = [];\n for (const name of names) {\n const problem = rpcNameProblem(host, name, surface);\n if (problem !== undefined) throw new TypeError(problem);\n if (!methods.includes(name)) methods.push(name);\n }\n return {\n methods,\n handlers: surface.handlers.filter((name) => hasPrototypeMethod(host, name)),\n };\n}\n"],"mappings":";;;;;;AAKA,MAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAsCD,SAAgB,gBAAgB,MAAiB,MAA8C;CAC7F,KACE,IAAI,YAAqB,KAAK,WAC9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M,OAAO;EAClD,IAAI,YAAY,KAAA,GAAW,MAAM,IAAI,UAAU,OAAO;EACtD,IAAI,CAAC,QAAQ,SAAS,IAAI,GAAG,QAAQ,KAAK,IAAI;CAChD;CACA,OAAO;EACL;EACA,UAAU,QAAQ,SAAS,QAAQ,SAAS,mBAAmB,MAAM,IAAI,CAAC;CAC5E;AACF"}
@@ -0,0 +1,13 @@
1
+ //#region src/host/host-members.d.ts
2
+ /** Host members the application context calls, which are never RPC methods. */
3
+ type HostHookName = 'onModuleInit' | 'onApplicationBootstrap' | 'onModuleDestroy' | 'beforeApplicationShutdown' | 'onApplicationShutdown' | 'dispose' | 'collectEntrypoints';
4
+ /**
5
+ * The names a host's `rpc` list may take: its public methods, less the
6
+ * `Excluded` names. TypeScript `private` and `protected` methods are not
7
+ * among them.
8
+ */
9
+ type RpcMethodOf<Host, Excluded extends string> = { [K in keyof Host]: K extends string ? K extends Excluded | HostHookName ? never : Host[K] extends ((...args: never[]) => unknown) ? K : never : never; }[keyof Host];
10
+ /** The RPC methods `Method` of `Host`, asynchronous, as the entrypoint's stubs call them. */
11
+ type RpcMethods<Host, Method extends keyof Host> = { [K in Method]: Host[K] extends ((...args: infer Args) => infer Result) ? (...args: Args) => Promise<Awaited<Result>> : never; };
12
+ //#endregion
13
+ export { RpcMethods as n, RpcMethodOf as t };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
2
+ import { a as ScheduledEvent, i as CloudflareScheduledEvent, n as MountOpenApiOptions, r as CLOUDFLARE_SCHEDULED_EVENT, t as CloudflareApplication } from "./cloudflare-application-CXDy9C1R.js";
3
+ import { _ as defineCloudflareApp, a as CloudflareApp, c as CloudflareEntrypointDescriptor, d as CloudflareWorkerOptions, f as CloudflareWorkflowDescriptor, g as createCloudflareWorker, h as createCloudflareApp, i as CLOUDFLARE_WORKFLOW, l as CloudflareWorker, m as cloudflareAdapter, n as CLOUDFLARE_ENTRYPOINT, o as CloudflareAppOptions, p as CreateCloudflareAppOptions, r as CLOUDFLARE_WORKER, s as CloudflareDurableObjectDescriptor, t as CLOUDFLARE_DURABLE_OBJECT, u as CloudflareWorkerDescriptor, v as isCloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-CuFNUJJD.js";
3
4
  import { a as DoPitrId, c as DoPitrUnavailableError, d as isDoPitrUnavailable, f as readDoPitrBookmark, i as DoPitrBookmarkRead, l as VelaDoPitrRpc, n as DoPitrArmOptions, o as DoPitrNamespace, r as DoPitrArmResult, s as DoPitrStorage, t as VelaNonceDurableObject, u as armDoPitr } from "./nonce.durable-object-Bg1e0BMD.js";
4
- import { a as CloudflareWorkerOptions, c as createCloudflareApp, d as MountOpenApiOptions, f as CLOUDFLARE_SCHEDULED_EVENT, i as CloudflareWorkerDescriptor, l as createCloudflareWorker, m as ScheduledEvent, n as CloudflareAppOptions, o as CreateCloudflareAppOptions, p as CloudflareScheduledEvent, r as CloudflareWorker, s as cloudflareAdapter, t as CLOUDFLARE_WORKER, u as CloudflareApplication } from "./cloudflare-factory-eGiet0mg.js";
5
5
  import { DynamicModule, Type, VelaEnv } from "@velajs/vela";
6
- import { BroadcastCommand } from "@velajs/vela/websocket";
6
+ import { Binding, BindingRef, EnvFactory, RuntimeAdapter } from "@velajs/vela/module-kit";
7
7
  import { CommitStamp, CursorLog, InvalidationCommand, LiveDriver, LiveInvalidationSink, ResumeVerdict } from "@velajs/vela/live";
8
- import { EnvFactory } from "@velajs/vela/module-kit";
8
+ import { BroadcastCommand } from "@velajs/vela/websocket";
9
9
  import { CacheEntry, CacheEntryReader, CacheEntryWriter, CacheInvalidationStore, CacheStore } from "@velajs/vela/cache";
10
10
  import { FeatureFlagDriver, FlagContext } from "@velajs/feature-flags";
11
11
  import { ThrottlerStore } from "@velajs/vela/throttler";
@@ -14,21 +14,82 @@ import { NonceStore } from "@velajs/vela/security";
14
14
  /** Stable, collision-free Durable Object name for one gateway's room. */
15
15
  export declare function durableObjectRoomName(gatewayPath: string, roomId: string): string;
16
16
  //#endregion
17
+ //#region src/rpc/entrypoint-error.d.ts
18
+ /** What a failed JS-RPC call of a Vela entrypoint carries across the RPC boundary. */
19
+ interface EntrypointErrorInit {
20
+ /** An HTTP error status, 400–599. */
21
+ readonly status: number;
22
+ /** A stable error code, such as `not_found` or `internal`. */
23
+ readonly code: string;
24
+ readonly message: string;
25
+ /** Client-safe details of a client fault (4xx), such as validation issues. */
26
+ readonly details?: unknown;
27
+ }
28
+ /**
29
+ * The one error the JS-RPC methods of a Vela entrypoint reject with: a
30
+ * Durable Object from `VelaDurableObject()` and a service entrypoint from
31
+ * `VelaEntrypoint()`. The entrypoint reports the original error first, then
32
+ * renders it as HTTP renders a response with server bodies redacted
33
+ * (`renderHttpError`): a 4xx `HttpException` keeps its code, message and
34
+ * details; a branded `VelaError` keeps its code and message at any status, and
35
+ * its details below 500; a 5xx `HttpException` becomes its status's code and
36
+ * title; an unknown error becomes `500 internal "Internal Server Error"`. A 4xx
37
+ * `HttpException` constructed with an object response keeps only its status
38
+ * (code `error`) unless that object is a canonical `{ error: { code, message,
39
+ * details } }` body. Only these own properties cross the RPC boundary: no stack
40
+ * frames, causes or other fields of the original.
41
+ *
42
+ * workerd rebuilds it on the caller's side as a plain `Error` with the same
43
+ * `name`, `status`, `code`, `message` and `details`; read it with
44
+ * {@link isEntrypointError}. That needs a Worker `compatibility_date` of
45
+ * 2026-04-21 or later, or the `enhanced_error_serialization` compatibility
46
+ * flag: before it, workerd delivers only an `Error` whose message is
47
+ * `EntrypointError: <message>`, without the status, code or details
48
+ * (`vela deploy check` warns about it). A host may throw one itself, for
49
+ * example to pass on another entrypoint's failure: a 4xx one keeps its code,
50
+ * message and details, a 5xx one only its status.
51
+ */
52
+ export declare class EntrypointError extends Error implements EntrypointErrorInit {
53
+ readonly name = "EntrypointError";
54
+ readonly status: number;
55
+ readonly code: string;
56
+ readonly details?: unknown;
57
+ constructor(init: EntrypointErrorInit);
58
+ }
59
+ /**
60
+ * Whether `error` is a failed JS-RPC call of a Vela entrypoint: an
61
+ * {@link EntrypointError}, or the plain `Error` workerd delivers for one to
62
+ * the caller. On a compatibility date before 2026-04-21 without
63
+ * `enhanced_error_serialization`, workerd drops the error's properties, so
64
+ * this is false.
65
+ */
66
+ export declare function isEntrypointError(error: unknown): error is EntrypointError;
67
+ //#endregion
17
68
  //#region src/bindings.d.ts
18
- export declare const kv: (ref: import("@velajs/vela/module-kit").BindingRef) => import("@velajs/vela/module-kit").Binding<KVNamespace<string>>;
19
- export declare const r2: (ref: import("@velajs/vela/module-kit").BindingRef) => import("@velajs/vela/module-kit").Binding<R2Bucket>;
20
- export declare const d1: (ref: import("@velajs/vela/module-kit").BindingRef) => import("@velajs/vela/module-kit").Binding<D1Database>;
21
- export declare const queue: (ref: import("@velajs/vela/module-kit").BindingRef) => import("@velajs/vela/module-kit").Binding<Queue<unknown>>;
22
- export declare const durableObject: (ref: import("@velajs/vela/module-kit").BindingRef) => import("@velajs/vela/module-kit").Binding<DurableObjectNamespace<undefined>>;
23
- export declare const rateLimit: (ref: import("@velajs/vela/module-kit").BindingRef) => import("@velajs/vela/module-kit").Binding<RateLimit>;
69
+ export declare const kv: (ref: BindingRef) => Binding<KVNamespace<string>>;
70
+ export declare const r2: (ref: BindingRef) => Binding<R2Bucket>;
71
+ export declare const d1: (ref: BindingRef) => Binding<D1Database>;
72
+ export declare const queue: (ref: BindingRef) => Binding<Queue<unknown>>;
73
+ export declare const durableObject: (ref: BindingRef) => Binding<DurableObjectNamespace<undefined>>;
74
+ export declare const rateLimit: (ref: BindingRef) => Binding<RateLimit>;
75
+ /**
76
+ * A reference to a Workflow binding declared under `workflows`, whose
77
+ * instances take `Params`: for a class from `VelaWorkflow()`,
78
+ * `workflow<WorkflowParams<SignupWorkflow>>({ binding: 'SIGNUP_WORKFLOW' })`.
79
+ * Called with an application's ENV, it returns the native binding typed with
80
+ * those params: `await signups(env).create({ params: { email } })`. The
81
+ * runtime checks that the binding is a Workflow; its params are what the
82
+ * Workflow class declares.
83
+ */
84
+ export declare function workflow<Params = unknown>(ref: BindingRef): Binding<Workflow<Params>>;
24
85
  //#endregion
25
86
  //#region src/services/kv-cache.store.d.ts
26
87
  /** A KV namespace, or a function that reads it when an operation needs it. */
27
88
  type KVNamespaceSource = KVNamespace | (() => KVNamespace);
28
89
  /**
29
90
  * Native KV JSON value store. Metadata retains logical expiry even when KV's
30
- * physical retention rounds up to its 60-second minimum. Legacy values without
31
- * metadata remain readable, but cannot safely backfill another tier.
91
+ * physical retention rounds up to its 60-second minimum. Values without
92
+ * Vela expiry metadata are cache misses.
32
93
  */
33
94
  export declare class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {
34
95
  #private;
@@ -386,4 +447,4 @@ interface DurableObjectNonceStoreOptions {
386
447
  */
387
448
  export declare function durableObjectNonceStore(options: DurableObjectNonceStoreOptions): NonceStore;
388
449
  //#endregion
389
- export { CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, type CfLiveDriver, type CloudflareAppOptions, CloudflareApplication, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorker, type CloudflareWorkerDescriptor, type CloudflareWorkerOptions, type CreateCloudflareAppOptions, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type FlagshipBinding, type FlagshipFlagDriverOptions, type KVNamespaceSource, type KvFlagDriverOptions, type LiveNamespace, type MountOpenApiOptions, type QueueConsumerMetadata, type RateLimitStoreOptions, type ScheduledEvent, type VelaDoPitrRpc, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, isDoPitrUnavailable, readDoPitrBookmark };
450
+ export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, type CfLiveDriver, type CloudflareApp, type CloudflareAppOptions, CloudflareApplication, type CloudflareDurableObjectDescriptor, type CloudflareEntrypointDescriptor, type CloudflareRoot, type CloudflareScheduledEvent, type CloudflareWorker, type CloudflareWorkerDescriptor, type CloudflareWorkerOptions, type CloudflareWorkflowDescriptor, type CreateCloudflareAppOptions, type DoPitrArmOptions, type DoPitrArmResult, type DoPitrBookmarkRead, type DoPitrId, type DoPitrNamespace, type DoPitrStorage, DoPitrUnavailableError, type DurableObjectLiveOptions, type DurableObjectNonceNamespace, type DurableObjectNonceStoreOptions, type EntrypointErrorInit, type FlagshipBinding, type FlagshipFlagDriverOptions, type KVNamespaceSource, type KvFlagDriverOptions, type LiveNamespace, type MountOpenApiOptions, type QueueConsumerMetadata, type RateLimitStoreOptions, type ScheduledEvent, type VelaDoPitrRpc, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp, isDoPitrUnavailable, readDoPitrBookmark };
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { durableObjectRoomName } from "./websocket/room-id.js";
2
2
  import { CLOUDFLARE_SCHEDULED_EVENT } from "./scheduled-event.js";
3
3
  import { CloudflareApplication } from "./cloudflare-application.js";
4
- import { d1, durableObject, kv, queue, r2, rateLimit } from "./bindings.js";
4
+ import { d1, durableObject, kv, queue, r2, rateLimit, workflow } from "./bindings.js";
5
5
  import { durableObjectLive } from "./websocket/live-driver.js";
6
- import { CLOUDFLARE_WORKER, cloudflareAdapter, createCloudflareApp, createCloudflareWorker } from "./cloudflare-factory.js";
6
+ import { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, defineCloudflareApp, isCloudflareApp } from "./cloudflare-factory.js";
7
+ import { EntrypointError, isEntrypointError } from "./rpc/entrypoint-error.js";
7
8
  import { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation } from "./services/kv-cache.store.js";
8
9
  import { FlagshipFlagDriver, flagshipFlagDriver } from "./services/flagship-flag.driver.js";
9
10
  import { KvFlagDriver, kvFlagDriver } from "./services/kv-flag.driver.js";
@@ -12,4 +13,4 @@ import { DoPitrUnavailableError, armDoPitr, isDoPitrUnavailable, readDoPitrBookm
12
13
  import { DoCursorLog, liveInvalidateToRoom } from "./websocket/do-live.js";
13
14
  import { rateLimitStore } from "./rate-limit/cloudflare-rate-limit.store.js";
14
15
  import { durableObjectNonceStore } from "./nonce/durable-object-nonce.store.js";
15
- export { CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagshipFlagDriver, isDoPitrUnavailable, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark };
16
+ export { CLOUDFLARE_DURABLE_OBJECT, CLOUDFLARE_ENTRYPOINT, CLOUDFLARE_SCHEDULED_EVENT, CLOUDFLARE_WORKER, CLOUDFLARE_WORKFLOW, CloudflareApplication, DoCursorLog, DoPitrUnavailableError, EntrypointError, FlagshipFlagDriver, KVCacheInvalidationStore, KVCacheStore, KvFlagDriver, QueueConsumer, armDoPitr, cloudflareAdapter, createCloudflareApp, createCloudflareWorker, d1, defineCloudflareApp, durableObject, durableObjectLive, durableObjectNonceStore, durableObjectRoomName, flagshipFlagDriver, isCloudflareApp, isDoPitrUnavailable, isEntrypointError, kv, kvCache, kvCacheInvalidation, kvFlagDriver, liveInvalidateToRoom, queue, r2, rateLimit, rateLimitStore, readDoPitrBookmark, workflow };
@@ -0,0 +1,19 @@
1
+ //#region src/root-module.ts
2
+ /**
3
+ * @internal `root` with `providers` added to the root module's own providers,
4
+ * so each one injects what the root module can see.
5
+ */
6
+ function withRootProviders(root, providers) {
7
+ if (typeof root === "function") return {
8
+ module: root,
9
+ providers: [...providers]
10
+ };
11
+ return {
12
+ ...root,
13
+ providers: [...root.providers ?? [], ...providers]
14
+ };
15
+ }
16
+ //#endregion
17
+ export { withRootProviders };
18
+
19
+ //# sourceMappingURL=root-module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root-module.js","names":[],"sources":["../src/root-module.ts"],"sourcesContent":["import type { DynamicModule, Type } from '@velajs/vela';\n\n/**\n * The root a Worker or Durable Object is built from: a module class or a\n * `DynamicModule`, declared once at module scope. Configuration that needs\n * bindings belongs in providers and `forRootAsync({ inject: [ENV] })`\n * factories, which run for each application with that application's ENV.\n */\nexport type CloudflareRoot = Type | DynamicModule;\n\n/**\n * @internal `root` with `providers` added to the root module's own providers,\n * so each one injects what the root module can see.\n */\nexport function withRootProviders(root: CloudflareRoot, providers: readonly Type[]): DynamicModule {\n if (typeof root === 'function') return { module: root, providers: [...providers] };\n return { ...root, providers: [...(root.providers ?? []), ...providers] };\n}\n"],"mappings":";;;;;AAcA,SAAgB,kBAAkB,MAAsB,WAA2C;CACjG,IAAI,OAAO,SAAS,YAAY,OAAO;EAAE,QAAQ;EAAM,WAAW,CAAC,GAAG,SAAS;CAAE;CACjF,OAAO;EAAE,GAAG;EAAM,WAAW,CAAC,GAAI,KAAK,aAAa,CAAC,GAAI,GAAG,SAAS;CAAE;AACzE"}