@velajs/cloudflare 1.31.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +62 -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 +72 -11
  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/tail/on-tail.js +46 -0
  45. package/dist/tail/on-tail.js.map +1 -0
  46. package/dist/tail/tail-dispatch.js +67 -0
  47. package/dist/tail/tail-dispatch.js.map +1 -0
  48. package/dist/tail.d.ts +39 -0
  49. package/dist/tail.js +2 -0
  50. package/dist/testing.d.ts +55 -3
  51. package/dist/testing.js +78 -1
  52. package/dist/testing.js.map +1 -1
  53. package/dist/websocket/do-bootstrap.js +40 -37
  54. package/dist/websocket/do-bootstrap.js.map +1 -1
  55. package/dist/websocket/websocket.durable-object.js +37 -8
  56. package/dist/websocket/websocket.durable-object.js.map +1 -1
  57. package/dist/worker-events.js +49 -0
  58. package/dist/worker-events.js.map +1 -0
  59. package/dist/workflow/vela-workflow.js +104 -0
  60. package/dist/workflow/vela-workflow.js.map +1 -0
  61. package/dist/workflows.d.ts +82 -0
  62. package/dist/workflows.js +2 -0
  63. package/package.json +23 -7
  64. package/dist/root-module-C23bUwt_.d.ts +0 -11
