@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.
- package/CHANGELOG.md +62 -0
- package/README.md +154 -10
- package/dist/bindings.js +17 -1
- package/dist/bindings.js.map +1 -1
- package/dist/{cloudflare-factory-eGiet0mg.d.ts → cloudflare-application-CXDy9C1R.d.ts} +9 -98
- package/dist/cloudflare-application.js +8 -0
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
- package/dist/cloudflare-factory.js +153 -20
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/durable-object/boot.js +76 -0
- package/dist/durable-object/boot.js.map +1 -0
- package/dist/durable-object/host-dispatch.js +134 -0
- package/dist/durable-object/host-dispatch.js.map +1 -0
- package/dist/durable-object/host-methods.js +47 -0
- package/dist/durable-object/host-methods.js.map +1 -0
- package/dist/durable-object/tokens.js +17 -0
- package/dist/durable-object/tokens.js.map +1 -0
- package/dist/durable-object/vela-durable-object.js +121 -0
- package/dist/durable-object/vela-durable-object.js.map +1 -0
- package/dist/durable-objects.d.ts +131 -9
- package/dist/durable-objects.js +3 -1
- package/dist/email/email-dispatch.js +65 -0
- package/dist/email/email-dispatch.js.map +1 -0
- package/dist/email/on-email.js +57 -0
- package/dist/email/on-email.js.map +1 -0
- package/dist/email.d.ts +51 -0
- package/dist/email.js +3 -0
- package/dist/entrypoint/vela-entrypoint.js +160 -0
- package/dist/entrypoint/vela-entrypoint.js.map +1 -0
- package/dist/entrypoints.d.ts +93 -0
- package/dist/entrypoints.js +2 -0
- package/dist/host/host-invoker.js +276 -0
- package/dist/host/host-invoker.js.map +1 -0
- package/dist/host/host-members.js +73 -0
- package/dist/host/host-members.js.map +1 -0
- package/dist/host-members-DECj_4yz.d.ts +13 -0
- package/dist/index.d.ts +72 -11
- package/dist/index.js +4 -3
- package/dist/root-module.js +19 -0
- package/dist/root-module.js.map +1 -0
- package/dist/rpc/entrypoint-error.js +145 -0
- package/dist/rpc/entrypoint-error.js.map +1 -0
- package/dist/tail/on-tail.js +46 -0
- package/dist/tail/on-tail.js.map +1 -0
- package/dist/tail/tail-dispatch.js +67 -0
- package/dist/tail/tail-dispatch.js.map +1 -0
- package/dist/tail.d.ts +39 -0
- package/dist/tail.js +2 -0
- package/dist/testing.d.ts +55 -3
- package/dist/testing.js +78 -1
- package/dist/testing.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +40 -37
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +37 -8
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/worker-events.js +49 -0
- package/dist/worker-events.js.map +1 -0
- package/dist/workflow/vela-workflow.js +104 -0
- package/dist/workflow/vela-workflow.js.map +1 -0
- package/dist/workflows.d.ts +82 -0
- package/dist/workflows.js +2 -0
- package/package.json +23 -7
- package/dist/root-module-C23bUwt_.d.ts +0 -11
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { HttpException, renderHttpError } from "@velajs/vela";
|
|
2
|
+
//#region src/rpc/entrypoint-error.ts
|
|
3
|
+
const NAME = "EntrypointError";
|
|
4
|
+
const CODE = /^[A-Za-z0-9_.:-]{1,160}$/;
|
|
5
|
+
const MAX_MESSAGE_LENGTH = 2048;
|
|
6
|
+
/**
|
|
7
|
+
* The one error the JS-RPC methods of a Vela entrypoint reject with: a
|
|
8
|
+
* Durable Object from `VelaDurableObject()` and a service entrypoint from
|
|
9
|
+
* `VelaEntrypoint()`. The entrypoint reports the original error first, then
|
|
10
|
+
* renders it as HTTP renders a response with server bodies redacted
|
|
11
|
+
* (`renderHttpError`): a 4xx `HttpException` keeps its code, message and
|
|
12
|
+
* details; a branded `VelaError` keeps its code and message at any status, and
|
|
13
|
+
* its details below 500; a 5xx `HttpException` becomes its status's code and
|
|
14
|
+
* title; an unknown error becomes `500 internal "Internal Server Error"`. A 4xx
|
|
15
|
+
* `HttpException` constructed with an object response keeps only its status
|
|
16
|
+
* (code `error`) unless that object is a canonical `{ error: { code, message,
|
|
17
|
+
* details } }` body. Only these own properties cross the RPC boundary: no stack
|
|
18
|
+
* frames, causes or other fields of the original.
|
|
19
|
+
*
|
|
20
|
+
* workerd rebuilds it on the caller's side as a plain `Error` with the same
|
|
21
|
+
* `name`, `status`, `code`, `message` and `details`; read it with
|
|
22
|
+
* {@link isEntrypointError}. That needs a Worker `compatibility_date` of
|
|
23
|
+
* 2026-04-21 or later, or the `enhanced_error_serialization` compatibility
|
|
24
|
+
* flag: before it, workerd delivers only an `Error` whose message is
|
|
25
|
+
* `EntrypointError: <message>`, without the status, code or details
|
|
26
|
+
* (`vela deploy check` warns about it). A host may throw one itself, for
|
|
27
|
+
* example to pass on another entrypoint's failure: a 4xx one keeps its code,
|
|
28
|
+
* message and details, a 5xx one only its status.
|
|
29
|
+
*/
|
|
30
|
+
var EntrypointError = class extends Error {
|
|
31
|
+
name = NAME;
|
|
32
|
+
status;
|
|
33
|
+
code;
|
|
34
|
+
constructor(init) {
|
|
35
|
+
super(init.message);
|
|
36
|
+
this.status = init.status;
|
|
37
|
+
this.code = init.code;
|
|
38
|
+
if (init.details !== void 0) Object.defineProperty(this, "details", {
|
|
39
|
+
value: init.details,
|
|
40
|
+
enumerable: true,
|
|
41
|
+
writable: false,
|
|
42
|
+
configurable: true
|
|
43
|
+
});
|
|
44
|
+
this.stack = `${NAME}: ${this.message}`;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Whether `error` is a failed JS-RPC call of a Vela entrypoint: an
|
|
49
|
+
* {@link EntrypointError}, or the plain `Error` workerd delivers for one to
|
|
50
|
+
* the caller. On a compatibility date before 2026-04-21 without
|
|
51
|
+
* `enhanced_error_serialization`, workerd drops the error's properties, so
|
|
52
|
+
* this is false.
|
|
53
|
+
*/
|
|
54
|
+
function isEntrypointError(error) {
|
|
55
|
+
if (typeof error !== "object" || error === null) return false;
|
|
56
|
+
return Reflect.get(error, "name") === NAME && typeof Reflect.get(error, "status") === "number" && typeof Reflect.get(error, "code") === "string" && typeof Reflect.get(error, "message") === "string";
|
|
57
|
+
}
|
|
58
|
+
/** @internal The redacted failure of an invocation that failed outside its pipeline. */
|
|
59
|
+
function internalEntrypointError() {
|
|
60
|
+
return new EntrypointError({
|
|
61
|
+
status: 500,
|
|
62
|
+
code: "internal",
|
|
63
|
+
message: "Internal Server Error"
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function clientDetails(value) {
|
|
67
|
+
if (value === void 0) return void 0;
|
|
68
|
+
try {
|
|
69
|
+
const text = JSON.stringify(value);
|
|
70
|
+
return text === void 0 ? void 0 : JSON.parse(text);
|
|
71
|
+
} catch {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function fromRendered(rendered) {
|
|
76
|
+
const status = Number.isInteger(rendered.status) && rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;
|
|
77
|
+
const body = rendered.body;
|
|
78
|
+
const wire = typeof body === "object" && body !== null ? Reflect.get(body, "error") : void 0;
|
|
79
|
+
const field = (name) => typeof wire === "object" && wire !== null ? Reflect.get(wire, name) : void 0;
|
|
80
|
+
const rawCode = field("code");
|
|
81
|
+
const rawMessage = field("message");
|
|
82
|
+
const code = typeof rawCode === "string" && CODE.test(rawCode) ? rawCode : status >= 500 ? "internal" : "error";
|
|
83
|
+
return new EntrypointError({
|
|
84
|
+
status,
|
|
85
|
+
code,
|
|
86
|
+
message: status >= 500 && code === "internal" ? "Internal Server Error" : typeof rawMessage === "string" ? rawMessage.slice(0, MAX_MESSAGE_LENGTH) : "Entrypoint request failed",
|
|
87
|
+
details: status < 500 ? clientDetails(field("details")) : void 0
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* An {@link EntrypointError} a host rethrows, such as another entrypoint's
|
|
92
|
+
* failure: a client fault keeps its code, message and details; a server fault
|
|
93
|
+
* keeps only its status, rendered like an `HttpException` of that status.
|
|
94
|
+
*/
|
|
95
|
+
function renderPassedOn(error) {
|
|
96
|
+
if (Number.isInteger(error.status) && error.status >= 400 && error.status < 500) return {
|
|
97
|
+
status: error.status,
|
|
98
|
+
body: { error: {
|
|
99
|
+
code: error.code,
|
|
100
|
+
message: error.message,
|
|
101
|
+
details: error.details
|
|
102
|
+
} }
|
|
103
|
+
};
|
|
104
|
+
return renderHttpError(new HttpException("Entrypoint request failed", error.status));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Render a failure of a JS-RPC call, after it was reported: the application's
|
|
108
|
+
* `ExceptionHandler.render` first, then the HTTP renderer with server bodies
|
|
109
|
+
* redacted. A 4xx {@link EntrypointError} passes through.
|
|
110
|
+
*/
|
|
111
|
+
function renderEntrypointError(error, reporter, context) {
|
|
112
|
+
if (isEntrypointError(error)) return fromRendered(renderPassedOn(error));
|
|
113
|
+
const override = reporter.render(error, context);
|
|
114
|
+
if (override instanceof Response) {
|
|
115
|
+
override.body?.cancel().catch(() => {});
|
|
116
|
+
return fromRendered(renderHttpError(new HttpException("Entrypoint request failed", override.status)));
|
|
117
|
+
}
|
|
118
|
+
return fromRendered(override ?? renderHttpError(error, {
|
|
119
|
+
catalog: reporter.catalog,
|
|
120
|
+
redactServerBodies: true
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Render a failure of a Durable Object's `fetch()` as the HTTP edge does: the
|
|
125
|
+
* application's `ExceptionHandler.render`, else the canonical JSON error body.
|
|
126
|
+
*/
|
|
127
|
+
function renderEntrypointResponse(error, reporter, context) {
|
|
128
|
+
if (isEntrypointError(error)) {
|
|
129
|
+
const rendered = fromRendered(renderPassedOn(error));
|
|
130
|
+
return Response.json({ error: {
|
|
131
|
+
code: rendered.code,
|
|
132
|
+
message: rendered.message,
|
|
133
|
+
...rendered.details === void 0 ? {} : { details: rendered.details }
|
|
134
|
+
} }, { status: rendered.status });
|
|
135
|
+
}
|
|
136
|
+
const override = reporter.render(error, context);
|
|
137
|
+
if (override instanceof Response) return override;
|
|
138
|
+
const rendered = override ?? renderHttpError(error, { catalog: reporter.catalog });
|
|
139
|
+
const status = rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;
|
|
140
|
+
return Response.json(rendered.body, { status });
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
export { EntrypointError, internalEntrypointError, isEntrypointError, renderEntrypointError, renderEntrypointResponse };
|
|
144
|
+
|
|
145
|
+
//# sourceMappingURL=entrypoint-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entrypoint-error.js","names":[],"sources":["../../src/rpc/entrypoint-error.ts"],"sourcesContent":["import { HttpException, renderHttpError, type RenderedHttpError } from '@velajs/vela';\nimport type { ErrorReporter } from '@velajs/vela/module-kit';\n\nconst NAME = 'EntrypointError';\nconst CODE = /^[A-Za-z0-9_.:-]{1,160}$/;\nconst MAX_MESSAGE_LENGTH = 2048;\n\n/** What a failed JS-RPC call of a Vela entrypoint carries across the RPC boundary. */\nexport interface EntrypointErrorInit {\n /** An HTTP error status, 400–599. */\n readonly status: number;\n /** A stable error code, such as `not_found` or `internal`. */\n readonly code: string;\n readonly message: string;\n /** Client-safe details of a client fault (4xx), such as validation issues. */\n readonly details?: unknown;\n}\n\n/**\n * The one error the JS-RPC methods of a Vela entrypoint reject with: a\n * Durable Object from `VelaDurableObject()` and a service entrypoint from\n * `VelaEntrypoint()`. The entrypoint reports the original error first, then\n * renders it as HTTP renders a response with server bodies redacted\n * (`renderHttpError`): a 4xx `HttpException` keeps its code, message and\n * details; a branded `VelaError` keeps its code and message at any status, and\n * its details below 500; a 5xx `HttpException` becomes its status's code and\n * title; an unknown error becomes `500 internal \"Internal Server Error\"`. A 4xx\n * `HttpException` constructed with an object response keeps only its status\n * (code `error`) unless that object is a canonical `{ error: { code, message,\n * details } }` body. Only these own properties cross the RPC boundary: no stack\n * frames, causes or other fields of the original.\n *\n * workerd rebuilds it on the caller's side as a plain `Error` with the same\n * `name`, `status`, `code`, `message` and `details`; read it with\n * {@link isEntrypointError}. That needs a Worker `compatibility_date` of\n * 2026-04-21 or later, or the `enhanced_error_serialization` compatibility\n * flag: before it, workerd delivers only an `Error` whose message is\n * `EntrypointError: <message>`, without the status, code or details\n * (`vela deploy check` warns about it). A host may throw one itself, for\n * example to pass on another entrypoint's failure: a 4xx one keeps its code,\n * message and details, a 5xx one only its status.\n */\nexport class EntrypointError extends Error implements EntrypointErrorInit {\n override readonly name = NAME;\n readonly status: number;\n readonly code: string;\n declare readonly details?: unknown;\n\n constructor(init: EntrypointErrorInit) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n if (init.details !== undefined) {\n Object.defineProperty(this, 'details', {\n value: init.details,\n enumerable: true,\n writable: false,\n configurable: true,\n });\n }\n // workerd serializes the stack across RPC; it would disclose the entrypoint's frames.\n this.stack = `${NAME}: ${this.message}`;\n }\n}\n\n/**\n * Whether `error` is a failed JS-RPC call of a Vela entrypoint: an\n * {@link EntrypointError}, or the plain `Error` workerd delivers for one to\n * the caller. On a compatibility date before 2026-04-21 without\n * `enhanced_error_serialization`, workerd drops the error's properties, so\n * this is false.\n */\nexport function isEntrypointError(error: unknown): error is EntrypointError {\n if (typeof error !== 'object' || error === null) return false;\n return (\n Reflect.get(error, 'name') === NAME &&\n typeof Reflect.get(error, 'status') === 'number' &&\n typeof Reflect.get(error, 'code') === 'string' &&\n typeof Reflect.get(error, 'message') === 'string'\n );\n}\n\n/** @internal The redacted failure of an invocation that failed outside its pipeline. */\nexport function internalEntrypointError(): EntrypointError {\n return new EntrypointError({ status: 500, code: 'internal', message: 'Internal Server Error' });\n}\n\n// JSON-safe client details only: an RPC failure must stay serializable.\nfunction clientDetails(value: unknown): unknown {\n if (value === undefined) return undefined;\n try {\n const text = JSON.stringify(value);\n return text === undefined ? undefined : JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction fromRendered(rendered: Pick<RenderedHttpError, 'status' | 'body'>): EntrypointError {\n const status =\n Number.isInteger(rendered.status) && rendered.status >= 400 && rendered.status <= 599\n ? rendered.status\n : 500;\n const body: unknown = rendered.body;\n const wire: unknown =\n typeof body === 'object' && body !== null ? Reflect.get(body, 'error') : undefined;\n const field = (name: string): unknown =>\n typeof wire === 'object' && wire !== null ? Reflect.get(wire, name) : undefined;\n const rawCode = field('code');\n const rawMessage = field('message');\n const code =\n typeof rawCode === 'string' && CODE.test(rawCode)\n ? rawCode\n : status >= 500\n ? 'internal'\n : 'error';\n const message =\n status >= 500 && code === 'internal'\n ? 'Internal Server Error'\n : typeof rawMessage === 'string'\n ? rawMessage.slice(0, MAX_MESSAGE_LENGTH)\n : 'Entrypoint request failed';\n const details = status < 500 ? clientDetails(field('details')) : undefined;\n return new EntrypointError({ status, code, message, details });\n}\n\n/**\n * An {@link EntrypointError} a host rethrows, such as another entrypoint's\n * failure: a client fault keeps its code, message and details; a server fault\n * keeps only its status, rendered like an `HttpException` of that status.\n */\nfunction renderPassedOn(error: EntrypointError): Pick<RenderedHttpError, 'status' | 'body'> {\n if (Number.isInteger(error.status) && error.status >= 400 && error.status < 500) {\n return {\n status: error.status,\n body: { error: { code: error.code, message: error.message, details: error.details } },\n };\n }\n return renderHttpError(new HttpException('Entrypoint request failed', error.status));\n}\n\n/**\n * Render a failure of a JS-RPC call, after it was reported: the application's\n * `ExceptionHandler.render` first, then the HTTP renderer with server bodies\n * redacted. A 4xx {@link EntrypointError} passes through.\n */\nexport function renderEntrypointError(\n error: unknown,\n reporter: ErrorReporter,\n context: unknown,\n): EntrypointError {\n if (isEntrypointError(error)) return fromRendered(renderPassedOn(error));\n const override = reporter.render(error, context);\n if (override instanceof Response) {\n void override.body?.cancel().catch(() => {});\n return fromRendered(\n renderHttpError(new HttpException('Entrypoint request failed', override.status)),\n );\n }\n return fromRendered(\n override ?? renderHttpError(error, { catalog: reporter.catalog, redactServerBodies: true }),\n );\n}\n\n/**\n * Render a failure of a Durable Object's `fetch()` as the HTTP edge does: the\n * application's `ExceptionHandler.render`, else the canonical JSON error body.\n */\nexport function renderEntrypointResponse(\n error: unknown,\n reporter: ErrorReporter,\n context: unknown,\n): Response {\n if (isEntrypointError(error)) {\n const rendered = fromRendered(renderPassedOn(error));\n return Response.json(\n {\n error: {\n code: rendered.code,\n message: rendered.message,\n ...(rendered.details === undefined ? {} : { details: rendered.details }),\n },\n },\n { status: rendered.status },\n );\n }\n const override = reporter.render(error, context);\n if (override instanceof Response) return override;\n const rendered = override ?? renderHttpError(error, { catalog: reporter.catalog });\n const status = rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;\n return Response.json(rendered.body, { status });\n}\n"],"mappings":";;AAGA,MAAM,OAAO;AACb,MAAM,OAAO;AACb,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;AAqC3B,IAAa,kBAAb,cAAqC,MAAqC;CACxE,OAAyB;CACzB;CACA;CAGA,YAAY,MAA2B;EACrC,MAAM,KAAK,OAAO;EAClB,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;EACjB,IAAI,KAAK,YAAY,KAAA,GACnB,OAAO,eAAe,MAAM,WAAW;GACrC,OAAO,KAAK;GACZ,YAAY;GACZ,UAAU;GACV,cAAc;EAChB,CAAC;EAGH,KAAK,QAAQ,GAAG,KAAK,IAAI,KAAK;CAChC;AACF;;;;;;;;AASA,SAAgB,kBAAkB,OAA0C;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OACE,QAAQ,IAAI,OAAO,MAAM,MAAM,QAC/B,OAAO,QAAQ,IAAI,OAAO,QAAQ,MAAM,YACxC,OAAO,QAAQ,IAAI,OAAO,MAAM,MAAM,YACtC,OAAO,QAAQ,IAAI,OAAO,SAAS,MAAM;AAE7C;;AAGA,SAAgB,0BAA2C;CACzD,OAAO,IAAI,gBAAgB;EAAE,QAAQ;EAAK,MAAM;EAAY,SAAS;CAAwB,CAAC;AAChG;AAGA,SAAS,cAAc,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AG,OAAO,aAAa,eAAe,KAAK,CAAC;CACvE,MAAM,WAAW,SAAS,OAAO,OAAO,OAAO;CAC/C,IAAI,oBAAoB,UAAU;EAChC,SAAc,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,OAAO,aACL,gBAAgB,IAAI,cAAc,6BAA6B,SAAS,MAAM,CAAC,CACjF;CACF;CACA,OAAO,aACL,YAAY,gBAAgB,OAAO;EAAE,SAAS,SAAS;EAAS,oBAAoB;CAAK,CAAC,CAC5F;AACF;;;;;AAMA,SAAgB,yBACd,OACA,UACA,SACU;CACV,IAAI,kBAAkB,KAAK,GAAG;EAC5B,MAAM,WAAW,aAAa,eAAe,KAAK,CAAC;EACnD,OAAO,SAAS,KACd,EACE,OAAO;GACL,MAAM,SAAS;GACf,SAAS,SAAS;GAClB,GAAI,SAAS,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,SAAS,QAAQ;EACxE,EACF,GACA,EAAE,QAAQ,SAAS,OAAO,CAC5B;CACF;CACA,MAAM,WAAW,SAAS,OAAO,OAAO,OAAO;CAC/C,IAAI,oBAAoB,UAAU,OAAO;CACzC,MAAM,WAAW,YAAY,gBAAgB,OAAO,EAAE,SAAS,SAAS,QAAQ,CAAC;CACjF,MAAM,SAAS,SAAS,UAAU,OAAO,SAAS,UAAU,MAAM,SAAS,SAAS;CACpF,OAAO,SAAS,KAAK,SAAS,MAAM,EAAE,OAAO,CAAC;AAChD"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { registerWorkerEvent } from "../worker-events.js";
|
|
2
|
+
import { TAIL_METADATA, receiveTail } from "./tail-dispatch.js";
|
|
3
|
+
import { MetadataRegistry, registerEntrypointKind } from "@velajs/vela/module-kit";
|
|
4
|
+
//#region src/tail/on-tail.ts
|
|
5
|
+
registerEntrypointKind({
|
|
6
|
+
kind: "cf:tail",
|
|
7
|
+
metaKey: TAIL_METADATA,
|
|
8
|
+
level: "method"
|
|
9
|
+
});
|
|
10
|
+
registerWorkerEvent("tail", (application, events) => receiveTail(application, events));
|
|
11
|
+
/**
|
|
12
|
+
* Handle Tail Workers events (entrypoint kind `cf:tail`): the method of an
|
|
13
|
+
* `@Injectable()` provider receives each batch of `TraceItem`s that the
|
|
14
|
+
* Workers naming this one in `tail_consumers` produce:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* @Injectable()
|
|
18
|
+
* export class ErrorTail {
|
|
19
|
+
* constructor(private readonly alerts: AlertsService) {}
|
|
20
|
+
*
|
|
21
|
+
* @OnTail()
|
|
22
|
+
* async observe(events: TraceItem[]): Promise<void> {
|
|
23
|
+
* const failed = events.filter((event) => event.outcome !== 'ok');
|
|
24
|
+
* if (failed.length > 0) await this.alerts.notify(failed);
|
|
25
|
+
* }
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Importing it gives the Worker (`app.worker`) its `tail` handler. Every
|
|
30
|
+
* `@OnTail()` handler receives every batch, each in its own execution scope
|
|
31
|
+
* through its scoped guards, interceptors and filters. A failure is reported
|
|
32
|
+
* (`edge: 'tail'`) and never thrown into the platform's tail loop. When the
|
|
33
|
+
* application fails to start, no ExceptionHandler exists to report through:
|
|
34
|
+
* the handler logs the error to the console and resolves, and the next batch
|
|
35
|
+
* retries the start.
|
|
36
|
+
*/
|
|
37
|
+
function OnTail() {
|
|
38
|
+
return (target, key) => {
|
|
39
|
+
if (typeof key !== "string") throw new TypeError("@OnTail() decorates a string-named method.");
|
|
40
|
+
MetadataRegistry.appendCustomClassMeta(target.constructor, TAIL_METADATA, { methodName: key });
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { OnTail };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=on-tail.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"on-tail.js","names":[],"sources":["../../src/tail/on-tail.ts"],"sourcesContent":["import { MetadataRegistry, registerEntrypointKind } from '@velajs/vela/module-kit';\nimport { registerWorkerEvent } from '../worker-events';\nimport { TAIL_METADATA, receiveTail, type OnTailMetadata } from './tail-dispatch';\n\n// The entrypoint kind, declared next to its decorator; importing the decorator\n// also gives every Worker of the isolate its `tail` handler.\nregisterEntrypointKind({ kind: 'cf:tail', metaKey: TAIL_METADATA, level: 'method' });\nregisterWorkerEvent('tail', (application, events) => receiveTail(application, events));\n\n/** A method decorator whose method receives a batch of Tail Workers events. */\nexport type OnTailDecorator = <Handler extends (events: TraceItem[]) => unknown>(\n target: object,\n key: string | symbol,\n descriptor: TypedPropertyDescriptor<Handler>,\n) => void;\n\n/**\n * Handle Tail Workers events (entrypoint kind `cf:tail`): the method of an\n * `@Injectable()` provider receives each batch of `TraceItem`s that the\n * Workers naming this one in `tail_consumers` produce:\n *\n * ```ts\n * @Injectable()\n * export class ErrorTail {\n * constructor(private readonly alerts: AlertsService) {}\n *\n * @OnTail()\n * async observe(events: TraceItem[]): Promise<void> {\n * const failed = events.filter((event) => event.outcome !== 'ok');\n * if (failed.length > 0) await this.alerts.notify(failed);\n * }\n * }\n * ```\n *\n * Importing it gives the Worker (`app.worker`) its `tail` handler. Every\n * `@OnTail()` handler receives every batch, each in its own execution scope\n * through its scoped guards, interceptors and filters. A failure is reported\n * (`edge: 'tail'`) and never thrown into the platform's tail loop. When the\n * application fails to start, no ExceptionHandler exists to report through:\n * the handler logs the error to the console and resolves, and the next batch\n * retries the start.\n */\nexport function OnTail(): OnTailDecorator {\n return (target, key) => {\n if (typeof key !== 'string') throw new TypeError('@OnTail() decorates a string-named method.');\n MetadataRegistry.appendCustomClassMeta<OnTailMetadata>(target.constructor, TAIL_METADATA, {\n methodName: key,\n });\n };\n}\n"],"mappings":";;;;AAMA,uBAAuB;CAAE,MAAM;CAAW,SAAS;CAAe,OAAO;AAAS,CAAC;AACnF,oBAAoB,SAAS,aAAa,WAAW,YAAY,aAAa,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCrF,SAAgB,SAA0B;CACxC,QAAQ,QAAQ,QAAQ;EACtB,IAAI,OAAO,QAAQ,UAAU,MAAM,IAAI,UAAU,4CAA4C;EAC7F,iBAAiB,sBAAsC,OAAO,aAAa,eAAe,EACxF,YAAY,IACd,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { entrypointInvoker, observedSettlement } from "../host/host-invoker.js";
|
|
2
|
+
import { resolveErrorReporter } from "@velajs/vela/module-kit";
|
|
3
|
+
//#region src/tail/tail-dispatch.ts
|
|
4
|
+
/** The metadata key `@OnTail()` records its handlers under (entrypoint kind `cf:tail`). */
|
|
5
|
+
const TAIL_METADATA = "cloudflare:tail";
|
|
6
|
+
function handlerName(meta) {
|
|
7
|
+
const methodName = typeof meta === "object" && meta !== null ? Reflect.get(meta, "methodName") : void 0;
|
|
8
|
+
if (typeof methodName !== "string") throw new Error("Invalid @OnTail() metadata.");
|
|
9
|
+
return methodName;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The Worker's `tail` handler: {@link dispatchTail} to the application built
|
|
13
|
+
* for the event's environment. An application that fails to start has no
|
|
14
|
+
* ExceptionHandler to report through, so the error is logged to the console
|
|
15
|
+
* and the handler still resolves; the next batch retries the start.
|
|
16
|
+
*/
|
|
17
|
+
async function receiveTail(application, events) {
|
|
18
|
+
let started;
|
|
19
|
+
try {
|
|
20
|
+
started = await application();
|
|
21
|
+
} catch (error) {
|
|
22
|
+
console.error("[vela] tail events were not delivered: the application failed to start:", error);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
await dispatchTail(started, events);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Deliver a batch of Tail Workers events to every `@OnTail()` handler of the
|
|
29
|
+
* application, each in its own execution scope through its scoped guards,
|
|
30
|
+
* interceptors and filters. A failure, in a handler or around it, is reported
|
|
31
|
+
* (`edge: 'tail'`) and never reaches the platform: a failing tail handler
|
|
32
|
+
* must not fail the events it observes.
|
|
33
|
+
*/
|
|
34
|
+
async function dispatchTail(application, events) {
|
|
35
|
+
const container = application.getContainer();
|
|
36
|
+
const handlers = application.entrypoints.ofKind("cf:tail");
|
|
37
|
+
await Promise.all(handlers.map(async (entry) => {
|
|
38
|
+
let source = "an @OnTail() handler";
|
|
39
|
+
try {
|
|
40
|
+
const method = handlerName(entry.meta);
|
|
41
|
+
const invoker = entrypointInvoker(container, entry, "tail");
|
|
42
|
+
source = invoker.report("cf:tail", method).source ?? source;
|
|
43
|
+
if (!Array.isArray(events)) throw new TypeError("The tail handler received no events.");
|
|
44
|
+
await invoker.invoke({
|
|
45
|
+
kind: "cf:tail",
|
|
46
|
+
method,
|
|
47
|
+
args: [events],
|
|
48
|
+
payload: events,
|
|
49
|
+
settlement: observedSettlement
|
|
50
|
+
});
|
|
51
|
+
} catch (error) {
|
|
52
|
+
try {
|
|
53
|
+
resolveErrorReporter(container).report(error, {
|
|
54
|
+
edge: "tail",
|
|
55
|
+
source,
|
|
56
|
+
kind: "cf:tail"
|
|
57
|
+
});
|
|
58
|
+
} catch {
|
|
59
|
+
console.error(`[vela] tail error in ${source}:`, error);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { TAIL_METADATA, dispatchTail, receiveTail };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=tail-dispatch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tail-dispatch.js","names":[],"sources":["../../src/tail/tail-dispatch.ts"],"sourcesContent":["import { resolveErrorReporter, type EntrypointExecutionContext } from '@velajs/vela/module-kit';\nimport type { CloudflareApplication } from '../cloudflare-application';\nimport { entrypointInvoker, observedSettlement } from '../host/host-invoker';\n\n/** The metadata key `@OnTail()` records its handlers under (entrypoint kind `cf:tail`). */\nexport const TAIL_METADATA = 'cloudflare:tail';\n\n/** One `@OnTail()` handler. */\nexport interface OnTailMetadata {\n readonly methodName: string;\n}\n\n/** The ExecutionContext guards, interceptors and filters receive around an `@OnTail()` handler. */\nexport type TailExecutionContext = EntrypointExecutionContext<'cf:tail'>;\n\nfunction handlerName(meta: unknown): string {\n const methodName: unknown =\n typeof meta === 'object' && meta !== null ? Reflect.get(meta, 'methodName') : undefined;\n if (typeof methodName !== 'string') throw new Error('Invalid @OnTail() metadata.');\n return methodName;\n}\n\n/**\n * The Worker's `tail` handler: {@link dispatchTail} to the application built\n * for the event's environment. An application that fails to start has no\n * ExceptionHandler to report through, so the error is logged to the console\n * and the handler still resolves; the next batch retries the start.\n */\nexport async function receiveTail(\n application: () => Promise<CloudflareApplication>,\n events: unknown,\n): Promise<void> {\n let started: CloudflareApplication;\n try {\n started = await application();\n } catch (error) {\n console.error('[vela] tail events were not delivered: the application failed to start:', error);\n return;\n }\n await dispatchTail(started, events);\n}\n\n/**\n * Deliver a batch of Tail Workers events to every `@OnTail()` handler of the\n * application, each in its own execution scope through its scoped guards,\n * interceptors and filters. A failure, in a handler or around it, is reported\n * (`edge: 'tail'`) and never reaches the platform: a failing tail handler\n * must not fail the events it observes.\n */\nexport async function dispatchTail(\n application: CloudflareApplication,\n events: unknown,\n): Promise<void> {\n const container = application.getContainer();\n const handlers = application.entrypoints.ofKind('cf:tail');\n await Promise.all(\n handlers.map(async (entry) => {\n let source = 'an @OnTail() handler';\n try {\n const method = handlerName(entry.meta);\n const invoker = entrypointInvoker(container, entry, 'tail');\n source = invoker.report('cf:tail', method).source ?? source;\n if (!Array.isArray(events)) throw new TypeError('The tail handler received no events.');\n await invoker.invoke({\n kind: 'cf:tail',\n method,\n args: [events],\n payload: events,\n settlement: observedSettlement,\n });\n } catch (error) {\n try {\n resolveErrorReporter(container).report(error, { edge: 'tail', source, kind: 'cf:tail' });\n } catch {\n console.error(`[vela] tail error in ${source}:`, error);\n }\n }\n }),\n );\n}\n"],"mappings":";;;;AAKA,MAAa,gBAAgB;AAU7B,SAAS,YAAY,MAAuB;CAC1C,MAAM,aACJ,OAAO,SAAS,YAAY,SAAS,OAAO,QAAQ,IAAI,MAAM,YAAY,IAAI,KAAA;CAChF,IAAI,OAAO,eAAe,UAAU,MAAM,IAAI,MAAM,6BAA6B;CACjF,OAAO;AACT;;;;;;;AAQA,eAAsB,YACpB,aACA,QACe;CACf,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,YAAY;CAC9B,SAAS,OAAO;EACd,QAAQ,MAAM,2EAA2E,KAAK;EAC9F;CACF;CACA,MAAM,aAAa,SAAS,MAAM;AACpC;;;;;;;;AASA,eAAsB,aACpB,aACA,QACe;CACf,MAAM,YAAY,YAAY,aAAa;CAC3C,MAAM,WAAW,YAAY,YAAY,OAAO,SAAS;CACzD,MAAM,QAAQ,IACZ,SAAS,IAAI,OAAO,UAAU;EAC5B,IAAI,SAAS;EACb,IAAI;GACF,MAAM,SAAS,YAAY,MAAM,IAAI;GACrC,MAAM,UAAU,kBAAkB,WAAW,OAAO,MAAM;GAC1D,SAAS,QAAQ,OAAO,WAAW,MAAM,CAAC,CAAC,UAAU;GACrD,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,UAAU,sCAAsC;GACtF,MAAM,QAAQ,OAAO;IACnB,MAAM;IACN;IACA,MAAM,CAAC,MAAM;IACb,SAAS;IACT,YAAY;GACd,CAAC;EACH,SAAS,OAAO;GACd,IAAI;IACF,qBAAqB,SAAS,CAAC,CAAC,OAAO,OAAO;KAAE,MAAM;KAAQ;KAAQ,MAAM;IAAU,CAAC;GACzF,QAAQ;IACN,QAAQ,MAAM,wBAAwB,OAAO,IAAI,KAAK;GACxD;EACF;CACF,CAAC,CACH;AACF"}
|
package/dist/tail.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import "./vela-env-DFvyoNT3.js";
|
|
2
|
+
import "./cloudflare-application-CXDy9C1R.js";
|
|
3
|
+
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
|
4
|
+
//#region src/tail/on-tail.d.ts
|
|
5
|
+
/** A method decorator whose method receives a batch of Tail Workers events. */
|
|
6
|
+
type OnTailDecorator = <Handler extends (events: TraceItem[]) => unknown>(target: object, key: string | symbol, descriptor: TypedPropertyDescriptor<Handler>) => void;
|
|
7
|
+
/**
|
|
8
|
+
* Handle Tail Workers events (entrypoint kind `cf:tail`): the method of an
|
|
9
|
+
* `@Injectable()` provider receives each batch of `TraceItem`s that the
|
|
10
|
+
* Workers naming this one in `tail_consumers` produce:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* @Injectable()
|
|
14
|
+
* export class ErrorTail {
|
|
15
|
+
* constructor(private readonly alerts: AlertsService) {}
|
|
16
|
+
*
|
|
17
|
+
* @OnTail()
|
|
18
|
+
* async observe(events: TraceItem[]): Promise<void> {
|
|
19
|
+
* const failed = events.filter((event) => event.outcome !== 'ok');
|
|
20
|
+
* if (failed.length > 0) await this.alerts.notify(failed);
|
|
21
|
+
* }
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* Importing it gives the Worker (`app.worker`) its `tail` handler. Every
|
|
26
|
+
* `@OnTail()` handler receives every batch, each in its own execution scope
|
|
27
|
+
* through its scoped guards, interceptors and filters. A failure is reported
|
|
28
|
+
* (`edge: 'tail'`) and never thrown into the platform's tail loop. When the
|
|
29
|
+
* application fails to start, no ExceptionHandler exists to report through:
|
|
30
|
+
* the handler logs the error to the console and resolves, and the next batch
|
|
31
|
+
* retries the start.
|
|
32
|
+
*/
|
|
33
|
+
export declare function OnTail(): OnTailDecorator;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/tail/tail-dispatch.d.ts
|
|
36
|
+
/** The ExecutionContext guards, interceptors and filters receive around an `@OnTail()` handler. */
|
|
37
|
+
type TailExecutionContext = EntrypointExecutionContext<'cf:tail'>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export type { OnTailDecorator, TailExecutionContext };
|
package/dist/tail.js
ADDED
package/dist/testing.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import {
|
|
3
|
-
import { a as CloudflareWorkerOptions } from "./cloudflare-factory-eGiet0mg.js";
|
|
2
|
+
import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-CuFNUJJD.js";
|
|
4
3
|
import { VelaEnv } from "@velajs/vela";
|
|
5
4
|
import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
|
|
6
5
|
import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
|
|
@@ -45,7 +44,7 @@ export interface TestingQueueResult {
|
|
|
45
44
|
readonly delaySeconds?: number;
|
|
46
45
|
}[];
|
|
47
46
|
}
|
|
48
|
-
/** The Worker's `fetch`, `queue` and `
|
|
47
|
+
/** The Worker's `fetch`, `queue`, `scheduled`, `email` and `tail` handlers for one test application. */
|
|
49
48
|
export interface TestingWorker {
|
|
50
49
|
/** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */
|
|
51
50
|
readonly module: TestingModule;
|
|
@@ -61,9 +60,62 @@ export interface TestingWorker {
|
|
|
61
60
|
scheduled(cron: string, options?: {
|
|
62
61
|
scheduledTime?: Date | number;
|
|
63
62
|
}): Promise<void>;
|
|
63
|
+
/**
|
|
64
|
+
* Deliver an Email Workers message (such as one from {@link emailMessage})
|
|
65
|
+
* to the application's `@OnEmail()` handlers, as the Worker's `email`
|
|
66
|
+
* handler does: a message no handler accepts is rejected.
|
|
67
|
+
*/
|
|
68
|
+
email(message: ForwardableEmailMessage): Promise<void>;
|
|
69
|
+
/** Deliver Tail Workers events (such as {@link traceItem}s) to its `@OnTail()` handlers. */
|
|
70
|
+
tail(events: TraceItem[]): Promise<void>;
|
|
64
71
|
/** Wait for background work (`waitUntil`) of every event, then close the application. */
|
|
65
72
|
close(): Promise<void>;
|
|
66
73
|
}
|
|
74
|
+
/** An Email Workers message built by {@link emailMessage}, recording what handlers did with it. */
|
|
75
|
+
export interface TestingEmailMessage extends ForwardableEmailMessage {
|
|
76
|
+
/** The reason passed to `setReject()`, when a handler rejected the message. */
|
|
77
|
+
readonly rejectReason: string | undefined;
|
|
78
|
+
/** The `forward()` calls, in order. */
|
|
79
|
+
readonly forwards: readonly {
|
|
80
|
+
readonly rcptTo: string;
|
|
81
|
+
readonly headers?: Headers;
|
|
82
|
+
}[];
|
|
83
|
+
/** The `reply()` calls, in order. */
|
|
84
|
+
readonly replies: readonly (EmailMessage | EmailReplyMessageBuilder)[];
|
|
85
|
+
}
|
|
86
|
+
/** What {@link emailMessage} builds a message from. */
|
|
87
|
+
export interface TestingEmailInit {
|
|
88
|
+
/** The envelope sender (`MAIL FROM`). */
|
|
89
|
+
readonly from: string;
|
|
90
|
+
/** The envelope recipient (`RCPT TO`), which `@OnEmail({ to })` routes on. */
|
|
91
|
+
readonly to: string;
|
|
92
|
+
readonly subject?: string;
|
|
93
|
+
/** The plain-text body of the default raw message. */
|
|
94
|
+
readonly text?: string;
|
|
95
|
+
/** Further headers; `From`, `To` and `Subject` default from the fields above. */
|
|
96
|
+
readonly headers?: HeadersInit;
|
|
97
|
+
/** The raw RFC 5322 message; built from the headers and `text` by default. */
|
|
98
|
+
readonly raw?: string | Uint8Array;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* An Email Workers message (`ForwardableEmailMessage`) for tests, in the
|
|
102
|
+
* spirit of `cloudflare:test`'s `createMessageBatch()`: `raw`, `rawSize` and
|
|
103
|
+
* `headers` describe the message, and `setReject()`, `forward()` and `reply()`
|
|
104
|
+
* record what the handlers did (`rejectReason`, `forwards`, `replies`) instead
|
|
105
|
+
* of sending anything.
|
|
106
|
+
*
|
|
107
|
+
* ```ts
|
|
108
|
+
* const message = emailMessage({ from: 'ada@example.net', to: 'support@example.com', subject: 'Help' });
|
|
109
|
+
* await worker.email(message);
|
|
110
|
+
* expect(message.forwards).toEqual([{ rcptTo: 'team@example.com' }]);
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
export declare function emailMessage(init: TestingEmailInit): TestingEmailMessage;
|
|
114
|
+
/**
|
|
115
|
+
* A Tail Workers event (`TraceItem`) for tests: an `ok` fetch-less invocation
|
|
116
|
+
* of the Worker `producer`, with `overrides` applied.
|
|
117
|
+
*/
|
|
118
|
+
export declare function traceItem(overrides?: Partial<TraceItem>): TraceItem;
|
|
67
119
|
/**
|
|
68
120
|
* Build `rootModule` as `createCloudflareWorker(rootModule, options)` does
|
|
69
121
|
* (its adapters, then its `configure` hook), through `@velajs/testing`, and
|
package/dist/testing.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { CloudflareApplication } from "./cloudflare-application.js";
|
|
2
2
|
import { cloudflareCreateOptions, configureCloudflareApplication } from "./cloudflare-factory.js";
|
|
3
|
+
import { dispatchEmail } from "./email/email-dispatch.js";
|
|
4
|
+
import { dispatchTail } from "./tail/tail-dispatch.js";
|
|
3
5
|
import { parseCronMetadata } from "@velajs/vela/module-kit";
|
|
4
6
|
import { env } from "cloudflare:workers";
|
|
5
7
|
import * as cloudflareTest from "cloudflare:test";
|
|
@@ -7,6 +9,79 @@ import { Test } from "@velajs/testing";
|
|
|
7
9
|
//#region src/testing.ts
|
|
8
10
|
const pool = cloudflareTest;
|
|
9
11
|
/**
|
|
12
|
+
* An Email Workers message (`ForwardableEmailMessage`) for tests, in the
|
|
13
|
+
* spirit of `cloudflare:test`'s `createMessageBatch()`: `raw`, `rawSize` and
|
|
14
|
+
* `headers` describe the message, and `setReject()`, `forward()` and `reply()`
|
|
15
|
+
* record what the handlers did (`rejectReason`, `forwards`, `replies`) instead
|
|
16
|
+
* of sending anything.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* const message = emailMessage({ from: 'ada@example.net', to: 'support@example.com', subject: 'Help' });
|
|
20
|
+
* await worker.email(message);
|
|
21
|
+
* expect(message.forwards).toEqual([{ rcptTo: 'team@example.com' }]);
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
function emailMessage(init) {
|
|
25
|
+
const headers = new Headers(init.headers);
|
|
26
|
+
if (!headers.has("from")) headers.set("from", init.from);
|
|
27
|
+
if (!headers.has("to")) headers.set("to", init.to);
|
|
28
|
+
if (init.subject !== void 0 && !headers.has("subject")) headers.set("subject", init.subject);
|
|
29
|
+
const raw = init.raw ?? `${[...headers].map(([name, value]) => `${name}: ${value}`).join("\r\n")}\r\n\r\n${init.text ?? ""}`;
|
|
30
|
+
const bytes = typeof raw === "string" ? new TextEncoder().encode(raw) : raw;
|
|
31
|
+
let rejectReason;
|
|
32
|
+
const forwards = [];
|
|
33
|
+
const replies = [];
|
|
34
|
+
return {
|
|
35
|
+
from: init.from,
|
|
36
|
+
to: init.to,
|
|
37
|
+
headers,
|
|
38
|
+
rawSize: bytes.byteLength,
|
|
39
|
+
raw: new ReadableStream({ start(controller) {
|
|
40
|
+
controller.enqueue(bytes.slice());
|
|
41
|
+
controller.close();
|
|
42
|
+
} }),
|
|
43
|
+
get rejectReason() {
|
|
44
|
+
return rejectReason;
|
|
45
|
+
},
|
|
46
|
+
forwards,
|
|
47
|
+
replies,
|
|
48
|
+
setReject(reason) {
|
|
49
|
+
rejectReason = reason;
|
|
50
|
+
},
|
|
51
|
+
async forward(rcptTo, forwardHeaders) {
|
|
52
|
+
forwards.push(forwardHeaders === void 0 ? { rcptTo } : {
|
|
53
|
+
rcptTo,
|
|
54
|
+
headers: forwardHeaders
|
|
55
|
+
});
|
|
56
|
+
return { messageId: `forward-${forwards.length}@vela.test` };
|
|
57
|
+
},
|
|
58
|
+
async reply(message) {
|
|
59
|
+
replies.push(message);
|
|
60
|
+
return { messageId: `reply-${replies.length}@vela.test` };
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* A Tail Workers event (`TraceItem`) for tests: an `ok` fetch-less invocation
|
|
66
|
+
* of the Worker `producer`, with `overrides` applied.
|
|
67
|
+
*/
|
|
68
|
+
function traceItem(overrides = {}) {
|
|
69
|
+
return {
|
|
70
|
+
event: null,
|
|
71
|
+
eventTimestamp: Date.now(),
|
|
72
|
+
logs: [],
|
|
73
|
+
exceptions: [],
|
|
74
|
+
diagnosticsChannelEvents: [],
|
|
75
|
+
scriptName: "producer",
|
|
76
|
+
outcome: "ok",
|
|
77
|
+
executionModel: "stateless",
|
|
78
|
+
truncated: false,
|
|
79
|
+
cpuTime: 0,
|
|
80
|
+
wallTime: 0,
|
|
81
|
+
...overrides
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
10
85
|
* Build `rootModule` as `createCloudflareWorker(rootModule, options)` does
|
|
11
86
|
* (its adapters, then its `configure` hook), through `@velajs/testing`, and
|
|
12
87
|
* drive its Worker handlers inside the Workers Vitest pool.
|
|
@@ -83,6 +158,8 @@ async function createTestingWorker(rootModule, options = {}) {
|
|
|
83
158
|
}), env$1, ctx);
|
|
84
159
|
await pool.waitOnExecutionContext(ctx);
|
|
85
160
|
},
|
|
161
|
+
email: (message) => dispatchEmail(app, message),
|
|
162
|
+
tail: (events) => dispatchTail(app, events),
|
|
86
163
|
async close() {
|
|
87
164
|
await Promise.all([...responses].map((response) => response.bodyUsed ? void 0 : response.body?.cancel().catch(() => {})));
|
|
88
165
|
responses.clear();
|
|
@@ -106,6 +183,6 @@ function queueJob(queue, job, data, { id = crypto.randomUUID(), attempts = 1 } =
|
|
|
106
183
|
};
|
|
107
184
|
}
|
|
108
185
|
//#endregion
|
|
109
|
-
export { createTestingWorker, queueJob };
|
|
186
|
+
export { createTestingWorker, emailMessage, queueJob, traceItem };
|
|
110
187
|
|
|
111
188
|
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":["workersEnv","env"],"sources":["../src/testing.ts"],"sourcesContent":["import './vela-env';\n// @ts-expect-error `cloudflare:test` is the virtual module of the Workers Vitest pool\n// (@cloudflare/vitest-plugin); it is typed below instead of by this package's build.\nimport * as cloudflareTest from 'cloudflare:test';\nimport { env as workersEnv } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport { parseCronMetadata } from '@velajs/vela/module-kit';\nimport type { QueueJob, QueueJobDefinition, QueueJobInput } from '@velajs/vela/queue';\nimport { Test, type TestingModule, type TestingModuleBuilder } from '@velajs/testing';\nimport { CloudflareApplication } from './cloudflare-application';\nimport {\n cloudflareCreateOptions,\n configureCloudflareApplication,\n type CloudflareWorkerOptions,\n} from './cloudflare-factory';\nimport type { CloudflareRoot } from './root-module';\n\n/** The `cloudflare:test` helpers this module drives (see @cloudflare/vitest-plugin). */\ninterface WorkersTestPool {\n createExecutionContext(): ExecutionContext;\n waitOnExecutionContext(ctx: ExecutionContext): Promise<void>;\n createScheduledController(options?: {\n scheduledTime?: Date | number;\n cron?: string;\n }): ScheduledController;\n createMessageBatch<Body>(\n queueName: string,\n messages: { id: string; timestamp: Date | number; attempts: number; body: Body }[],\n ): MessageBatch<Body>;\n getQueueResult(\n batch: MessageBatch,\n ctx: ExecutionContext,\n ): Promise<Omit<TestingQueueResult, 'error'>>;\n}\n\nconst pool: WorkersTestPool = cloudflareTest;\n\nexport interface TestingWorkerOptions extends CloudflareWorkerOptions {\n /**\n * The Workers environment the application is built for and every event\n * carries. Defaults to the test Worker's `env` from `cloudflare:workers`,\n * with the bindings the Vitest pool's Wrangler configuration declares.\n */\n env?: VelaEnv;\n /**\n * Adjust the testing module before it compiles: `overrideProvider`,\n * `overrideModule().useModule()`, enhancer overrides and `useMocker`.\n */\n overrides?: (module: TestingModuleBuilder) => TestingModuleBuilder;\n}\n\n/** One message of a {@link TestingWorker.queue} batch. */\nexport interface TestingQueueMessage<Body = unknown> {\n readonly body: Body;\n /** Defaults to a random UUID. */\n readonly id?: string;\n /** The delivery attempt, 1-based; defaults to 1. */\n readonly attempts?: number;\n readonly timestamp?: Date | number;\n}\n\n/** What the queue handler did with a batch: `cloudflare:test`'s `getQueueResult()`, plus its outcome. */\nexport interface TestingQueueResult {\n /** `'exception'` when the handler rejected: Cloudflare then retries every message it did not acknowledge. */\n readonly outcome: 'ok' | 'exception';\n /** The handler's rejection, when `outcome` is `'exception'`. */\n readonly error?: unknown;\n readonly ackAll: boolean;\n readonly retryBatch: { readonly retry: boolean; readonly delaySeconds?: number };\n /** Ids of the messages acknowledged one by one. */\n readonly explicitAcks: readonly string[];\n readonly retryMessages: readonly { readonly msgId: string; readonly delaySeconds?: number }[];\n}\n\n/** The Worker's `fetch`, `queue` and `scheduled` handlers for one test application. */\nexport interface TestingWorker {\n /** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */\n readonly module: TestingModule;\n readonly env: VelaEnv;\n /** Send a request through the Worker's `fetch` handler; a path resolves against `http://localhost`. */\n fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;\n /** Deliver one batch of the physical `queue` to the Worker's `queue` handler. */\n queue(queue: string, messages: readonly TestingQueueMessage[]): Promise<TestingQueueResult>;\n /**\n * Fire the cron trigger `cron` and wait for its `@Cron` jobs. Rejects when\n * no job declares `cron`: Cloudflare delivers the literal trigger expression.\n */\n scheduled(cron: string, options?: { scheduledTime?: Date | number }): Promise<void>;\n /** Wait for background work (`waitUntil`) of every event, then close the application. */\n close(): Promise<void>;\n}\n\n/**\n * Build `rootModule` as `createCloudflareWorker(rootModule, options)` does\n * (its adapters, then its `configure` hook), through `@velajs/testing`, and\n * drive its Worker handlers inside the Workers Vitest pool.\n *\n * ```ts\n * const worker = await createTestingWorker(AppModule, {\n * overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),\n * });\n * const response = await worker.fetch('/todos');\n * const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);\n * await worker.scheduled('0 3 * * *');\n * await worker.close();\n * ```\n */\nexport async function createTestingWorker(\n rootModule: CloudflareRoot,\n options: TestingWorkerOptions = {},\n): Promise<TestingWorker> {\n const { env = workersEnv, overrides, configure, ...appOptions } = options;\n const builder = Test.createTestingModule(\n { imports: [rootModule] },\n cloudflareCreateOptions({ ...appOptions, env }),\n );\n const module = await (overrides ? overrides(builder) : builder).compile();\n let app: CloudflareApplication;\n try {\n app = await configureCloudflareApplication(\n new CloudflareApplication(await module.createApplication(), env),\n env,\n configure,\n );\n } catch (error) {\n await module.close();\n throw error;\n }\n const contexts = new Set<ExecutionContext>();\n const context = (): ExecutionContext => {\n const ctx = pool.createExecutionContext();\n contexts.add(ctx);\n return ctx;\n };\n // A request completes once its response body is consumed: close() cancels\n // the bodies a test never read, so waiting for its background work ends.\n const responses = new Set<Response>();\n return {\n module,\n env,\n async fetch(input, init) {\n const request =\n typeof input === 'string' && input.startsWith('/')\n ? new Request(new URL(input, 'http://localhost'), init)\n : new Request(input, init);\n const response = await app.fetch(request, env, context());\n responses.add(response);\n return response;\n },\n async queue(queue, messages) {\n const batch = pool.createMessageBatch(\n queue,\n messages.map((message) => ({\n id: message.id ?? crypto.randomUUID(),\n timestamp: message.timestamp ?? Date.now(),\n attempts: message.attempts ?? 1,\n body: message.body,\n })),\n );\n const ctx = context();\n try {\n await app.queue(batch, env, ctx);\n } catch (error) {\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'exception', error };\n }\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'ok' };\n },\n async scheduled(cron, { scheduledTime } = {}) {\n const declared = app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .map((entry) => entry.meta.expression);\n if (!declared.includes(cron)) {\n throw new Error(\n `No @Cron job declares ${JSON.stringify(cron)}. Declared: ` +\n `${declared.map((expression) => JSON.stringify(expression)).join(', ') || '(none)'}.`,\n );\n }\n const ctx = context();\n await app.scheduled(pool.createScheduledController({ cron, scheduledTime }), env, ctx);\n await pool.waitOnExecutionContext(ctx);\n },\n async close() {\n await Promise.all(\n [...responses].map((response) =>\n response.bodyUsed ? undefined : response.body?.cancel().catch(() => {}),\n ),\n );\n responses.clear();\n await Promise.all([...contexts].map((ctx) => pool.waitOnExecutionContext(ctx)));\n contexts.clear();\n await module.close();\n },\n };\n}\n\n/**\n * A queue message carrying a Vela job envelope, as `QueueClient.add()` sends\n * it: `queue` is the logical queue a `@Processor` handles, and `job` a job\n * definition (whose wire input `data` must match) or a job name.\n */\nexport function queueJob<const D extends QueueJobDefinition>(\n queue: string,\n job: D,\n data: QueueJobInput<D>,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string,\n data: unknown,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string | QueueJobDefinition,\n data: unknown,\n { id = crypto.randomUUID(), attempts = 1 }: { id?: string; attempts?: number } = {},\n): TestingQueueMessage<QueueJob> {\n const name = typeof job === 'string' ? job : job.name;\n return { id, attempts, body: { id, queue, name, data, attempt: attempts } };\n}\n"],"mappings":";;;;;;;AAmCA,MAAM,OAAwB;;;;;;;;;;;;;;;;AAwE9B,eAAsB,oBACpB,YACA,UAAgC,CAAC,GACT;CACxB,MAAM,EAAE,KAAA,QAAMA,KAAY,WAAW,WAAW,GAAG,eAAe;CAClE,MAAM,UAAU,KAAK,oBACnB,EAAE,SAAS,CAAC,UAAU,EAAE,GACxB,wBAAwB;EAAE,GAAG;EAAY,KAAA;CAAI,CAAC,CAChD;CACA,MAAM,SAAS,OAAO,YAAY,UAAU,OAAO,IAAI,QAAA,CAAS,QAAQ;CACxE,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,+BACV,IAAI,sBAAsB,MAAM,OAAO,kBAAkB,GAAGC,KAAG,GAC/DA,OACA,SACF;CACF,SAAS,OAAO;EACd,MAAM,OAAO,MAAM;EACnB,MAAM;CACR;CACA,MAAM,2BAAW,IAAI,IAAsB;CAC3C,MAAM,gBAAkC;EACtC,MAAM,MAAM,KAAK,uBAAuB;EACxC,SAAS,IAAI,GAAG;EAChB,OAAO;CACT;CAGA,MAAM,4BAAY,IAAI,IAAc;CACpC,OAAO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AuB,GAAG;EACvC;EACA,MAAM,QAAQ;GACZ,MAAM,QAAQ,IACZ,CAAC,GAAG,SAAS,CAAC,CAAC,KAAK,aAClB,SAAS,WAAW,KAAA,IAAY,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC,CACxE,CACF;GACA,UAAU,MAAM;GAChB,MAAM,QAAQ,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAK,QAAQ,KAAK,uBAAuB,GAAG,CAAC,CAAC;GAC9E,SAAS,MAAM;GACf,MAAM,OAAO,MAAM;EACrB;CACF;AACF;AAmBA,SAAgB,SACd,OACA,KACA,MACA,EAAE,KAAK,OAAO,WAAW,GAAG,WAAW,MAA0C,CAAC,GACnD;CAE/B,OAAO;EAAE;EAAI;EAAU,MAAM;GAAE;GAAI;GAAO,MAD7B,OAAO,QAAQ,WAAW,MAAM,IAAI;GACD;GAAM,SAAS;EAAS;CAAE;AAC5E"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":["workersEnv","env"],"sources":["../src/testing.ts"],"sourcesContent":["import './vela-env';\n// @ts-expect-error `cloudflare:test` is the virtual module of the Workers Vitest pool\n// (@cloudflare/vitest-plugin); it is typed below instead of by this package's build.\nimport * as cloudflareTest from 'cloudflare:test';\nimport { env as workersEnv } from 'cloudflare:workers';\nimport type { VelaEnv } from '@velajs/vela';\nimport { parseCronMetadata } from '@velajs/vela/module-kit';\nimport type { QueueJob, QueueJobDefinition, QueueJobInput } from '@velajs/vela/queue';\nimport { Test, type TestingModule, type TestingModuleBuilder } from '@velajs/testing';\nimport { CloudflareApplication } from './cloudflare-application';\nimport {\n cloudflareCreateOptions,\n configureCloudflareApplication,\n type CloudflareWorkerOptions,\n} from './cloudflare-factory';\nimport { dispatchEmail } from './email/email-dispatch';\nimport type { CloudflareRoot } from './root-module';\nimport { dispatchTail } from './tail/tail-dispatch';\n\n/** The `cloudflare:test` helpers this module drives (see @cloudflare/vitest-plugin). */\ninterface WorkersTestPool {\n createExecutionContext(): ExecutionContext;\n waitOnExecutionContext(ctx: ExecutionContext): Promise<void>;\n createScheduledController(options?: {\n scheduledTime?: Date | number;\n cron?: string;\n }): ScheduledController;\n createMessageBatch<Body>(\n queueName: string,\n messages: { id: string; timestamp: Date | number; attempts: number; body: Body }[],\n ): MessageBatch<Body>;\n getQueueResult(\n batch: MessageBatch,\n ctx: ExecutionContext,\n ): Promise<Omit<TestingQueueResult, 'error'>>;\n}\n\nconst pool: WorkersTestPool = cloudflareTest;\n\nexport interface TestingWorkerOptions extends CloudflareWorkerOptions {\n /**\n * The Workers environment the application is built for and every event\n * carries. Defaults to the test Worker's `env` from `cloudflare:workers`,\n * with the bindings the Vitest pool's Wrangler configuration declares.\n */\n env?: VelaEnv;\n /**\n * Adjust the testing module before it compiles: `overrideProvider`,\n * `overrideModule().useModule()`, enhancer overrides and `useMocker`.\n */\n overrides?: (module: TestingModuleBuilder) => TestingModuleBuilder;\n}\n\n/** One message of a {@link TestingWorker.queue} batch. */\nexport interface TestingQueueMessage<Body = unknown> {\n readonly body: Body;\n /** Defaults to a random UUID. */\n readonly id?: string;\n /** The delivery attempt, 1-based; defaults to 1. */\n readonly attempts?: number;\n readonly timestamp?: Date | number;\n}\n\n/** What the queue handler did with a batch: `cloudflare:test`'s `getQueueResult()`, plus its outcome. */\nexport interface TestingQueueResult {\n /** `'exception'` when the handler rejected: Cloudflare then retries every message it did not acknowledge. */\n readonly outcome: 'ok' | 'exception';\n /** The handler's rejection, when `outcome` is `'exception'`. */\n readonly error?: unknown;\n readonly ackAll: boolean;\n readonly retryBatch: { readonly retry: boolean; readonly delaySeconds?: number };\n /** Ids of the messages acknowledged one by one. */\n readonly explicitAcks: readonly string[];\n readonly retryMessages: readonly { readonly msgId: string; readonly delaySeconds?: number }[];\n}\n\n/** The Worker's `fetch`, `queue`, `scheduled`, `email` and `tail` handlers for one test application. */\nexport interface TestingWorker {\n /** The compiled testing module: `get()`, `resolveInRequest()`, the fluent `http` client. */\n readonly module: TestingModule;\n readonly env: VelaEnv;\n /** Send a request through the Worker's `fetch` handler; a path resolves against `http://localhost`. */\n fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;\n /** Deliver one batch of the physical `queue` to the Worker's `queue` handler. */\n queue(queue: string, messages: readonly TestingQueueMessage[]): Promise<TestingQueueResult>;\n /**\n * Fire the cron trigger `cron` and wait for its `@Cron` jobs. Rejects when\n * no job declares `cron`: Cloudflare delivers the literal trigger expression.\n */\n scheduled(cron: string, options?: { scheduledTime?: Date | number }): Promise<void>;\n /**\n * Deliver an Email Workers message (such as one from {@link emailMessage})\n * to the application's `@OnEmail()` handlers, as the Worker's `email`\n * handler does: a message no handler accepts is rejected.\n */\n email(message: ForwardableEmailMessage): Promise<void>;\n /** Deliver Tail Workers events (such as {@link traceItem}s) to its `@OnTail()` handlers. */\n tail(events: TraceItem[]): Promise<void>;\n /** Wait for background work (`waitUntil`) of every event, then close the application. */\n close(): Promise<void>;\n}\n\n/** An Email Workers message built by {@link emailMessage}, recording what handlers did with it. */\nexport interface TestingEmailMessage extends ForwardableEmailMessage {\n /** The reason passed to `setReject()`, when a handler rejected the message. */\n readonly rejectReason: string | undefined;\n /** The `forward()` calls, in order. */\n readonly forwards: readonly { readonly rcptTo: string; readonly headers?: Headers }[];\n /** The `reply()` calls, in order. */\n readonly replies: readonly (EmailMessage | EmailReplyMessageBuilder)[];\n}\n\n/** What {@link emailMessage} builds a message from. */\nexport interface TestingEmailInit {\n /** The envelope sender (`MAIL FROM`). */\n readonly from: string;\n /** The envelope recipient (`RCPT TO`), which `@OnEmail({ to })` routes on. */\n readonly to: string;\n readonly subject?: string;\n /** The plain-text body of the default raw message. */\n readonly text?: string;\n /** Further headers; `From`, `To` and `Subject` default from the fields above. */\n readonly headers?: HeadersInit;\n /** The raw RFC 5322 message; built from the headers and `text` by default. */\n readonly raw?: string | Uint8Array;\n}\n\n/**\n * An Email Workers message (`ForwardableEmailMessage`) for tests, in the\n * spirit of `cloudflare:test`'s `createMessageBatch()`: `raw`, `rawSize` and\n * `headers` describe the message, and `setReject()`, `forward()` and `reply()`\n * record what the handlers did (`rejectReason`, `forwards`, `replies`) instead\n * of sending anything.\n *\n * ```ts\n * const message = emailMessage({ from: 'ada@example.net', to: 'support@example.com', subject: 'Help' });\n * await worker.email(message);\n * expect(message.forwards).toEqual([{ rcptTo: 'team@example.com' }]);\n * ```\n */\nexport function emailMessage(init: TestingEmailInit): TestingEmailMessage {\n const headers = new Headers(init.headers);\n if (!headers.has('from')) headers.set('from', init.from);\n if (!headers.has('to')) headers.set('to', init.to);\n if (init.subject !== undefined && !headers.has('subject')) headers.set('subject', init.subject);\n const raw =\n init.raw ??\n `${[...headers].map(([name, value]) => `${name}: ${value}`).join('\\r\\n')}\\r\\n\\r\\n${init.text ?? ''}`;\n const bytes = typeof raw === 'string' ? new TextEncoder().encode(raw) : raw;\n let rejectReason: string | undefined;\n const forwards: { rcptTo: string; headers?: Headers }[] = [];\n const replies: (EmailMessage | EmailReplyMessageBuilder)[] = [];\n return {\n from: init.from,\n to: init.to,\n headers,\n rawSize: bytes.byteLength,\n raw: new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes.slice());\n controller.close();\n },\n }),\n get rejectReason() {\n return rejectReason;\n },\n forwards,\n replies,\n setReject(reason: string): void {\n rejectReason = reason;\n },\n async forward(rcptTo: string, forwardHeaders?: Headers): Promise<EmailSendResult> {\n forwards.push(\n forwardHeaders === undefined ? { rcptTo } : { rcptTo, headers: forwardHeaders },\n );\n return { messageId: `forward-${forwards.length}@vela.test` };\n },\n async reply(message: EmailMessage | EmailReplyMessageBuilder): Promise<EmailSendResult> {\n replies.push(message);\n return { messageId: `reply-${replies.length}@vela.test` };\n },\n };\n}\n\n/**\n * A Tail Workers event (`TraceItem`) for tests: an `ok` fetch-less invocation\n * of the Worker `producer`, with `overrides` applied.\n */\nexport function traceItem(overrides: Partial<TraceItem> = {}): TraceItem {\n return {\n event: null,\n eventTimestamp: Date.now(),\n logs: [],\n exceptions: [],\n diagnosticsChannelEvents: [],\n scriptName: 'producer',\n outcome: 'ok',\n executionModel: 'stateless',\n truncated: false,\n cpuTime: 0,\n wallTime: 0,\n ...overrides,\n };\n}\n\n/**\n * Build `rootModule` as `createCloudflareWorker(rootModule, options)` does\n * (its adapters, then its `configure` hook), through `@velajs/testing`, and\n * drive its Worker handlers inside the Workers Vitest pool.\n *\n * ```ts\n * const worker = await createTestingWorker(AppModule, {\n * overrides: (module) => module.overrideProvider(Mailer).useValue(fakeMailer),\n * });\n * const response = await worker.fetch('/todos');\n * const result = await worker.queue('todo-events', [queueJob('todos', todoCreated, { id: '1' })]);\n * await worker.scheduled('0 3 * * *');\n * await worker.close();\n * ```\n */\nexport async function createTestingWorker(\n rootModule: CloudflareRoot,\n options: TestingWorkerOptions = {},\n): Promise<TestingWorker> {\n const { env = workersEnv, overrides, configure, ...appOptions } = options;\n const builder = Test.createTestingModule(\n { imports: [rootModule] },\n cloudflareCreateOptions({ ...appOptions, env }),\n );\n const module = await (overrides ? overrides(builder) : builder).compile();\n let app: CloudflareApplication;\n try {\n app = await configureCloudflareApplication(\n new CloudflareApplication(await module.createApplication(), env),\n env,\n configure,\n );\n } catch (error) {\n await module.close();\n throw error;\n }\n const contexts = new Set<ExecutionContext>();\n const context = (): ExecutionContext => {\n const ctx = pool.createExecutionContext();\n contexts.add(ctx);\n return ctx;\n };\n // A request completes once its response body is consumed: close() cancels\n // the bodies a test never read, so waiting for its background work ends.\n const responses = new Set<Response>();\n return {\n module,\n env,\n async fetch(input, init) {\n const request =\n typeof input === 'string' && input.startsWith('/')\n ? new Request(new URL(input, 'http://localhost'), init)\n : new Request(input, init);\n const response = await app.fetch(request, env, context());\n responses.add(response);\n return response;\n },\n async queue(queue, messages) {\n const batch = pool.createMessageBatch(\n queue,\n messages.map((message) => ({\n id: message.id ?? crypto.randomUUID(),\n timestamp: message.timestamp ?? Date.now(),\n attempts: message.attempts ?? 1,\n body: message.body,\n })),\n );\n const ctx = context();\n try {\n await app.queue(batch, env, ctx);\n } catch (error) {\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'exception', error };\n }\n return { ...(await pool.getQueueResult(batch, ctx)), outcome: 'ok' };\n },\n async scheduled(cron, { scheduledTime } = {}) {\n const declared = app.entrypoints\n .ofKind('schedule:cron', parseCronMetadata)\n .map((entry) => entry.meta.expression);\n if (!declared.includes(cron)) {\n throw new Error(\n `No @Cron job declares ${JSON.stringify(cron)}. Declared: ` +\n `${declared.map((expression) => JSON.stringify(expression)).join(', ') || '(none)'}.`,\n );\n }\n const ctx = context();\n await app.scheduled(pool.createScheduledController({ cron, scheduledTime }), env, ctx);\n await pool.waitOnExecutionContext(ctx);\n },\n email: (message) => dispatchEmail(app, message),\n tail: (events) => dispatchTail(app, events),\n async close() {\n await Promise.all(\n [...responses].map((response) =>\n response.bodyUsed ? undefined : response.body?.cancel().catch(() => {}),\n ),\n );\n responses.clear();\n await Promise.all([...contexts].map((ctx) => pool.waitOnExecutionContext(ctx)));\n contexts.clear();\n await module.close();\n },\n };\n}\n\n/**\n * A queue message carrying a Vela job envelope, as `QueueClient.add()` sends\n * it: `queue` is the logical queue a `@Processor` handles, and `job` a job\n * definition (whose wire input `data` must match) or a job name.\n */\nexport function queueJob<const D extends QueueJobDefinition>(\n queue: string,\n job: D,\n data: QueueJobInput<D>,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string,\n data: unknown,\n options?: { id?: string; attempts?: number },\n): TestingQueueMessage<QueueJob>;\nexport function queueJob(\n queue: string,\n job: string | QueueJobDefinition,\n data: unknown,\n { id = crypto.randomUUID(), attempts = 1 }: { id?: string; attempts?: number } = {},\n): TestingQueueMessage<QueueJob> {\n const name = typeof job === 'string' ? job : job.name;\n return { id, attempts, body: { id, queue, name, data, attempt: attempts } };\n}\n"],"mappings":";;;;;;;;;AAqCA,MAAM,OAAwB;;;;;;;;;;;;;;AAuG9B,SAAgB,aAAa,MAA6C;CACxE,MAA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