@velajs/cloudflare 1.33.0 → 1.35.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 (46) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +218 -4
  3. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +9 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +6 -0
  5. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +8 -0
  6. package/dist/bindings.js +25 -1
  7. package/dist/bindings.js.map +1 -1
  8. package/dist/{cloudflare-application-CXDy9C1R.d.ts → cloudflare-application-Dsscb3Mo.d.ts} +2 -2
  9. package/dist/cloudflare-application.js +1 -1
  10. package/dist/cloudflare-application.js.map +1 -1
  11. package/dist/{cloudflare-factory-CuFNUJJD.d.ts → cloudflare-factory-DM9CBvNH.d.ts} +5 -5
  12. package/dist/cloudflare-factory.js +1 -1
  13. package/dist/cloudflare-factory.js.map +1 -1
  14. package/dist/durable-objects.d.ts +1 -1
  15. package/dist/email.d.ts +1 -1
  16. package/dist/entrypoints.d.ts +1 -1
  17. package/dist/index.d.ts +76 -11
  18. package/dist/index.js +2 -2
  19. package/dist/pipelines.d.ts +20 -0
  20. package/dist/pipelines.js +87 -0
  21. package/dist/pipelines.js.map +1 -0
  22. package/dist/queue/cloudflare-queues.js +3 -3
  23. package/dist/queue/cloudflare-queues.js.map +1 -1
  24. package/dist/queue-events/consume.js +120 -0
  25. package/dist/queue-events/consume.js.map +1 -0
  26. package/dist/queue-events.d.ts +71 -0
  27. package/dist/queue-events.js +2 -0
  28. package/dist/queues.d.ts +1 -1
  29. package/dist/services/flagship-flag.driver.js +64 -6
  30. package/dist/services/flagship-flag.driver.js.map +1 -1
  31. package/dist/storage/r2-storage.js +1 -1
  32. package/dist/storage/r2-storage.js.map +1 -1
  33. package/dist/storage.d.ts +1 -1
  34. package/dist/tail.d.ts +1 -1
  35. package/dist/testing.d.ts +1 -1
  36. package/dist/tracing.d.ts +15 -0
  37. package/dist/tracing.js +24 -0
  38. package/dist/tracing.js.map +1 -0
  39. package/dist/workflow/portable-workflow-step.js +62 -0
  40. package/dist/workflow/portable-workflow-step.js.map +1 -0
  41. package/dist/workflow/vela-workflow-definition.js +78 -0
  42. package/dist/workflow/vela-workflow-definition.js.map +1 -0
  43. package/dist/workflow-definitions.d.ts +33 -0
  44. package/dist/workflow-definitions.js +2 -0
  45. package/dist/workflows.d.ts +1 -1
  46. package/package.json +32 -10
