@velajs/cloudflare 1.31.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +154 -10
  3. package/dist/bindings.js +17 -1
  4. package/dist/bindings.js.map +1 -1
  5. package/dist/{cloudflare-factory-eGiet0mg.d.ts → cloudflare-application-CXDy9C1R.d.ts} +9 -98
  6. package/dist/cloudflare-application.js +8 -0
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +153 -20
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/durable-object/boot.js +76 -0
  12. package/dist/durable-object/boot.js.map +1 -0
  13. package/dist/durable-object/host-dispatch.js +134 -0
  14. package/dist/durable-object/host-dispatch.js.map +1 -0
  15. package/dist/durable-object/host-methods.js +47 -0
  16. package/dist/durable-object/host-methods.js.map +1 -0
  17. package/dist/durable-object/tokens.js +17 -0
  18. package/dist/durable-object/tokens.js.map +1 -0
  19. package/dist/durable-object/vela-durable-object.js +121 -0
  20. package/dist/durable-object/vela-durable-object.js.map +1 -0
  21. package/dist/durable-objects.d.ts +131 -9
  22. package/dist/durable-objects.js +3 -1
  23. package/dist/email/email-dispatch.js +65 -0
  24. package/dist/email/email-dispatch.js.map +1 -0
  25. package/dist/email/on-email.js +57 -0
  26. package/dist/email/on-email.js.map +1 -0
  27. package/dist/email.d.ts +51 -0
  28. package/dist/email.js +3 -0
  29. package/dist/entrypoint/vela-entrypoint.js +160 -0
  30. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  31. package/dist/entrypoints.d.ts +93 -0
  32. package/dist/entrypoints.js +2 -0
  33. package/dist/host/host-invoker.js +276 -0
  34. package/dist/host/host-invoker.js.map +1 -0
  35. package/dist/host/host-members.js +73 -0
  36. package/dist/host/host-members.js.map +1 -0
  37. package/dist/host-members-DECj_4yz.d.ts +13 -0
  38. package/dist/index.d.ts +74 -13
  39. package/dist/index.js +4 -3
  40. package/dist/root-module.js +19 -0
  41. package/dist/root-module.js.map +1 -0
  42. package/dist/rpc/entrypoint-error.js +145 -0
  43. package/dist/rpc/entrypoint-error.js.map +1 -0
  44. package/dist/services/kv-cache.store.js +4 -4
  45. package/dist/services/kv-cache.store.js.map +1 -1
  46. package/dist/tail/on-tail.js +46 -0
  47. package/dist/tail/on-tail.js.map +1 -0
  48. package/dist/tail/tail-dispatch.js +67 -0
  49. package/dist/tail/tail-dispatch.js.map +1 -0
  50. package/dist/tail.d.ts +39 -0
  51. package/dist/tail.js +2 -0
  52. package/dist/testing.d.ts +55 -3
  53. package/dist/testing.js +78 -1
  54. package/dist/testing.js.map +1 -1
  55. package/dist/websocket/binding-gateways.js +1 -1
  56. package/dist/websocket/binding-gateways.js.map +1 -1
  57. package/dist/websocket/do-bootstrap.js +40 -37
  58. package/dist/websocket/do-bootstrap.js.map +1 -1
  59. package/dist/websocket/websocket.durable-object.js +37 -8
  60. package/dist/websocket/websocket.durable-object.js.map +1 -1
  61. package/dist/worker-events.js +49 -0
  62. package/dist/worker-events.js.map +1 -0
  63. package/dist/workflow/vela-workflow.js +104 -0
  64. package/dist/workflow/vela-workflow.js.map +1 -0
  65. package/dist/workflows.d.ts +82 -0
  66. package/dist/workflows.js +2 -0
  67. package/package.json +23 -7
  68. package/dist/root-module-C23bUwt_.d.ts +0 -11
@@ -0,0 +1,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;E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;CACjF,MAAM,SAAS,SAAS,UAAU,OAAO,SAAS,UAAU,MAAM,SAAS,SAAS;CACpF,OAAO,SAAS,KAAK,SAAS,MAAM,EAAE,OAAO,CAAC;AAChD"}
@@ -3,8 +3,8 @@ import { kv } from "../bindings.js";
3
3
  const namespaceOf = (source) => typeof source === "function" ? source : () => source;
4
4
  /**
5
5
  * Native KV JSON value store. Metadata retains logical expiry even when KV's
6
- * physical retention rounds up to its 60-second minimum. Legacy values without
7
- * metadata remain readable, but cannot safely backfill another tier.
6
+ * physical retention rounds up to its 60-second minimum. Values without
7
+ * Vela expiry metadata are cache misses.
8
8
  */
9
9
  var KVCacheStore = class {
10
10
  #namespace;
@@ -22,13 +22,13 @@ var KVCacheStore = class {
22
22
  if (value === null) return void 0;
23
23
  if (typeof metadata === "object" && metadata !== null && "velaCacheExpiresAt" in metadata) {
24
24
  const expiresAt = metadata.velaCacheExpiresAt;
25
+ if (expiresAt === null) return { value };
25
26
  if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) return void 0;
26
27
  return {
27
28
  value,
28
29
  expiresAt
29
30
  };
30
31
  }
31
- return { value };
32
32
  }