@@ -0,0 +1,134 @@
1
+ import { internalEntrypointError, renderEntrypointResponse } from "../rpc/entrypoint-error.js";
2
+ import { createDurableObjectContext, withDurableObjectHost } from "./boot.js";
3
+ import { HostInvoker, callRpcMethod, catchWith, claimingFilter, hostModuleId, platformSettlement } from "../host/host-invoker.js";
4
+ import { getErrorStatus } from "@velajs/vela";
5
+ import { trackResponseStream } from "@velajs/vela/module-kit";
6
+ //#region src/durable-object/host-dispatch.ts
7
+ const fetchSettlement = {
8
+ success(value) {
9
+ if (!(value instanceof Response)) throw new TypeError("A Durable Object host fetch() must return a Response.");
10
+ return value;
11
+ },
12
+ async failure(error, failure) {
13
+ const filter = claimingFilter(failure.filters, error);
14
+ let current = error;
15
+ if (filter) {
16
+ const caught = await catchWith(filter, error, failure);
17
+ if (caught.handled) {
18
+ if (caught.value instanceof Response) return caught.value;
19
+ if (caught.value !== void 0) return Response.json(caught.value, { status: getErrorStatus(error) });
20
+ } else current = caught.error;
21
+ }
22
+ return renderEntrypointResponse(current, failure.reporter, failure.context);
23
+ }
24
+ };
25
+ const alarmSettlement = platformSettlement(true);
26
+ const webSocketSettlement = platformSettlement(false);
27
+ /**
28
+ * Runs the invocations of one Durable Object instance's host: each RPC call
29
+ * and event in a fresh execution scope (request-scoped providers are built
30
+ * per invocation) through the host's scoped guards, pipes (RPC arguments
31
+ * only), interceptors and exception filters. Application-wide `APP_*`
32
+ * components do not apply: an object's callers are other Workers and the
33
+ * platform, with no HTTP request. Failures are reported first; an RPC call
34
+ * rejects with an `EntrypointError`, a `fetch()` renders a JSON error
35
+ * response, and alarms and WebSocket events rethrow for the platform.
36
+ */
37
+ var DurableObjectHostDispatcher = class {
38
+ context;
39
+ #invoker;
40
+ #methods;
41
+ constructor(context, host, moduleId, members, waitUntil) {
42
+ this.context = context;
43
+ this.#invoker = new HostInvoker({
44
+ container: context.getContainer(),
45
+ host,
46
+ moduleId,
47
+ edge: "durable-object",
48
+ waitUntil
49
+ });
50
+ this.#methods = new Set(members.methods);
51
+ }
52
+ /**
53
+ * Call the host's RPC method `method`. It rejects only with an
54
+ * `EntrypointError`, also when the invocation fails before its pipeline
55
+ * renders the error.
56
+ */
57
+ call(method, args) {
58
+ return callRpcMethod(this.#invoker, this.#methods, method, args);
59
+ }
60
+ /**
61
+ * Serve the host's `fetch()`; any failure becomes a JSON error response. A
62
+ * streamed body keeps the invocation's scope (its request-scoped providers
63
+ * and managed work) open until it is sent.
64
+ */
65
+ async fetch(request) {
66
+ try {
67
+ return await this.#invoker.invoke({
68
+ kind: "cf:do:fetch",
69
+ method: "fetch",
70
+ args: [request],
71
+ settlement: fetchSettlement,
72
+ transmit: (response) => this.#transmit(request, response)
73
+ });
74
+ } catch (error) {
75
+ this.#invoker.reportOutside(error, this.#invoker.report("cf:do:fetch", "fetch"));
76
+ const failure = internalEntrypointError();
77
+ return Response.json({ error: {
78
+ code: failure.code,
79
+ message: failure.message
80
+ } }, { status: failure.status });
81
+ }
82
+ }
83
+ async alarm(info) {
84
+ await this.#invoker.invoke({
85
+ kind: "cf:do:alarm",
86
+ method: "alarm",
87
+ args: info === void 0 ? [] : [info],
88
+ settlement: alarmSettlement
89
+ });
90
+ }
91
+ async webSocket(handler, args) {
92
+ await this.#invoker.invoke({
93
+ kind: "cf:do:websocket",
94
+ method: handler,
95
+ args,
96
+ settlement: webSocketSettlement
97
+ });
98
+ }
99
+ /**
100
+ * How a `fetch()` response is sent: a streamed body keeps the scope open
101
+ * until it was read, failed or was cancelled, and the object's `waitUntil`
102
+ * holds that completion. A HEAD response sends no body, so its body is
103
+ * cancelled before the scope finishes. A WebSocket upgrade (101) and a
104
+ * bodyless response need nothing.
105
+ */
106
+ #transmit(request, response) {
107
+ if (response.body === null || response.status === 101) return void 0;
108
+ if (request.method === "HEAD") return {
109
+ value: new Response(null, response),
110
+ sent: response.body.cancel(),
111
+ background: false
112
+ };
113
+ const stream = trackResponseStream(response.body);
114
+ return {
115
+ value: new Response(stream.body, response),
116
+ sent: stream.done,
117
+ background: true
118
+ };
119
+ }
120
+ };
121
+ /**
122
+ * Boot one Durable Object instance's application context from `root` with
123
+ * `host` added to the root module's providers, and return its dispatcher,
124
+ * which serves `members`.
125
+ */
126
+ async function createDurableObjectHost(root, host, options, members) {
127
+ const context = await createDurableObjectContext(withDurableObjectHost(root, host), options);
128
+ const rootClass = typeof root === "function" ? root : root.module;
129
+ return new DurableObjectHostDispatcher(context, host, hostModuleId(context.getContainer(), host, rootClass), members, options.waitUntil);
130
+ }
131
+ //#endregion
132
+ export { DurableObjectHostDispatcher, createDurableObjectHost };
133
+
134
+ //# sourceMappingURL=host-dispatch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-dispatch.js","names":[],"sources":["../../src/durable-object/host-dispatch.ts"],"sourcesContent":["import { getErrorStatus } from '@velajs/vela';\nimport type { Type, VelaApplicationContext } from '@velajs/vela';\nimport { trackResponseStream, type EntrypointExecutionContext } from '@velajs/vela/module-kit';\nimport type { CloudflareRoot } from '../root-module';\nimport {\n HostInvoker,\n callRpcMethod,\n catchWith,\n claimingFilter,\n hostModuleId,\n platformSettlement,\n type Settlement,\n type Transmission,\n} from '../host/host-invoker';\nimport { internalEntrypointError, renderEntrypointResponse } from '../rpc/entrypoint-error';\nimport {\n createDurableObjectContext,\n withDurableObjectHost,\n type DurableObjectContextOptions,\n} from './boot';\nimport type { DurableObjectHostMembers } from './host-methods';\n\n/**\n * The `ExecutionContext.getType()` of a Durable Object invocation: `rpc` for\n * a host method called over RPC, `cf:do:fetch`, `cf:do:alarm` and\n * `cf:do:websocket` for the object's event handlers. `getPayload()` is the\n * invocation's arguments.\n */\nexport type DurableObjectInvocationKind = 'rpc' | 'cf:do:fetch' | 'cf:do:alarm' | 'cf:do:websocket';\n\n/** The ExecutionContext guards, interceptors and filters receive around a Durable Object invocation. */\nexport type DurableObjectExecutionContext = EntrypointExecutionContext<DurableObjectInvocationKind>;\n\n/** A WebSocket hibernation handler a host implements. */\nexport type DurableObjectWebSocketHandler =\n | 'webSocketMessage'\n | 'webSocketClose'\n | 'webSocketError';\n\nconst fetchSettlement: Settlement<Response> = {\n success(value) {\n if (!(value instanceof Response)) {\n throw new TypeError('A Durable Object host fetch() must return a Response.');\n }\n return value;\n },\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) {\n if (caught.value instanceof Response) return caught.value;\n if (caught.value !== undefined) {\n return Response.json(caught.value, { status: getErrorStatus(error) });\n }\n } else {\n current = caught.error;\n }\n }\n return renderEntrypointResponse(current, failure.reporter, failure.context);\n },\n};\n\n// Alarms are retried by the platform: managed work that fails fails the alarm too.\nconst alarmSettlement = platformSettlement(true);\nconst webSocketSettlement = platformSettlement(false);\n\n/**\n * Runs the invocations of one Durable Object instance's host: each RPC call\n * and event in a fresh execution scope (request-scoped providers are built\n * per invocation) through the host's scoped guards, pipes (RPC arguments\n * only), interceptors and exception filters. Application-wide `APP_*`\n * components do not apply: an object's callers are other Workers and the\n * platform, with no HTTP request. Failures are reported first; an RPC call\n * rejects with an `EntrypointError`, a `fetch()` renders a JSON error\n * response, and alarms and WebSocket events rethrow for the platform.\n */\nexport class DurableObjectHostDispatcher {\n readonly context: VelaApplicationContext;\n readonly #invoker: HostInvoker;\n readonly #methods: ReadonlySet<string>;\n\n constructor(\n context: VelaApplicationContext,\n host: Type,\n moduleId: string | undefined,\n members: DurableObjectHostMembers,\n waitUntil?: (promise: Promise<unknown>) => void,\n ) {\n this.context = context;\n this.#invoker = new HostInvoker({\n container: context.getContainer(),\n host,\n moduleId,\n edge: 'durable-object',\n waitUntil,\n });\n this.#methods = new Set(members.methods);\n }\n\n /**\n * Call the host's RPC method `method`. It rejects only with an\n * `EntrypointError`, also when the invocation fails before its pipeline\n * renders the error.\n */\n call(method: string, args: readonly unknown[]): Promise<unknown> {\n return callRpcMethod(this.#invoker, this.#methods, method, args);\n }\n\n /**\n * Serve the host's `fetch()`; any failure becomes a JSON error response. A\n * streamed body keeps the invocation's scope (its request-scoped providers\n * and managed work) open until it is sent.\n */\n async fetch(request: Request): Promise<Response> {\n try {\n return await this.#invoker.invoke({\n kind: 'cf:do:fetch',\n method: 'fetch',\n args: [request],\n settlement: fetchSettlement,\n transmit: (response) => this.#transmit(request, response),\n });\n } catch (error) {\n this.#invoker.reportOutside(error, this.#invoker.report('cf:do:fetch', 'fetch'));\n const failure = internalEntrypointError();\n return Response.json(\n { error: { code: failure.code, message: failure.message } },\n { status: failure.status },\n );\n }\n }\n\n async alarm(info?: AlarmInvocationInfo): Promise<void> {\n await this.#invoker.invoke({\n kind: 'cf:do:alarm',\n method: 'alarm',\n args: info === undefined ? [] : [info],\n settlement: alarmSettlement,\n });\n }\n\n async webSocket(handler: DurableObjectWebSocketHandler, args: readonly unknown[]): Promise<void> {\n await this.#invoker.invoke({\n kind: 'cf:do:websocket',\n method: handler,\n args,\n settlement: webSocketSettlement,\n });\n }\n\n /**\n * How a `fetch()` response is sent: a streamed body keeps the scope open\n * until it was read, failed or was cancelled, and the object's `waitUntil`\n * holds that completion. A HEAD response sends no body, so its body is\n * cancelled before the scope finishes. A WebSocket upgrade (101) and a\n * bodyless response need nothing.\n */\n #transmit(request: Request, response: Response): Transmission<Response> | undefined {\n if (response.body === null || response.status === 101) return undefined;\n if (request.method === 'HEAD') {\n return {\n value: new Response(null, response),\n sent: response.body.cancel(),\n background: false,\n };\n }\n const stream = trackResponseStream(response.body);\n return { value: new Response(stream.body, response), sent: stream.done, background: true };\n }\n}\n\n/** @internal Options of {@link createDurableObjectHost}. */\nexport interface DurableObjectHostOptions extends DurableObjectContextOptions {\n /** Keeps the object alive for work that outlives an invocation, such as a streamed body. */\n readonly waitUntil?: (promise: Promise<unknown>) => void;\n}\n\n/**\n * Boot one Durable Object instance's application context from `root` with\n * `host` added to the root module's providers, and return its dispatcher,\n * which serves `members`.\n */\nexport async function createDurableObjectHost(\n root: CloudflareRoot,\n host: Type,\n options: DurableObjectHostOptions,\n members: DurableObjectHostMembers,\n): Promise<DurableObjectHostDispatcher> {\n const context = await createDurableObjectContext(withDurableObjectHost(root, host), options);\n const rootClass = typeof root === 'function' ? root : root.module;\n const moduleId = hostModuleId(context.getContainer(), host, rootClass);\n return new DurableObjectHostDispatcher(context, host, moduleId, members, options.waitUntil);\n}\n"],"mappings":";;;;;;AAuCA,MAAM,kBAAwC;CAC5C,QAAQ,OAAO;EACb,IAAI,EAAE,iBAAiB,WACrB,MAAM,IAAI,UAAU,uDAAuD;EAE7E,OAAO;CACT;CACA,MAAM,QAAQ,OAAO,SAAS;EAC5B,MAAM,SAAS,eAAe,QAAQ,SAAS,KAAK;EACpD,IAAI,UAAU;EACd,IAAI,QAAQ;GACV,MAAM,SAAS,MAAM,UAAU,QAAQ,OAAO,OAAO;GACrD,IAAI,OAAO,SAAS;IAClB,IAAI,OAAO,iBAAiB,UAAU,OAAO,OAAO;IACpD,IAAI,OAAO,UAAU,KAAA,GACnB,OAAO,SAAS,KAAK,OAAO,OAAO,EAAE,QAAQ,eAAe,KAAK,EAAE,CAAC;GAExE,OACE,UAAU,OAAO;EAErB;EACA,OAAO,yBAAyB,SAAS,QAAQ,UAAU,QAAQ,OAAO;CAC5E;AACF;AAGA,MAAM,kBAAkB,mBAAmB,IAAI;AAC/C,MAAM,sBAAsB,mBAAmB,KAAK;;;;;;;;;;;AAYpD,IAAa,8BAAb,MAAyC;CACvC;CACA;CACA;CAEA,YACE,SACA,MACA,UACA,SACA,WACA;EACA,KAAK,UAAU;EACf,KAAK,WAAW,IAAI,YAAY;GAC9B,WAAW,QAAQ,aAAa;GAChC;GACA;GACA,MAAM;GACN;EACF,CAAC;EACD,KAAK,WAAW,IAAI,IAAI,QAAQ,OAAO;CACzC;;;;;;CAOA,KAAK,QAAgB,MAA4C;EAC/D,OAAO,cAAc,KAAK,UAAU,KAAK,UAAU,QAAQ,IAAI;CACjE;;;;;;CAOA,MAAM,MAAM,SAAqC;EAC/C,IAAI;GACF,OAAO,MAAM,KAAK,SAAS,OAAO;IAChC,MAAM;IACN,QAAQ;IACR,MAAM,CAAC,OAAO;IACd,YAAY;IACZ,WAAW,aAAa,KAAK,UAAU,SAAS,QAAQ;GAC1D,CAAC;EACH,SAAS,OAAO;GACd,KAAK,SAAS,cAAc,OAAO,KAAK,SAAS,OAAO,eAAe,OAAO,CAAC;GAC/E,MAAM,UAAU,wBAAwB;GACxC,OAAO,SAAS,KACd,EAAE,OAAO;IAAE,MAAM,QAAQ;IAAM,SAAS,QAAQ;GAAQ,EAAE,GAC1D,EAAE,QAAQ,QAAQ,OAAO,CAC3B;EACF;CACF;CAEA,MAAM,MAAM,MAA2C;EACrD,MAAM,KAAK,SAAS,OAAO;GACzB,MAAM;GACN,QAAQ;GACR,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,CAAC,IAAI;GACrC,YAAY;EACd,CAAC;CACH;CAEA,MAAM,UAAU,SAAwC,MAAyC;EAC/F,MAAM,KAAK,SAAS,OAAO;GACzB,MAAM;GACN,QAAQ;GACR;GACA,YAAY;EACd,CAAC;CACH;;;;;;;;CASA,UAAU,SAAkB,UAAwD;EAClF,IAAI,SAAS,SAAS,QAAQ,SAAS,WAAW,KAAK,OAAO,KAAA;EAC9D,IAAI,QAAQ,WAAW,QACrB,OAAO;GACL,OAAO,IAAI,SAAS,MAAM,QAAQ;GAClC,MAAM,SAAS,KAAK,OAAO;GAC3B,YAAY;EACd;EAEF,MAAM,SAAS,oBAAoB,SAAS,IAAI;EAChD,OAAO;GAAE,OAAO,IAAI,SAAS,OAAO,MAAM,QAAQ;GAAG,MAAM,OAAO;GAAM,YAAY;EAAK;CAC3F;AACF;;;;;;AAaA,eAAsB,wBACpB,MACA,MACA,SACA,SACsC;CACtC,MAAM,UAAU,MAAM,2BAA2B,sBAAsB,MAAM,IAAI,GAAG,OAAO;CAC3F,MAAM,YAAY,OAAO,SAAS,aAAa,OAAO,KAAK;CAE3D,OAAO,IAAI,4BAA4B,SAAS,MAD/B,aAAa,QAAQ,aAAa,GAAG,MAAM,SACN,GAAU,SAAS,QAAQ,SAAS;AAC5F"}
@@ -0,0 +1,47 @@
1
+ import { hostMembers } from "../host/host-members.js";
2
+ //#region src/durable-object/host-methods.ts
3
+ /** Durable Object event handlers a host may implement; the object delegates them. */
4
+ const DURABLE_OBJECT_HANDLERS = [
5
+ "fetch",
6
+ "alarm",
7
+ "webSocketMessage",
8
+ "webSocketClose",
9
+ "webSocketError"
10
+ ];
11
+ /**
12
+ * Names an RPC method cannot take: the Durable Object's own `ctx` and `env`,
13
+ * the stub members that shadow any RPC method of that name (`connect()`, a
14
+ * TCP socket, `dup()`, and the `id` and `name` properties), and `then`, which
15
+ * would make the stub and its results thenables.
16
+ */
17
+ const DURABLE_OBJECT = {
18
+ label: "Durable Object",
19
+ reserved: /* @__PURE__ */ new Set([
20
+ "ctx",
21
+ "env",
22
+ "connect",
23
+ "dup",
24
+ "id",
25
+ "name",
26
+ "then"
27
+ ]),
28
+ handlers: DURABLE_OBJECT_HANDLERS
29
+ };
30
+ /**
31
+ * The members of `host` its Durable Object class exposes: the RPC methods
32
+ * `rpc` names, and the event handlers it implements. Each `rpc` entry must
33
+ * name a string-keyed method on the host's prototype chain (below
34
+ * `Object.prototype`); a hook, an event handler, a name the Durable Object or
35
+ * its stubs own, an accessor or an instance field throws, and so does a host
36
+ * whose prototype defines `then`. Nothing else is an RPC method, TypeScript
37
+ * `private` and `protected` methods included. `fetch`, `alarm` and the
38
+ * WebSocket handlers, when the host defines them, become the object's
39
+ * handlers. Read at class definition, without constructing the host.
40
+ */
41
+ function durableObjectHostMembers(host, rpc) {
42
+ return hostMembers(host, rpc, DURABLE_OBJECT);
43
+ }
44
+ //#endregion
45
+ export { DURABLE_OBJECT_HANDLERS, durableObjectHostMembers };
46
+
47
+ //# sourceMappingURL=host-methods.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-methods.js","names":[],"sources":["../../src/durable-object/host-methods.ts"],"sourcesContent":["import {\n hostMembers,\n type HostClass,\n type HostMembers,\n type RpcSurface,\n} from '../host/host-members';\n\n/** Durable Object event handlers a host may implement; the object delegates them. */\nexport const DURABLE_OBJECT_HANDLERS = [\n 'fetch',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n] as const;\n\nexport type DurableObjectHandlerName = (typeof DURABLE_OBJECT_HANDLERS)[number];\n\n/**\n * Names an RPC method cannot take: the Durable Object's own `ctx` and `env`,\n * the stub members that shadow any RPC method of that name (`connect()`, a\n * TCP socket, `dup()`, and the `id` and `name` properties), and `then`, which\n * would make the stub and its results thenables.\n */\nconst DURABLE_OBJECT: RpcSurface<DurableObjectHandlerName> = {\n label: 'Durable Object',\n reserved: new Set(['ctx', 'env', 'connect', 'dup', 'id', 'name', 'then']),\n handlers: DURABLE_OBJECT_HANDLERS,\n};\n\n/** What a host class contributes to its Durable Object class. */\nexport type DurableObjectHostMembers = HostMembers<DurableObjectHandlerName>;\n\n/**\n * The members of `host` its Durable Object class exposes: the RPC methods\n * `rpc` names, and the event handlers it implements. Each `rpc` entry must\n * name a string-keyed method on the host's prototype chain (below\n * `Object.prototype`); a hook, an event handler, a name the Durable Object or\n * its stubs own, an accessor or an instance field throws, and so does a host\n * whose prototype defines `then`. Nothing else is an RPC method, TypeScript\n * `private` and `protected` methods included. `fetch`, `alarm` and the\n * WebSocket handlers, when the host defines them, become the object's\n * handlers. Read at class definition, without constructing the host.\n */\nexport function durableObjectHostMembers(\n host: HostClass,\n rpc?: readonly string[],\n): {\n methods: string[];\n handlers: DurableObjectHandlerName[];\n} {\n return hostMembers(host, rpc, DURABLE_OBJECT);\n}\n"],"mappings":";;;AAQA,MAAa,0BAA0B;CACrC;CACA;CACA;CACA;CACA;AACF;;;;;;;AAUA,MAAM,iBAAuD;CAC3D,OAAO;CACP,0BAAU,IAAI,IAAI;EAAC;EAAO;EAAO;EAAW;EAAO;EAAM;EAAQ;CAAM,CAAC;CACxE,UAAU;AACZ;;;;;;;;;;;;AAgBA,SAAgB,yBACd,MACA,KAIA;CACA,OAAO,YAAY,MAAM,KAAK,cAAc;AAC9C"}
@@ -0,0 +1,17 @@
1
+ import { InjectionToken } from "@velajs/vela";
2
+ //#region src/durable-object/tokens.ts
3
+ /**
4
+ * This Durable Object's `DurableObjectState` (`ctx` in a hand-written class),
5
+ * injectable in the application context the object boots: storage, id,
6
+ * `blockConcurrencyWhile`, WebSocket hibernation. Registered only inside a
7
+ * Durable Object; a provider the Worker builds too injects it with `@Optional()`.
8
+ */
9
+ const DO_STATE = /* @__PURE__ */ new InjectionToken("vela.DO_STATE");
10
+ /** This Durable Object's transactional storage, `DO_STATE.storage`. */
11
+ const DO_STORAGE = /* @__PURE__ */ new InjectionToken("vela.DO_STORAGE");
12
+ /** This Durable Object's id, `DO_STATE.id` (`id.name` when addressed by name). */
13
+ const DO_ID = /* @__PURE__ */ new InjectionToken("vela.DO_ID");
14
+ //#endregion
15
+ export { DO_ID, DO_STATE, DO_STORAGE };
16
+
17
+ //# sourceMappingURL=tokens.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokens.js","names":[],"sources":["../../src/durable-object/tokens.ts"],"sourcesContent":["import { InjectionToken } from '@velajs/vela';\n\n/**\n * This Durable Object's `DurableObjectState` (`ctx` in a hand-written class),\n * injectable in the application context the object boots: storage, id,\n * `blockConcurrencyWhile`, WebSocket hibernation. Registered only inside a\n * Durable Object; a provider the Worker builds too injects it with `@Optional()`.\n */\nexport const DO_STATE = /* @__PURE__ */ new InjectionToken<DurableObjectState>('vela.DO_STATE');\n\n/** This Durable Object's transactional storage, `DO_STATE.storage`. */\nexport const DO_STORAGE = /* @__PURE__ */ new InjectionToken<DurableObjectStorage>(\n 'vela.DO_STORAGE',\n);\n\n/** This Durable Object's id, `DO_STATE.id` (`id.name` when addressed by name). */\nexport const DO_ID = /* @__PURE__ */ new InjectionToken<DurableObjectId>('vela.DO_ID');\n"],"mappings":";;;;;;;;AAQA,MAAa,2BAA2B,IAAI,eAAmC,eAAe;;AAG9F,MAAa,6BAA6B,IAAI,eAC5C,iBACF;;AAGA,MAAa,wBAAwB,IAAI,eAAgC,YAAY"}
@@ -0,0 +1,121 @@
1
+ import { CLOUDFLARE_DURABLE_OBJECT, registerDurableObject } from "../cloudflare-factory.js";
2
+ import { internalEntrypointError } from "../rpc/entrypoint-error.js";
3
+ import { durableObjectDefinition, startDurableObject } from "./boot.js";
4
+ import { createDurableObjectHost } from "./host-dispatch.js";
5
+ import { durableObjectHostMembers } from "./host-methods.js";
6
+ import { DurableObject } from "cloudflare:workers";
7
+ //#region src/durable-object/vela-durable-object.ts
8
+ /** The dispatcher each instance boots, readable by the methods defined outside the class body. */
9
+ const dispatchers = /* @__PURE__ */ new WeakMap();
10
+ function dispatcherOf(instance) {
11
+ const dispatcher = dispatchers.get(instance);
12
+ if (!dispatcher) throw new TypeError("Durable Object method called on a foreign receiver.");
13
+ return dispatcher;
14
+ }
15
+ /** An RPC caller learns that the object failed to start, never why. */
16
+ async function startedDispatcher(instance) {
17
+ try {
18
+ return await dispatcherOf(instance);
19
+ } catch {
20
+ throw internalEntrypointError();
21
+ }
22
+ }
23
+ /**
24
+ * A Durable Object class whose instances each boot one application context
25
+ * from `root` (a module class, a `DynamicModule`, or an app from
26
+ * `defineCloudflareApp`, whose runtime adapters it shares), with `host`, an
27
+ * `@Injectable()` class, added to the root module's providers. Export a named
28
+ * subclass matching the Wrangler `class_name`:
29
+ *
30
+ * ```ts
31
+ * @Injectable()
32
+ * export class CounterHost {
33
+ * constructor(@Inject(DO_STORAGE) private readonly storage: DurableObjectStorage) {}
34
+ * async increment(by: number): Promise<number> {
35
+ * const value = ((await this.storage.get<number>('value')) ?? 0) + by;
36
+ * await this.storage.put('value', value);
37
+ * return value;
38
+ * }
39
+ * }
40
+ * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
41
+ * // In the Worker: await env.COUNTER.getByName('orders').increment(1)
42
+ * ```
43
+ *
44
+ * - The host methods the `rpc` option names are the class's JS-RPC methods,
45
+ * typed so `DurableObjectNamespace<Counter>` stubs expose exactly their
46
+ * signatures. No other method is reachable over RPC: not an unlisted public
47
+ * method, a TypeScript `private` helper or a hook. A listed name that is not
48
+ * a prototype method of the host throws here, and so does a host whose
49
+ * prototype defines `then()`, which would make every instance a thenable.
50
+ * `fetch`, `alarm`, `webSocketMessage`, `webSocketClose` and
51
+ * `webSocketError`, when the host defines them, become the object's
52
+ * handlers.
53
+ * - The context boots in the constructor under `blockConcurrencyWhile`, so no
54
+ * event runs before it is ready. It injects `ENV` (the object's
55
+ * environment), `DO_STATE`, `DO_STORAGE` and `DO_ID`, and reaches WebSocket
56
+ * rooms and live invalidation as the Worker does.
57
+ * - Each call and event runs in its own execution scope through the host's
58
+ * scoped guards, pipes, interceptors and filters (`getType()` is `rpc`, or
59
+ * `cf:do:fetch`, `cf:do:alarm`, `cf:do:websocket`); a streamed `fetch()`
60
+ * body keeps its scope open until it finishes. Failures are reported; an
61
+ * RPC call rejects with an `EntrypointError` and nothing else.
62
+ */
63
+ function VelaDurableObject(root, host, options = {}) {
64
+ const definition = durableObjectDefinition(root);
65
+ const members = durableObjectHostMembers(host, options.rpc);
66
+ class VelaHostDurableObject extends DurableObject {
67
+ constructor(ctx, env) {
68
+ super(ctx, env);
69
+ dispatchers.set(this, startDurableObject(ctx, host.name, () => createDurableObjectHost(definition.rootModule, host, {
70
+ env,
71
+ state: ctx,
72
+ adapters: definition.adapters,
73
+ waitUntil: (promise) => ctx.waitUntil(promise)
74
+ }, members)));
75
+ }
76
+ }
77
+ const prototype = VelaHostDurableObject.prototype;
78
+ const define = (name, value) => {
79
+ Object.defineProperty(prototype, name, {
80
+ value,
81
+ writable: true,
82
+ configurable: true
83
+ });
84
+ };
85
+ for (const method of members.methods) define(method, async function(...args) {
86
+ return (await startedDispatcher(this)).call(method, args);
87
+ });
88
+ for (const handler of members.handlers) if (handler === "fetch") define("fetch", async function(request) {
89
+ let dispatcher;
90
+ try {
91
+ dispatcher = await dispatcherOf(this);
92
+ } catch {
93
+ return Response.json({ error: {
94
+ code: "internal",
95
+ message: "Internal Server Error"
96
+ } }, { status: 500 });
97
+ }
98
+ return dispatcher.fetch(request);
99
+ });
100
+ else if (handler === "alarm") define("alarm", async function(info) {
101
+ return (await dispatcherOf(this)).alarm(info);
102
+ });
103
+ else define(handler, async function(...args) {
104
+ return (await dispatcherOf(this)).webSocket(handler, args);
105
+ });
106
+ const descriptor = {
107
+ kind: "host",
108
+ rootModule: definition.rootModule,
109
+ host,
110
+ methods: members.methods,
111
+ durableObject: VelaHostDurableObject
112
+ };
113
+ Object.defineProperty(VelaHostDurableObject, "name", { value: `${host.name}DurableObject` });
114
+ if (definition.app) registerDurableObject(definition.app, descriptor);
115
+ Object.defineProperty(VelaHostDurableObject, CLOUDFLARE_DURABLE_OBJECT, { value: descriptor });
116
+ return VelaHostDurableObject;
117
+ }
118
+ //#endregion
119
+ export { VelaDurableObject };
120
+
121
+ //# sourceMappingURL=vela-durable-object.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vela-durable-object.js","names":[],"sources":["../../src/durable-object/vela-durable-object.ts"],"sourcesContent":["import { DurableObject } from 'cloudflare:workers';\nimport type { Type, VelaEnv } from '@velajs/vela';\nimport {\n CLOUDFLARE_DURABLE_OBJECT,\n registerDurableObject,\n type CloudflareDurableObjectDescriptor,\n} from '../cloudflare-factory';\nimport { durableObjectDefinition, startDurableObject, type DurableObjectRoot } from './boot';\nimport { internalEntrypointError } from '../rpc/entrypoint-error';\nimport type { RpcMethodOf, RpcMethods } from '../host/host-members';\nimport { createDurableObjectHost, type DurableObjectHostDispatcher } from './host-dispatch';\nimport { durableObjectHostMembers, type DurableObjectHandlerName } from './host-methods';\n\n/**\n * Host members that are never RPC methods, besides the lifecycle, disposal and\n * entrypoint hooks the application context calls: the object's event\n * handlers, the names the Durable Object class or its stubs own (`ctx`,\n * `env`, `connect`, `dup`, `id`, `name`), and `then`.\n */\ntype NotRpcMethod =\n | DurableObjectHandlerName\n | 'ctx'\n | 'env'\n | 'connect'\n | 'dup'\n | 'id'\n | 'name'\n | 'then';\n\n/**\n * The names a host's `rpc` list may take: its public methods, less hooks,\n * event handlers and names the Durable Object or its stubs own. TypeScript\n * `private` and `protected` methods are not among them.\n */\nexport type DurableObjectRpcMethod<Host> = RpcMethodOf<Host, NotRpcMethod>;\n\n/**\n * The RPC methods a `VelaDurableObject(root, Host, { rpc })` class exposes:\n * the host methods `Method` names, asynchronous. A stub of the class\n * (`env.COUNTER.getByName(name)`) calls them with these signatures.\n */\nexport type DurableObjectRpc<Host, Method extends DurableObjectRpcMethod<Host>> = RpcMethods<\n Host,\n Method\n>;\n\n/** Options of {@link VelaDurableObject}. */\nexport interface VelaDurableObjectOptions<Method extends string = string> {\n /**\n * The host methods callers may invoke over JS-RPC, such as\n * `['increment', 'reset']`: public methods declared in the host's class\n * body (or inherited). Nothing else is an RPC method, so TypeScript\n * `private` helpers, hooks and unlisted methods stay unreachable. Without\n * it the object serves only its event handlers.\n */\n readonly rpc?: readonly Method[];\n}\n\n/**\n * The class `VelaDurableObject(root, Host, { rpc })` returns: export a named\n * subclass of it. It also carries its `CloudflareDurableObjectDescriptor`\n * under the static `CLOUDFLARE_DURABLE_OBJECT` key, for tools.\n */\nexport type VelaDurableObjectClass<\n Host,\n Method extends DurableObjectRpcMethod<Host> = never,\n> = new (\n ctx: DurableObjectState,\n env: VelaEnv,\n) => DurableObject<VelaEnv> & DurableObjectRpc<Host, Method>;\n\n/** The dispatcher each instance boots, readable by the methods defined outside the class body. */\nconst dispatchers = new WeakMap<object, Promise<DurableObjectHostDispatcher>>();\n\nfunction dispatcherOf(instance: object): Promise<DurableObjectHostDispatcher> {\n const dispatcher = dispatchers.get(instance);\n if (!dispatcher) throw new TypeError('Durable Object method called on a foreign receiver.');\n return dispatcher;\n}\n\n/** An RPC caller learns that the object failed to start, never why. */\nasync function startedDispatcher(instance: object): Promise<DurableObjectHostDispatcher> {\n try {\n return await dispatcherOf(instance);\n } catch {\n throw internalEntrypointError();\n }\n}\n\n/**\n * A Durable Object class whose instances each boot one application context\n * from `root` (a module class, a `DynamicModule`, or an app from\n * `defineCloudflareApp`, whose runtime adapters it shares), with `host`, an\n * `@Injectable()` class, added to the root module's providers. Export a named\n * subclass matching the Wrangler `class_name`:\n *\n * ```ts\n * @Injectable()\n * export class CounterHost {\n * constructor(@Inject(DO_STORAGE) private readonly storage: DurableObjectStorage) {}\n * async increment(by: number): Promise<number> {\n * const value = ((await this.storage.get<number>('value')) ?? 0) + by;\n * await this.storage.put('value', value);\n * return value;\n * }\n * }\n * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}\n * // In the Worker: await env.COUNTER.getByName('orders').increment(1)\n * ```\n *\n * - The host methods the `rpc` option names are the class's JS-RPC methods,\n * typed so `DurableObjectNamespace<Counter>` stubs expose exactly their\n * signatures. No other method is reachable over RPC: not an unlisted public\n * method, a TypeScript `private` helper or a hook. A listed name that is not\n * a prototype method of the host throws here, and so does a host whose\n * prototype defines `then()`, which would make every instance a thenable.\n * `fetch`, `alarm`, `webSocketMessage`, `webSocketClose` and\n * `webSocketError`, when the host defines them, become the object's\n * handlers.\n * - The context boots in the constructor under `blockConcurrencyWhile`, so no\n * event runs before it is ready. It injects `ENV` (the object's\n * environment), `DO_STATE`, `DO_STORAGE` and `DO_ID`, and reaches WebSocket\n * rooms and live invalidation as the Worker does.\n * - Each call and event runs in its own execution scope through the host's\n * scoped guards, pipes, interceptors and filters (`getType()` is `rpc`, or\n * `cf:do:fetch`, `cf:do:alarm`, `cf:do:websocket`); a streamed `fetch()`\n * body keeps its scope open until it finishes. Failures are reported; an\n * RPC call rejects with an `EntrypointError` and nothing else.\n */\nexport function VelaDurableObject<\n Host extends object,\n const Method extends DurableObjectRpcMethod<Host> = never,\n>(\n root: DurableObjectRoot,\n host: Type<Host>,\n options: VelaDurableObjectOptions<Method> = {},\n): VelaDurableObjectClass<Host, Method> {\n const definition = durableObjectDefinition(root);\n const members = durableObjectHostMembers(host, options.rpc);\n\n class VelaHostDurableObject extends DurableObject<VelaEnv> {\n constructor(ctx: DurableObjectState, env: VelaEnv) {\n super(ctx, env);\n dispatchers.set(\n this,\n startDurableObject(ctx, host.name, () =>\n createDurableObjectHost(\n definition.rootModule,\n host,\n {\n env,\n state: ctx,\n adapters: definition.adapters,\n waitUntil: (promise) => ctx.waitUntil(promise),\n },\n members,\n ),\n ),\n );\n }\n }\n\n const prototype = VelaHostDurableObject.prototype;\n const define = (name: string, value: (this: object, ...args: never[]) => unknown): void => {\n Object.defineProperty(prototype, name, { value, writable: true, configurable: true });\n };\n for (const method of members.methods) {\n define(method, async function (this: object, ...args: unknown[]) {\n return (await startedDispatcher(this)).call(method, args);\n });\n }\n for (const handler of members.handlers) {\n if (handler === 'fetch') {\n define('fetch', async function (this: object, request: Request) {\n let dispatcher: DurableObjectHostDispatcher;\n try {\n dispatcher = await dispatcherOf(this);\n } catch {\n return Response.json(\n { error: { code: 'internal', message: 'Internal Server Error' } },\n { status: 500 },\n );\n }\n return dispatcher.fetch(request);\n });\n } else if (handler === 'alarm') {\n define('alarm', async function (this: object, info?: AlarmInvocationInfo) {\n return (await dispatcherOf(this)).alarm(info);\n });\n } else {\n define(handler, async function (this: object, ...args: unknown[]) {\n return (await dispatcherOf(this)).webSocket(handler, args);\n });\n }\n }\n\n const descriptor: CloudflareDurableObjectDescriptor = {\n kind: 'host',\n rootModule: definition.rootModule,\n host,\n methods: members.methods,\n durableObject: VelaHostDurableObject,\n };\n Object.defineProperty(VelaHostDurableObject, 'name', { value: `${host.name}DurableObject` });\n if (definition.app) registerDurableObject(definition.app, descriptor);\n Object.defineProperty(VelaHostDurableObject, CLOUDFLARE_DURABLE_OBJECT, { value: descriptor });\n // The RPC methods are defined on the prototype above, at runtime, from the rpc list.\n return VelaHostDurableObject as unknown as VelaDurableObjectClass<Host, Method>;\n}\n"],"mappings":";;;;;;;;AAwEA,MAAM,8BAAc,IAAI,QAAsD;AAE9E,SAAS,aAAa,UAAwD;CAC5E,MAAM,aAAa,YAAY,IAAI,QAAQ;CAC3C,IAAI,CAAC,YAAY,MAAM,IAAI,UAAU,qDAAqD;CAC1F,OAAO;AACT;;AAGA,eAAe,kBAAkB,UAAwD;CACvF,IAAI;EACF,OAAO,MAAM,aAAa,QAAQ;CACpC,QAAQ;EACN,MAAM,wBAAwB;CAChC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,kBAId,MACA,MACA,UAA4C,CAAC,GACP;CACtC,MAAM,aAAa,wBAAwB,IAAI;CAC/C,MAAM,UAAU,yBAAyB,MAAM,QAAQ,GAAG;CAE1D,MAAM,8BAA8B,cAAuB;EACzD,YAAY,KAAyB,KAAc;GACjD,MAAM,KAAK,GAAG;GACd,YAAY,IACV,MACA,mBAAmB,KAAK,KAAK,YAC3B,wBACE,WAAW,YACX,MACA;IACE;IACA,OAAO;IACP,UAAU,WAAW;IACrB,YAAY,YAAY,IAAI,UAAU,OAAO;GAC/C,GACA,OACF,CACF,CACF;EACF;CACF;CAEA,MAAM,YAAY,sBAAsB;CACxC,MAAM,UAAU,MAAc,UAA6D;EACzF,OAAO,eAAe,WAAW,MAAM;GAAE;GAAO,UAAU;GAAM,cAAc;EAAK,CAAC;CACtF;CACA,KAAK,MAAM,UAAU,QAAQ,SAC3B,OAAO,QAAQ,eAA8B,GAAG,MAAiB;EAC/D,QAAQ,MAAM,kBAAkB,IAAI,EAAA,CAAG,KAAK,QAAQ,IAAI;CAC1D,CAAC;CAEH,KAAK,MAAM,WAAW,QAAQ,UAC5B,IAAI,YAAY,SACd,OAAO,SAAS,eAA8B,SAAkB;EAC9D,IAAI;EACJ,IAAI;GACF,aAAa,MAAM,aAAa,IAAI;EACtC,QAAQ;GACN,OAAO,SAAS,KACd,EAAE,OAAO;IAAE,MAAM;IAAY,SAAS;GAAwB,EAAE,GAChE,EAAE,QAAQ,IAAI,CAChB;EACF;EACA,OAAO,WAAW,MAAM,OAAO;CACjC,CAAC;MACI,IAAI,YAAY,SACrB,OAAO,SAAS,eAA8B,MAA4B;EACxE,QAAQ,MAAM,aAAa,IAAI,EAAA,CAAG,MAAM,IAAI;CAC9C,CAAC;MAED,OAAO,SAAS,eAA8B,GAAG,MAAiB;EAChE,QAAQ,MAAM,aAAa,IAAI,EAAA,CAAG,UAAU,SAAS,IAAI;CAC3D,CAAC;CAIL,MAAM,aAAgD;EACpD,MAAM;EACN,YAAY,WAAW;EACvB;EACA,SAAS,QAAQ;EACjB,eAAe;CACjB;CACA,OAAO,eAAe,uBAAuB,QAAQ,EAAE,OAAO,GAAG,KAAK,KAAK,eAAe,CAAC;CAC3F,IAAI,WAAW,KAAK,sBAAsB,WAAW,KAAK,UAAU;CACpE,OAAO,eAAe,uBAAuB,2BAA2B,EAAE,OAAO,WAAW,CAAC;CAE7F,OAAO;AACT"}
@@ -1,18 +1,139 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
2
+ import { a as CloudflareApp, y as CloudflareRoot } from "./cloudflare-factory-CuFNUJJD.js";
3
+ import { n as RpcMethods, t as RpcMethodOf } from "./host-members-DECj_4yz.js";
3
4
  import { l as VelaDoPitrRpc, t as VelaNonceDurableObject } from "./nonce.durable-object-Bg1e0BMD.js";