@@ -0,0 +1,120 @@
1
+ import { isStandardSchema, validateSchema } from "@velajs/vela/validation";
2
+ //#region src/queue-events/consume.ts
3
+ var QueueEventError = class extends Error {
4
+ code;
5
+ constructor(code, options) {
6
+ super(`Queue event ${code}`, options);
7
+ this.code = code;
8
+ this.name = "QueueEventError";
9
+ }
10
+ };
11
+ /** Successful siblings are already acknowledged; failures have requested native retries. */
12
+ var QueueEventsBatchError = class extends AggregateError {
13
+ failures;
14
+ constructor(failures) {
15
+ super(failures.map(({ error }) => error), `${failures.length} queue event(s) failed`);
16
+ this.failures = failures;
17
+ this.name = "QueueEventsBatchError";
18
+ }
19
+ };
20
+ const dispatch = Symbol("queue-event-dispatch");
21
+ function nonempty(value) {
22
+ return typeof value === "string" && value.trim().length > 0;
23
+ }
24
+ /** No module registration or global state: define handlers alongside their consuming provider. */
25
+ function defineQueueEvent(options) {
26
+ if (!nonempty(options.type) || !nonempty(options.source.type) || !Object.values(options.source).every(nonempty)) throw new TypeError("Queue event type and source expectations must be nonempty strings");
27
+ if (!isStandardSchema(options.schema)) throw new TypeError("Expected a Standard Schema validator");
28
+ const { type, schema, handle } = options;
29
+ const source = Object.entries(options.source);
30
+ return Object.freeze({
31
+ type,
32
+ async [dispatch](event, context) {
33
+ if (!source.every(([key, value]) => event.source[key] === value)) throw new QueueEventError("unexpected-source");
34
+ let payload;
35
+ try {
36
+ payload = await validateSchema(schema, event.payload);
37
+ } catch (cause) {
38
+ throw new QueueEventError("invalid-payload", { cause });
39
+ }
40
+ try {
41
+ await handle({
42
+ ...event,
43
+ payload
44
+ }, context);
45
+ } catch (cause) {
46
+ throw new QueueEventError("handler-failed", { cause });
47
+ }
48
+ }
49
+ });
50
+ }
51
+ function record(value) {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+ function parseEvent(value) {
55
+ if (!record(value) || !nonempty(value.type) || !record(value.source) || !nonempty(value.source.type) || !Object.hasOwn(value, "payload") || !record(value.metadata)) throw new QueueEventError("invalid-envelope");
56
+ const { source, metadata } = value;
57
+ if (!nonempty(metadata.accountId) || !nonempty(metadata.eventSubscriptionId) || !Number.isInteger(metadata.eventSchemaVersion) || !nonempty(metadata.eventTimestamp) || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(metadata.eventTimestamp) || !Number.isFinite(Date.parse(metadata.eventTimestamp)) || new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !== metadata.eventTimestamp.slice(0, 10)) throw new QueueEventError("invalid-envelope");
58
+ if (metadata.eventSchemaVersion !== 1) throw new QueueEventError("unsupported-version");
59
+ return {
60
+ type: value.type,
61
+ source: {
62
+ ...source,
63
+ type: value.source.type
64
+ },
65
+ payload: value.payload,
66
+ metadata: {
67
+ ...metadata,
68
+ accountId: metadata.accountId,
69
+ eventSubscriptionId: metadata.eventSubscriptionId,
70
+ eventSchemaVersion: 1,
71
+ eventTimestamp: metadata.eventTimestamp
72
+ }
73
+ };
74
+ }
75
+ /**
76
+ * Await each validated handler, then acknowledge that message. Every malformed,
77
+ * unmatched or failing message requests retry; all siblings are attempted before
78
+ * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.
79
+ * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
80
+ */
81
+ async function consumeQueueEvents(batch, options) {
82
+ if (!nonempty(options.queue) || !nonempty(options.accountId) || options.eventSubscriptionIds.length === 0 || !options.eventSubscriptionIds.every(nonempty)) throw new TypeError("Expected a physical queue, account and nonempty subscription allowlist");
83
+ if (batch.queue !== options.queue) throw new Error("Unexpected physical queue for platform events");
84
+ const handlers = /* @__PURE__ */ new Map();
85
+ for (const handler of options.handlers) {
86
+ if (handlers.has(handler.type)) throw new TypeError(`Duplicate queue event handler: ${handler.type}`);
87
+ handlers.set(handler.type, handler);
88
+ }
89
+ const accountId = options.accountId;
90
+ const subscriptions = new Set(options.eventSubscriptionIds);
91
+ const failures = [];
92
+ for (const message of batch.messages) {
93
+ try {
94
+ const event = parseEvent(message.body);
95
+ if (event.metadata.accountId !== accountId) throw new QueueEventError("unexpected-account");
96
+ if (!subscriptions.has(event.metadata.eventSubscriptionId)) throw new QueueEventError("unexpected-subscription");
97
+ const handler = handlers.get(event.type);
98
+ if (!handler) throw new QueueEventError("unhandled-type");
99
+ await handler[dispatch](event, {
100
+ queue: batch.queue,
101
+ messageId: message.id,
102
+ timestamp: message.timestamp,
103
+ attempts: message.attempts
104
+ });
105
+ } catch (error) {
106
+ message.retry();
107
+ failures.push({
108
+ messageId: message.id,
109
+ error: error instanceof QueueEventError ? error : new QueueEventError("handler-failed", { cause: error })
110
+ });
111
+ continue;
112
+ }
113
+ message.ack();
114
+ }
115
+ if (failures.length > 0) throw new QueueEventsBatchError(failures);
116
+ }
117
+ //#endregion
118
+ export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
119
+
120
+ //# sourceMappingURL=consume.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consume.js","names":[],"sources":["../../src/queue-events/consume.ts"],"sourcesContent":["import { isStandardSchema, validateSchema, type StandardSchemaV1 } from '@velajs/vela/validation';\n\nexport interface QueueEvent<Payload = unknown> {\n readonly type: string;\n readonly source: Readonly<Record<string, unknown>> & { readonly type: string };\n readonly payload: Payload;\n readonly metadata: Readonly<Record<string, unknown>> & {\n readonly accountId: string;\n readonly eventSubscriptionId: string;\n readonly eventSchemaVersion: 1;\n readonly eventTimestamp: string;\n };\n}\n\n/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */\nexport interface QueueEventContext {\n readonly queue: string;\n readonly messageId: string;\n readonly timestamp: Date;\n readonly attempts: number;\n}\n\nexport type QueueEventErrorCode =\n | 'invalid-envelope'\n | 'unsupported-version'\n | 'unexpected-account'\n | 'unexpected-subscription'\n | 'unhandled-type'\n | 'unexpected-source'\n | 'invalid-payload'\n | 'handler-failed';\n\nexport class QueueEventError extends Error {\n constructor(\n readonly code: QueueEventErrorCode,\n options?: ErrorOptions,\n ) {\n super(`Queue event ${code}`, options);\n this.name = 'QueueEventError';\n }\n}\n\nexport interface QueueEventFailure {\n readonly messageId: string;\n readonly error: QueueEventError;\n}\n\n/** Successful siblings are already acknowledged; failures have requested native retries. */\nexport class QueueEventsBatchError extends AggregateError {\n constructor(readonly failures: readonly QueueEventFailure[]) {\n super(\n failures.map(({ error }) => error),\n `${failures.length} queue event(s) failed`,\n );\n this.name = 'QueueEventsBatchError';\n }\n}\n\nexport interface QueueEventOptions<Payload> {\n /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */\n readonly type: string;\n /** Exact matches for source.type and any source selectors required by the application. */\n readonly source: Readonly<Record<string, string>> & { readonly type: string };\n readonly schema: StandardSchemaV1<unknown, Payload>;\n readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;\n}\n\nconst dispatch = Symbol('queue-event-dispatch');\n\n/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */\nexport interface QueueEventHandler {\n readonly type: string;\n readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/** No module registration or global state: define handlers alongside their consuming provider. */\nexport function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler {\n if (\n !nonempty(options.type) ||\n !nonempty(options.source.type) ||\n !Object.values(options.source).every(nonempty)\n ) {\n throw new TypeError('Queue event type and source expectations must be nonempty strings');\n }\n if (!isStandardSchema(options.schema))\n throw new TypeError('Expected a Standard Schema validator');\n const { type, schema, handle } = options;\n const source = Object.entries(options.source);\n return Object.freeze({\n type,\n async [dispatch](event: QueueEvent, context: QueueEventContext) {\n if (!source.every(([key, value]) => event.source[key] === value)) {\n throw new QueueEventError('unexpected-source');\n }\n let payload: Payload;\n try {\n payload = await validateSchema(schema, event.payload);\n } catch (cause) {\n throw new QueueEventError('invalid-payload', { cause });\n }\n try {\n await handle({ ...event, payload }, context);\n } catch (cause) {\n throw new QueueEventError('handler-failed', { cause });\n }\n },\n });\n}\n\nexport interface ConsumeQueueEventsOptions {\n /** Dedicated physical queue name, also claimed by @QueueConsumer. */\n readonly queue: string;\n readonly accountId: string;\n readonly eventSubscriptionIds: readonly string[];\n /** One handler per exact event type; each may require source selectors. */\n readonly handlers: readonly QueueEventHandler[];\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseEvent(value: unknown): QueueEvent {\n if (\n !record(value) ||\n !nonempty(value.type) ||\n !record(value.source) ||\n !nonempty(value.source.type) ||\n !Object.hasOwn(value, 'payload') ||\n !record(value.metadata)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n const { source, metadata } = value;\n if (\n !nonempty(metadata.accountId) ||\n !nonempty(metadata.eventSubscriptionId) ||\n !Number.isInteger(metadata.eventSchemaVersion) ||\n !nonempty(metadata.eventTimestamp) ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(\n metadata.eventTimestamp,\n ) ||\n !Number.isFinite(Date.parse(metadata.eventTimestamp)) ||\n // Date.parse normalizes impossible dates such as February 30. Reject those too.\n new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !==\n metadata.eventTimestamp.slice(0, 10)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n if (metadata.eventSchemaVersion !== 1) throw new QueueEventError('unsupported-version');\n return {\n type: value.type,\n source: { ...source, type: value.source.type },\n payload: value.payload,\n metadata: {\n ...metadata,\n accountId: metadata.accountId,\n eventSubscriptionId: metadata.eventSubscriptionId,\n eventSchemaVersion: 1,\n eventTimestamp: metadata.eventTimestamp,\n },\n };\n}\n\n/**\n * Await each validated handler, then acknowledge that message. Every malformed,\n * unmatched or failing message requests retry; all siblings are attempted before\n * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.\n * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.\n */\nexport async function consumeQueueEvents(\n batch: MessageBatch<unknown>,\n options: ConsumeQueueEventsOptions,\n): Promise<void> {\n if (\n !nonempty(options.queue) ||\n !nonempty(options.accountId) ||\n options.eventSubscriptionIds.length === 0 ||\n !options.eventSubscriptionIds.every(nonempty)\n ) {\n throw new TypeError('Expected a physical queue, account and nonempty subscription allowlist');\n }\n if (batch.queue !== options.queue)\n throw new Error('Unexpected physical queue for platform events');\n const handlers = new Map<string, QueueEventHandler>();\n for (const handler of options.handlers) {\n if (handlers.has(handler.type))\n throw new TypeError(`Duplicate queue event handler: ${handler.type}`);\n handlers.set(handler.type, handler);\n }\n const accountId = options.accountId;\n const subscriptions = new Set(options.eventSubscriptionIds);\n const failures: QueueEventFailure[] = [];\n for (const message of batch.messages) {\n try {\n const event = parseEvent(message.body);\n if (event.metadata.accountId !== accountId) throw new QueueEventError('unexpected-account');\n if (!subscriptions.has(event.metadata.eventSubscriptionId))\n throw new QueueEventError('unexpected-subscription');\n const handler = handlers.get(event.type);\n if (!handler) throw new QueueEventError('unhandled-type');\n await handler[dispatch](event, {\n queue: batch.queue,\n messageId: message.id,\n timestamp: message.timestamp,\n attempts: message.attempts,\n });\n } catch (error) {\n message.retry();\n failures.push({\n messageId: message.id,\n error:\n error instanceof QueueEventError\n ? error\n : new QueueEventError('handler-failed', { cause: error }),\n });\n continue;\n }\n message.ack();\n }\n if (failures.length > 0) throw new QueueEventsBatchError(failures);\n}\n"],"mappings":";;AAgCA,IAAa,kBAAb,cAAqC,MAAM;CAE9B;CADX,YACE,MACA,SACA;EACA,MAAM,eAAe,QAAQ,OAAO;EAH3B,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CACnC;CAArB,YAAY,UAAiD;EAC3D,MACE,SAAS,KAAK,EAAE,YAAY,KAAK,GACjC,GAAG,SAAS,OAAO,uBACrB;EAJmB,KAAA,WAAA;EAKnB,KAAK,OAAO;CACd;AACF;AAWA,MAAM,WAAW,OAAO,sBAAsB;AAQ9C,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;AAGA,SAAgB,iBAA0B,SAAwD;CAChG,IACE,CAAC,SAAS,QAAQ,IAAI,KACtB,CAAC,SAAS,QAAQ,OAAO,IAAI,KAC7B,CAAC,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,MAAM,QAAQ,GAE7C,MAAM,IAAI,UAAU,mEAAmE;CAEzF,IAAI,CAAC,iBAAiB,QAAQ,MAAM,GAClC,MAAM,IAAI,UAAU,sCAAsC;CAC5D,MAAM,EAAE,MAAM,QAAQ,WAAW;CACjC,MAAM,SAAS,OAAO,QAAQ,QAAQ,MAAM;CAC5C,OAAO,OAAO,OAAO;EACnB;EACA,OAAO,UAAU,OAAmB,SAA4B;GAC9D,IAAI,CAAC,OAAO,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,SAAS,KAAK,GAC7D,MAAM,IAAI,gBAAgB,mBAAmB;GAE/C,IAAI;GACJ,IAAI;IACF,UAAU,MAAM,eAAe,QAAQ,MAAM,OAAO;GACtD,SAAS,OAAO;IACd,MAAM,IAAI,gBAAgB,mBAAmB,EAAE,MAAM,CAAC;GACxD;GACA,IAAI;IACF,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GAAG,MAAM,IAAI,sBAAsB,QAAQ;AACnE"}
@@ -0,0 +1,71 @@
1
+ import { StandardSchemaV1 } from "@velajs/vela/validation";
2
+ //#region src/queue-events/consume.d.ts
3
+ interface QueueEvent<Payload = unknown> {
4
+ readonly type: string;
5
+ readonly source: Readonly<Record<string, unknown>> & {
6
+ readonly type: string;
7
+ };
8
+ readonly payload: Payload;
9
+ readonly metadata: Readonly<Record<string, unknown>> & {
10
+ readonly accountId: string;
11
+ readonly eventSubscriptionId: string;
12
+ readonly eventSchemaVersion: 1;
13
+ readonly eventTimestamp: string;
14
+ };
15
+ }
16
+ /** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */
17
+ interface QueueEventContext {
18
+ readonly queue: string;
19
+ readonly messageId: string;
20
+ readonly timestamp: Date;
21
+ readonly attempts: number;
22
+ }
23
+ type QueueEventErrorCode = 'invalid-envelope' | 'unsupported-version' | 'unexpected-account' | 'unexpected-subscription' | 'unhandled-type' | 'unexpected-source' | 'invalid-payload' | 'handler-failed';
24
+ export declare class QueueEventError extends Error {
25
+ readonly code: QueueEventErrorCode;
26
+ constructor(code: QueueEventErrorCode, options?: ErrorOptions);
27
+ }
28
+ interface QueueEventFailure {
29
+ readonly messageId: string;
30
+ readonly error: QueueEventError;
31
+ }
32
+ /** Successful siblings are already acknowledged; failures have requested native retries. */
33
+ export declare class QueueEventsBatchError extends AggregateError {
34
+ readonly failures: readonly QueueEventFailure[];
35
+ constructor(failures: readonly QueueEventFailure[]);
36
+ }
37
+ interface QueueEventOptions<Payload> {
38
+ /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */
39
+ readonly type: string;
40
+ /** Exact matches for source.type and any source selectors required by the application. */
41
+ readonly source: Readonly<Record<string, string>> & {
42
+ readonly type: string;
43
+ };
44
+ readonly schema: StandardSchemaV1<unknown, Payload>;
45
+ readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;
46
+ }
47
+ declare const dispatch: unique symbol;
48
+ /** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */
49
+ interface QueueEventHandler {
50
+ readonly type: string;
51
+ readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;
52
+ }
53
+ /** No module registration or global state: define handlers alongside their consuming provider. */
54
+ export declare function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler;
55
+ interface ConsumeQueueEventsOptions {
56
+ /** Dedicated physical queue name, also claimed by @QueueConsumer. */
57
+ readonly queue: string;
58
+ readonly accountId: string;
59
+ readonly eventSubscriptionIds: readonly string[];
60
+ /** One handler per exact event type; each may require source selectors. */
61
+ readonly handlers: readonly QueueEventHandler[];
62
+ }
63
+ /**
64
+ * Await each validated handler, then acknowledge that message. Every malformed,
65
+ * unmatched or failing message requests retry; all siblings are attempted before
66
+ * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.
67
+ * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
68
+ */
69
+ export declare function consumeQueueEvents(batch: MessageBatch<unknown>, options: ConsumeQueueEventsOptions): Promise<void>;
70
+ //#endregion
71
+ export type { ConsumeQueueEventsOptions, QueueEvent, QueueEventContext, QueueEventErrorCode, QueueEventFailure, QueueEventHandler, QueueEventOptions };
@@ -0,0 +1,2 @@
1
+ import { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent } from "./queue-events/consume.js";
2
+ export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
package/dist/queues.d.ts CHANGED
@@ -11,7 +11,7 @@ interface CloudflareQueueProducer {
11
11
  *
12
12
  * ```ts
13
13
  * QueueModule.forRoot({ driver: cloudflareQueues() })
14
- * QueueModule.registerQueue({ name: 'email', binding: 'EMAIL_QUEUE' })
14
+ * QueueModule.forFeature([{ name: 'email', binding: 'EMAIL_QUEUE' }])
15
15
  * ```
16
16
  *
17
17
  * Each application gets its own driver. Producing reads the registered binding
@@ -3,8 +3,9 @@
3
3
  * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
4
4
  *
5
5
  * A thin, honest wrapper: each contract method maps 1:1 onto the binding's
6
- * corresponding value method, forwarding the caller's `fallback` (the binding's
7
- * `defaultValue`) and evaluation context. The binding resolves the fallback on
6
+ * corresponding native method, forwarding the caller's `fallback` (the binding's
7
+ * `defaultValue`) and validated scalar evaluation context. Optional detail methods
8
+ * preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on
8
9
  * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`
9
10
  * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
10
11
  * the never-throw guarantee.
@@ -30,22 +31,79 @@ var FlagshipFlagDriver = class {
30
31
  this.name = options.name ?? "flagship";
31
32
  }
32
33
  getBoolean(key, fallback, ctx) {
33
- return this.resolve().getBooleanValue(key, fallback, ctx);
34
+ return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));
34
35
  }
35
36
  getString(key, fallback, ctx) {
36
- return this.resolve().getStringValue(key, fallback, ctx);
37
+ return this.resolve().getStringValue(key, fallback, nativeContext(ctx));
37
38
  }
38
39
  getNumber(key, fallback, ctx) {
39
- return this.resolve().getNumberValue(key, fallback, ctx);
40
+ return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));
40
41
  }
41
42
  getObject(key, fallback, ctx) {
42
- return this.resolve().getObjectValue(key, fallback, ctx);
43
+ return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));
44
+ }
45
+ getBooleanDetails(key, fallback, ctx) {
46
+ return this.details(key, fallback, ctx, (binding, context) => binding.getBooleanDetails ? binding.getBooleanDetails(key, fallback, context) : binding.getBooleanValue(key, fallback, context).then((value) => ({
47
+ flagKey: key,
48
+ value,
49
+ reason: "UNKNOWN"
50
+ })));
51
+ }
52
+ getStringDetails(key, fallback, ctx) {
53
+ return this.details(key, fallback, ctx, (binding, context) => binding.getStringDetails ? binding.getStringDetails(key, fallback, context) : binding.getStringValue(key, fallback, context).then((value) => ({
54
+ flagKey: key,
55
+ value,
56
+ reason: "UNKNOWN"
57
+ })));
58
+ }
59
+ getNumberDetails(key, fallback, ctx) {
60
+ return this.details(key, fallback, ctx, (binding, context) => binding.getNumberDetails ? binding.getNumberDetails(key, fallback, context) : binding.getNumberValue(key, fallback, context).then((value) => ({
61
+ flagKey: key,
62
+ value,
63
+ reason: "UNKNOWN"
64
+ })));
65
+ }
66
+ getObjectDetails(key, fallback, ctx) {
67
+ return this.details(key, fallback, ctx, (binding, context) => binding.getObjectDetails ? binding.getObjectDetails(key, fallback, context) : binding.getObjectValue(key, fallback, context).then((value) => ({
68
+ flagKey: key,
69
+ value,
70
+ reason: "UNKNOWN"
71
+ })));
72
+ }
73
+ async details(key, fallback, ctx, read) {
74
+ let context;
75
+ try {
76
+ context = nativeContext(ctx);
77
+ } catch {
78
+ return {
79
+ flagKey: key,
80
+ value: fallback,
81
+ reason: "ERROR",
82
+ errorCode: "INVALID_CONTEXT"
83
+ };
84
+ }
85
+ const details = await read(this.resolve(), context);
86
+ return {
87
+ ...details,
88
+ reason: details.reason === void 0 ? "UNKNOWN" : details.reason
89
+ };
43
90
  }
44
91
  };
45
92
  /** Convenience factory for {@link FlagshipFlagDriver}. */
46
93
  function flagshipFlagDriver(binding, options) {
47
94
  return new FlagshipFlagDriver(binding, options);
48
95
  }
96
+ /** Copy only validated scalar attributes; never coerce nested or non-finite values. */
97
+ function nativeContext(ctx) {
98
+ if (ctx === void 0) return void 0;
99
+ if (ctx === null || typeof ctx !== "object" || Array.isArray(ctx) || Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null) throw new TypeError("Invalid Flagship evaluation context");
100
+ const entries = [];
101
+ for (const [key, value] of Object.entries(ctx)) {
102
+ if (typeof value !== "string" && typeof value !== "boolean" && !(typeof value === "number" && Number.isFinite(value))) throw new TypeError("Invalid Flagship evaluation context");
103
+ entries.push([key, value]);
104
+ }
105
+ return Object.fromEntries(entries);
106
+ }
49
107
  //#endregion
50
108
  export { FlagshipFlagDriver, flagshipFlagDriver };
51
109
 
@@ -1 +1 @@
1
- {"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — the four typed value methods. 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 */\nexport interface FlagshipBinding {\n getBooleanValue(key: string, defaultValue: boolean, context?: FlagContext): Promise<boolean>;\n getStringValue(key: string, defaultValue: string, context?: FlagContext): Promise<string>;\n getNumberValue(key: string, defaultValue: number, context?: FlagContext): Promise<number>;\n getObjectValue(key: string, defaultValue: object, context?: FlagContext): Promise<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 value method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and evaluation context. 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, ctx);\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, ctx);\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, ctx);\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, ctx);\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,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,GAAG;CAC1D;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;CAEA,UAAU,KAAa,UAAkB,KAAqC;EAC5E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;AACF;;AAGA,SAAgB,mBACd,SACA,SACoB;CACpB,OAAO,IAAI,mBAAmB,SAAS,OAAO;AAChD"}
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;EAC5E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,cAAc,GAAG,CAAC;CACxE;CACA,kBACE,KACA,UACA,KACyC;EACzC,OAAO,KAAK,QAAQ,KAAK,UAAU,MAAM,SAAS,YAChD,QAAQ,oBACJ,QAAQ,kBAAkB,KAAK,UAAU,OAAO,IAChD,QACG,gBAAgB,KAAK,UA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,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"}
@@ -6,7 +6,7 @@ import { r2Driver } from "@velajs/storage/drivers/r2";
6
6
  * application's `ENV` by name:
7
7
  *
8
8
  * ```ts
