@velajs/cloudflare 1.35.0 → 1.36.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 (109) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +28 -6
  3. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorate.js +1 -2
  4. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorateMetadata.js +1 -2
  5. package/dist/_virtual/{_@oxc-project_runtime@0.150.0 → _@oxc-project_runtime@0.160.0}/helpers/esm/decorateParam.js +1 -2
  6. package/dist/bindings.js +1 -2
  7. package/dist/{cloudflare-application-Dsscb3Mo.d.ts → cloudflare-application-Zw9th_-h.d.ts} +2 -7
  8. package/dist/cloudflare-application.js +2 -3
  9. package/dist/cloudflare-application.js.map +1 -1
  10. package/dist/{cloudflare-factory-DM9CBvNH.d.ts → cloudflare-factory-Ab6XoKqO.d.ts} +5 -9
  11. package/dist/cloudflare-factory.js +5 -6
  12. package/dist/cloudflare-factory.js.map +1 -1
  13. package/dist/decorators/queue-consumer.js +1 -2
  14. package/dist/diagnostics.js +1 -2
  15. package/dist/durable-object/boot.js +5 -6
  16. package/dist/durable-object/host-dispatch.js +4 -5
  17. package/dist/durable-object/host-dispatch.js.map +1 -1
  18. package/dist/durable-object/host-methods.js +1 -2
  19. package/dist/durable-object/tokens.js +1 -2
  20. package/dist/durable-object/vela-durable-object.js +3 -4
  21. package/dist/durable-objects.d.ts +7 -19
  22. package/dist/durable-objects.js +1 -1
  23. package/dist/email/email-dispatch.js +1 -2
  24. package/dist/email/on-email.js +2 -3
  25. package/dist/email.d.ts +2 -6
  26. package/dist/email.js +1 -1
  27. package/dist/entrypoint/vela-entrypoint.js +4 -5
  28. package/dist/entrypoints.d.ts +3 -5
  29. package/dist/entrypoints.js +1 -2
  30. package/dist/environment.js +1 -2
  31. package/dist/host/host-invoker.js +2 -3
  32. package/dist/host/host-invoker.js.map +1 -1
  33. package/dist/host/host-members.js +1 -2
  34. package/dist/{host-members-DECj_4yz.d.ts → host-members-bKCWuJP2.d.ts} +0 -2
  35. package/dist/index.d.ts +53 -42
  36. package/dist/index.js +6 -5
  37. package/dist/nonce/durable-object-nonce.store.js +1 -2
  38. package/dist/nonce/nonce-validation.js +1 -2
  39. package/dist/nonce/nonce.durable-object.js +2 -3
  40. package/dist/nonce/nonce.durable-object.js.map +1 -1
  41. package/dist/{nonce.durable-object-Bg1e0BMD.d.ts → nonce.durable-object-Csuy3U9e.d.ts} +0 -4
  42. package/dist/pipelines.d.ts +1 -3
  43. package/dist/pipelines.js +1 -2
  44. package/dist/platform.js +2 -3
  45. package/dist/queue/cloudflare-queues.js +3 -4
  46. package/dist/queue-events/consume.js +1 -2
  47. package/dist/queue-events/consume.js.map +1 -1
  48. package/dist/queue-events.d.ts +1 -2
  49. package/dist/queue-events.js +1 -2
  50. package/dist/queues.d.ts +1 -3
  51. package/dist/queues.js +1 -2
  52. package/dist/rate-limit/cloudflare-rate-limit.store.js +1 -2
  53. package/dist/rate-limit/d1-throttler.store.js +96 -0
  54. package/dist/rate-limit/d1-throttler.store.js.map +1 -0
  55. package/dist/root-module.js +1 -2
  56. package/dist/rpc/entrypoint-error.js +1 -2
  57. package/dist/rpc/entrypoint-error.js.map +1 -1
  58. package/dist/schedule-diagnostics.js +2 -3
  59. package/dist/schedule-diagnostics.js.map +1 -1
  60. package/dist/scheduled-event.js +1 -2
  61. package/dist/services/flagship-flag.driver.js +1 -2
  62. package/dist/services/flagship-flag.driver.js.map +1 -1
  63. package/dist/services/kv-cache.store.js +1 -2
  64. package/dist/services/kv-cache.store.js.map +1 -1
  65. package/dist/services/kv-flag.driver.js +1 -2
  66. package/dist/services/kv-flag.driver.js.map +1 -1
  67. package/dist/storage/r2-storage.js +2 -3
  68. package/dist/storage.d.ts +1 -3
  69. package/dist/storage.js +1 -2
  70. package/dist/tail/on-tail.js +2 -3
  71. package/dist/tail/tail-dispatch.js +2 -3
  72. package/dist/tail.d.ts +2 -6
  73. package/dist/tail.js +1 -2
  74. package/dist/testing.d.ts +5 -5
  75. package/dist/testing.js +6 -6
  76. package/dist/testing.js.map +1 -1
  77. package/dist/tracing.d.ts +1 -3
  78. package/dist/tracing.js +3 -4
  79. package/dist/{vela-env-DFvyoNT3.d.ts → vela-env-5graXefc.d.ts} +0 -1
  80. package/dist/websocket/binding-gateways.js +2 -3
  81. package/dist/websocket/cf-room-registry.js +2 -3
  82. package/dist/websocket/cf-room-registry.js.map +1 -1
  83. package/dist/websocket/cf-ws-client.js +2 -3
  84. package/dist/websocket/cf-ws-client.js.map +1 -1
  85. package/dist/websocket/do-bootstrap.js +5 -6
  86. package/dist/websocket/do-live.js +4 -5
  87. package/dist/websocket/do-live.js.map +1 -1
  88. package/dist/websocket/do-pitr.js +1 -2
  89. package/dist/websocket/do-pitr.js.map +1 -1
  90. package/dist/websocket/do-state.js +1 -2
  91. package/dist/websocket/do-websocket-host.js +3 -4
  92. package/dist/websocket/do-websocket-host.js.map +1 -1
  93. package/dist/websocket/live-driver.js +3 -4
  94. package/dist/websocket/live-driver.js.map +1 -1
  95. package/dist/websocket/room-id.js +1 -2
  96. package/dist/websocket/websocket.durable-object.js +5 -6
  97. package/dist/websocket/websocket.durable-object.js.map +1 -1
  98. package/dist/websocket/worker-transport.js +3 -4
  99. package/dist/websocket/ws-attachment.js +1 -2
  100. package/dist/worker-events.js +1 -2
  101. package/dist/workflow/portable-workflow-step.js +1 -2
  102. package/dist/workflow/vela-workflow-definition.js +7 -8
  103. package/dist/workflow/vela-workflow-definition.js.map +1 -1
  104. package/dist/workflow/vela-workflow.js +2 -3
  105. package/dist/workflow-definitions.d.ts +2 -4
  106. package/dist/workflow-definitions.js +1 -2
  107. package/dist/workflows.d.ts +2 -4
  108. package/dist/workflows.js +1 -2
  109. package/package.json +19 -19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"d1-throttler.store.js","names":[],"sources":["../../src/rate-limit/d1-throttler.store.ts"],"sourcesContent":["import type { VelaEnv } from '@velajs/vela';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { ThrottlerStorageRecord, ThrottlerStore } from '@velajs/vela/throttler';\nimport { d1 } from '../bindings';\n\nexport interface D1ThrottlerStoreOptions {\n /** The D1 binding (declared under `d1_databases`) that holds the counters. */\n binding: string;\n /** Counter table, created by {@link d1ThrottlerMigration}. Default `vela_rate_limits`. */\n table?: string;\n /** Bound attacker-influenced tracking keys before they reach D1. Default 1024 bytes. */\n maxKeyBytes?: number;\n /**\n * Remove up to this many ended windows on about one count in 100, so the\n * table does not grow with every client ever seen. Default 100; 0 never\n * prunes (prune on a schedule instead).\n */\n pruneBatch?: number;\n}\n\n/** A D1 store with its table and a way to drop ended windows on a schedule. */\nexport interface D1ThrottlerStore extends ThrottlerStore {\n /** Delete up to `limit` ended windows; answers how many went. */\n prune(limit?: number): Promise<number>;\n}\n\nconst DEFAULT_TABLE = 'vela_rate_limits';\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;\nconst PRUNE_ODDS = 0.01;\n\nfunction tableName(table: string | undefined): string {\n const name = table ?? DEFAULT_TABLE;\n if (!IDENTIFIER.test(name)) {\n throw new TypeError(`Invalid throttler table name '${name}'`);\n }\n return name;\n}\n\n/**\n * The statements that create the counter table and its expiry index, for a D1\n * migration file (each one a complete statement; end them with `;`).\n */\nexport function d1ThrottlerMigration(options: { table?: string } = {}): string[] {\n const table = tableName(options.table);\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\"key\" TEXT PRIMARY KEY NOT NULL, \"count\" INTEGER NOT NULL, \"reset_at\" INTEGER NOT NULL) WITHOUT ROWID`,\n `CREATE INDEX IF NOT EXISTS \"${table}_reset_at\" ON \"${table}\" (\"reset_at\")`,\n ];\n}\n\n/**\n * `ThrottlerModule` storage on D1, read from each application's `ENV` by name:\n *\n * ```ts\n * ThrottlerModule.forRoot({\n * throttlers: [{ name: 'login', ttl: 10 * 60_000, limit: 30 }],\n * storage: d1ThrottlerStore({ binding: 'DB' }),\n * })\n * ```\n *\n * Every count is one `INSERT … ON CONFLICT … RETURNING` statement: D1 runs it\n * atomically on the database's primary, so all isolates and locations share\n * one exact fixed-window counter per key, with windows of any length and\n * `@Throttle()` overrides. Each counted request costs one D1 write, and about\n * one in 100 also deletes up to `pruneBatch` ended windows. The store\n * also reads and resets counters, which `FailureCounter` needs. Create the\n * table with {@link d1ThrottlerMigration}.\n */\nexport function d1ThrottlerStore(options: D1ThrottlerStoreOptions): EnvFactory<D1ThrottlerStore> {\n const table = tableName(options.table);\n const maxKeyBytes = options.maxKeyBytes ?? 1_024;\n if (!Number.isSafeInteger(maxKeyBytes) || maxKeyBytes <= 0 || maxKeyBytes > 4_096) {\n throw new RangeError('maxKeyBytes must be between 1 and 4096');\n }\n const pruneBatch = options.pruneBatch ?? 100;\n if (!Number.isSafeInteger(pruneBatch) || pruneBatch < 0 || pruneBatch > 10_000) {\n throw new RangeError('pruneBatch must be an integer from 0 to 10000');\n }\n const database = d1({ binding: options.binding });\n const encoder = new TextEncoder();\n const quoted = `\"${table}\"`;\n const countSql =\n `INSERT INTO ${quoted} (\"key\", \"count\", \"reset_at\") VALUES (?1, 1, ?2 + ?3) ` +\n `ON CONFLICT (\"key\") DO UPDATE SET ` +\n `\"count\" = CASE WHEN \"reset_at\" <= ?2 THEN 1 ELSE \"count\" + 1 END, ` +\n `\"reset_at\" = CASE WHEN \"reset_at\" <= ?2 THEN ?2 + ?3 ELSE \"reset_at\" END ` +\n `RETURNING \"count\", \"reset_at\"`;\n const readSql = `SELECT \"count\", \"reset_at\" FROM ${quoted} WHERE \"key\" = ?1 AND \"reset_at\" > ?2`;\n const resetSql = `DELETE FROM ${quoted} WHERE \"key\" = ?1`;\n const pruneSql =\n `DELETE FROM ${quoted} WHERE \"key\" IN ` +\n `(SELECT \"key\" FROM ${quoted} WHERE \"reset_at\" <= ?1 LIMIT ?2)`;\n\n const checkKey = (key: string): void => {\n if (\n typeof key !== 'string' ||\n key.length === 0 ||\n /[\\u0000-\\u001f\\u007f]/.test(key) ||\n encoder.encode(key).byteLength > maxKeyBytes\n ) {\n throw new Error('Refusing an invalid or oversized rate-limit key');\n }\n };\n const record = (row: unknown, now: number): ThrottlerStorageRecord => {\n const count: unknown =\n typeof row === 'object' && row !== null ? Reflect.get(row, 'count') : undefined;\n const resetAt: unknown =\n typeof row === 'object' && row !== null ? Reflect.get(row, 'reset_at') : undefined;\n if (typeof count !== 'number' || typeof resetAt !== 'number') {\n throw new Error('D1 throttler table returned an invalid counter');\n }\n return { count, ttlMs: Math.max(1, resetAt - now) };\n };\n\n return (env: VelaEnv): D1ThrottlerStore => {\n const db = (): D1Database => database(env);\n const prune = async (limit = pruneBatch || 100): Promise<number> => {\n if (!Number.isSafeInteger(limit) || limit < 1)\n throw new RangeError('prune limit must be positive');\n const result = await db().prepare(pruneSql).bind(Date.now(), limit).run();\n return result.meta.changes ?? 0;\n };\n return {\n validate(throttlers) {\n for (const { name, ttl } of throttlers) {\n if (!Number.isSafeInteger(ttl) || ttl < 1) {\n throw new Error(`Throttler '${name}' needs a positive whole-millisecond ttl`);\n }\n }\n },\n\n async increment(key: string, ttl: number): Promise<ThrottlerStorageRecord> {\n checkKey(key);\n if (!Number.isSafeInteger(ttl) || ttl < 1) {\n throw new Error('Rate-limit windows must be positive whole milliseconds');\n }\n const now = Date.now();\n const row = await db().prepare(countSql).bind(key, now, ttl).first();\n // Housekeeping must not fail the request it rides on; the next\n // attempt (or a scheduled prune) removes what this one could not.\n if (pruneBatch > 0 && Math.random() < PRUNE_ODDS) await prune(pruneBatch).catch(() => 0);\n return record(row, now);\n },\n\n async get(key: string): Promise<ThrottlerStorageRecord | undefined> {\n checkKey(key);\n const now = Date.now();\n const row = await db().prepare(readSql).bind(key, now).first();\n return row === null ? undefined : record(row, now);\n },\n\n async reset(key: string): Promise<void> {\n checkKey(key);\n await db().prepare(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E,SAAS,GAAG;IACZ,MAAM,MAAM,KAAK,IAAI;IACrB,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,OAAO,CAAC,CAAC,KAAK,KAAK,GAAG,CAAC,CAAC,MAAM;IAC7D,OAAO,QAAQ,OAAO,KAAA,IAAY,OAAO,KAAK,GAAG;GACnD;GAEA,MAAM,MAAM,KAA4B;IACtC,SAAS,GAAG;IACZ,MAAM,GAAG,CAAC,CAAC,QAAQ,QAAQ,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI;GAC7C;GAEA;EACF;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- //#region src/root-module.ts
1
+ // src/root-module.ts
2
2
  /**
3
3
  * @internal `root` with `providers` added to the root module's own providers,
4
4
  * so each one injects what the root module can see.
@@ -13,7 +13,6 @@ function withRootProviders(root, providers) {
13
13
  providers: [...root.providers ?? [], ...providers]
14
14
  };
15
15
  }
16
- //#endregion
17
16
  export { withRootProviders };
18
17
 
19
18
  //# sourceMappingURL=root-module.js.map
@@ -1,5 +1,5 @@
1
1
  import { HttpException, renderHttpError } from "@velajs/vela";
2
- //#region src/rpc/entrypoint-error.ts
2
+ // src/rpc/entrypoint-error.ts
3
3
  const NAME = "EntrypointError";
4
4
  const CODE = /^[A-Za-z0-9_.:-]{1,160}$/;
5
5
  const MAX_MESSAGE_LENGTH = 2048;
@@ -139,7 +139,6 @@ function renderEntrypointResponse(error, reporter, context) {
139
139
  const status = rendered.status >= 400 && rendered.status <= 599 ? rendered.status : 500;
140
140
  return Response.json(rendered.body, { status });
141
141
  }
142
- //#endregion
143
142
  export { EntrypointError, internalEntrypointError, isEntrypointError, renderEntrypointError, renderEntrypointResponse };
144
143
 
145
144
  //# sourceMappingURL=entrypoint-error.js.map
@@ -1 +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;;;;;;;;;;;;;;;;;;;;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S;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"}
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;CACtD,OAAO;CAChB;CACA;CAGT,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;A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IAAI,kBAAkB,KAAK,GAAG,OAAO,aAAa,eAAe,KAAK,CAAC;CACvE,MAAM,WAAW,SAAS,OAAO,OAAO,OAAO;CAC/C,IAAI,oBAAoB,UAAU;EAC3B,SAAS,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"}
@@ -1,6 +1,6 @@
1
- import { reportDiagnostic } from "./diagnostics.js";
2
1
  import { cronDialectAmbiguity, parseCronMetadata, parseIntervalMetadata, scheduledJobComponents } from "@velajs/vela/module-kit";
3
- //#region src/schedule-diagnostics.ts
2
+ import { reportDiagnostic } from "./diagnostics.js";
3
+ // src/schedule-diagnostics.ts
4
4
  function jobName(entry) {
5
5
  return `${typeof entry.token === "function" ? entry.token.name : String(entry.token)}.${entry.meta.methodName}`;
6
6
  }
@@ -38,7 +38,6 @@ function reportCloudflareScheduleDiagnostics(container, entrypoints) {
38
38
  }
39
39
  for (const entry of entrypoints.ofKind("schedule:interval", parseIntervalMetadata)) reportDiagnostic(container, `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, or run it under ScheduleNodeModule on Node.`);
40
40
  }
41
- //#endregion
42
41
  export { reportCloudflareScheduleDiagnostics };
43
42
 
44
43
  //# sourceMappingURL=schedule-diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schedule-diagnostics.js","names":[],"sources":["../src/schedule-diagnostics.ts"],"sourcesContent":["import {\n cronDialectAmbiguity,\n parseCronMetadata,\n parseIntervalMetadata,\n scheduledJobComponents,\n} from '@velajs/vela/module-kit';\nimport type { VelaApplication } from '@velajs/vela';\nimport type { Entrypoint, Container } from '@velajs/vela/module-kit';\nimport { reportDiagnostic as reportScheduleDiagnostic } from './diagnostics';\n\nfunction jobName(entry: Entrypoint<{ methodName: string }>): string {\n const owner = typeof entry.token === 'function' ? entry.token.name : String(entry.token);\n return `${owner}.${entry.meta.methodName}`;\n}\n\n/**\n * Guards, interceptors and filters declared for a job never run on its\n * trigger, and a direct job that declares guards is refused on every trigger.\n */\nfunction reportComponents(\n container: Container,\n label: string,\n entry: Entrypoint<{ methodName: string }>,\n): void {\n const decorators = scheduledJobComponents(container, entry);\n if (decorators.length === 0) return;\n const named =\n decorators.length > 1\n ? `${decorators.slice(0, -1).join(', ')} and ${decorators.at(-1)!}`\n : decorators.join('');\n const refused = decorators.includes('@UseGuards')\n ? ', and one that declares guards refuses to run'\n : '';\n reportScheduleDiagnostic(\n container,\n `[vela] ${label} declares ${named}, which do not run for scheduled jobs: a direct job ` +\n `runs no guards, interceptors or filters${refused}. Use signed ScheduleModule dispatch ` +\n `and declare them on the signed route to run the job through the request pipeline.`,\n );\n}\n\n/**\n * Report schedule declarations a Workers cron trigger cannot honor as written:\n * a dialect-ambiguous `@Cron`, `dialect: 'unix'`, `timeZone: 'local'`,\n * `@Interval` jobs, and guards, interceptors or filters declared for a job\n * (a direct job that declares guards is refused when it fires).\n * The container's diagnostics policy applies: `'throw'` fails bootstrap and the\n * default `'log'` warns once per declaration, so the first event of a Worker\n * (which bootstraps the application) never fails because of these checks.\n * `vela deploy check` rejects the cron declarations, `@Interval` jobs and\n * guarded direct jobs before deployment (`ambiguous-cron-dialect`,\n * `incompatible-cron-options`, `unsupported-interval`, `scheduled-job-guards`).\n */\nexport function reportCloudflareScheduleDiagnostics(\n container: Container,\n entrypoints: VelaApplication['entrypoints'],\n): void {\n for (const entry of entrypoints.ofKind('schedule:cron', parseCronMetadata)) {\n const cron = `@Cron('${entry.meta.expression}') on ${jobName(entry)}`;\n const ambiguity = cronDialectAmbiguity(entry.meta);\n if (ambiguity) {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares no dialect, and ${ambiguity}. Workers deliver the trigger ` +\n `with Cloudflare semantics while Node reads it with Vela's unix dialect; declare ` +\n `{ dialect: 'cloudflare' } so it fires on the same days on every runtime.`,\n );\n }\n if (entry.meta.dialect === 'unix') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares dialect 'unix', but Cloudflare delivers its trigger with ` +\n `Cloudflare cron semantics (weekdays 1 = Sunday through 7 = Saturday). Declare ` +\n `{ dialect: 'cloudflare' } and write the expression for Cloudflare.`,\n );\n }\n if (entry.meta.timeZone === 'local') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares timeZone 'local', but Cloudflare cron triggers run in UTC. ` +\n `Remove timeZone or set it to 'UTC'.`,\n );\n }\n reportComponents(container, cron, entry);\n }\n for (const entry of entrypoints.ofKind('schedule:interval', parseIntervalMetadata)) {\n reportScheduleDiagnostic(\n container,\n `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron ` +\n `triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, ` +\n `or run it under ScheduleNodeModule on Node.`,\n );\n }\n}\n"],"mappings":";;;AAUA,SAAS,QAAQ,OAAmD;CAElE,OAAO,GADO,OAAO,MAAM,UAAU,aAAa,MAAM,MAAM,OAAO,OAAO,MAAM,KAAK,EACvE,GAAG,MAAM,KAAK;AAChC;;;;;AAMA,SAAS,iBACP,WACA,OACA,OACM;CACN,MAAM,aAAa,uBAAuB,WAAW,KAAK;CAC1D,IAAI,WAAW,WAAW,GAAG;CAC7B,MAAM,QACJ,WAAW,SAAS,IAChB,GAAG,WAAW,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,WAAW,GAAG,EAAE,MAC7D,WAAW,KAAK,EAAE;CACxB,MAAM,UAAU,WAAW,SAAS,YAAY,IAC5C,kDACA;CACJ,iBACE,WACA,UAAU,MAAM,YAAY,MAAM,6FACU,QAAQ,uHAEtD;AACF;;;;;;;;;;;;;AAcA,SAAgB,oCACd,WACA,aACM;CACN,KAAK,MAAM,SAAS,YAAY,OAAO,iBAAiB,iBAAiB,GAAG;EAC1E,MAAM,OAAO,UAAU,MAAM,KAAK,WAAW,QAAQ,QAAQ,KAAK;EAClE,MAAM,YAAY,qBAAqB,MAAM,IAAI;EACjD,IAAI,WACF,iBACE,WACA,UAAU,KAAK,4BAA4B,UAAU,uLAGvD;EAEF,IAAI,MAAM,KAAK,YAAY,QACzB,iBACE,WACA,UAAU,KAAK,oNAGjB;EAEF,IAAI,MAAM,KAAK,aAAa,SAC1B,iBACE,WACA,UAAU,KAAK,yGAEjB;EAEF,iBAAiB,WAAW,MAAM,KAAK;CACzC;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,qBAAqB,qBAAqB,GAC/E,iBACE,WACA,oBAAoB,MAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,EAAE,6JAG1D;AAEJ"}
1
+ {"version":3,"file":"schedule-diagnostics.js","names":["reportScheduleDiagnostic"],"sources":["../src/schedule-diagnostics.ts"],"sourcesContent":["import {\n cronDialectAmbiguity,\n parseCronMetadata,\n parseIntervalMetadata,\n scheduledJobComponents,\n} from '@velajs/vela/module-kit';\nimport type { VelaApplication } from '@velajs/vela';\nimport type { Entrypoint, Container } from '@velajs/vela/module-kit';\nimport { reportDiagnostic as reportScheduleDiagnostic } from './diagnostics';\n\nfunction jobName(entry: Entrypoint<{ methodName: string }>): string {\n const owner = typeof entry.token === 'function' ? entry.token.name : String(entry.token);\n return `${owner}.${entry.meta.methodName}`;\n}\n\n/**\n * Guards, interceptors and filters declared for a job never run on its\n * trigger, and a direct job that declares guards is refused on every trigger.\n */\nfunction reportComponents(\n container: Container,\n label: string,\n entry: Entrypoint<{ methodName: string }>,\n): void {\n const decorators = scheduledJobComponents(container, entry);\n if (decorators.length === 0) return;\n const named =\n decorators.length > 1\n ? `${decorators.slice(0, -1).join(', ')} and ${decorators.at(-1)!}`\n : decorators.join('');\n const refused = decorators.includes('@UseGuards')\n ? ', and one that declares guards refuses to run'\n : '';\n reportScheduleDiagnostic(\n container,\n `[vela] ${label} declares ${named}, which do not run for scheduled jobs: a direct job ` +\n `runs no guards, interceptors or filters${refused}. Use signed ScheduleModule dispatch ` +\n `and declare them on the signed route to run the job through the request pipeline.`,\n );\n}\n\n/**\n * Report schedule declarations a Workers cron trigger cannot honor as written:\n * a dialect-ambiguous `@Cron`, `dialect: 'unix'`, `timeZone: 'local'`,\n * `@Interval` jobs, and guards, interceptors or filters declared for a job\n * (a direct job that declares guards is refused when it fires).\n * The container's diagnostics policy applies: `'throw'` fails bootstrap and the\n * default `'log'` warns once per declaration, so the first event of a Worker\n * (which bootstraps the application) never fails because of these checks.\n * `vela deploy check` rejects the cron declarations, `@Interval` jobs and\n * guarded direct jobs before deployment (`ambiguous-cron-dialect`,\n * `incompatible-cron-options`, `unsupported-interval`, `scheduled-job-guards`).\n */\nexport function reportCloudflareScheduleDiagnostics(\n container: Container,\n entrypoints: VelaApplication['entrypoints'],\n): void {\n for (const entry of entrypoints.ofKind('schedule:cron', parseCronMetadata)) {\n const cron = `@Cron('${entry.meta.expression}') on ${jobName(entry)}`;\n const ambiguity = cronDialectAmbiguity(entry.meta);\n if (ambiguity) {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares no dialect, and ${ambiguity}. Workers deliver the trigger ` +\n `with Cloudflare semantics while Node reads it with Vela's unix dialect; declare ` +\n `{ dialect: 'cloudflare' } so it fires on the same days on every runtime.`,\n );\n }\n if (entry.meta.dialect === 'unix') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares dialect 'unix', but Cloudflare delivers its trigger with ` +\n `Cloudflare cron semantics (weekdays 1 = Sunday through 7 = Saturday). Declare ` +\n `{ dialect: 'cloudflare' } and write the expression for Cloudflare.`,\n );\n }\n if (entry.meta.timeZone === 'local') {\n reportScheduleDiagnostic(\n container,\n `[vela] ${cron} declares timeZone 'local', but Cloudflare cron triggers run in UTC. ` +\n `Remove timeZone or set it to 'UTC'.`,\n );\n }\n reportComponents(container, cron, entry);\n }\n for (const entry of entrypoints.ofKind('schedule:interval', parseIntervalMetadata)) {\n reportScheduleDiagnostic(\n container,\n `[vela] @Interval(${entry.meta.ms}) on ${jobName(entry)} never runs on Workers: cron ` +\n `triggers drive only @Cron jobs. Replace it with a @Cron job and a Wrangler trigger, ` +\n `or run it under ScheduleNodeModule on Node.`,\n );\n }\n}\n"],"mappings":";;;AAUA,SAAS,QAAQ,OAAmD;CAElE,OAAO,GADO,OAAO,MAAM,UAAU,aAAa,MAAM,MAAM,OAAO,OAAO,MAAM,KAAK,EACvE,GAAG,MAAM,KAAK;AAChC;;;;;AAMA,SAAS,iBACP,WACA,OACA,OACM;CACN,MAAM,aAAa,uBAAuB,WAAW,KAAK;CAC1D,IAAI,WAAW,WAAW,GAAG;CAC7B,MAAM,QACJ,WAAW,SAAS,IAChB,GAAG,WAAW,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,WAAW,GAAG,EAAE,MAC7D,WAAW,KAAK,EAAE;CACxB,MAAM,UAAU,WAAW,SAAS,YAAY,IAC5C,kDACA;CACJA,iBACE,WACA,UAAU,MAAM,YAAY,MAAM,6FACU,QAAQ,uHAEtD;AACF;;;;;;;;;;;;;AAcA,SAAgB,oCACd,WACA,aACM;CACN,KAAK,MAAM,SAAS,YAAY,OAAO,iBAAiB,iBAAiB,GAAG;EAC1E,MAAM,OAAO,UAAU,MAAM,KAAK,WAAW,QAAQ,QAAQ,KAAK;EAClE,MAAM,YAAY,qBAAqB,MAAM,IAAI;EACjD,IAAI,WACFA,iBACE,WACA,UAAU,KAAK,4BAA4B,UAAU,uLAGvD;EAEF,IAAI,MAAM,KAAK,YAAY,QACzBA,iBACE,WACA,UAAU,KAAK,oNAGjB;EAEF,IAAI,MAAM,KAAK,aAAa,SAC1BA,iBACE,WACA,UAAU,KAAK,yGAEjB;EAEF,iBAAiB,WAAW,MAAM,KAAK;CACzC;CACA,KAAK,MAAM,SAAS,YAAY,OAAO,qBAAqB,qBAAqB,GAC/EA,iBACE,WACA,oBAAoB,MAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,EAAE,6JAG1D;AAEJ"}
@@ -1,6 +1,6 @@
1
1
  import { InjectionToken, Scope, defineProvider } from "@velajs/vela";
2
2
  import { SCHEDULE_INVOCATION_SEED } from "@velajs/vela/module-kit";
3
- //#region src/scheduled-event.ts
3
+ // src/scheduled-event.ts
4
4
  /**
5
5
  * Request-scoped Cloudflare view of the scheduled trigger, seeded into each
6
6
  * `@Cron` job's invocation scope by the Cloudflare adapter. Inject it where a
@@ -62,7 +62,6 @@ function registerScheduledEventSeed(container) {
62
62
  container.register(defineProvider(SCHEDULE_INVOCATION_SEED, { useValue: seedScheduledEvent }));
63
63
  container.markGlobalToken(SCHEDULE_INVOCATION_SEED);
64
64
  }
65
- //#endregion
66
65
  export { CLOUDFLARE_SCHEDULED_EVENT, cloudflareScheduledEvent, registerScheduledEventSeed };
67
66
 
68
67
  //# sourceMappingURL=scheduled-event.js.map
@@ -1,4 +1,4 @@
1
- //#region src/services/flagship-flag.driver.ts
1
+ // src/services/flagship-flag.driver.ts
2
2
  /**
3
3
  * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
4
4
  *
@@ -104,7 +104,6 @@ function nativeContext(ctx) {
104
104
  }
105
105
  return Object.fromEntries(entries);
106
106
  }
107
- //#endregion
108
107
  export { FlagshipFlagDriver, flagshipFlagDriver };
109
108
 
110
109
  //# sourceMappingURL=flagship-flag.driver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext, FlagEvaluationDetails } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — typed value methods and optional evaluation details. The binding itself returns the supplied\n * `defaultValue` on evaluation errors; transport-level failures reject and are\n * left to propagate (never-throw is the service layer's job, not the driver's).\n *\n * @see https://developers.cloudflare.com/flagship/binding/\n */\ntype NativeFlagDetails<T> = Omit<FlagEvaluationDetails<T>, 'reason'> & { reason?: string };\n\nexport interface FlagshipBinding {\n getBooleanValue(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<boolean>;\n getStringValue(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<string>;\n getNumberValue(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<number>;\n getObjectValue(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<unknown>;\n getBooleanDetails?(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<boolean>>;\n getStringDetails?(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<string>>;\n getNumberDetails?(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<number>>;\n getObjectDetails?(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<unknown>>;\n}\n\nexport interface FlagshipFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"flagship\"`. */\n name?: string;\n}\n\n/**\n * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.\n *\n * A thin, honest wrapper: each contract method maps 1:1 onto the binding's\n * corresponding native method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and validated scalar evaluation context. Optional detail methods\n * preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on\n * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`\n * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns\n * the never-throw guarantee.\n *\n * Build the driver inside a provider factory with the native environment:\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),\n * });\n * ```\n *\n * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the\n * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a\n * bare driver.\n */\nexport class FlagshipFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly resolve: () => FlagshipBinding;\n\n constructor(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options: FlagshipFlagDriverOptions = {},\n ) {\n this.resolve = typeof binding === 'function' ? binding : () => binding;\n this.name = options.name ?? 'flagship';\n }\n\n getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean> {\n return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, nativeContext(ctx));\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));\n }\n getBooleanDetails(\n key: string,\n fallback: boolean,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<boolean>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getBooleanDetails\n ? binding.getBooleanDetails(key, fallback, context)\n : binding\n .getBooleanValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getStringDetails(\n key: string,\n fallback: string,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<string>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getStringDetails\n ? binding.getStringDetails(key, fallback, context)\n : binding\n .getStringValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getNumberDetails(\n key: string,\n fallback: number,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<number>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getNumberDetails\n ? binding.getNumberDetails(key, fallback, context)\n : binding\n .getNumberValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getObjectDetails(\n key: string,\n fallback: object,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<unknown>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getObjectDetails\n ? binding.getObjectDetails(key, fallback, context)\n : binding\n .getObjectValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n private async details<T>(\n key: string,\n fallback: T,\n ctx: FlagContext | undefined,\n read: (\n binding: FlagshipBinding,\n context: Record<string, string | number | boolean> | undefined,\n ) => Promise<NativeFlagDetails<T>>,\n ): Promise<FlagEvaluationDetails<T>> {\n let context: Record<string, string | number | boolean> | undefined;\n try {\n context = nativeContext(ctx);\n } catch {\n return { flagKey: key, value: fallback, reason: 'ERROR', errorCode: 'INVALID_CONTEXT' };\n }\n const details = await read(this.resolve(), context);\n return { ...details, reason: details.reason === undefined ? 'UNKNOWN' : details.reason };\n }\n}\n\n/** Convenience factory for {@link FlagshipFlagDriver}. */\nexport function flagshipFlagDriver(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options?: FlagshipFlagDriverOptions,\n): FlagshipFlagDriver {\n return new FlagshipFlagDriver(binding, options);\n}\n\n/** Copy only validated scalar attributes; never coerce nested or non-finite values. */\nfunction nativeContext(\n ctx: FlagContext | undefined,\n): Record<string, string | number | boolean> | undefined {\n if (ctx === undefined) return undefined;\n if (\n ctx === null ||\n typeof ctx !== 'object' ||\n Array.isArray(ctx) ||\n (Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null)\n )\n throw new TypeError('Invalid Flagship evaluation context');\n const entries: [string, string | number | boolean][] = [];\n for (const [key, value] of Object.entries(ctx)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'boolean' &&\n !(typeof value === 'number' && Number.isFinite(value))\n )\n throw new TypeError('Invalid Flagship evaluation context');\n entries.push([key, value]);\n }\n return Object.fromEntries(entries);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,IAAa,qBAAb,MAA6D;CAC3D;CACA;CAEA,YACE,SACA,UAAqC,CAAC,GACtC;EACA,KAAK,UAAU,OAAO,YAAY,aAAa,gBAAgB;EAC/D,KAAK,OAAO,QAAQ,QAAQ;CAC9B;CAEA,WAAW,KAAa,UAAmB,KAAqC;EAC9E,OAAO,KAAK,QAAQ,CAAC,CAAC,gBAAgB,KAAK,UAAU,cAAc,GAAG,CAAC;CACzE;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,cAAc,GAAG,CAAC;CACxE;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,cAAc,GAAG,CAAC;CACxE;CAEA,UAAU,KAAa,UAAkB,KAAqC;E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F;EACA,MAAM,UAAU,MAAM,KAAK,KAAK,QAAQ,GAAG,OAAO;EAClD,OAAO;GAAE,GAAG;GAAS,QAAQ,QAAQ,WAAW,KAAA,IAAY,YAAY,QAAQ;EAAO;CACzF;AACF;;AAGA,SAAgB,mBACd,SACA,SACoB;CACpB,OAAO,IAAI,mBAAmB,SAAS,OAAO;AAChD;;AAGA,SAAS,cACP,KACuD;CACvD,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,IACE,QAAQ,QACR,OAAO,QAAQ,YACf,MAAM,QAAQ,GAAG,KAChB,OAAO,eAAe,GAAG,MAAM,OAAO,aAAa,OAAO,eAAe,GAAG,MAAM,MAEnF,MAAM,IAAI,UAAU,qCAAqC;CAC3D,MAAM,UAAiD,CAAC;CACxD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAAG;EAC9C,IACE,OAAO,UAAU,YACjB,OAAO,UAAU,aACjB,EAAE,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAEpD,MAAM,IAAI,UAAU,qCAAqC;EAC3D,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC;CAC3B;CACA,OAAO,OAAO,YAAY,OAAO;AACnC"}
1
+ {"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext, FlagEvaluationDetails } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — typed value methods and optional evaluation details. The binding itself returns the supplied\n * `defaultValue` on evaluation errors; transport-level failures reject and are\n * left to propagate (never-throw is the service layer's job, not the driver's).\n *\n * @see https://developers.cloudflare.com/flagship/binding/\n */\ntype NativeFlagDetails<T> = Omit<FlagEvaluationDetails<T>, 'reason'> & { reason?: string };\n\nexport interface FlagshipBinding {\n getBooleanValue(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<boolean>;\n getStringValue(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<string>;\n getNumberValue(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<number>;\n getObjectValue(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<unknown>;\n getBooleanDetails?(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<boolean>>;\n getStringDetails?(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<string>>;\n getNumberDetails?(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<number>>;\n getObjectDetails?(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<unknown>>;\n}\n\nexport interface FlagshipFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"flagship\"`. */\n name?: string;\n}\n\n/**\n * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.\n *\n * A thin, honest wrapper: each contract method maps 1:1 onto the binding's\n * corresponding native method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and validated scalar evaluation context. Optional detail methods\n * preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on\n * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`\n * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns\n * the never-throw guarantee.\n *\n * Build the driver inside a provider factory with the native environment:\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),\n * });\n * ```\n *\n * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the\n * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a\n * bare driver.\n */\nexport class FlagshipFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly resolve: () => FlagshipBinding;\n\n constructor(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options: FlagshipFlagDriverOptions = {},\n ) {\n this.resolve = typeof binding === 'function' ? binding : () => binding;\n this.name = options.name ?? 'flagship';\n }\n\n getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean> {\n return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, nativeContext(ctx));\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));\n }\n getBooleanDetails(\n key: string,\n fallback: boolean,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<boolean>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getBooleanDetails\n ? binding.getBooleanDetails(key, fallback, context)\n : binding\n .getBooleanValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getStringDetails(\n key: string,\n fallback: string,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<string>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getStringDetails\n ? binding.getStringDetails(key, fallback, context)\n : binding\n .getStringValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getNumberDetails(\n key: string,\n fallback: number,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<number>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getNumberDetails\n ? binding.getNumberDetails(key, fallback, context)\n : binding\n .getNumberValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getObjectDetails(\n key: string,\n fallback: object,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<unknown>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getObjectDetails\n ? binding.getObjectDetails(key, fallback, context)\n : binding\n .getObjectValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n private async details<T>(\n key: string,\n fallback: T,\n ctx: FlagContext | undefined,\n read: (\n binding: FlagshipBinding,\n context: Record<string, string | number | boolean> | undefined,\n ) => Promise<NativeFlagDetails<T>>,\n ): Promise<FlagEvaluationDetails<T>> {\n let context: Record<string, string | number | boolean> | undefined;\n try {\n context = nativeContext(ctx);\n } catch {\n return { flagKey: key, value: fallback, reason: 'ERROR', errorCode: 'INVALID_CONTEXT' };\n }\n const details = await read(this.resolve(), context);\n return { ...details, reason: details.reason === undefined ? 'UNKNOWN' : details.reason };\n }\n}\n\n/** Convenience factory for {@link FlagshipFlagDriver}. */\nexport function flagshipFlagDriver(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options?: FlagshipFlagDriverOptions,\n): FlagshipFlagDriver {\n return new FlagshipFlagDriver(binding, options);\n}\n\n/** Copy only validated scalar attributes; never coerce nested or non-finite values. */\nfunction nativeContext(\n ctx: FlagContext | undefined,\n): Record<string, string | number | boolean> | undefined {\n if (ctx === undefined) return undefined;\n if (\n ctx === null ||\n typeof ctx !== 'object' ||\n Array.isArray(ctx) ||\n (Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null)\n )\n throw new TypeError('Invalid Flagship evaluation context');\n const entries: [string, string | number | boolean][] = [];\n for (const [key, value] of Object.entries(ctx)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'boolean' &&\n !(typeof value === 'number' && Number.isFinite(value))\n )\n throw new TypeError('Invalid Flagship evaluation context');\n entries.push([key, value]);\n }\n return Object.fromEntries(entries);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,IAAa,qBAAb,MAA6D;CAClD;CACQ;CAEjB,YACE,SACA,UAAqC,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,5 +1,5 @@
1
1
  import { kv } from "../bindings.js";
2
- //#region src/services/kv-cache.store.ts
2
+ // src/services/kv-cache.store.ts
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
@@ -102,7 +102,6 @@ function kvCacheInvalidation(ref) {
102
102
  const namespace = kv(ref);
103
103
  return (env) => new KVCacheInvalidationStore(() => namespace(env));
104
104
  }
105
- //#endregion
106
105
  export { KVCacheInvalidationStore, KVCacheStore, kvCache, kvCacheInvalidation };
107
106
 
108
107
  //# sourceMappingURL=kv-cache.store.js.map
@@ -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. 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;GA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,KAAK,WAAW;CACzB;CAEA,MAAM,WAAW,KAA8B;EAC7C,MAAM,QAAiB,MAAM,KAAK,GAAG,IAAI,KAAK,MAAM;EACpD,IAAI,UAAU,MAAM,OAAO;EAC3B,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,MACpE,MAAM,IAAI,UAAU,2BAA2B;EACjD,OAAO;CACT;CACA,MAAM,WAAW,KAA4B;EAC3C,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,CAAC,CAAC;CAC5D;AACF;;;;;;AAOA,SAAgB,QAAQ,KAAkD;CACxE,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,mBAAmB,UAAU,GAAG,CAAC;AACvD;;;;;;AAOA,SAAgB,oBAAoB,KAA8D;CAChG,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,+BAA+B,UAAU,GAAG,CAAC;AACnE"}
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. 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;CACzE;CACT,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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AAC;GACtE,SAAS,KAAK,gBAAgB,KAAA,IAAY,KAAK;EACjD,SAAS;CACX;AACF;;;;;;;AAQA,IAAa,2BAAb,MAAwE;CAC7D;CACT,YAAY,WAA8B;EACxC,KAAK,aAAa,YAAY,SAAS;CACzC;CAEA,IAAY,KAAkB;EAC5B,OAAO,KAAK,WAAW;CACzB;CAEA,MAAM,WAAW,KAA8B;EAC7C,MAAM,QAAiB,MAAM,KAAK,GAAG,IAAI,KAAK,MAAM;EACpD,IAAI,UAAU,MAAM,OAAO;EAC3B,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,MACpE,MAAM,IAAI,UAAU,2BAA2B;EACjD,OAAO;CACT;CACA,MAAM,WAAW,KAA4B;EAC3C,MAAM,KAAK,GAAG,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,CAAC,CAAC;CAC5D;AACF;;;;;;AAOA,SAAgB,QAAQ,KAAkD;CACxE,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,mBAAmB,UAAU,GAAG,CAAC;AACvD;;;;;;AAOA,SAAgB,oBAAoB,KAA8D;CAChG,MAAM,YAAY,GAAG,GAAG;CACxB,QAAQ,QAAQ,IAAI,+BAA+B,UAAU,GAAG,CAAC;AACnE"}
@@ -1,4 +1,4 @@
1
- //#region src/services/kv-flag.driver.ts
1
+ // src/services/kv-flag.driver.ts
2
2
  /**
3
3
  * Cloudflare KV-backed {@link FeatureFlagDriver}. Flags are stored as JSON
4
4
  * values under an optional key prefix and read with `get(key, 'json')`. Reads
@@ -56,7 +56,6 @@ var KvFlagDriver = class {
56
56
  function kvFlagDriver(kv, options) {
57
57
  return new KvFlagDriver(kv, options);
58
58
  }
59
- //#endregion
60
59
  export { KvFlagDriver, kvFlagDriver };
61
60
 
62
61
  //# sourceMappingURL=kv-flag.driver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"kv-flag.driver.js","names":[],"sources":["../../src/services/kv-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext } from '@velajs/feature-flags';\n\nexport interface KvFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"kv\"`. */\n name?: string;\n /** Prefix prepended to every flag key before the KV read. Default `\"\"` (none). */\n prefix?: string;\n}\n\n/**\n * Cloudflare KV-backed {@link FeatureFlagDriver}. Flags are stored as JSON\n * values under an optional key prefix and read with `get(key, 'json')`. Reads\n * are type-checked against the requested type: a missing key or a value of the\n * wrong JSON type returns the caller's `fallback`. KV has no targeting, so the\n * evaluation context is ignored.\n *\n * The driver stays honest — it does **not** swallow errors. A KV failure (or a\n * `SyntaxError` from a malformed stored value) propagates; the never-throw\n * guarantee lives in `@velajs/feature-flags`'s service layer.\n *\n * Placed like {@link KVCacheStore}: construct it in a wiring factory over a\n * resolved {@link KVNamespace}.\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [new KvFlagDriver(env.CACHE, { prefix: 'flag:' })] }),\n * });\n * ```\n */\nexport class KvFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly prefix: string;\n\n constructor(\n private readonly ns: KVNamespace,\n options: KvFlagDriverOptions = {},\n ) {\n this.name = options.name ?? 'kv';\n this.prefix = options.prefix ?? '';\n }\n\n getBoolean(key: string, fallback: boolean, _ctx?: FlagContext): Promise<boolean> {\n return this.read(key, fallback, (v) => typeof v === 'boolean');\n }\n\n getString(key: string, fallback: string, _ctx?: FlagContext): Promise<string> {\n return this.read(key, fallback, (v) => typeof v === 'string');\n }\n\n getNumber(key: string, fallback: number, _ctx?: FlagContext): Promise<number> {\n return this.read(key, fallback, (v) => typeof v === 'number');\n }\n\n getObject(key: string, fallback: object, _ctx?: FlagContext): Promise<unknown> {\n return this.read(key, fallback, (v) => typeof v === 'object' && v !== null);\n }\n\n /**\n * Reads and JSON-parses the (prefixed) key, returning the parsed value only\n * when `matches` accepts its type; otherwise the caller's fallback. A missing\n * key reads as `null` → fallback. Read/parse errors are left to propagate.\n */\n private async read<T>(\n key: string,\n fallback: T,\n matches: (value: unknown) => value is T,\n ): Promise<T> {\n const value = await this.ns.get(this.prefix + key, 'json');\n if (value === null || value === undefined) return fallback;\n return matches(value) ? value : fallback;\n }\n}\n\n/** Convenience factory for {@link KvFlagDriver}. */\nexport function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver {\n return new KvFlagDriver(kv, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,eAAb,MAAuD;CAKlC;CAJnB;CACA;CAEA,YACE,IACA,UAA+B,CAAC,GAChC;EAFiB,KAAA,KAAA;EAGjB,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,SAAS,QAAQ,UAAU;CAClC;CAEA,WAAW,KAAa,UAAmB,MAAsC;EAC/E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,SAAS;CAC/D;CAEA,UAAU,KAAa,UAAkB,MAAqC;EAC5E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,QAAQ;CAC9D;CAEA,UAAU,KAAa,UAAkB,MAAqC;EAC5E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,QAAQ;CAC9D;CAEA,UAAU,KAAa,UAAkB,MAAsC;EAC7E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,YAAY,MAAM,IAAI;CAC5E;;;;;;CAOA,MAAc,KACZ,KACA,UACA,SACY;EACZ,MAAM,QAAQ,MAAM,KAAK,GAAG,IAAI,KAAK,SAAS,KAAK,MAAM;EACzD,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;EAClD,OAAO,QAAQ,KAAK,IAAI,QAAQ;CAClC;AACF;;AAGA,SAAgB,aAAa,IAAiB,SAA6C;CACzF,OAAO,IAAI,aAAa,IAAI,OAAO;AACrC"}
1
+ {"version":3,"file":"kv-flag.driver.js","names":[],"sources":["../../src/services/kv-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext } from '@velajs/feature-flags';\n\nexport interface KvFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"kv\"`. */\n name?: string;\n /** Prefix prepended to every flag key before the KV read. Default `\"\"` (none). */\n prefix?: string;\n}\n\n/**\n * Cloudflare KV-backed {@link FeatureFlagDriver}. Flags are stored as JSON\n * values under an optional key prefix and read with `get(key, 'json')`. Reads\n * are type-checked against the requested type: a missing key or a value of the\n * wrong JSON type returns the caller's `fallback`. KV has no targeting, so the\n * evaluation context is ignored.\n *\n * The driver stays honest — it does **not** swallow errors. A KV failure (or a\n * `SyntaxError` from a malformed stored value) propagates; the never-throw\n * guarantee lives in `@velajs/feature-flags`'s service layer.\n *\n * Placed like {@link KVCacheStore}: construct it in a wiring factory over a\n * resolved {@link KVNamespace}.\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [new KvFlagDriver(env.CACHE, { prefix: 'flag:' })] }),\n * });\n * ```\n */\nexport class KvFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly prefix: string;\n\n constructor(\n private readonly ns: KVNamespace,\n options: KvFlagDriverOptions = {},\n ) {\n this.name = options.name ?? 'kv';\n this.prefix = options.prefix ?? '';\n }\n\n getBoolean(key: string, fallback: boolean, _ctx?: FlagContext): Promise<boolean> {\n return this.read(key, fallback, (v) => typeof v === 'boolean');\n }\n\n getString(key: string, fallback: string, _ctx?: FlagContext): Promise<string> {\n return this.read(key, fallback, (v) => typeof v === 'string');\n }\n\n getNumber(key: string, fallback: number, _ctx?: FlagContext): Promise<number> {\n return this.read(key, fallback, (v) => typeof v === 'number');\n }\n\n getObject(key: string, fallback: object, _ctx?: FlagContext): Promise<unknown> {\n return this.read(key, fallback, (v) => typeof v === 'object' && v !== null);\n }\n\n /**\n * Reads and JSON-parses the (prefixed) key, returning the parsed value only\n * when `matches` accepts its type; otherwise the caller's fallback. A missing\n * key reads as `null` → fallback. Read/parse errors are left to propagate.\n */\n private async read<T>(\n key: string,\n fallback: T,\n matches: (value: unknown) => value is T,\n ): Promise<T> {\n const value = await this.ns.get(this.prefix + key, 'json');\n if (value === null || value === undefined) return fallback;\n return matches(value) ? value : fallback;\n }\n}\n\n/** Convenience factory for {@link KvFlagDriver}. */\nexport function kvFlagDriver(kv: KVNamespace, options?: KvFlagDriverOptions): KvFlagDriver {\n return new KvFlagDriver(kv, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,eAAb,MAAuD;CAKlC;CAJV;CACQ;CAEjB,YACmB,IACjB,UAA+B,CAAC,GAChC;EAFiB,KAAA,KAAA;EAGjB,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,SAAS,QAAQ,UAAU;CAClC;CAEA,WAAW,KAAa,UAAmB,MAAsC;EAC/E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,SAAS;CAC/D;CAEA,UAAU,KAAa,UAAkB,MAAqC;EAC5E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,QAAQ;CAC9D;CAEA,UAAU,KAAa,UAAkB,MAAqC;EAC5E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,QAAQ;CAC9D;CAEA,UAAU,KAAa,UAAkB,MAAsC;EAC7E,OAAO,KAAK,KAAK,KAAK,WAAW,MAAM,OAAO,MAAM,YAAY,MAAM,IAAI;CAC5E;;;;;;CAOA,MAAc,KACZ,KACA,UACA,SACY;EACZ,MAAM,QAAQ,MAAM,KAAK,GAAG,IAAI,KAAK,SAAS,KAAK,MAAM;EACzD,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;EAClD,OAAO,QAAQ,KAAK,IAAI,QAAQ;CAClC;AACF;;AAGA,SAAgB,aAAa,IAAiB,SAA6C;CACzF,OAAO,IAAI,aAAa,IAAI,OAAO;AACrC"}
@@ -1,6 +1,6 @@
1
- import { r2 } from "../bindings.js";
2
1
  import { r2Driver } from "@velajs/storage/drivers/r2";
3
- //#region src/storage/r2-storage.ts
2
+ import { r2 } from "../bindings.js";
3
+ // src/storage/r2-storage.ts
4
4
  /**
5
5
  * The native R2 driver for `@velajs/storage`, reading its bucket from the
6
6
  * application's `ENV` by name:
@@ -24,7 +24,6 @@ function r2Storage(options) {
24
24
  bucket: bucket(env)
25
25
  });
26
26
  }
27
- //#endregion
28
27
  export { r2Storage };
29
28
 
30
29
  //# sourceMappingURL=r2-storage.js.map
package/dist/storage.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- import "./vela-env-DFvyoNT3.js";
1
+ import "./vela-env-5graXefc.js";
2
2
  import { EnvFactory } from "@velajs/vela/module-kit";
3
3
  import { StorageDriver } from "@velajs/storage";
4
4
  import { R2DriverOptions } from "@velajs/storage/drivers/r2";
5
- //#region src/storage/r2-storage.d.ts
6
5
  /** `r2Storage` options: the bucket's binding name and the native driver's settings. */
7
6
  interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {
8
7
  /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */
@@ -24,5 +23,4 @@ interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {
24
23
  * `http: { download: 'proxy' }` controller.
25
24
  */
26
25
  export declare function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>>;
27
- //#endregion
28
26
  export type { R2StorageOptions };
package/dist/storage.js CHANGED
@@ -1,2 +1 @@
1
- import { r2Storage } from "./storage/r2-storage.js";
2
- export { r2Storage };
1
+ export { r2Storage } from "./storage/r2-storage.js";
@@ -1,7 +1,7 @@
1
+ import { MetadataRegistry, registerEntrypointKind } from "@velajs/vela/module-kit";
1
2
  import { registerWorkerEvent } from "../worker-events.js";
2
3
  import { TAIL_METADATA, receiveTail } from "./tail-dispatch.js";
3
- import { MetadataRegistry, registerEntrypointKind } from "@velajs/vela/module-kit";
4
- //#region src/tail/on-tail.ts
4
+ // src/tail/on-tail.ts
5
5
  registerEntrypointKind({
6
6
  kind: "cf:tail",
7
7
  metaKey: TAIL_METADATA,
@@ -40,7 +40,6 @@ function OnTail() {
40
40
  MetadataRegistry.appendCustomClassMeta(target.constructor, TAIL_METADATA, { methodName: key });
41
41
  };
42
42
  }
43
- //#endregion
44
43
  export { OnTail };
45
44
 
46
45
  //# sourceMappingURL=on-tail.js.map
@@ -1,6 +1,6 @@
1
- import { entrypointInvoker, observedSettlement } from "../host/host-invoker.js";
2
1
  import { resolveErrorReporter } from "@velajs/vela/module-kit";
3
- //#region src/tail/tail-dispatch.ts
2
+ import { entrypointInvoker, observedSettlement } from "../host/host-invoker.js";
3
+ // src/tail/tail-dispatch.ts
4
4
  /** The metadata key `@OnTail()` records its handlers under (entrypoint kind `cf:tail`). */
5
5
  const TAIL_METADATA = "cloudflare:tail";
6
6
  function handlerName(meta) {
@@ -61,7 +61,6 @@ async function dispatchTail(application, events) {
61
61
  }
62
62
  }));
63
63
  }
64
- //#endregion
65
64
  export { TAIL_METADATA, dispatchTail, receiveTail };
66
65
 
67
66
  //# sourceMappingURL=tail-dispatch.js.map
package/dist/tail.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import "./vela-env-DFvyoNT3.js";
2
- import "./cloudflare-application-Dsscb3Mo.js";
1
+ import "./vela-env-5graXefc.js";
3
2
  import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
4
- //#region src/tail/on-tail.d.ts
3
+ import "./cloudflare-application-Zw9th_-h.js";
5
4
  /** A method decorator whose method receives a batch of Tail Workers events. */
6
5
  type OnTailDecorator = <Handler extends (events: TraceItem[]) => unknown>(target: object, key: string | symbol, descriptor: TypedPropertyDescriptor<Handler>) => void;
7
6
  /**
@@ -31,9 +30,6 @@ type OnTailDecorator = <Handler extends (events: TraceItem[]) => unknown>(target
31
30
  * retries the start.
32
31
  */
33
32
  export declare function OnTail(): OnTailDecorator;
34
- //#endregion
35
- //#region src/tail/tail-dispatch.d.ts
36
33
  /** The ExecutionContext guards, interceptors and filters receive around an `@OnTail()` handler. */
37
34
  type TailExecutionContext = EntrypointExecutionContext<'cf:tail'>;
38
- //#endregion
39
35
  export type { OnTailDecorator, TailExecutionContext };
package/dist/tail.js CHANGED
@@ -1,2 +1 @@
1
- import { OnTail } from "./tail/on-tail.js";
2
- export { OnTail };
1
+ export { OnTail } from "./tail/on-tail.js";
package/dist/testing.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- import "./vela-env-DFvyoNT3.js";
2
- import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
1
+ import "./vela-env-5graXefc.js";
3
2
  import { VelaEnv } from "@velajs/vela";
4
3
  import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
5
4
  import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
6
- //#region src/testing.d.ts
5
+ import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-Ab6XoKqO.js";
7
6
  export interface TestingWorkerOptions extends CloudflareWorkerOptions {
8
7
  /**
9
8
  * The Workers environment the application is built for and every event
@@ -96,6 +95,8 @@ export interface TestingEmailInit {
96
95
  readonly headers?: HeadersInit;
97
96
  /** The raw RFC 5322 message; built from the headers and `text` by default. */
98
97
  readonly raw?: string | Uint8Array;
98
+ /** What the message reports as `canBeForwarded`; `true` by default. */
99
+ readonly canBeForwarded?: boolean;
99
100
  }
100
101
  /**
101
102
  * An Email Workers message (`ForwardableEmailMessage`) for tests, in the
@@ -144,5 +145,4 @@ export declare function queueJob<const D extends QueueJobDefinition>(queue: stri
144
145
  export declare function queueJob(queue: string, job: string, data: unknown, options?: {
145
146
  id?: string;
146
147
  attempts?: number;
147
- }): TestingQueueMessage<QueueJob>;
148
- //#endregion
148
+ }): TestingQueueMessage<QueueJob>;
package/dist/testing.js CHANGED
@@ -1,12 +1,12 @@
1
+ import * as cloudflareTest from "cloudflare:test";
2
+ import { env } from "cloudflare:workers";
3
+ import { parseCronMetadata } from "@velajs/vela/module-kit";
4
+ import { Test } from "@velajs/testing";
1
5
  import { CloudflareApplication } from "./cloudflare-application.js";
2
6
  import { cloudflareCreateOptions, configureCloudflareApplication } from "./cloudflare-factory.js";
3
7
  import { dispatchEmail } from "./email/email-dispatch.js";
4
8
  import { dispatchTail } from "./tail/tail-dispatch.js";
5
- import { parseCronMetadata } from "@velajs/vela/module-kit";
6
- import { env } from "cloudflare:workers";
7
- import * as cloudflareTest from "cloudflare:test";
8
- import { Test } from "@velajs/testing";
9
- //#region src/testing.ts
9
+ // src/testing.ts
10
10
  const pool = cloudflareTest;
11
11
  /**
12
12
  * An Email Workers message (`ForwardableEmailMessage`) for tests, in the
@@ -36,6 +36,7 @@ function emailMessage(init) {
36
36
  to: init.to,
37
37
  headers,
38
38
  rawSize: bytes.byteLength,
39
+ canBeForwarded: init.canBeForwarded ?? true,
39
40
  raw: new ReadableStream({ start(controller) {
40
41
  controller.enqueue(bytes.slice());
41
42
  controller.close();
@@ -182,7 +183,6 @@ function queueJob(queue, job, data, { id = crypto.randomUUID(), attempts = 1 } =
182
183
  }
183
184
  };
184
185
  }
185
- //#endregion
186
186
  export { createTestingWorker, emailMessage, queueJob, traceItem };
187
187
 
188
188
  //# sourceMappingURL=testing.js.map
@@ -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 { 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,MAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;CACxC,IAAI,CAAC,QAAQ,IAAI,MAAM,GAAG,QAAQ,IAAI,QAAQ,KAAK,IAAI;CACvD,IAAI,CAAC,QAAQ,IAAI,IAAI,GAAG,QAAQ,IAAI,MAAM,KAAK,EAAE;CACjD,IAAI,KAAK,YAAY,KAAA,KAAa,CAAC,QAAQ,IAAI,SAAS,GAAG,QAAQ,IAAI,WAAW,KAAK,OAAO;CAC9F,MAAM,MACJ,KAAK,OACL,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,IAAI,OAAO,CAAC,CAAC,KAAK,MAAM,EAAE,UAAU,KAAK,QAAQ;CAClG,MAAM,QAAQ,OAAO,QAAQ,WAAW,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,IAAI;CACxE,IAAI;CACJ,MAAM,WAAoD,CAAC;CAC3D,MAAM,UAAuD,CAAC;CAC9D,OAAO;EACL,MAAM,KAAK;EACX,IAAI,KAAK;EACT;EACA,SAAS,MAAM;EACf,KAAK,IAAI,eAA2B,EAClC,MAAM,YAAY;GAChB,WAAW,QAAQ,MAAM,MAAM,CAAC;GAChC,WAAW,MAAM;EACnB,EACF,CAAC;EACD,IAAI,eAAe;GACjB,OAAO;EACT;EACA;EACA;EACA,UAAU,QAAsB;GAC9B,eAAe;EACjB;EACA,MAAM,QAAQ,QAAgB,gBAAoD;GAChF,SAAS,KACP,mBAAmB,KAAA,IAAY,EAAE,OAAO,IAAI;IAAE;IAAQ,SAAS;GAAe,CAChF;GACA,OAAO,EAAE,WAAW,WAA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AS,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":["env","workersEnv"],"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 /** What the message reports as `canBeForwarded`; `true` by default. */\n readonly canBeForwarded?: boolean;\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 canBeForwarded: init.canBeForwarded ?? true,\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;;;;;;;;;;;;;;AAyG9B,SAAgB,aAAa,MAA6C;CACxE,MAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;CACxC,IAAI,CAAC,Q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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"}
package/dist/tracing.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { CallHandler, ExecutionContext, NestInterceptor } from "@velajs/vela";
2
- //#region src/tracing.d.ts
3
2
  /**
4
3
  * Native Workers spans around awaited HTTP/RPC handler work. Register through
5
4
  * `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.
@@ -11,5 +10,4 @@ import { CallHandler, ExecutionContext, NestInterceptor } from "@velajs/vela";
11
10
  */
12
11
  export declare class CloudflareTracingInterceptor implements NestInterceptor {
13
12
  intercept(context: ExecutionContext, next: CallHandler): Promise<unknown>;
14
- }
15
- //#endregion
13
+ }