4
5
  import { DurableObject } from "cloudflare:workers";
5
- import { VelaEnv } from "@velajs/vela";
6
- import { BroadcastCommand } from "@velajs/vela/websocket";
6
+ import { DynamicModule, InjectionToken, Type, VelaEnv } from "@velajs/vela";
7
+ import { EntrypointExecutionContext, RuntimeAdapter } from "@velajs/vela/module-kit";
7
8
  import { CommitStamp, InvalidationCommand, LiveInspection } from "@velajs/vela/live";
9
+ import { BroadcastCommand } from "@velajs/vela/websocket";
10
+ //#region src/durable-object/boot.d.ts
11
+ /**
12
+ * What a Durable Object class is built from: a static root module (a module
13
+ * class or a `DynamicModule`), or an app from `defineCloudflareApp`, whose
14
+ * root and runtime adapters the object shares with the Worker.
15
+ */
16
+ type DurableObjectRoot = CloudflareRoot | CloudflareApp;
17
+ //#endregion
18
+ //#region src/durable-object/host-methods.d.ts
19
+ /** Durable Object event handlers a host may implement; the object delegates them. */
20
+ declare const DURABLE_OBJECT_HANDLERS: readonly ['fetch', 'alarm', 'webSocketMessage', 'webSocketClose', 'webSocketError'];
21
+ type DurableObjectHandlerName = (typeof DURABLE_OBJECT_HANDLERS)[number];
22
+ //#endregion
23
+ //#region src/durable-object/vela-durable-object.d.ts
24
+ /**
25
+ * Host members that are never RPC methods, besides the lifecycle, disposal and
26
+ * entrypoint hooks the application context calls: the object's event
27
+ * handlers, the names the Durable Object class or its stubs own (`ctx`,
28
+ * `env`, `connect`, `dup`, `id`, `name`), and `then`.
29
+ */
30
+ type NotRpcMethod = DurableObjectHandlerName | 'ctx' | 'env' | 'connect' | 'dup' | 'id' | 'name' | 'then';
31
+ /**
32
+ * The names a host's `rpc` list may take: its public methods, less hooks,
33
+ * event handlers and names the Durable Object or its stubs own. TypeScript
34
+ * `private` and `protected` methods are not among them.
35
+ */
36
+ type DurableObjectRpcMethod<Host> = RpcMethodOf<Host, NotRpcMethod>;
37
+ /**
38
+ * The RPC methods a `VelaDurableObject(root, Host, { rpc })` class exposes:
39
+ * the host methods `Method` names, asynchronous. A stub of the class
40
+ * (`env.COUNTER.getByName(name)`) calls them with these signatures.
41
+ */
42
+ type DurableObjectRpc<Host, Method extends DurableObjectRpcMethod<Host>> = RpcMethods<Host, Method>;
43
+ /** Options of {@link VelaDurableObject}. */
44
+ interface VelaDurableObjectOptions<Method extends string = string> {
45
+ /**
46
+ * The host methods callers may invoke over JS-RPC, such as
47
+ * `['increment', 'reset']`: public methods declared in the host's class
48
+ * body (or inherited). Nothing else is an RPC method, so TypeScript
49
+ * `private` helpers, hooks and unlisted methods stay unreachable. Without
50
+ * it the object serves only its event handlers.
51
+ */
52
+ readonly rpc?: readonly Method[];
53
+ }
54
+ /**
55
+ * The class `VelaDurableObject(root, Host, { rpc })` returns: export a named
56
+ * subclass of it. It also carries its `CloudflareDurableObjectDescriptor`
57
+ * under the static `CLOUDFLARE_DURABLE_OBJECT` key, for tools.
58
+ */
59
+ type VelaDurableObjectClass<Host, Method extends DurableObjectRpcMethod<Host> = never> = new (ctx: DurableObjectState, env: VelaEnv) => DurableObject<VelaEnv> & DurableObjectRpc<Host, Method>;
60
+ /**
61
+ * A Durable Object class whose instances each boot one application context
62
+ * from `root` (a module class, a `DynamicModule`, or an app from
63
+ * `defineCloudflareApp`, whose runtime adapters it shares), with `host`, an
64
+ * `@Injectable()` class, added to the root module's providers. Export a named
65
+ * subclass matching the Wrangler `class_name`:
66
+ *
67
+ * ```ts
68
+ * @Injectable()
69
+ * export class CounterHost {
70
+ * constructor(@Inject(DO_STORAGE) private readonly storage: DurableObjectStorage) {}
71
+ * async increment(by: number): Promise<number> {
72
+ * const value = ((await this.storage.get<number>('value')) ?? 0) + by;
73
+ * await this.storage.put('value', value);
74
+ * return value;
75
+ * }
76
+ * }
77
+ * export class Counter extends VelaDurableObject(app, CounterHost, { rpc: ['increment'] }) {}
78
+ * // In the Worker: await env.COUNTER.getByName('orders').increment(1)
79
+ * ```
80
+ *
81
+ * - The host methods the `rpc` option names are the class's JS-RPC methods,
82
+ * typed so `DurableObjectNamespace<Counter>` stubs expose exactly their
83
+ * signatures. No other method is reachable over RPC: not an unlisted public
84
+ * method, a TypeScript `private` helper or a hook. A listed name that is not
85
+ * a prototype method of the host throws here, and so does a host whose
86
+ * prototype defines `then()`, which would make every instance a thenable.
87
+ * `fetch`, `alarm`, `webSocketMessage`, `webSocketClose` and
88
+ * `webSocketError`, when the host defines them, become the object's
89
+ * handlers.
90
+ * - The context boots in the constructor under `blockConcurrencyWhile`, so no
91
+ * event runs before it is ready. It injects `ENV` (the object's
92
+ * environment), `DO_STATE`, `DO_STORAGE` and `DO_ID`, and reaches WebSocket
93
+ * rooms and live invalidation as the Worker does.
94
+ * - Each call and event runs in its own execution scope through the host's
95
+ * scoped guards, pipes, interceptors and filters (`getType()` is `rpc`, or
96
+ * `cf:do:fetch`, `cf:do:alarm`, `cf:do:websocket`); a streamed `fetch()`
97
+ * body keeps its scope open until it finishes. Failures are reported; an
98
+ * RPC call rejects with an `EntrypointError` and nothing else.
99
+ */
100
+ export declare function VelaDurableObject<Host extends object, const Method extends DurableObjectRpcMethod<Host> = never>(root: DurableObjectRoot, host: Type<Host>, options?: VelaDurableObjectOptions<Method>): VelaDurableObjectClass<Host, Method>;
101
+ //#endregion
102
+ //#region src/durable-object/host-dispatch.d.ts
103
+ /**
104
+ * The `ExecutionContext.getType()` of a Durable Object invocation: `rpc` for
105
+ * a host method called over RPC, `cf:do:fetch`, `cf:do:alarm` and
106
+ * `cf:do:websocket` for the object's event handlers. `getPayload()` is the
107
+ * invocation's arguments.
108
+ */
109
+ type DurableObjectInvocationKind = 'rpc' | 'cf:do:fetch' | 'cf:do:alarm' | 'cf:do:websocket';
110
+ /** The ExecutionContext guards, interceptors and filters receive around a Durable Object invocation. */
111
+ type DurableObjectExecutionContext = EntrypointExecutionContext<DurableObjectInvocationKind>;
112
+ //#endregion
113
+ //#region src/durable-object/tokens.d.ts
114
+ /**
115
+ * This Durable Object's `DurableObjectState` (`ctx` in a hand-written class),
116
+ * injectable in the application context the object boots: storage, id,
117
+ * `blockConcurrencyWhile`, WebSocket hibernation. Registered only inside a
118
+ * Durable Object; a provider the Worker builds too injects it with `@Optional()`.
119
+ */
120
+ export declare const DO_STATE: InjectionToken<DurableObjectState<unknown>>;
121
+ /** This Durable Object's transactional storage, `DO_STATE.storage`. */
122
+ export declare const DO_STORAGE: InjectionToken<DurableObjectStorage>;
123
+ /** This Durable Object's id, `DO_STATE.id` (`id.name` when addressed by name). */
124
+ export declare const DO_ID: InjectionToken<DurableObjectId>;
125
+ //#endregion
8
126
  //#region src/websocket/websocket.durable-object.d.ts