9
- * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
9
+ * StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) })
10
10
  * ```
11
11
  *
12
12
  * `StorageModule` builds the driver on the first storage operation of each
@@ -1 +1 @@
1
- {"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })\n * ```\n *\n * `StorageModule` builds the driver on the first storage operation of each\n * application, so a static module graph serves every environment and boot\n * touches no binding. A missing or mistyped binding fails that operation with\n * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot\n * presign uploads; serve downloads through `publicBaseUrl` or the module's\n * `http: { download: 'proxy' }` controller.\n */\nexport function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>> {\n const { binding, ...driver } = options;\n const bucket = r2({ binding });\n return (env) => r2Driver({ ...driver, bucket: bucket(env) });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAgB,UAAU,SAAgE;CACxF,MAAM,EAAE,SAAS,GAAG,WAAW;CAC/B,MAAM,SAAS,GAAG,EAAE,QAAQ,CAAC;CAC7B,QAAQ,QAAQ,SAAS;EAAE,GAAG;EAAQ,QAAQ,OAAO,GAAG;CAAE,CAAC;AAC7D"}
1
+ {"version":3,"file":"r2-storage.js","names":[],"sources":["../../src/storage/r2-storage.ts"],"sourcesContent":["import type { EnvFactory } from '@velajs/vela/module-kit';\nimport type { StorageDriver } from '@velajs/storage';\nimport { r2Driver, type R2DriverOptions } from '@velajs/storage/drivers/r2';\nimport { r2 } from '../bindings';\n\n/** `r2Storage` options: the bucket's binding name and the native driver's settings. */\nexport interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {\n /** The bucket's binding name, declared under `r2_buckets` in the Wrangler configuration. */\n binding: string;\n}\n\n/**\n * The native R2 driver for `@velajs/storage`, reading its bucket from the\n * application's `ENV` by name:\n *\n * ```ts\n * StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) })\n * ```\n *\n * `StorageModule` builds the driver on the first storage operation of each\n * application, so a static module graph serves every environment and boot\n * touches no binding. A missing or mistyped binding fails that operation with\n * a message naming the binding and `r2_buckets`. Like `r2Driver`, it cannot\n * presign uploads; serve downloads through `publicBaseUrl` or the module's\n * `http: { download: 'proxy' }` controller.\n */\nexport function r2Storage(options: R2StorageOptions): EnvFactory<StorageDriver<R2Bucket>> {\n const { binding, ...driver } = options;\n const bucket = r2({ binding });\n return (env) => r2Driver({ ...driver, bucket: bucket(env) });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAgB,UAAU,SAAgE;CACxF,MAAM,EAAE,SAAS,GAAG,WAAW;CAC/B,MAAM,SAAS,GAAG,EAAE,QAAQ,CAAC;CAC7B,QAAQ,QAAQ,SAAS;EAAE,GAAG;EAAQ,QAAQ,OAAO,GAAG;CAAE,CAAC;AAC7D"}
package/dist/storage.d.ts CHANGED
@@ -13,7 +13,7 @@ interface R2StorageOptions extends Omit<R2DriverOptions, 'bucket'> {
13
13
  * application's `ENV` by name:
14
14
  *
15
15
  * ```ts
16
- * StorageModule.forRoot({ driver: r2Storage({ binding: 'UPLOADS' }) })
16
+ * StorageModule.register({ driver: r2Storage({ binding: 'UPLOADS' }) })
17
17
  * ```
18
18
  *
19
19
  * `StorageModule` builds the driver on the first storage operation of each
package/dist/tail.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import "./cloudflare-application-CXDy9C1R.js";
2
+ import "./cloudflare-application-Dsscb3Mo.js";
3
3
  import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
4
4
  //#region src/tail/on-tail.d.ts
5
5
  /** A method decorator whose method receives a batch of Tail Workers events. */
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./vela-env-DFvyoNT3.js";
2
- import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-CuFNUJJD.js";
2
+ import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
3
3
  import { VelaEnv } from "@velajs/vela";
4
4
  import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
5
5
  import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
@@ -0,0 +1,15 @@
1
+ import { CallHandler, ExecutionContext, NestInterceptor } from "@velajs/vela";
2
+ //#region src/tracing.d.ts
3
+ /**
4
+ * Native Workers spans around awaited HTTP/RPC handler work. Register through
5
+ * `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.
6
+ *
7
+ * The callback establishes the native async parent for inner interceptors,
8
+ * handler code and awaited platform calls. Guards/pipes run before it; response
9
+ * streams, deferred work and scope disposal can outlive it. Cloudflare owns
10
+ * sampling, ending and export. This is not a portable Telemetry recorder.
11
+ */
12
+ export declare class CloudflareTracingInterceptor implements NestInterceptor {
13
+ intercept(context: ExecutionContext, next: CallHandler): Promise<unknown>;
14
+ }
15
+ //#endregion
@@ -0,0 +1,24 @@
1
+ import __decorate from "./_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
2
+ import { Injectable } from "@velajs/vela";
3
+ import { tracing } from "cloudflare:workers";
4
+ //#region src/tracing.ts
5
+ const MAX_LABEL_LENGTH = 128;
6
+ let CloudflareTracingInterceptor = class CloudflareTracingInterceptor {
7
+ intercept(context, next) {
8
+ const kind = context.getType();
9
+ if (kind !== "http" && kind !== "rpc") return next.handle();
10
+ return tracing.enterSpan(kind === "http" ? "vela.http.handler" : "vela.rpc.handler", (span) => {
11
+ if (span.isTraced) {
12
+ span.setAttribute("vela.handler.class", context.getClass().name.slice(0, MAX_LABEL_LENGTH));
13
+ const method = context.getHandlerName();
14
+ if (typeof method === "string") span.setAttribute("vela.handler.method", method.slice(0, MAX_LABEL_LENGTH));
15
+ }
16
+ return next.handle();
17
+ });
18
+ }
19
+ };
20
+ CloudflareTracingInterceptor = __decorate([Injectable()], CloudflareTracingInterceptor);
21
+ //#endregion
22
+ export { CloudflareTracingInterceptor };
23
+
24
+ //# sourceMappingURL=tracing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing.js","names":[],"sources":["../src/tracing.ts"],"sourcesContent":["import { tracing } from 'cloudflare:workers';\nimport {\n Injectable,\n type CallHandler,\n type ExecutionContext,\n type NestInterceptor,\n} from '@velajs/vela';\n\nconst MAX_LABEL_LENGTH = 128;\n\n/**\n * Native Workers spans around awaited HTTP/RPC handler work. Register through\n * `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.\n *\n * The callback establishes the native async parent for inner interceptors,\n * handler code and awaited platform calls. Guards/pipes run before it; response\n * streams, deferred work and scope disposal can outlive it. Cloudflare owns\n * sampling, ending and export. This is not a portable Telemetry recorder.\n */\n@Injectable()\nexport class CloudflareTracingInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Promise<unknown> {\n const kind = context.getType();\n if (kind !== 'http' && kind !== 'rpc') return next.handle();\n\n return tracing.enterSpan(kind === 'http' ? 'vela.http.handler' : 'vela.rpc.handler', (span) => {\n if (span.isTraced) {\n span.setAttribute('vela.handler.class', context.getClass().name.slice(0, MAX_LABEL_LENGTH));\n const method = context.getHandlerName();\n // Symbol descriptions may contain caller data; only declared string\n // method names belong in these fixed, bounded instrumentation labels.\n if (typeof method === 'string') {\n span.setAttribute('vela.handler.method', method.slice(0, MAX_LABEL_LENGTH));\n }\n }\n // Return the actual handler promise from INSIDE enterSpan. Starting a\n // span in an onStart observer would lose native parent-child nesting.\n return next.handle();\n });\n }\n}\n"],"mappings":";;;;AAQA,MAAM,mBAAmB;AAYlB,IAAM,+BAAN,MAAM,6BAAwD;CACnE,UAAU,SAA2B,MAAqC;EACxE,MAAM,OAAO,QAAQ,QAAQ;EAC7B,IAAI,SAAS,UAAU,SAAS,OAAO,OAAO,KAAK,OAAO;EAE1D,OAAO,QAAQ,UAAU,SAAS,SAAS,sBAAsB,qBAAqB,SAAS;GAC7F,IAAI,KAAK,UAAU;IACjB,KAAK,aAAa,sBAAsB,QAAQ,SAAS,CAAC,CAAC,KAAK,MAAM,GAAG,gBAAgB,CAAC;IAC1F,MAAM,SAAS,QAAQ,eAAe;IAGtC,IAAI,OAAO,WAAW,UACpB,KAAK,aAAa,uBAAuB,OAAO,MAAM,GAAG,gBAAgB,CAAC;GAE9E;GAGA,OAAO,KAAK,OAAO;EACrB,CAAC;CACH;AACF;AArBC,+BAAA,WAAA,CAAA,WAAW,CAAA,GAAA,4BAAA"}
@@ -0,0 +1,62 @@
1
+ import { NonRetryableError } from "cloudflare:workflows";
2
+ import { convertNonRetryableError } from "@velajs/workflow";
3
+ //#region src/workflow/portable-workflow-step.ts
4
+ function duration(value) {
5
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
6
+ if (typeof value === "string" && /^\d+(?:\.\d+)? (?:second|minute|hour|day|week|month|year)s?$/.test(value)) return value;
7
+ throw new NonRetryableError("Invalid Workflow duration.");
8
+ }
9
+ function config(value) {
10
+ if (value.retries && (!Number.isInteger(value.retries.limit) || value.retries.limit < 0)) throw new NonRetryableError("Workflow retries.limit must be a nonnegative integer.");
11
+ return {
12
+ ...value.timeout !== void 0 ? { timeout: duration(value.timeout) } : {},
13
+ ...value.retries ? { retries: {
14
+ ...value.retries,
15
+ delay: duration(value.retries.delay ?? 1e4)
16
+ } } : {}
17
+ };
18
+ }
19
+ /** Translate at callback boundaries, before the engine decides whether a failure should retry. */
20
+ function portableWorkflowStep(native) {
21
+ async function run(name, second, third, fourth) {
22
+ const callback = typeof second === "function" ? second : third;
23
+ if (typeof callback !== "function") throw new TypeError("Workflow step.do requires a callback.");
24
+ const declaredRollback = typeof second === "function" ? third : fourth;
25
+ const rollback = typeof declaredRollback === "object" ? declaredRollback : void 0;
26
+ const forward = async (context) => {
27
+ try {
28
+ return await callback(context);
29
+ } catch (error) {
30
+ return convertNonRetryableError(error, NonRetryableError);
31
+ }
32
+ };
33
+ let rollbackOptions;
34
+ if (rollback?.rollback) {
35
+ const undo = rollback.rollback;
36
+ rollbackOptions = {
37
+ rollback: async (context) => {
38
+ try {
39
+ await undo(context);
40
+ } catch (error) {
41
+ convertNonRetryableError(error, NonRetryableError);
42
+ }
43
+ },
44
+ ...rollback.rollbackConfig ? { rollbackConfig: config(rollback.rollbackConfig) } : {}
45
+ };
46
+ } else if (rollback?.rollbackConfig) throw new NonRetryableError("Workflow rollbackConfig requires a rollback handler.");
47
+ return typeof second === "function" ? native.do(name, forward, rollbackOptions) : native.do(name, config(second), forward, rollbackOptions);
48
+ }
49
+ return {
50
+ do: run,
51
+ sleep: (name, value) => native.sleep(name, duration(value)),
52
+ sleepUntil: (name, timestamp) => native.sleepUntil(name, timestamp),
53
+ waitForEvent: (name, options) => native.waitForEvent(name, {
54
+ type: options.type,
55
+ ...options.timeout !== void 0 ? { timeout: duration(options.timeout) } : {}
56
+ })
57
+ };
58
+ }
59
+ //#endregion
60
+ export { portableWorkflowStep };
61
+
62
+ //# sourceMappingURL=portable-workflow-step.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portable-workflow-step.js","names":[],"sources":["../../src/workflow/portable-workflow-step.ts"],"sourcesContent":["import type { WorkflowSleepDuration, WorkflowStep, WorkflowStepConfig } from 'cloudflare:workers';\nimport { NonRetryableError } from 'cloudflare:workflows';\nimport {\n convertNonRetryableError,\n type WorkflowStepConfigLike,\n type WorkflowStepContextLike,\n type WorkflowStepLike,\n type WorkflowStepRollbackOptionsLike,\n} from '@velajs/workflow';\n\nfunction duration(value: string | number): WorkflowSleepDuration {\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value;\n if (\n typeof value === 'string' &&\n /^\\d+(?:\\.\\d+)? (?:second|minute|hour|day|week|month|year)s?$/.test(value)\n )\n return value as WorkflowSleepDuration;\n throw new NonRetryableError('Invalid Workflow duration.');\n}\n\nfunction config(value: WorkflowStepConfigLike): WorkflowStepConfigLike & WorkflowStepConfig {\n if (value.retries && (!Number.isInteger(value.retries.limit) || value.retries.limit < 0))\n throw new NonRetryableError('Workflow retries.limit must be a nonnegative integer.');\n return {\n ...(value.timeout !== undefined ? { timeout: duration(value.timeout) } : {}),\n ...(value.retries\n ? {\n retries: {\n ...value.retries,\n // Cloudflare's default delay is ten seconds. The portable contract permits omission.\n delay: duration(value.retries.delay ?? 10_000),\n },\n }\n : {}),\n };\n}\n\n/** Translate at callback boundaries, before the engine decides whether a failure should retry. */\nexport function portableWorkflowStep(native: WorkflowStep): WorkflowStepLike {\n // Portable result types are unconstrained. Native checkpoint serialization remains\n // authoritative and rejects unsupported values; only this call boundary erases that constraint.\n async function run<T>(\n name: string,\n second: WorkflowStepConfigLike | ((context: WorkflowStepContextLike) => Promise<T>),\n third?: ((context: WorkflowStepContextLike) => Promise<T>) | WorkflowStepRollbackOptionsLike<T>,\n fourth?: WorkflowStepRollbackOptionsLike<T>,\n ): Promise<T> {\n const callback = typeof second === 'function' ? second : third;\n if (typeof callback !== 'function')\n throw new TypeError('Workflow step.do requires a callback.');\n const declaredRollback = typeof second === 'function' ? third : fourth;\n const rollback = typeof declaredRollback === 'object' ? declaredRollback : undefined;\n const forward = async (context: WorkflowStepContextLike): Promise<T> => {\n try {\n // The engine validates checkpoint serialization and rejects unsupported results.\n return await callback(context);\n } catch (error) {\n return convertNonRetryableError(error, NonRetryableError);\n }\n };\n let rollbackOptions: WorkflowStepRollbackOptionsLike<T> | undefined;\n if (rollback?.rollback) {\n const undo = rollback.rollback;\n rollbackOptions = {\n rollback: async (context) => {\n try {\n await undo(context);\n } catch (error) {\n convertNonRetryableError(error, NonRetryableError);\n }\n },\n ...(rollback.rollbackConfig ? { rollbackConfig: config(rollback.rollbackConfig) } : {}),\n };\n } else if (rollback?.rollbackConfig) {\n throw new NonRetryableError('Workflow rollbackConfig requires a rollback handler.');\n }\n return typeof second === 'function'\n ? (native.do as WorkflowStepLike['do'])(name, forward, rollbackOptions)\n : (native.do as WorkflowStepLike['do'])(name, config(second), forward, rollbackOptions);\n }\n\n return {\n do: run,\n sleep: (name, value) => native.sleep(name, duration(value)),\n sleepUntil: (name, timestamp) => native.sleepUntil(name, timestamp),\n waitForEvent: (name, options) =>\n native.waitForEvent(name, {\n type: options.type,\n ...(options.timeout !== undefined ? { timeout: duration(options.timeout) } : {}),\n }),\n };\n}\n"],"mappings":";;;AAUA,SAAS,SAAS,OAA+C;CAC/D,IAAI,OAAO,UAAU,YAAY,OAAO,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BAAkB,sDAAsD;EAEpF,OAAO,OAAO,WAAW,aACpB,OAAO,GAA8B,MAAM,SAAS,eAAe,IACnE,OAAO,GAA8B,MAAM,OAAO,MAAM,GAAG,SAAS,eAAe;CAC1F;CAEA,OAAO;EACL,IAAI;EACJ,QAAQ,MAAM,UAAU,OAAO,MAAM,MAAM,SAAS,KAAK,CAAC;EAC1D,aAAa,MAAM,cAAc,OAAO,WAAW,MAAM,SAAS;EAClE,eAAe,MAAM,YACnB,OAAO,aAAa,MAAM;GACxB,MAAM,QAAQ;GACd,GAAI,QAAQ,YAAY,KAAA,IAAY,EAAE,SAAS,SAAS,QAAQ,OAAO,EAAE,IAAI,CAAC;EAChF,CAAC;CACL;AACF"}
@@ -0,0 +1,78 @@
1
+ import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
2
+ import { VelaWorkflow } from "./vela-workflow.js";
3
+ import { portableWorkflowStep } from "./portable-workflow-step.js";
4
+ import __decorateMetadata from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js";
5
+ import __decorateParam from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js";
6
+ import { ENV, Inject, Injectable, ModuleRef, Scope } from "@velajs/vela";
7
+ import { SchemaValidationError, isValidationSchema, parseSchemaAsync } from "@velajs/vela/validation";
8
+ import { NonRetryableError } from "cloudflare:workflows";
9
+ import { convertNonRetryableError, createWorkflowRunContext, isWorkflowDefinition } from "@velajs/workflow";
10
+ //#region src/workflow/vela-workflow-definition.ts
11
+ function isEnvironment(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ /**
15
+ * Run a portable workflow or compiled agent through Vela's native Workflow host.
16
+ * Export a named subclass and use that name in Wrangler's `class_name`.
17
+ * The deployed `event.workflowName` labels logs; no export name or binding is inferred.
18
+ */
19
+ function VelaWorkflowDefinition(app, options) {
20
+ if (!isValidationSchema(options.params)) throw new TypeError("VelaWorkflowDefinition params requires a validation schema.");
21
+ if (!Array.isArray(options.inject) || typeof options.useFactory !== "function") throw new TypeError("VelaWorkflowDefinition requires inject and useFactory.");
22
+ const { params: schema, useFactory } = options;
23
+ const inject = [...options.inject];
24
+ let PortableWorkflowHost = class PortableWorkflowHost {
25
+ modules;
26
+ env;
27
+ constructor(modules, env) {
28
+ this.modules = modules;
29
+ this.env = env;
30
+ }
31
+ async run(event, step) {
32
+ try {
33
+ const env = this.env;
34
+ if (!isEnvironment(env)) throw new TypeError("Workflow environment must be an object.");
35
+ const resolved = await Promise.all(inject.map((token) => this.modules.resolve(token)));
36
+ const runtime = await useFactory(...resolved);
37
+ if (!runtime || !isWorkflowDefinition(runtime.definition) || typeof runtime.definition.handler !== "function" || typeof runtime.run !== "function") throw new TypeError("Workflow factory must return { definition, run }.");
38
+ return await runtime.definition.handler(createWorkflowRunContext({
39
+ env,
40
+ event,
41
+ exportName: event.workflowName,
42
+ run: runtime.run,
43
+ step: portableWorkflowStep(step),
44
+ nonRetryableErrorClass: NonRetryableError
45
+ }));
46
+ } catch (error) {
47
+ return convertNonRetryableError(error, NonRetryableError);
48
+ }
49
+ }
50
+ };
51
+ PortableWorkflowHost = __decorate([
52
+ Injectable({ scope: Scope.REQUEST }),
53
+ __decorateParam(0, Inject(ModuleRef)),
54
+ __decorateParam(1, Inject(ENV)),
55
+ __decorateMetadata("design:paramtypes", [typeof ModuleRef === "undefined" ? Object : ModuleRef, Object])
56
+ ], PortableWorkflowHost);
57
+ const NativeWorkflow = VelaWorkflow(app, PortableWorkflowHost);
58
+ class ValidatedWorkflow extends NativeWorkflow {
59
+ async run(event, step) {
60
+ let params;
61
+ try {
62
+ params = await parseSchemaAsync(schema, event.payload);
63
+ } catch (error) {
64
+ if (error instanceof SchemaValidationError) throw new NonRetryableError("Workflow trigger parameters failed validation.");
65
+ return convertNonRetryableError(error, NonRetryableError);
66
+ }
67
+ return super.run({
68
+ ...event,
69
+ payload: params
70
+ }, step);
71
+ }
72
+ }
73
+ return ValidatedWorkflow;
74
+ }
75
+ //#endregion
76
+ export { VelaWorkflowDefinition };
77
+
78
+ //# sourceMappingURL=vela-workflow-definition.js.map