33
33
  async set(key, value, ttl) {
34
34
  if (ttl !== void 0 && (!Number.isFinite(ttl) || ttl < 0)) throw new TypeError("Cache TTL must be finite and nonnegative.");
@@ -36,7 +36,7 @@ var KVCacheStore = class {
36
36
  value,
37
37
  expiresAt: Date.now() + ttl * 1e3
38
38
  });
39
- await this.ns.put(key, JSON.stringify(value));
39
+ await this.ns.put(key, JSON.stringify(value), { metadata: { velaCacheExpiresAt: null } });
40
40
  }
41
41
  async setEntry(key, entry) {
42
42
  if (!Number.isFinite(entry.expiresAt)) throw new TypeError("Cache expiry must be finite.");
@@ -1 +1 @@
1
- {"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum. Legacy values without\n * metadata remain readable, but cannot safely backfill another tier.\n */\nexport class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async get(key: string): Promise<unknown> {\n return (await this.getEntry(key))?.value;\n }\n\n async getEntry(key: string): Promise<{ value: unknown; expiresAt?: number } | undefined> {\n const { value, metadata } = await this.ns.getWithMetadata<unknown, unknown>(key, 'json');\n if (value === null) return undefined;\n if (typeof metadata === 'object' && metadata !== null && 'velaCacheExpiresAt' in metadata) {\n const expiresAt = metadata.velaCacheExpiresAt;\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= Date.now())\n return undefined;\n return { value, expiresAt };\n }\n return { value };\n }\n\n async set(key: string, value: unknown, ttl?: number): Promise<void> {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))\n throw new TypeError('Cache TTL must be finite and nonnegative.');\n if (ttl !== undefined) return this.setEntry(key, { value, expiresAt: Date.now() + ttl * 1000 });\n await this.ns.put(key, JSON.stringify(value));\n }\n\n async setEntry(key: string, entry: CacheEntry): Promise<void> {\n if (!Number.isFinite(entry.expiresAt)) throw new TypeError('Cache expiry must be finite.');\n const remaining = (entry.expiresAt - Date.now()) / 1000;\n if (remaining <= 0) return this.del(key);\n await this.ns.put(key, JSON.stringify(entry.value), {\n expirationTtl: Math.max(60, Math.ceil(remaining)),\n metadata: { velaCacheExpiresAt: entry.expiresAt },\n });\n }\n\n async del(key: string): Promise<void> {\n await this.ns.delete(key);\n }\n\n /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */\n async clear(): Promise<void> {\n let cursor: string | undefined;\n do {\n const list = await this.ns.list(cursor ? { cursor } : undefined);\n await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));\n cursor = list.list_complete ? undefined : list.cursor;\n } while (cursor);\n }\n}\n\n/**\n * Optional, eventually consistent generation store. Use a dedicated KV namespace\n * without TTL/lifecycle cleanup. Never delete/reset generations while entries can\n * survive. Concurrent writes and cached/negative reads prevent strong invalidation;\n * this is unsuitable for strict read-after-write or authorization revocation.\n */\nexport class KVCacheInvalidationStore implements CacheInvalidationStore {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async getVersion(key: string): Promise<string> {\n const value: unknown = await this.ns.get(key, 'json');\n if (value === null) return 'initial';\n if (typeof value !== 'string' || value.length === 0 || value.length > 2048)\n throw new TypeError('Invalid cache generation.');\n return value;\n }\n async invalidate(key: string): Promise<void> {\n await this.ns.put(key, JSON.stringify(crypto.randomUUID()));\n }\n}\n\n/**\n * `CacheModule`'s value store over the KV namespace named `binding`, read from\n * each application's `ENV` when an operation needs it:\n * `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\nexport function kvCache(ref: { binding: string }): EnvFactory<CacheStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheStore(() => namespace(env));\n}\n\n/**\n * `CacheModule`'s generation store over a dedicated KV namespace named\n * `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see\n * {@link KVCacheInvalidationStore}.\n */\nexport function kvCacheInvalidation(ref: { binding: string }): EnvFactory<CacheInvalidationStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheInvalidationStore(() => namespace(env));\n}\n"],"mapp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../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum. Values without\n * Vela expiry metadata are cache misses.\n */\nexport class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async get(key: string): Promise<unknown> {\n return (await this.getEntry(key))?.value;\n }\n\n async getEntry(key: string): Promise<{ value: unknown; expiresAt?: number } | undefined> {\n const { value, metadata } = await this.ns.getWithMetadata<unknown, unknown>(key, 'json');\n if (value === null) return undefined;\n if (typeof metadata === 'object' && metadata !== null && 'velaCacheExpiresAt' in metadata) {\n const expiresAt = metadata.velaCacheExpiresAt;\n if (expiresAt === null) return { value };\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= Date.now())\n return undefined;\n return { value, expiresAt };\n }\n return undefined;\n }\n\n async set(key: string, value: unknown, ttl?: number): Promise<void> {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))\n throw new TypeError('Cache TTL must be finite and nonnegative.');\n if (ttl !== undefined) return this.setEntry(key, { value, expiresAt: Date.now() + ttl * 1000 });\n await this.ns.put(key, JSON.stringify(value), { metadata: { velaCacheExpiresAt: null } });\n }\n\n async setEntry(key: string, entry: CacheEntry): Promise<void> {\n if (!Number.isFinite(entry.expiresAt)) throw new TypeError('Cache expiry must be finite.');\n const remaining = (entry.expiresAt - Date.now()) / 1000;\n if (remaining <= 0) return this.del(key);\n await this.ns.put(key, JSON.stringify(entry.value), {\n expirationTtl: Math.max(60, Math.ceil(remaining)),\n metadata: { velaCacheExpiresAt: entry.expiresAt },\n });\n }\n\n async del(key: string): Promise<void> {\n await this.ns.delete(key);\n }\n\n /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */\n async clear(): Promise<void> {\n let cursor: string | undefined;\n do {\n const list = await this.ns.list(cursor ? { cursor } : undefined);\n await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));\n cursor = list.list_complete ? undefined : list.cursor;\n } while (cursor);\n }\n}\n\n/**\n * Optional, eventually consistent generation store. Use a dedicated KV namespace\n * without TTL/lifecycle cleanup. Never delete/reset generations while entries can\n * survive. Concurrent writes and cached/negative reads prevent strong invalidation;\n * this is unsuitable for strict read-after-write or authorization revocation.\n */\nexport class KVCacheInvalidationStore implements CacheInvalidationStore {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async getVersion(key: string): Promise<string> {\n const value: unknown = await this.ns.get(key, 'json');\n if (value === null) return 'initial';\n if (typeof value !== 'string' || value.length === 0 || value.length > 2048)\n throw new TypeError('Invalid cache generation.');\n return value;\n }\n async invalidate(key: string): Promise<void> {\n await this.ns.put(key, JSON.stringify(crypto.randomUUID()));\n }\n}\n\n/**\n * `CacheModule`'s value store over the KV namespace named `binding`, read from\n * each application's `ENV` when an operation needs it:\n * `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\nexport function kvCache(ref: { binding: string }): EnvFactory<CacheStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheStore(() => namespace(env));\n}\n\n/**\n * `CacheModule`'s generation store over a dedicated KV namespace named\n * `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see\n * {@link KVCacheInvalidationStore}.\n */\nexport function kvCacheInvalidation(ref: { binding: string }): EnvFactory<CacheInvalidationStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheInvalidationStore(() => namespace(env));\n}\n"],"mappings":";;AAaA,MAAM,eAAe,WACnB,OAAO,WAAW,aAAa,eAAe;;;;;;AAOhD,IAAa,eAAb,MAAoF;CAClF;CACA,YAAY,WAA8B;EACxC,KAAK,aAAa,YAAY,SAAS;CACzC;CAEA,IAAY,KAAkB;EAC5B,OAAO,KAAK,WAAW;CACzB;CAEA,MAAM,IAAI,KAA+B;EACvC,QAAQ,MAAM,KAAK,SAAS,GAAG,EAAA,EAAI;CACrC;CAEA,MAAM,SAAS,KAA0E;EACvF,MAAM,EAAE,OAAO,aAAa,MAAM,KAAK,GAAG,gBAAkC,KAAK,MAAM;EACvF,IAAI,UAAU,MAAM,OAAO,KAAA;EAC3B,IAAI,OAAO,aAAa,YAAY,aAAa,QAAQ,wBAAwB,UAAU;GACzF,MAAM,YAAY,SAAS;GAC3B,IAAI,cAAc,MAAM,OAAO,EAAE,MAAM;GACvC,IAAI,OAAO,cAAc,YAAY,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,KAAK,IAAI,GACxF,OAAO,KAAA;GACT,OAAO;IAAE;IAAO;GAAU;EAC5B;CAEF;CAEA,MAAM,IAAI,KAAa,OAAgB,KAA6B;EAClE,IAAI,QAAQ,KAAA,MAAc,CAAC,OAAO,SAAS,GAAG,KAAK,MAAM,IACvD,MAAM,IAAI,UAAU,2CAA2C;EACjE,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAK,SAAS,KAAK;GAAE;GAAO,WAAW,KAAK,IAAI,IAAI,MAAM;EAAK,CAAC;EAC9F,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,KAAK,GAAG,EAAE,UAAU,EAAE,oBAAoB,KAAK,EAAE,CAAC;CAC1F;CAEA,MAAM,SAAS,KAAa,OAAkC;EAC5D,IAAI,CAAC,OAAO,SAAS,MAAM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AmB,UAAU,GAAG,CAAC;AACvD;;;;;;AAOA,SAAgB,oBAAoB,KAA8D;CAChG,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,+BAA+B,UAAU,GAAG,CAAC;AACnE"}
@@ -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
@@ -0,0 +1,2 @@
1
+ import { OnTail } from "./tail/on-tail.js";
2
+ export { OnTail };
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import { t as CloudflareRoot } from "./root-module-C23bUwt_.js";
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 `scheduled` handlers for one test application. */
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