9
127
  /**
10
128
  * Base class for the WebSocket Durable Object. The user exports a named subclass
11
- * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, or
12
- * from a `DynamicModule` declared at module scope:
129
+ * (matching their `wrangler.toml` `class_name`) built from their `AppModule`, a
130
+ * `DynamicModule` declared at module scope, or the app from
131
+ * `defineCloudflareApp`, whose runtime adapters the object shares:
13
132
  *
14
133
  * ```ts
15
- * export class ChatRoom extends VelaWebSocketDurableObject(AppModule) {}
134
+ * const app = defineCloudflareApp(AppModule);
135
+ * export class ChatRoom extends VelaWebSocketDurableObject(app) {}
136
+ * export default app.worker;
16
137
  * ```
17
138
  *
18
139
  * It owns the raw hibernation socket lifecycle (Hono's `upgradeWebSocket` cannot
@@ -21,12 +142,13 @@ import { CommitStamp, InvalidationCommand, LiveInspection } from "@velajs/vela/l
21
142
  * `WebSocketModule.forRoot()`: this object registers the platform that binds
22
143
  * its server to these sockets, delivers live invalidations locally and keeps
23
144
  * the live cursor log in its SQLite storage. The DO's `env` is the
24
- * application's ENV, as in the Worker.
145
+ * application's ENV, as in the Worker, and its application context injects
146
+ * `DO_STATE`, `DO_STORAGE` and `DO_ID` like every Vela Durable Object's.
25
147
  */
