@lunora/workflow 1.0.0-alpha.4 → 1.0.0-alpha.41

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 (35) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +25 -2
  3. package/dist/do/index.d.mts +16 -16
  4. package/dist/do/index.d.ts +16 -16
  5. package/dist/do/index.mjs +1 -44
  6. package/dist/index.d.mts +170 -123
  7. package/dist/index.d.ts +170 -123
  8. package/dist/index.mjs +1 -9
  9. package/dist/packem_shared/MAX_BRANCHES-C05O5LY9.mjs +1 -0
  10. package/dist/packem_shared/NonRetryableError-9ZqDUzwT.mjs +1 -0
  11. package/dist/packem_shared/WorkflowsRestError-HhBsn3PQ.mjs +1 -0
  12. package/dist/packem_shared/branch-marker-CCpWfS5k.mjs +1 -0
  13. package/dist/packem_shared/createRunStep-DB1SaYfF.mjs +1 -0
  14. package/dist/packem_shared/createWaitForEvent-DjWsI895.mjs +1 -0
  15. package/dist/packem_shared/createWorkflowContext-zQR_9N-v.mjs +1 -0
  16. package/dist/packem_shared/createWorkflowRunContext-C83Yp2Qp.mjs +1 -0
  17. package/dist/packem_shared/createWorkflows-LvAyUyKq.mjs +1 -0
  18. package/dist/packem_shared/defineStep-D1-9eOnA.mjs +1 -0
  19. package/dist/packem_shared/defineWorkflow-tKaIifbZ.mjs +1 -0
  20. package/dist/packem_shared/defineWorkflowEvent-suERPEEV.mjs +1 -0
  21. package/dist/packem_shared/run-step-D7XRYstF.mjs +1 -0
  22. package/dist/packem_shared/types.d-C7jti0tm.d.mts +522 -0
  23. package/dist/packem_shared/types.d-C7jti0tm.d.ts +522 -0
  24. package/package.json +3 -2
  25. package/dist/packem_shared/MAX_BRANCHES-C9MJIFii.mjs +0 -108
  26. package/dist/packem_shared/NonRetryableError-Dn2dTyBS.mjs +0 -27
  27. package/dist/packem_shared/WorkflowsRestError-b06i7K5j.mjs +0 -118
  28. package/dist/packem_shared/createRunStep-8jOXxP2o.mjs +0 -54
  29. package/dist/packem_shared/createWorkflowContext-D6thzmlF.mjs +0 -14
  30. package/dist/packem_shared/createWorkflowRunContext-BsMyGuMR.mjs +0 -110
  31. package/dist/packem_shared/createWorkflows-BoSYVIXg.mjs +0 -23
  32. package/dist/packem_shared/defineStep-DJQtLw7g.mjs +0 -28
  33. package/dist/packem_shared/defineWorkflow-DbUC-oCN.mjs +0 -15
  34. package/dist/packem_shared/types.d-Fdeu2P2C.d.mts +0 -394
  35. package/dist/packem_shared/types.d-Fdeu2P2C.d.ts +0 -394
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { a as Workflows, L as LunoraWorkflowsOptions, S as StepArgsValidator, b as StepConfig, c as StepDefinition, d as WorkflowConfig, W as WorkflowDefinition, e as WorkflowBranch, f as WorkflowInstanceStatus, g as WorkflowEventLike, h as WorkflowStepLike, i as WorkflowRunContext, j as WorkflowLogger, k as WorkflowRunFunction, l as WorkflowRunStepFunction } from "./packem_shared/types.d-Fdeu2P2C.js";
2
- export type { A as ArgsOf, F as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, m as RunStepOptions, n as StepHandler, o as StepRollbackContext, p as StepRollbackHandler, q as StepRunContext, r as WorkflowBindingLike, s as WorkflowBranchOutputs, t as WorkflowCreateOptions, u as WorkflowHandle, v as WorkflowHandler, w as WorkflowInstanceLike, x as WorkflowParallelFunction, y as WorkflowRollbackContextLike, z as WorkflowRollbackHandlerLike, B as WorkflowSpawnFunction, C as WorkflowSpawnOptions, D as WorkflowStatusResult, E as WorkflowStepConfigLike, G as WorkflowStepContextLike, H as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-Fdeu2P2C.js";
3
- import '@lunora/values';
1
+ import { a as Workflows, L as LunoraWorkflowsOptions, b as WorkflowEventDefinition, S as StepArgsValidator, c as StepConfig, d as StepDefinition, e as WorkflowConfig, W as WorkflowDefinition, f as WorkflowBranch, g as WorkflowInstanceStatus, h as WorkflowEventLike, i as WorkflowStepLike, j as WorkflowRunContext, k as WorkflowLogger, l as WorkflowRunFunction, m as WorkflowRunStepFunction, n as WorkflowWaitForEventFunction } from "./packem_shared/types.d-C7jti0tm.js";
2
+ export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionKind, o as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, p as RunStepOptions, q as StepHandler, r as StepRollbackContext, s as StepRollbackHandler, t as StepRunContext, u as WaitForEventOptions, v as WorkflowBindingLike, w as WorkflowBranchOutputs, x as WorkflowCreateOptions, y as WorkflowHandle, z as WorkflowHandler, C as WorkflowInstanceLike, D as WorkflowParallelFunction, E as WorkflowRollbackContextLike, G as WorkflowRollbackHandlerLike, H as WorkflowSpawnFunction, J as WorkflowSpawnOptions, K as WorkflowStatusResult, M as WorkflowStepConfigLike, N as WorkflowStepContextLike, O as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-C7jti0tm.js";
3
+ import { Validator } from '@lunora/values';
4
+ import { LunoraError } from '@lunora/errors';
4
5
  /** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
5
6
  interface WorkflowBindingSpec {
6
7
  /** The Cloudflare `Workflow` binding name, e.g. `WORKFLOW_ORDER_PIPELINE`. */
@@ -9,108 +10,138 @@ interface WorkflowBindingSpec {
9
10
  exportName: string;
10
11
  }
11
12
  /**
12
- * Build the `ctx.workflows` handle for a request: resolve every spec's
13
- * `env[binding]` into the `exportName → Workflow binding` map and wrap it in
14
- * {@link createWorkflows}. A spec whose binding is absent from `env` is skipped
15
- * here — the helpful "no workflow named …" error is raised lazily by
16
- * `workflows.get(name)` when the missing workflow is actually used.
17
- */
13
+ * Build the `ctx.workflows` handle for a request: resolve every spec's
14
+ * `env[binding]` into the `exportName → Workflow binding` map and wrap it in
15
+ * {@link createWorkflows}. A spec whose binding is absent from `env` is skipped
16
+ * here — the helpful "no workflow named …" error is raised lazily by
17
+ * `workflows.get(name)` when the missing workflow is actually used.
18
+ */
18
19
  declare const createWorkflowContext: (env: Record<string, unknown>, specs: ReadonlyArray<WorkflowBindingSpec>) => Workflows;
19
20
  /**
20
- * Build the `ctx.workflows` handle from a map of `lunora/workflows.ts` export
21
- * name → Cloudflare `Workflow` binding. `get(name)` resolves the typed handle;
22
- * an unknown name throws with the list of declared workflows.
23
- */
21
+ * Build the `ctx.workflows` handle from a map of `lunora/workflows.ts` export
22
+ * name → Cloudflare `Workflow` binding. `get(name)` resolves the typed handle;
23
+ * an unknown name throws with the list of declared workflows.
24
+ */
24
25
  declare const createWorkflows: (options: LunoraWorkflowsOptions) => Workflows;
25
26
  /**
26
- * Declare a reusable durable step. Same `args` map shape a Lunora `query` /
27
- * `mutation` / `action` uses, so a step reads like a function:
28
- *
29
- * ```ts
30
- * // lunora/steps.ts
31
- * import { defineStep } from "@lunora/workflow";
32
- * import { v } from "@lunora/values";
33
- *
34
- * export const fetchImage = defineStep("fetch image", {
35
- * args: { imageKey: v.string() },
36
- * returns: v.object({ data: v.bytes() }),
37
- * handler: async (ctx, { imageKey }) => {
38
- * const object = await (ctx.env.BUCKET as R2Bucket).get(imageKey);
39
- * return { data: new Uint8Array(await object!.arrayBuffer()) };
40
- * },
41
- * rollback: async (ctx) => {
42
- * await (ctx.env.BUCKET as R2Bucket).delete(`tmp/${ctx.args.imageKey}`);
43
- * },
44
- * });
45
- * ```
46
- *
47
- * Then, inside a `defineWorkflow` handler:
48
- *
49
- * ```ts
50
- * const { data } = await ctx.runStep(fetchImage, { imageKey: ctx.params.imageKey });
51
- * ```
52
- */
27
+ * Declare an external event, its wire type, and its payload shape.
28
+ *
29
+ * ```ts
30
+ * // lunora/events.ts
31
+ * import { defineWorkflowEvent } from "@lunora/workflow";
32
+ * import { v } from "@lunora/values";
33
+ *
34
+ * export const orderApproved = defineWorkflowEvent("order-approved", v.object({ approvedBy: v.string() }));
35
+ * ```
36
+ *
37
+ * Wait on it inside a workflow body — the payload is typed and validated:
38
+ *
39
+ * ```ts
40
+ * const { approvedBy } = await ctx.waitForEvent(orderApproved, { name: "await approval", timeout: "7 days" });
41
+ * ```
42
+ *
43
+ * …and send it from a mutation/action with the same definition:
44
+ *
45
+ * ```ts
46
+ * await ctx.workflows.get("orderPipeline").sendEvent(instanceId, orderApproved, { approvedBy });
47
+ * ```
48
+ */
49
+ declare const defineWorkflowEvent: <Payload>(type: string, payload: Validator<Payload>) => WorkflowEventDefinition<Payload>;
50
+ /**
51
+ * True when a value is usable as an event definition. The brand alone is not the
52
+ * test: the predicate hands the caller a `type` and a `payload.parse`, so it checks
53
+ * for both (and for the reserved namespace) rather than trusting a public boolean.
54
+ */
55
+ declare const isWorkflowEventDefinition: (value: unknown) => value is WorkflowEventDefinition;
56
+ /**
57
+ * Declare a reusable durable step. Same `args` map shape a Lunora `query` /
58
+ * `mutation` / `action` uses, so a step reads like a function:
59
+ *
60
+ * ```ts
61
+ * // lunora/steps.ts
62
+ * import { defineStep } from "@lunora/workflow";
63
+ * import { v } from "@lunora/values";
64
+ *
65
+ * export const fetchImage = defineStep("fetch image", {
66
+ * args: { imageKey: v.string() },
67
+ * returns: v.object({ data: v.bytes() }),
68
+ * handler: async (ctx, { imageKey }) => {
69
+ * const object = await (ctx.env.BUCKET as R2Bucket).get(imageKey);
70
+ * return { data: new Uint8Array(await object!.arrayBuffer()) };
71
+ * },
72
+ * rollback: async (ctx) => {
73
+ * await (ctx.env.BUCKET as R2Bucket).delete(`tmp/${ctx.args.imageKey}`);
74
+ * },
75
+ * });
76
+ * ```
77
+ *
78
+ * Then, inside a `defineWorkflow` handler:
79
+ *
80
+ * ```ts
81
+ * const { data } = await ctx.runStep(fetchImage, { imageKey: ctx.params.imageKey });
82
+ * ```
83
+ */
53
84
  declare const defineStep: <A extends StepArgsValidator, Result>(name: string, config: StepConfig<A, Result>) => StepDefinition<A, Result>;
54
85
  /** True when a value is a `defineStep` result (the runtime brand check). */
55
86
  declare const isStepDefinition: (value: unknown) => value is StepDefinition;
56
87
  /**
57
- * The generated `WorkflowEntrypoint` class name for a `lunora/workflows.ts`
58
- * export: `orderPipeline` → `OrderPipelineWorkflow`. wrangler's
59
- * `workflows[].class_name` references it, so codegen and the config layer MUST
60
- * derive it identically — always via this helper.
61
- */
88
+ * The generated `WorkflowEntrypoint` class name for a `lunora/workflows.ts`
89
+ * export: `orderPipeline` → `OrderPipelineWorkflow`. wrangler's
90
+ * `workflows[].class_name` references it, so codegen and the config layer MUST
91
+ * derive it identically — always via this helper.
92
+ */
62
93
  declare const workflowClassName: (exportName: string) => string;
63
94
  /**
64
- * The wrangler binding name for a workflow export: `orderPipeline` →
65
- * `WORKFLOW_ORDER_PIPELINE`, `etl` → `WORKFLOW_ETL`. The `WORKFLOW_` prefix
66
- * namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
67
- * workflow export can never collide with the built-in bindings.
68
- */
95
+ * The wrangler binding name for a workflow export: `orderPipeline` →
96
+ * `WORKFLOW_ORDER_PIPELINE`, `etl` → `WORKFLOW_ETL`. The `WORKFLOW_` prefix
97
+ * namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
98
+ * workflow export can never collide with the built-in bindings.
99
+ */
69
100
  declare const workflowBindingName: (exportName: string) => string;
70
101
  /**
71
- * The stable workflow name wrangler registers (`workflows[].name`):
72
- * `orderPipeline` → `order-pipeline`. Used as the deployed workflow's
73
- * identifier when no explicit `name` override is given.
74
- */
102
+ * The stable workflow name wrangler registers (`workflows[].name`):
103
+ * `orderPipeline` → `order-pipeline`. Used as the deployed workflow's
104
+ * identifier when no explicit `name` override is given.
105
+ */
75
106
  declare const workflowDefaultName: (exportName: string) => string;
76
107
  /**
77
- * Declare a durable workflow deployed alongside the app. Pure validation +
78
- * branding: codegen discovers the export, emits the `WorkflowEntrypoint`
79
- * subclass (`_generated/workflows.ts`), and wires the typed `ctx.workflows`
80
- * handle; the config layer reconciles the wrangler `workflows[]` entry from the
81
- * same definition.
82
- *
83
- * ```ts
84
- * // lunora/workflows.ts
85
- * import { defineWorkflow } from "@lunora/workflow";
86
- * import { api } from "./_generated/api";
87
- *
88
- * export const orderPipeline = defineWorkflow&lt;{ orderId: string }>({
89
- * handler: async (ctx) => {
90
- * const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
91
- * await ctx.step.sleep("cool-off", "1 minute");
92
- * await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
93
- * return order;
94
- * },
95
- * });
96
- * ```
97
- */
108
+ * Declare a durable workflow deployed alongside the app. Pure validation +
109
+ * branding: codegen discovers the export, emits the `WorkflowEntrypoint`
110
+ * subclass (`_generated/workflows.ts`), and wires the typed `ctx.workflows`
111
+ * handle; the config layer reconciles the wrangler `workflows[]` entry from the
112
+ * same definition.
113
+ *
114
+ * ```ts
115
+ * // lunora/workflows.ts
116
+ * import { defineWorkflow } from "@lunora/workflow";
117
+ * import { api } from "./_generated/api";
118
+ *
119
+ * export const orderPipeline = defineWorkflow<{ orderId: string }>({
120
+ * handler: async (ctx) => {
121
+ * const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
122
+ * await ctx.step.sleep("cool-off", "1 minute");
123
+ * await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
124
+ * return order;
125
+ * },
126
+ * });
127
+ * ```
128
+ */
98
129
  declare const defineWorkflow: <Params = Record<string, unknown>, Output = unknown>(config: WorkflowConfig<Params, Output>) => WorkflowDefinition<Params, Output>;
99
130
  /** True when a value is a `defineWorkflow` result (the runtime brand check). */
100
131
  declare const isWorkflowDefinition: (value: unknown) => value is WorkflowDefinition;
101
132
  /**
102
- * Throw from a workflow step (or handler) to fail the instance immediately
103
- * **without** retrying — the portable mirror of `cloudflare:workflows`'
104
- * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
105
- *
106
- * ```ts
107
- * import { NonRetryableError } from "@lunora/workflow";
108
- *
109
- * if (order.status === "cancelled") {
110
- * throw new NonRetryableError("order already cancelled — no point retrying");
111
- * }
112
- * ```
113
- */
133
+ * Throw from a workflow step (or handler) to fail the instance immediately
134
+ * **without** retrying — the portable mirror of `cloudflare:workflows`'
135
+ * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
136
+ *
137
+ * ```ts
138
+ * import { NonRetryableError } from "@lunora/workflow";
139
+ *
140
+ * if (order.status === "cancelled") {
141
+ * throw new NonRetryableError("order already cancelled — no point retrying");
142
+ * }
143
+ * ```
144
+ */
114
145
  declare class NonRetryableError extends Error {
115
146
  constructor(message: string, name?: string);
116
147
  }
@@ -119,33 +150,31 @@ declare const isNonRetryableError: (value: unknown) => value is NonRetryableErro
119
150
  /** Constructor shape of `cloudflare:workflows`' native `NonRetryableError`. */
120
151
  type NativeNonRetryableErrorConstructor = new (message: string, name?: string) => Error;
121
152
  /**
122
- * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
123
- * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
124
- * boundary where the native constructor is available; everywhere else the
125
- * portable error is thrown unchanged (and still honored by name).
126
- */
153
+ * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
154
+ * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
155
+ * boundary where the native constructor is available; everywhere else the
156
+ * portable error is thrown unchanged (and still honored by name).
157
+ */
127
158
  declare const toNativeNonRetryableError: (error: NonRetryableError, NativeNonRetryableError: NativeNonRetryableErrorConstructor) => Error;
128
159
  /**
129
- * If `error` is a portable {@link NonRetryableError} and a native constructor is
130
- * available, rethrow it as the native error; otherwise rethrow `error` as-is.
131
- * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
132
- */
160
+ * If `error` is a portable {@link NonRetryableError} and a native constructor is
161
+ * available, rethrow it as the native error; otherwise rethrow `error` as-is.
162
+ * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
163
+ */
133
164
  declare const convertNonRetryableError: (error: unknown, NativeNonRetryableError: NativeNonRetryableErrorConstructor | undefined) => never;
134
165
  /** Hard cap on branches per `ctx.parallel` call — auto-scale, never silently spawn unbounded DOs. */
135
166
  declare const MAX_BRANCHES = 100;
136
- /** The params key the parent injects so a child knows to signal completion back. Stripped before the user handler sees `ctx.params`. */
137
-
138
167
  /**
139
- * Build a single fan-out branch: a declared child workflow referenced by its
140
- * `lunora/workflows.ts` export name, plus the params it is created with. Pass the
141
- * output type as the generic argument so `ctx.parallel(...)` infers the result
142
- * tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
143
- */
168
+ * Build a single fan-out branch: a declared child workflow referenced by its
169
+ * `lunora/workflows.ts` export name, plus the params it is created with. Pass the
170
+ * output type as the generic argument so `ctx.parallel(...)` infers the result
171
+ * tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
172
+ */
144
173
  declare const branch: <Output = unknown>(workflow: string, params?: Record<string, unknown>, options?: {
174
+ compensateWith?: string;
145
175
  id?: string;
146
176
  timeout?: number | string;
147
177
  }) => WorkflowBranch<Output>;
148
- /** Build the success outcome a completed branch reports to its parent. */
149
178
  /** The lifecycle mutations the REST API exposes via `PATCH .../instances/{id}`. */
150
179
  type WorkflowInstanceAction = "pause" | "resume" | "terminate";
151
180
  /** Configuration for a {@link WorkflowsRestClient}. */
@@ -193,8 +222,7 @@ interface WorkflowInstancePage {
193
222
  totalCount?: number;
194
223
  }
195
224
  /** Thrown when the REST API responds non-2xx or `success: false`; carries the status plus body for the caller to surface. */
196
- declare class WorkflowsRestError extends Error {
197
- readonly status: number;
225
+ declare class WorkflowsRestError extends LunoraError {
198
226
  constructor(status: number, body: string);
199
227
  }
200
228
  /** The observe client: list instances, read one instance's steps, and (with Edit scope) mutate its status. */
@@ -218,11 +246,11 @@ interface WorkflowsRestClient {
218
246
  }>;
219
247
  }
220
248
  /**
221
- * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
222
- * endpoint with the bearer token, unwraps Cloudflare's
223
- * `{ success, errors, result, result_info }` envelope, and normalizes the
224
- * snake_case payload into the camelCase shapes the studio renders.
225
- */
249
+ * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
250
+ * endpoint with the bearer token, unwraps Cloudflare's
251
+ * `{ success, errors, result, result_info }` envelope, and normalizes the
252
+ * snake_case payload into the camelCase shapes the studio renders.
253
+ */
226
254
  declare const createWorkflowsRestClient: (config: WorkflowsRestConfig) => WorkflowsRestClient;
227
255
  interface RunContextOptions<Params> {
228
256
  env: Record<string, unknown>;
@@ -236,12 +264,12 @@ interface RunContextOptions<Params> {
236
264
  /** Assemble the {@link WorkflowRunContext} passed to a `defineWorkflow` handler. */
237
265
  declare const createWorkflowRunContext: <Params = Record<string, unknown>>(options: RunContextOptions<Params>) => WorkflowRunContext<Params>;
238
266
  /**
239
- * Validate a step's args through its validator map, prefixing any
240
- * `ValidationError` with `step args.&lt;key>` so the failure points at the
241
- * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
242
- * — the same parser the procedure builder and HTTP routes use — so the
243
- * optional-skip and error-prefix semantics stay in lockstep across the framework.
244
- */
267
+ * Validate a step's args through its validator map, prefixing any
268
+ * `ValidationError` with `step args.<key>` so the failure points at the
269
+ * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
270
+ * — the same parser the procedure builder and HTTP routes use — so the
271
+ * optional-skip and error-prefix semantics stay in lockstep across the framework.
272
+ */
245
273
  declare const validateStepArgs: (validators: StepArgsValidator, source: Record<string, unknown>) => Record<string, unknown>;
246
274
  /** Dependencies needed to run a step: the native step API plus the workflow's env / runner / logger. */
247
275
  interface RunStepDeps {
@@ -257,10 +285,29 @@ interface RunStepDeps {
257
285
  step: WorkflowStepLike;
258
286
  }
259
287
  /**
260
- * Build the `ctx.runStep` function bound to one workflow invocation. Each call
261
- * runs the step through `step.do(...)`: validate args → run body → validate
262
- * result (when `returns` is declared), with any portable `NonRetryableError`
263
- * converted to the native one and any declared rollback forwarded to Cloudflare.
264
- */
288
+ * Build the `ctx.runStep` function bound to one workflow invocation. Each call
289
+ * runs the step through `step.do(...)`: validate args → run body → validate
290
+ * result (when `returns` is declared), with any portable `NonRetryableError`
291
+ * converted to the native one and any declared rollback forwarded to Cloudflare.
292
+ */
265
293
  declare const createRunStep: (deps: RunStepDeps) => WorkflowRunStepFunction;
266
- export { type LunoraWorkflowsOptions, MAX_BRANCHES, type NativeNonRetryableErrorConstructor, NonRetryableError, type StepArgsValidator, type StepConfig, type StepDefinition, type WorkflowBindingSpec, type WorkflowBranch, type WorkflowConfig, type WorkflowDefinition, type WorkflowEventLike, type WorkflowInstanceAction, type WorkflowInstanceDetail, type WorkflowInstancePage, type WorkflowInstanceStatus, type WorkflowInstanceSummary, type WorkflowLogger, type WorkflowRunContext, type WorkflowRunFunction, type WorkflowRunStepFunction, type WorkflowStepDetail, type WorkflowStepLike, type Workflows, type WorkflowsRestClient, type WorkflowsRestConfig, WorkflowsRestError, branch, convertNonRetryableError, createRunStep, createWorkflowContext, createWorkflowRunContext, createWorkflows, createWorkflowsRestClient, defineStep, defineWorkflow, isNonRetryableError, isStepDefinition, isWorkflowDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
294
+ /** Dependencies one workflow invocation's `ctx.waitForEvent` closes over. */
295
+ interface WaitForEventDeps {
296
+ /** Native `cloudflare:workflows` `NonRetryableError` constructor — injected by `src/do`; absent in Node tests. */
297
+ nonRetryableErrorClass?: NativeNonRetryableErrorConstructor;
298
+ /** The native Cloudflare durable-step API. */
299
+ step: WorkflowStepLike;
300
+ }
301
+ /**
302
+ * Build `ctx.waitForEvent` for one workflow invocation.
303
+ *
304
+ * Every failure here is **non-retryable**. A malformed definition or a reserved
305
+ * step name is a deterministic programmer error, and a payload that fails the
306
+ * validator has already consumed the event — replaying the wait cannot produce a
307
+ * different value, it can only hibernate the instance until its timeout. Each is
308
+ * raised through the shared {@link raiseNonRetryable}, the same classification path
309
+ * `ctx.runStep` uses, so the native error reaches Cloudflare and the instance fails
310
+ * fast.
311
+ */
312
+ declare const createWaitForEvent: (deps: WaitForEventDeps) => WorkflowWaitForEventFunction;
313
+ export { type LunoraWorkflowsOptions, MAX_BRANCHES, type NativeNonRetryableErrorConstructor, NonRetryableError, type StepArgsValidator, type StepConfig, type StepDefinition, type WorkflowBindingSpec, type WorkflowBranch, type WorkflowConfig, type WorkflowDefinition, type WorkflowEventDefinition, type WorkflowEventLike, type WorkflowInstanceAction, type WorkflowInstanceDetail, type WorkflowInstancePage, type WorkflowInstanceStatus, type WorkflowInstanceSummary, type WorkflowLogger, type WorkflowRunContext, type WorkflowRunFunction, type WorkflowRunStepFunction, type WorkflowStepDetail, type WorkflowStepLike, type WorkflowWaitForEventFunction, type Workflows, type WorkflowsRestClient, type WorkflowsRestConfig, WorkflowsRestError, branch, convertNonRetryableError, createRunStep, createWaitForEvent, createWorkflowContext, createWorkflowRunContext, createWorkflows, createWorkflowsRestClient, defineStep, defineWorkflow, defineWorkflowEvent, isNonRetryableError, isStepDefinition, isWorkflowDefinition, isWorkflowEventDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
package/dist/index.mjs CHANGED
@@ -1,9 +1 @@
1
- export { createWorkflowContext } from './packem_shared/createWorkflowContext-D6thzmlF.mjs';
2
- export { default as createWorkflows } from './packem_shared/createWorkflows-BoSYVIXg.mjs';
3
- export { defineStep, isStepDefinition } from './packem_shared/defineStep-DJQtLw7g.mjs';
4
- export { defineWorkflow, isWorkflowDefinition, workflowBindingName, workflowClassName, workflowDefaultName } from './packem_shared/defineWorkflow-DbUC-oCN.mjs';
5
- export { NonRetryableError, convertNonRetryableError, isNonRetryableError, toNativeNonRetryableError } from './packem_shared/NonRetryableError-Dn2dTyBS.mjs';
6
- export { MAX_BRANCHES, branch } from './packem_shared/MAX_BRANCHES-C9MJIFii.mjs';
7
- export { WorkflowsRestError, createWorkflowsRestClient } from './packem_shared/WorkflowsRestError-b06i7K5j.mjs';
8
- export { createWorkflowRunContext } from './packem_shared/createWorkflowRunContext-BsMyGuMR.mjs';
9
- export { createRunStep, validateStepArgs } from './packem_shared/createRunStep-8jOXxP2o.mjs';
1
+ import{createWorkflowContext as e}from"./packem_shared/createWorkflowContext-zQR_9N-v.mjs";import{default as f}from"./packem_shared/createWorkflows-LvAyUyKq.mjs";import{defineWorkflowEvent as a,isWorkflowEventDefinition as i}from"./packem_shared/defineWorkflowEvent-suERPEEV.mjs";import{defineStep as p,isStepDefinition as s}from"./packem_shared/defineStep-D1-9eOnA.mjs";import{defineWorkflow as m,isWorkflowDefinition as x,workflowBindingName as k,workflowClassName as W,workflowDefaultName as c}from"./packem_shared/defineWorkflow-tKaIifbZ.mjs";import{NonRetryableError as N,convertNonRetryableError as R,isNonRetryableError as v,toNativeNonRetryableError as d}from"./packem_shared/NonRetryableError-9ZqDUzwT.mjs";import{MAX_BRANCHES as C,branch as S}from"./packem_shared/MAX_BRANCHES-C05O5LY9.mjs";import{WorkflowsRestError as y,createWorkflowsRestClient as D}from"./packem_shared/WorkflowsRestError-HhBsn3PQ.mjs";import{createWorkflowRunContext as g}from"./packem_shared/createWorkflowRunContext-C83Yp2Qp.mjs";import{c as h,v as F}from"./packem_shared/run-step-D7XRYstF.mjs";import{createWaitForEvent as M}from"./packem_shared/createWaitForEvent-DjWsI895.mjs";export{C as MAX_BRANCHES,N as NonRetryableError,y as WorkflowsRestError,S as branch,R as convertNonRetryableError,h as createRunStep,M as createWaitForEvent,e as createWorkflowContext,g as createWorkflowRunContext,f as createWorkflows,D as createWorkflowsRestClient,p as defineStep,m as defineWorkflow,a as defineWorkflowEvent,v as isNonRetryableError,s as isStepDefinition,x as isWorkflowDefinition,i as isWorkflowEventDefinition,d as toNativeNonRetryableError,F as validateStepArgs,k as workflowBindingName,W as workflowClassName,c as workflowDefaultName};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}from"@lunora/errors";import{h as y,B as I,a as p}from"./branch-marker-CCpWfS5k.mjs";import{RESERVED_EVENT_TYPE_PREFIX as v}from"./defineWorkflowEvent-suERPEEV.mjs";import{NonRetryableError as d}from"./NonRetryableError-9ZqDUzwT.mjs";const h=100,g="lunora:spawn:",$="lunora:await:",x="lunora:signal:",B="lunora:compensate:",m=`${v}branch:`,b=(t,r,n)=>({compensateWith:n?.compensateWith,id:n?.id,params:r,timeout:n?.timeout,workflow:t}),w=t=>t instanceof Error?{message:t.message,name:t.name}:{message:String(t),name:"Error"},A=t=>({status:"ok",value:t}),N=t=>({error:w(t),status:"error"}),f=async(t,r,n)=>{for(let a=r.length-1;a>=0;a-=1){const o=r[a],c=o?.plan.item.compensateWith;if(!(o===void 0||c===void 0))try{const s=t.resolveBinding(c);await t.step.do(`${B}${o.plan.childId}`,async()=>{const e=`${o.plan.childId}:compensate`,i={branch:o.plan.item.workflow,error:n,index:o.plan.index,output:o.output};return await s.create({id:e,params:i}),e})}catch(s){t.log?.error(`ctx.parallel: group-saga compensation "${c}" for branch "${o.plan.item.workflow}" (#${String(o.plan.index)}) failed`,s)}}},k=t=>async n=>{if(n.length===0)return[];if(n.length>h)throw new d(`ctx.parallel: ${String(n.length)} branches exceeds the cap of ${String(h)} — split the fan-out or raise the work into fewer child workflows`);const a=n.map((e,i)=>{const l=t.nextChildId(e.id);return{childId:l,eventType:`${m}${l}`,index:i,item:e}}),o=new Set;for(const e of a){if(o.has(e.childId))throw new d(`ctx.parallel: duplicate branch id "${e.childId}" — each branch in a group must resolve to a unique child instance id (check explicit \`id\` options)`);o.add(e.childId)}await Promise.all(a.map(e=>t.step.do(`${g}${e.childId}`,async()=>{const i=t.resolveBinding(e.item.workflow),l={eventType:e.eventType,index:e.index,parentBinding:t.parentBinding,parentId:t.instanceId};return await i.create({id:e.childId,params:{...e.item.params,[p]:l}}),e.childId})));const c=[],s=[];for(const e of a){let i;try{i=(await t.step.waitForEvent(`${$}${e.childId}`,{timeout:e.item.timeout,type:e.eventType})).payload}catch(l){const u=w(l);throw await f(t,s,u),new d(`ctx.parallel: branch "${e.item.workflow}" (#${String(e.index)}) join failed: ${u.message}`)}if(i.status==="error")throw await f(t,s,i.error),new d(`ctx.parallel: branch "${e.item.workflow}" (#${String(e.index)}) failed: ${i.error.message}`);s.push({output:i.value,plan:e}),c.push(i.value)}return c},W=t=>async(r,n,a)=>{if(y(n))throw new E("BAD_REQUEST",`@lunora/workflow: params ${I}`);const o=t.nextChildId(a?.id);return await t.step.do(`${g}${o}`,async()=>(await t.resolveBinding(r).create({id:o,params:n}),o)),t.resolveBinding(r).get(o)},C=t=>{if(typeof t!="object"||t===null)return;const r=t[p];if(typeof r!="object"||r===null)return;const n=r;if(!(typeof n.eventType!="string"||typeof n.parentBinding!="string"||typeof n.parentId!="string"||typeof n.index!="number")&&!(!n.parentBinding.startsWith("WORKFLOW_")||!n.eventType.startsWith(m)))return{eventType:n.eventType,index:n.index,parentBinding:n.parentBinding,parentId:n.parentId}},F=t=>{if(typeof t!="object"||t===null)return t;const r={...t};return Reflect.deleteProperty(r,p),r},T=async(t,r,n)=>{const a=t.env[r.parentBinding];if(!a||typeof a.get!="function")return;const o=a.get.bind(a);await t.step.do(`${x}${String(r.index)}`,async()=>(await(await o(r.parentId)).sendEvent({payload:n,type:r.eventType}),r.eventType))},M=async(t,r,n)=>{try{await T(t,r,n)}catch(a){t.log?.error(`@lunora/workflow: failed to signal branch parent "${r.parentId}" (event "${r.eventType}")`,a)}};export{h as MAX_BRANCHES,b as branch,k as createParallel,W as createSpawn,N as errorOutcome,C as extractBranchMarker,A as okOutcome,T as signalBranchParent,M as signalBranchParentSafe,F as stripBranchMarker};
@@ -0,0 +1 @@
1
+ const s="__lunoraNonRetryable";class a extends Error{constructor(e,n="NonRetryableError"){super(e),this.name=n,this[s]=!0}}const c=t=>t instanceof Error&&t[s]===!0,r=(t,e)=>{const n=new e(t.message,t.name);return t.stack!==void 0&&(n.stack=t.stack),t.cause!==void 0&&n.cause===void 0&&(n.cause=t.cause),n},i=(t,e)=>{throw e!==void 0&&c(t)?r(t,e):t},u=(t,e,n)=>{const o=new a(t);return e!==void 0&&(o.cause=e),i(o,n)};export{a as NonRetryableError,i as convertNonRetryableError,c as isNonRetryableError,u as raiseNonRetryable,r as toNativeNonRetryableError};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";const R="https://api.cloudflare.com/client/v4/accounts",$={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},g=t=>typeof t=="string"&&Object.hasOwn($,t)?t:"unknown",u=t=>typeof t=="string"&&t!==""?t:void 0,S=(t,a)=>typeof t=="string"?t:a,A=t=>typeof t=="boolean"?t:void 0,_=t=>Array.isArray(t)?t.length:typeof t=="number"?t:void 0,f=t=>({createdOn:u(t.created_on),endedOn:u(t.ended_on),id:S(t.id,""),startedOn:u(t.started_on),status:g(t.status)}),I=t=>({attempts:_(t.attempts),end:u(t.end),error:t.error,name:S(t.name,""),output:t.output,start:u(t.start),success:A(t.success),type:u(t.type)});class l extends h{constructor(a,i){super("WORKFLOWS_REST_ERROR",`Cloudflare Workflows REST API returned ${String(a)}: ${i}`,{name:"WorkflowsRestError",status:a})}}const w=t=>{const a=t.fetch??globalThis.fetch.bind(globalThis),i=`${R}/${t.accountId}/workflows`,p=async(o,r)=>{const s=await a(`${i}${o}`,{...r,headers:{Authorization:`Bearer ${t.apiToken}`,"Content-Type":"application/json"}}),e=await s.text();let n;try{n=JSON.parse(e)}catch{throw new l(s.status,e)}if(!s.ok||n.success===!1)throw new l(s.status,e);return n};return{getInstance:async({instanceId:o,workflowName:r})=>{const e=(await p(`/${encodeURIComponent(r)}/instances/${encodeURIComponent(o)}`)).result??{},n=Array.isArray(e.steps)?e.steps:[];return{...f(e),error:e.error,output:e.output,params:e.params,steps:n.map(d=>I(d))}},listInstances:async({page:o,perPage:r,status:s,workflowName:e})=>{const n=new URLSearchParams;s!==void 0&&n.set("status",s),o!==void 0&&n.set("page",String(o)),r!==void 0&&n.set("per_page",String(r));const d=n.toString()===""?"":`?${n.toString()}`,y=await p(`/${encodeURIComponent(e)}/instances${d}`),m=Array.isArray(y.result)?y.result:[],c=y.result_info??{};return{instances:m.map(b=>f(b)),page:typeof c.page=="number"?c.page:o??1,perPage:typeof c.per_page=="number"?c.per_page:r??m.length,totalCount:typeof c.total_count=="number"?c.total_count:void 0}},setInstanceStatus:async({action:o,instanceId:r,workflowName:s})=>{const n=(await p(`/${encodeURIComponent(s)}/instances/${encodeURIComponent(r)}`,{body:JSON.stringify({status:o}),method:"PATCH"})).result??{};return{status:g(n.status)}}}};export{l as WorkflowsRestError,w as createWorkflowsRestClient};
@@ -0,0 +1 @@
1
+ const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),a=`may not contain the reserved workflow branch-marker key ("${e}")`;export{a as B,e as a,o as h};
@@ -0,0 +1 @@
1
+ import{c as p,v as o}from"./run-step-D7XRYstF.mjs";import"./defineWorkflowEvent-suERPEEV.mjs";import"./NonRetryableError-9ZqDUzwT.mjs";export{p as createRunStep,o as validateStepArgs};
@@ -0,0 +1 @@
1
+ import{eventDefinitionProblem as m,RESERVED_EVENT_TYPE_PREFIX as i}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as a}from"./NonRetryableError-9ZqDUzwT.mjs";const c=e=>async(r,t)=>{const n=m(r);if(n!==void 0)return a(`@lunora/workflow: ctx.waitForEvent ${n}`,void 0,e.nonRetryableErrorClass);if(t?.name?.startsWith(i)===!0)return a(`@lunora/workflow: ctx.waitForEvent step name "${t.name}" is reserved — the "${i}" prefix is used by the framework's own steps`,void 0,e.nonRetryableErrorClass);const s=await e.step.waitForEvent(t?.name??`event:${r.type}`,{timeout:t?.timeout,type:r.type});try{return r.payload.parse(s.payload)}catch(o){const l=o instanceof Error?o.message:String(o);return a(`@lunora/workflow: event "${r.type}" payload validation failed: ${l}`,o,e.nonRetryableErrorClass)}};export{c as createWaitForEvent};
@@ -0,0 +1 @@
1
+ import r from"./createWorkflows-LvAyUyKq.mjs";const i=(n,c)=>{const o={};for(const e of c){const t=n[e.binding];t&&typeof t.create=="function"&&typeof t.createBatch=="function"&&typeof t.get=="function"&&(o[e.exportName]=t)}return r({bindings:o})};export{i as createWorkflowContext};
@@ -0,0 +1 @@
1
+ import{F as w,c as v}from"./run-step-D7XRYstF.mjs";import{LunoraError as i}from"@lunora/errors";import{workflowBindingName as s}from"./defineWorkflow-tKaIifbZ.mjs";import{createSpawn as u,createParallel as m}from"./MAX_BRANCHES-C05O5LY9.mjs";import{createWaitForEvent as p}from"./createWaitForEvent-DjWsI895.mjs";const g=e=>({debug:(r,...n)=>{console.debug(e,r,...n)},error:(r,...n)=>{console.error(e,r,...n)},info:(r,...n)=>{console.info(e,r,...n)},warn:(r,...n)=>{console.warn(e,r,...n)}}),I=e=>{const r=g(`[workflow:${e.exportName}]`),n=w({env:e.env,fetchImpl:e.fetchImpl,label:"@lunora/workflow"}),f=t=>{const a=s(t),o=e.env[a];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new i("INTERNAL",`@lunora/workflow: cannot spawn child workflow "${t}" — no Workflow binding "${a}" on env (is it declared in lunora/workflows.ts?)`);return o};let l=0;const d=t=>{if(t!==void 0)return t;const a=`${e.event.instanceId}-c${String(l)}`;return l+=1,a},c={env:e.env,instanceId:e.event.instanceId,log:r,nextChildId:d,parentBinding:s(e.exportName),resolveBinding:f,step:e.step};return{env:e.env,event:e.event,log:r,parallel:m(c),params:e.event.payload,run:n,runStep:v({env:e.env,log:r,nonRetryableErrorClass:e.nonRetryableErrorClass,run:n,step:e.step}),spawn:u(c),step:e.step,waitForEvent:p({nonRetryableErrorClass:e.nonRetryableErrorClass,step:e.step})}};export{I as createWorkflowRunContext};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{h as w,B as f}from"./branch-marker-CCpWfS5k.mjs";import{eventDefinitionProblem as l}from"./defineWorkflowEvent-suERPEEV.mjs";const c=r=>{if(w(r?.params))throw new a("BAD_REQUEST",`@lunora/workflow: params ${f}`)},i=r=>({create:async o=>(c(o),r.create(o)),createBatch:async o=>{for(const e of o)c(e);return r.createBatch(o)},get:async o=>r.get(o),sendEvent:async(o,e,t)=>{const n=l(e);if(n!==void 0)throw new a("BAD_REQUEST",`@lunora/workflow: sendEvent ${n}`);await(await r.get(o)).sendEvent({payload:e.payload.parse(t),type:e.type})}}),k=r=>{const o=r.bindings??{};return{get:e=>{const t=o[e];if(t===void 0){const n=Object.keys(o),s=n.length===0?"no workflows are declared":`known workflows: ${n.join(", ")}`;throw new a("INTERNAL",`@lunora/workflow: no workflow named "${e}" (${s})`)}return i(t)}}};export{k as default};
@@ -0,0 +1 @@
1
+ const n=(r,e)=>{if(typeof r!="string"||r.length===0)throw new TypeError("defineStep: `name` must be a non-empty string (the durable step label)");const t=e.args;if(typeof t!="object"||t===null)throw new TypeError("defineStep: `args` must be a validator map (e.g. `{ id: v.string() }`)");if(typeof e.handler!="function")throw new TypeError("defineStep: `handler` must be a function (the step body)");if(e.rollback!==void 0&&typeof e.rollback!="function")throw new TypeError("defineStep: `rollback` must be a function when provided");return{args:e.args,config:e.config,handler:e.handler,isLunoraStep:!0,name:r,returns:e.returns,rollback:e.rollback,rollbackConfig:e.rollbackConfig}},o=r=>typeof r=="object"&&r!==null&&r.isLunoraStep===!0;export{n as defineStep,o as isStepDefinition};
@@ -0,0 +1 @@
1
+ const e=o=>`${o.charAt(0).toUpperCase()}${o.slice(1)}Workflow`,r=o=>`WORKFLOW_${o.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"_").toUpperCase()}`,n=o=>o.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"-").toLowerCase(),t=o=>{if(typeof o.handler!="function")throw new TypeError("defineWorkflow: `handler` must be a function (the workflow body)");if(o.name!==void 0&&(typeof o.name!="string"||o.name.length===0))throw new TypeError("defineWorkflow: `name` must be a non-empty string when provided");return{...o,isLunoraWorkflow:!0}},l=o=>typeof o=="object"&&o!==null&&o.isLunoraWorkflow===!0;export{t as defineWorkflow,l as isWorkflowDefinition,r as workflowBindingName,e as workflowClassName,n as workflowDefaultName};
@@ -0,0 +1 @@
1
+ const o="lunora:",r=e=>{if(typeof e!="object"||e===null||e.isLunoraWorkflowEvent!==!0)return"expects a `defineWorkflowEvent` definition";const t=e;if(typeof t.type!="string"||t.type.length===0)return"event `type` must be a non-empty string";if(t.type.startsWith(o))return`event type "${t.type}" is reserved — the "${o}" prefix is used by the framework's own events`;if(typeof t.payload?.parse!="function")return"event `payload` must be a validator (e.g. `v.object({ ok: v.boolean() })`)"},i=(e,t)=>{if(typeof e!="string"||e.length===0)throw new TypeError("defineWorkflowEvent: `type` must be a non-empty string (the wire event type)");const n=r({isLunoraWorkflowEvent:!0,payload:t,type:e});if(n!==void 0)throw new TypeError(`defineWorkflowEvent: ${n}`);return{isLunoraWorkflowEvent:!0,payload:t,type:e}},f=e=>r(e)===void 0;export{o as RESERVED_EVENT_TYPE_PREFIX,i as defineWorkflowEvent,r as eventDefinitionProblem,f as isWorkflowEventDefinition};
@@ -0,0 +1 @@
1
+ import{LunoraError as m,isLunoraError as T}from"@lunora/errors";import{parseValidatorMap as O}from"@lunora/values";import{RESERVED_EVENT_TYPE_PREFIX as w}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as N,convertNonRetryableError as S}from"./NonRetryableError-9ZqDUzwT.mjs";const _=(t,r,e)=>{if(r===void 0)return{dispose:()=>{},signal:t};const a=new AbortController,o=setTimeout(()=>{a.abort(e())},r);return{dispose:()=>{clearTimeout(o)},signal:a.signal}},f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",R=t=>{let r="",e=0;const a=t.length-2;for(;e<a;e+=3){const n=t[e]<<16|t[e+1]<<8|t[e+2];r+=f.charAt(n>>18&63)+f.charAt(n>>12&63)+f.charAt(n>>6&63)+f.charAt(n&63)}const o=t.length-e;if(o===1){const n=t[e]<<16;r+=f.charAt(n>>18&63)+f.charAt(n>>12&63)}else if(o===2){const n=t[e]<<16|t[e+1]<<8;r+=f.charAt(n>>18&63)+f.charAt(n>>12&63)+f.charAt(n>>6&63)}return r};new TextDecoder;const A=new TextEncoder,E="=",L=t=>{for(let r=0;r<t.length;r+=1)if(t.charCodeAt(r)>255)return!1;return!0},k=t=>R(A.encode(JSON.stringify(t))),x=t=>!t.startsWith(E)&&L(t)?t:`${E}${R(A.encode(t))}`,D="/_lunora/scheduler/dispatch",C=3e4,P=t=>{let r=t.length;for(;r>0&&t[r-1]==="/";)r-=1;return t.slice(0,r)},$=Symbol("lunoraDispatchFailure"),U=Symbol("lunoraDispatchMessageId"),v=(t,r)=>(Object.defineProperty(t,$,{value:!0}),r!==void 0&&Object.defineProperty(t,U,{value:r}),t),M=(t,r,e,a)=>{try{const o=JSON.parse(e)?.error;if(typeof o=="object"&&o!==null&&typeof o.code=="string"){const{code:n,data:c,message:l}=o;return v(new m(n,typeof l=="string"?l:void 0,{data:c,status:r}),a)}}catch{}return v(new m("INTERNAL",`${t}: function dispatch failed (${String(r)}): ${e}`,{status:r}),a)},J=new Set([400,403,404,422]),j=t=>T(t)&&t[$]===!0&&J.has(t.status),K=(t,r,e)=>new m("INTERNAL",`${t}: function dispatch to "${r}" timed out after ${String(e)}ms`,{status:503}),z=t=>{const{label:r}=t,e=globalThis.fetch,a=t.fetchImpl??(typeof e=="function"?e.bind(globalThis):void 0);return async(o,n,c={})=>{if(typeof a!="function")throw new TypeError(`${r}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const l=t.env.LUNORA_ORIGIN_URL;if(typeof l!="string"||l.length===0)throw new m("INTERNAL",`${r}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const d=t.env.LUNORA_ADMIN_TOKEN;if(typeof d!="string"||d.length===0)throw new m("INTERNAL",`${r}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const b=`${P(l)}${D}`,i={authorization:`Bearer ${d}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(i["x-lunora-userid"]=x(t.identity.userId)),t.identity?.claims!==void 0&&(i["x-lunora-identity"]=k(t.identity.claims));const p=c.timeoutMs??C,g=_(void 0,p,()=>new DOMException(`dispatch timed out after ${String(p)}ms`,"TimeoutError")),s=h=>{throw h instanceof Error&&h.name==="TimeoutError"?K(r,o.__lunoraRef,p):h};let u;try{try{u=await a(b,{body:JSON.stringify({args:n??{},functionPath:o.__lunoraRef,id:c.dedupId,shardKey:c.shardKey}),headers:i,method:"POST",signal:g.signal})}catch(y){return s(y)}if(!u.ok){let y;try{y=await u.text()}catch(I){return s(I)}throw M(r,u.status,y,c.messageId)}let h;try{h=await u.text()}catch(y){return s(y)}if(h.length===0)return;try{return JSON.parse(h)}catch{throw new m("INTERNAL",`${r}: function dispatch returned a non-JSON body (${String(u.status)}): ${h}`,{status:u.status})}}finally{g.dispose()}}},W=(t,r)=>O(t,r,"step args"),H=t=>async(r,e,a)=>{const o=a?.config??r.config,n=a?.name??r.name;if(n.startsWith(w))return N(`@lunora/workflow: ctx.runStep step name "${n}" is reserved — the "${w}" prefix is used by the framework's own steps`,void 0,t.nonRetryableErrorClass);const c=W(r.args,e),l=async i=>{const p={attempt:i.attempt,config:i.config,env:t.env,log:t.log,run:t.run,step:i.step};let g;try{g=await r.handler(p,c)}catch(s){return j(s)?N(s.message,s,t.nonRetryableErrorClass):S(s,t.nonRetryableErrorClass)}if(!r.returns)return g;try{return r.returns.parse(g)}catch(s){const u=s instanceof Error?s.message:String(s);return N(`step "${r.name}" returns validation failed: ${u}`,s,t.nonRetryableErrorClass)}},d=r.rollback,b=d?{rollback:async i=>{await d({args:c,env:t.env,error:i.error,log:t.log,output:i.output,run:t.run})},rollbackConfig:r.rollbackConfig}:void 0;return o===void 0?t.step.do(n,l,b):t.step.do(n,o,l,b)};export{z as F,H as c,W as v};