26
- export declare function VelaWebSocketDurableObject(rootModule: CloudflareRoot): new (ctx: DurableObjectState, env: VelaEnv) => DurableObject<VelaEnv> & VelaDoPitrRpc & {
148
+ export declare function VelaWebSocketDurableObject(root: DurableObjectRoot): new (ctx: DurableObjectState, env: VelaEnv) => DurableObject<VelaEnv> & VelaDoPitrRpc & {
27
149
  broadcast(cmd: BroadcastCommand): Promise<void>;
28
150
  invalidate(cmd: InvalidationCommand): Promise<CommitStamp | undefined>;
29
151
  inspectLive(): Promise<LiveInspection>;
30
152
  };
31
153
  //#endregion
32
- export { VelaNonceDurableObject };
154
+ export { type DurableObjectExecutionContext, type DurableObjectInvocationKind, type DurableObjectRoot, type DurableObjectRpc, type DurableObjectRpcMethod, type VelaDurableObjectClass, type VelaDurableObjectOptions, VelaNonceDurableObject };
@@ -1,3 +1,5 @@
1
+ import { DO_ID, DO_STATE, DO_STORAGE } from "./durable-object/tokens.js";
2
+ import { VelaDurableObject } from "./durable-object/vela-durable-object.js";
1
3
  import { VelaWebSocketDurableObject } from "./websocket/websocket.durable-object.js";
2
4
  import { VelaNonceDurableObject } from "./nonce/nonce.durable-object.js";
3
- export { VelaNonceDurableObject, VelaWebSocketDurableObject };
5
+ export { DO_ID, DO_STATE, DO_STORAGE, VelaDurableObject, VelaNonceDurableObject, VelaWebSocketDurableObject };
@@ -0,0 +1,65 @@
1
+ import { entrypointInvoker, platformSettlement, settleInvocations } from "../host/host-invoker.js";
2
+ //#region src/email/email-dispatch.ts
3
+ /** The metadata key `@OnEmail()` records its handlers under (entrypoint kind `cf:email`). */
4
+ const EMAIL_METADATA = "cloudflare:email";
5
+ /**
6
+ * The reason a message no handler accepts is rejected with: a permanent SMTP
7
+ * error the sending server reports to its sender.
8
+ */
9
+ const UNCLAIMED_EMAIL_REASON = "No handler accepts mail for this address.";
10
+ function isStringList(value) {
11
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
12
+ }
13
+ /** Validate `cf:email` entrypoint metadata. */
14
+ function parseOnEmailMetadata(meta) {
15
+ if (typeof meta !== "object" || meta === null) throw new Error("Invalid @OnEmail() metadata.");
16
+ const methodName = Reflect.get(meta, "methodName");
17
+ const to = Reflect.get(meta, "to");
18
+ if (typeof methodName !== "string" || to !== void 0 && !isStringList(to)) throw new Error("Invalid @OnEmail() metadata.");
19
+ return to === void 0 ? { methodName } : {
20
+ methodName,
21
+ to
22
+ };
23
+ }
24
+ /** Whether the platform's payload is an Email Workers message. */
25
+ function isEmailMessage(value) {
26
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "from") === "string" && typeof Reflect.get(value, "to") === "string" && typeof Reflect.get(value, "setReject") === "function";
27
+ }
28
+ const warned = /* @__PURE__ */ new WeakSet();
29
+ const emailSettlement = platformSettlement(false);
30
+ /**
31
+ * Deliver an Email Workers message to the application's `@OnEmail()`
32
+ * handlers: those whose `to` lists its envelope recipient, or else those
33
+ * without `to`. Each runs in its own execution scope through its scoped
34
+ * guards, interceptors and filters, with the native message. When no handler
35
+ * accepts it, the message is rejected with {@link UNCLAIMED_EMAIL_REASON}
36
+ * rather than dropped. A failure is reported (`edge: 'email'`) and, unless a
37
+ * filter handles it, rethrown once every handler settled.
38
+ */
39
+ async function dispatchEmail(application, message) {
40
+ if (!isEmailMessage(message)) throw new TypeError("The email handler received no email message.");
41
+ const entries = application.entrypoints.ofKind("cf:email", parseOnEmailMetadata);
42
+ const recipient = message.to.toLowerCase();
43
+ const addressed = entries.filter((entry) => entry.meta.to?.includes(recipient) === true);
44
+ const handlers = addressed.length > 0 ? addressed : entries.filter((entry) => entry.meta.to === void 0);
45
+ if (handlers.length === 0) {
46
+ message.setReject(UNCLAIMED_EMAIL_REASON);
47
+ if (!warned.has(application) && application.getContainer().getDiagnostics() !== "silent") {
48
+ warned.add(application);
49
+ console.warn(`[vela] An email arrived for a recipient no @OnEmail() handler accepts, and was rejected (${entries.length} handler${entries.length === 1 ? "" : "s"} declared). Add @OnEmail() without \`to\` to accept every other recipient.`);
50
+ }
51
+ return;
52
+ }
53
+ const container = application.getContainer();
54
+ await settleInvocations(handlers.map(async (entry) => entrypointInvoker(container, entry, "email").invoke({
55
+ kind: "cf:email",
56
+ method: entry.meta.methodName,
57
+ args: [message],
58
+ payload: message,
59
+ settlement: emailSettlement
60
+ })));
61
+ }
62
+ //#endregion
63
+ export { EMAIL_METADATA, UNCLAIMED_EMAIL_REASON, dispatchEmail, parseOnEmailMetadata };
64
+
65
+ //# sourceMappingURL=email-dispatch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email-dispatch.js","names":[],"sources":["../../src/email/email-dispatch.ts"],"sourcesContent":["import type { EntrypointExecutionContext } from '@velajs/vela/module-kit';\nimport type { CloudflareApplication } from '../cloudflare-application';\nimport { entrypointInvoker, platformSettlement, settleInvocations } from '../host/host-invoker';\n\n/** The metadata key `@OnEmail()` records its handlers under (entrypoint kind `cf:email`). */\nexport const EMAIL_METADATA = 'cloudflare:email';\n\n/** One `@OnEmail()` handler: its method and the recipients it accepts. */\nexport interface OnEmailMetadata {\n readonly methodName: string;\n /** Lowercased envelope recipients; undefined for a handler of every other recipient. */\n readonly to?: readonly string[];\n}\n\n/** The ExecutionContext guards, interceptors and filters receive around an `@OnEmail()` handler. */\nexport type EmailExecutionContext = EntrypointExecutionContext<'cf:email'>;\n\n/**\n * The reason a message no handler accepts is rejected with: a permanent SMTP\n * error the sending server reports to its sender.\n */\nexport const UNCLAIMED_EMAIL_REASON = 'No handler accepts mail for this address.';\n\nfunction isStringList(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((item) => typeof item === 'string');\n}\n\n/** Validate `cf:email` entrypoint metadata. */\nexport function parseOnEmailMetadata(meta: unknown): OnEmailMetadata {\n if (typeof meta !== 'object' || meta === null) throw new Error('Invalid @OnEmail() metadata.');\n const methodName: unknown = Reflect.get(meta, 'methodName');\n const to: unknown = Reflect.get(meta, 'to');\n if (typeof methodName !== 'string' || (to !== undefined && !isStringList(to))) {\n throw new Error('Invalid @OnEmail() metadata.');\n }\n return to === undefined ? { methodName } : { methodName, to };\n}\n\n/** Whether the platform's payload is an Email Workers message. */\nfunction isEmailMessage(value: unknown): value is ForwardableEmailMessage {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof Reflect.get(value, 'from') === 'string' &&\n typeof Reflect.get(value, 'to') === 'string' &&\n typeof Reflect.get(value, 'setReject') === 'function'\n );\n}\n\nconst warned = new WeakSet<CloudflareApplication>();\n\n// A handler failure reaches the platform unless a scoped filter handles it.\nconst emailSettlement = platformSettlement(false);\n\n/**\n * Deliver an Email Workers message to the application's `@OnEmail()`\n * handlers: those whose `to` lists its envelope recipient, or else those\n * without `to`. Each runs in its own execution scope through its scoped\n * guards, interceptors and filters, with the native message. When no handler\n * accepts it, the message is rejected with {@link UNCLAIMED_EMAIL_REASON}\n * rather than dropped. A failure is reported (`edge: 'email'`) and, unless a\n * filter handles it, rethrown once every handler settled.\n */\nexport async function dispatchEmail(\n application: CloudflareApplication,\n message: unknown,\n): Promise<void> {\n if (!isEmailMessage(message)) throw new TypeError('The email handler received no email message.');\n const entries = application.entrypoints.ofKind('cf:email', parseOnEmailMetadata);\n const recipient = message.to.toLowerCase();\n const addressed = entries.filter((entry) => entry.meta.to?.includes(recipient) === true);\n const handlers =\n addressed.length > 0 ? addressed : entries.filter((entry) => entry.meta.to === undefined);\n if (handlers.length === 0) {\n message.setReject(UNCLAIMED_EMAIL_REASON);\n if (!warned.has(application) && application.getContainer().getDiagnostics() !== 'silent') {\n warned.add(application);\n console.warn(\n `[vela] An email arrived for a recipient no @OnEmail() handler accepts, and was rejected ` +\n `(${entries.length} handler${entries.length === 1 ? '' : 's'} declared). Add ` +\n '@OnEmail() without `to` to accept every other recipient.',\n );\n }\n return;\n }\n const container = application.getContainer();\n await settleInvocations(\n handlers.map(async (entry) =>\n entrypointInvoker(container, entry, 'email').invoke({\n kind: 'cf:email',\n method: entry.meta.methodName,\n args: [message],\n payload: message,\n settlement: emailSettlement,\n }),\n ),\n );\n}\n"],"mappings":";;;AAKA,MAAa,iBAAiB;;;;;AAgB9B,MAAa,yBAAyB;AAEtC,SAAS,aAAa,OAAmC;CACvD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ;AAC/E;;AAGA,SAAgB,qBAAqB,MAAgC;CACnE,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,8BAA8B;CAC7F,MAAM,aAAsB,QAAQ,IAAI,MAAM,YAAY;CAC1D,MAAM,KAAc,QAAQ,IAAI,MAAM,IAAI;CAC1C,IAAI,OAAO,eAAe,YAAa,OAAO,KAAA,KAAa,CAAC,aAAa,EAAE,GACzE,MAAM,IAAI,MAAM,8BAA8B;CAEhD,OAAO,OAAO,KAAA,IAAY,EAAE,WAAW,IAAI;EAAE;EAAY;CAAG;AAC9D;;AAGA,SAAS,eAAe,OAAkD;CACxE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,QAAQ,IAAI,OAAO,MAAM,MAAM,YACtC,OAAO,QAAQ,IAAI,OAAO,IAAI,MAAM,YACpC,OAAO,QAAQ,IAAI,OAAO,WAAW,MAAM;AAE/C;AAEA,MAAM,yBAAS,IAAI,QAA+B;AAGlD,MAAM,kBAAkB,mBAAmB,KAAK;;;;;;;;;;AAWhD,eAAsB,cACpB,aACA,SACe;CACf,IAAI,CAAC,eAAe,OAAO,GAAG,MAAM,IAAI,UAAU,8CAA8C;CAChG,MAAM,UAAU,YAAY,YAAY,OAAO,YAAY,oBAAoB;CAC/E,MAAM,YAAY,QAAQ,GAAG,YAAY;CACzC,MAAM,YAAY,QAAQ,QAAQ,UAAU,MAAM,KAAK,IAAI,SAAS,SAAS,MAAM,IAAI;CACvF,MAAM,WACJ,UAAU,SAAS,IAAI,YAAY,QAAQ,QAAQ,UAAU,MAAM,KAAK,OAAO,KAAA,CAAS;CAC1F,IAAI,SAAS,WAAW,GAAG;EACzB,QAAQ,UAAU,sBAAsB;EACxC,IAAI,CAAC,OAAO,IAAI,WAAW,KAAK,YAAY,aAAa,CAAC,CAAC,eAAe,MAAM,UAAU;GACxF,OAAO,IAAI,WAAW;GACtB,QAAQ,KACN,4FACM,QAAQ,OAAO,UAAU,QAAQ,WAAW,IAAI,KAAK,IAAI,2EAEjE;EACF;EACA;CACF;CACA,MAAM,YAAY,YAAY,aAAa;CAC3C,MAAM,kBACJ,SAAS,IAAI,OAAO,UAClB,kBAAkB,WAAW,OAAO,OAAO,CAAC,CAAC,OAAO;EAClD,MAAM;EACN,QAAQ,MAAM,KAAK;EACnB,MAAM,CAAC,OAAO;EACd,SAAS;EACT,YAAY;CACd,CAAC,CACH,CACF;AACF"}