@lunora/workflow 1.0.0-alpha.1 → 1.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
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 WorkflowInstanceStatus, f as WorkflowLogger, g as WorkflowEventLike, h as WorkflowStepLike, i as WorkflowRunContext, j as WorkflowRunFunction, k as WorkflowRunStepFunction } from "./packem_shared/types.d-CQO_koGe.js";
2
- export type { A as ArgsOf, F as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, l as RunStepOptions, m as StepHandler, n as StepRollbackContext, o as StepRollbackHandler, p as StepRunContext, q as WorkflowBindingLike, r as WorkflowCreateOptions, s as WorkflowHandle, t as WorkflowHandler, u as WorkflowInstanceLike, v as WorkflowRollbackContextLike, w as WorkflowRollbackHandlerLike, x as WorkflowStatusResult, y as WorkflowStepConfigLike, z as WorkflowStepContextLike, B as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-CQO_koGe.js";
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-DZlXmeGi.js";
2
+ export type { A as ArgsOf, B as BranchCompensationParams, 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, C as WorkflowSpawnFunction, D as WorkflowSpawnOptions, E as WorkflowStatusResult, G as WorkflowStepConfigLike, H as WorkflowStepContextLike, J as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-DZlXmeGi.js";
3
+ import { LunoraError } from '@lunora/errors';
3
4
  import '@lunora/values';
4
5
  /** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
5
6
  interface WorkflowBindingSpec {
@@ -9,108 +10,108 @@ 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 a reusable durable step. Same `args` map shape a Lunora `query` /
28
+ * `mutation` / `action` uses, so a step reads like a function:
29
+ *
30
+ * ```ts
31
+ * // lunora/steps.ts
32
+ * import { defineStep } from "@lunora/workflow";
33
+ * import { v } from "@lunora/values";
34
+ *
35
+ * export const fetchImage = defineStep("fetch image", {
36
+ * args: { imageKey: v.string() },
37
+ * returns: v.object({ data: v.bytes() }),
38
+ * handler: async (ctx, { imageKey }) => {
39
+ * const object = await (ctx.env.BUCKET as R2Bucket).get(imageKey);
40
+ * return { data: new Uint8Array(await object!.arrayBuffer()) };
41
+ * },
42
+ * rollback: async (ctx) => {
43
+ * await (ctx.env.BUCKET as R2Bucket).delete(`tmp/${ctx.args.imageKey}`);
44
+ * },
45
+ * });
46
+ * ```
47
+ *
48
+ * Then, inside a `defineWorkflow` handler:
49
+ *
50
+ * ```ts
51
+ * const { data } = await ctx.runStep(fetchImage, { imageKey: ctx.params.imageKey });
52
+ * ```
53
+ */
53
54
  declare const defineStep: <A extends StepArgsValidator, Result>(name: string, config: StepConfig<A, Result>) => StepDefinition<A, Result>;
54
55
  /** True when a value is a `defineStep` result (the runtime brand check). */
55
56
  declare const isStepDefinition: (value: unknown) => value is StepDefinition;
56
57
  /**
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
- */
58
+ * The generated `WorkflowEntrypoint` class name for a `lunora/workflows.ts`
59
+ * export: `orderPipeline` → `OrderPipelineWorkflow`. wrangler's
60
+ * `workflows[].class_name` references it, so codegen and the config layer MUST
61
+ * derive it identically — always via this helper.
62
+ */
62
63
  declare const workflowClassName: (exportName: string) => string;
63
64
  /**
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
- */
65
+ * The wrangler binding name for a workflow export: `orderPipeline` →
66
+ * `WORKFLOW_ORDER_PIPELINE`, `etl` → `WORKFLOW_ETL`. The `WORKFLOW_` prefix
67
+ * namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
68
+ * workflow export can never collide with the built-in bindings.
69
+ */
69
70
  declare const workflowBindingName: (exportName: string) => string;
70
71
  /**
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
- */
72
+ * The stable workflow name wrangler registers (`workflows[].name`):
73
+ * `orderPipeline` → `order-pipeline`. Used as the deployed workflow's
74
+ * identifier when no explicit `name` override is given.
75
+ */
75
76
  declare const workflowDefaultName: (exportName: string) => string;
76
77
  /**
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
- */
78
+ * Declare a durable workflow deployed alongside the app. Pure validation +
79
+ * branding: codegen discovers the export, emits the `WorkflowEntrypoint`
80
+ * subclass (`_generated/workflows.ts`), and wires the typed `ctx.workflows`
81
+ * handle; the config layer reconciles the wrangler `workflows[]` entry from the
82
+ * same definition.
83
+ *
84
+ * ```ts
85
+ * // lunora/workflows.ts
86
+ * import { defineWorkflow } from "@lunora/workflow";
87
+ * import { api } from "./_generated/api";
88
+ *
89
+ * export const orderPipeline = defineWorkflow&lt;{ orderId: string }>({
90
+ * handler: async (ctx) => {
91
+ * const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
92
+ * await ctx.step.sleep("cool-off", "1 minute");
93
+ * await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
94
+ * return order;
95
+ * },
96
+ * });
97
+ * ```
98
+ */
98
99
  declare const defineWorkflow: <Params = Record<string, unknown>, Output = unknown>(config: WorkflowConfig<Params, Output>) => WorkflowDefinition<Params, Output>;
99
100
  /** True when a value is a `defineWorkflow` result (the runtime brand check). */
100
101
  declare const isWorkflowDefinition: (value: unknown) => value is WorkflowDefinition;
101
102
  /**
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
- */
103
+ * Throw from a workflow step (or handler) to fail the instance immediately
104
+ * **without** retrying — the portable mirror of `cloudflare:workflows`'
105
+ * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
106
+ *
107
+ * ```ts
108
+ * import { NonRetryableError } from "@lunora/workflow";
109
+ *
110
+ * if (order.status === "cancelled") {
111
+ * throw new NonRetryableError("order already cancelled — no point retrying");
112
+ * }
113
+ * ```
114
+ */
114
115
  declare class NonRetryableError extends Error {
115
116
  constructor(message: string, name?: string);
116
117
  }
@@ -119,18 +120,31 @@ declare const isNonRetryableError: (value: unknown) => value is NonRetryableErro
119
120
  /** Constructor shape of `cloudflare:workflows`' native `NonRetryableError`. */
120
121
  type NativeNonRetryableErrorConstructor = new (message: string, name?: string) => Error;
121
122
  /**
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
- */
123
+ * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
124
+ * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
125
+ * boundary where the native constructor is available; everywhere else the
126
+ * portable error is thrown unchanged (and still honored by name).
127
+ */
127
128
  declare const toNativeNonRetryableError: (error: NonRetryableError, NativeNonRetryableError: NativeNonRetryableErrorConstructor) => Error;
128
129
  /**
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
- */
130
+ * If `error` is a portable {@link NonRetryableError} and a native constructor is
131
+ * available, rethrow it as the native error; otherwise rethrow `error` as-is.
132
+ * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
133
+ */
133
134
  declare const convertNonRetryableError: (error: unknown, NativeNonRetryableError: NativeNonRetryableErrorConstructor | undefined) => never;
135
+ /** Hard cap on branches per `ctx.parallel` call — auto-scale, never silently spawn unbounded DOs. */
136
+ declare const MAX_BRANCHES = 100;
137
+ /**
138
+ * Build a single fan-out branch: a declared child workflow referenced by its
139
+ * `lunora/workflows.ts` export name, plus the params it is created with. Pass the
140
+ * output type as the generic argument so `ctx.parallel(...)` infers the result
141
+ * tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
142
+ */
143
+ declare const branch: <Output = unknown>(workflow: string, params?: Record<string, unknown>, options?: {
144
+ compensateWith?: string;
145
+ id?: string;
146
+ timeout?: number | string;
147
+ }) => WorkflowBranch<Output>;
134
148
  /** The lifecycle mutations the REST API exposes via `PATCH .../instances/{id}`. */
135
149
  type WorkflowInstanceAction = "pause" | "resume" | "terminate";
136
150
  /** Configuration for a {@link WorkflowsRestClient}. */
@@ -178,8 +192,7 @@ interface WorkflowInstancePage {
178
192
  totalCount?: number;
179
193
  }
180
194
  /** Thrown when the REST API responds non-2xx or `success: false`; carries the status plus body for the caller to surface. */
181
- declare class WorkflowsRestError extends Error {
182
- readonly status: number;
195
+ declare class WorkflowsRestError extends LunoraError {
183
196
  constructor(status: number, body: string);
184
197
  }
185
198
  /** The observe client: list instances, read one instance's steps, and (with Edit scope) mutate its status. */
@@ -203,30 +216,12 @@ interface WorkflowsRestClient {
203
216
  }>;
204
217
  }
205
218
  /**
206
- * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
207
- * endpoint with the bearer token, unwraps Cloudflare's
208
- * `{ success, errors, result, result_info }` envelope, and normalizes the
209
- * snake_case payload into the camelCase shapes the studio renders.
210
- */
219
+ * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
220
+ * endpoint with the bearer token, unwraps Cloudflare's
221
+ * `{ success, errors, result, result_info }` envelope, and normalizes the
222
+ * snake_case payload into the camelCase shapes the studio renders.
223
+ */
211
224
  declare const createWorkflowsRestClient: (config: WorkflowsRestConfig) => WorkflowsRestClient;
212
- interface RunnerOptions {
213
- /** Worker `env` — read `LUNORA_ORIGIN_URL` + `LUNORA_ADMIN_TOKEN` at call time. */
214
- env: Record<string, unknown>;
215
- /** Injectable fetch (tests); defaults to the global. */
216
- fetchImpl?: typeof fetch;
217
- }
218
- /**
219
- * Build a {@link WorkflowRunFunction} that invokes a Lunora function by POSTing
220
- * to the Worker's `/_lunora/scheduler/dispatch` endpoint — the same path the
221
- * SchedulerDO and the Queues workpool dispatch through — authenticated with the
222
- * admin bearer. The parsed JSON body (the function's return value) is resolved;
223
- * an empty/non-JSON body resolves to `undefined`.
224
- *
225
- * Wrap calls in `ctx.step.do(...)` to make them durable + memoized + retried.
226
- */
227
- declare const createWorkflowRunner: (options: RunnerOptions) => WorkflowRunFunction;
228
- /** Console-backed logger, prefixed with the workflow name for log correlation. */
229
- declare const createWorkflowLogger: (exportName: string) => WorkflowLogger;
230
225
  interface RunContextOptions<Params> {
231
226
  env: Record<string, unknown>;
232
227
  event: WorkflowEventLike<Params>;
@@ -239,12 +234,12 @@ interface RunContextOptions<Params> {
239
234
  /** Assemble the {@link WorkflowRunContext} passed to a `defineWorkflow` handler. */
240
235
  declare const createWorkflowRunContext: <Params = Record<string, unknown>>(options: RunContextOptions<Params>) => WorkflowRunContext<Params>;
241
236
  /**
242
- * Validate a step's args through its validator map, prefixing any
243
- * `ValidationError` with `step args.&lt;key>` so the failure points at the
244
- * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
245
- * — the same parser the procedure builder and HTTP routes use — so the
246
- * optional-skip and error-prefix semantics stay in lockstep across the framework.
247
- */
237
+ * Validate a step's args through its validator map, prefixing any
238
+ * `ValidationError` with `step args.&lt;key>` so the failure points at the
239
+ * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
240
+ * — the same parser the procedure builder and HTTP routes use — so the
241
+ * optional-skip and error-prefix semantics stay in lockstep across the framework.
242
+ */
248
243
  declare const validateStepArgs: (validators: StepArgsValidator, source: Record<string, unknown>) => Record<string, unknown>;
249
244
  /** Dependencies needed to run a step: the native step API plus the workflow's env / runner / logger. */
250
245
  interface RunStepDeps {
@@ -260,10 +255,10 @@ interface RunStepDeps {
260
255
  step: WorkflowStepLike;
261
256
  }
262
257
  /**
263
- * Build the `ctx.runStep` function bound to one workflow invocation. Each call
264
- * runs the step through `step.do(...)`: validate args → run body → validate
265
- * result (when `returns` is declared), with any portable `NonRetryableError`
266
- * converted to the native one and any declared rollback forwarded to Cloudflare.
267
- */
258
+ * Build the `ctx.runStep` function bound to one workflow invocation. Each call
259
+ * runs the step through `step.do(...)`: validate args → run body → validate
260
+ * result (when `returns` is declared), with any portable `NonRetryableError`
261
+ * converted to the native one and any declared rollback forwarded to Cloudflare.
262
+ */
268
263
  declare const createRunStep: (deps: RunStepDeps) => WorkflowRunStepFunction;
269
- export { type LunoraWorkflowsOptions, type NativeNonRetryableErrorConstructor, NonRetryableError, type StepArgsValidator, type StepConfig, type StepDefinition, type WorkflowBindingSpec, 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, convertNonRetryableError, createRunStep, createWorkflowContext, createWorkflowLogger, createWorkflowRunContext, createWorkflowRunner, createWorkflows, createWorkflowsRestClient, defineStep, defineWorkflow, isNonRetryableError, isStepDefinition, isWorkflowDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
264
+ 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 };
package/dist/index.mjs CHANGED
@@ -1,8 +1,9 @@
1
- export { createWorkflowContext } from './packem_shared/createWorkflowContext-D6thzmlF.mjs';
2
- export { default as createWorkflows } from './packem_shared/createWorkflows-BoSYVIXg.mjs';
1
+ export { createWorkflowContext } from './packem_shared/createWorkflowContext-oxZ5zj3x.mjs';
2
+ export { default as createWorkflows } from './packem_shared/createWorkflows-wq4fs72q.mjs';
3
3
  export { defineStep, isStepDefinition } from './packem_shared/defineStep-DJQtLw7g.mjs';
4
4
  export { defineWorkflow, isWorkflowDefinition, workflowBindingName, workflowClassName, workflowDefaultName } from './packem_shared/defineWorkflow-DbUC-oCN.mjs';
5
- export { NonRetryableError, convertNonRetryableError, isNonRetryableError, toNativeNonRetryableError } from './packem_shared/convertNonRetryableError-Dn2dTyBS.mjs';
6
- export { WorkflowsRestError, createWorkflowsRestClient } from './packem_shared/WorkflowsRestError-b06i7K5j.mjs';
7
- export { createWorkflowLogger, createWorkflowRunContext, createWorkflowRunner } from './packem_shared/createWorkflowLogger-FktqxNLe.mjs';
8
- export { createRunStep, validateStepArgs } from './packem_shared/createRunStep-BsK4LsUX.mjs';
5
+ export { NonRetryableError, convertNonRetryableError, isNonRetryableError, toNativeNonRetryableError } from './packem_shared/NonRetryableError-Dn2dTyBS.mjs';
6
+ export { MAX_BRANCHES, branch } from './packem_shared/MAX_BRANCHES-EO5xYS_3.mjs';
7
+ export { WorkflowsRestError, createWorkflowsRestClient } from './packem_shared/WorkflowsRestError-zmjOxTR1.mjs';
8
+ export { createWorkflowRunContext } from './packem_shared/createWorkflowRunContext-D62MbkFK.mjs';
9
+ export { createRunStep, validateStepArgs } from './packem_shared/createRunStep-8jOXxP2o.mjs';
@@ -0,0 +1,170 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+ import { NonRetryableError } from './NonRetryableError-Dn2dTyBS.mjs';
3
+
4
+ const MAX_BRANCHES = 100;
5
+ const BRANCH_MARKER_KEY = "__lunoraBranch";
6
+ const SPAWN_STEP_PREFIX = "lunora:spawn:";
7
+ const AWAIT_STEP_PREFIX = "lunora:await:";
8
+ const SIGNAL_STEP_PREFIX = "lunora:signal:";
9
+ const COMPENSATE_STEP_PREFIX = "lunora:compensate:";
10
+ const BRANCH_EVENT_PREFIX = "lunora:branch:";
11
+ const branch = (workflow, params, options) => {
12
+ return { compensateWith: options?.compensateWith, id: options?.id, params, timeout: options?.timeout, workflow };
13
+ };
14
+ const serializeError = (error) => {
15
+ if (error instanceof Error) {
16
+ return { message: error.message, name: error.name };
17
+ }
18
+ return { message: String(error), name: "Error" };
19
+ };
20
+ const okOutcome = (value) => {
21
+ return { status: "ok", value };
22
+ };
23
+ const errorOutcome = (error) => {
24
+ return { error: serializeError(error), status: "error" };
25
+ };
26
+ const compensateCompleted = async (deps, completed, error) => {
27
+ for (let cursor = completed.length - 1; cursor >= 0; cursor -= 1) {
28
+ const done = completed[cursor];
29
+ const compensateWith = done?.plan.item.compensateWith;
30
+ if (done === void 0 || compensateWith === void 0) {
31
+ continue;
32
+ }
33
+ try {
34
+ const compensation = deps.resolveBinding(compensateWith);
35
+ await deps.step.do(`${COMPENSATE_STEP_PREFIX}${done.plan.childId}`, async () => {
36
+ const compensateId = `${done.plan.childId}:compensate`;
37
+ const compensationParams = {
38
+ branch: done.plan.item.workflow,
39
+ error,
40
+ index: done.plan.index,
41
+ output: done.output
42
+ };
43
+ await compensation.create({ id: compensateId, params: compensationParams });
44
+ return compensateId;
45
+ });
46
+ } catch (compensationError) {
47
+ deps.log?.error(
48
+ `ctx.parallel: group-saga compensation "${compensateWith}" for branch "${done.plan.item.workflow}" (#${String(done.plan.index)}) failed`,
49
+ compensationError
50
+ );
51
+ }
52
+ }
53
+ };
54
+ const createParallel = (deps) => {
55
+ const run = async (branches) => {
56
+ if (branches.length === 0) {
57
+ return [];
58
+ }
59
+ if (branches.length > MAX_BRANCHES) {
60
+ throw new NonRetryableError(
61
+ `ctx.parallel: ${String(branches.length)} branches exceeds the cap of ${String(MAX_BRANCHES)} — split the fan-out or raise the work into fewer child workflows`
62
+ );
63
+ }
64
+ const planned = branches.map((item, index) => {
65
+ const childId = deps.nextChildId(item.id);
66
+ return { childId, eventType: `${BRANCH_EVENT_PREFIX}${childId}`, index, item };
67
+ });
68
+ const seenIds = /* @__PURE__ */ new Set();
69
+ for (const plan of planned) {
70
+ if (seenIds.has(plan.childId)) {
71
+ throw new NonRetryableError(
72
+ `ctx.parallel: duplicate branch id "${plan.childId}" — each branch in a group must resolve to a unique child instance id (check explicit \`id\` options)`
73
+ );
74
+ }
75
+ seenIds.add(plan.childId);
76
+ }
77
+ await Promise.all(
78
+ planned.map(
79
+ (plan) => deps.step.do(`${SPAWN_STEP_PREFIX}${plan.childId}`, async () => {
80
+ const binding = deps.resolveBinding(plan.item.workflow);
81
+ const marker = { eventType: plan.eventType, index: plan.index, parentBinding: deps.parentBinding, parentId: deps.instanceId };
82
+ await binding.create({ id: plan.childId, params: { ...plan.item.params, [BRANCH_MARKER_KEY]: marker } });
83
+ return plan.childId;
84
+ })
85
+ )
86
+ );
87
+ const results = [];
88
+ const completed = [];
89
+ for (const plan of planned) {
90
+ let outcome;
91
+ try {
92
+ const event = await deps.step.waitForEvent(`${AWAIT_STEP_PREFIX}${plan.childId}`, {
93
+ timeout: plan.item.timeout,
94
+ type: plan.eventType
95
+ });
96
+ outcome = event.payload;
97
+ } catch (joinError) {
98
+ const joinFailure = serializeError(joinError);
99
+ await compensateCompleted(deps, completed, joinFailure);
100
+ throw new NonRetryableError(`ctx.parallel: branch "${plan.item.workflow}" (#${String(plan.index)}) join failed: ${joinFailure.message}`);
101
+ }
102
+ if (outcome.status === "error") {
103
+ await compensateCompleted(deps, completed, outcome.error);
104
+ throw new NonRetryableError(`ctx.parallel: branch "${plan.item.workflow}" (#${String(plan.index)}) failed: ${outcome.error.message}`);
105
+ }
106
+ completed.push({ output: outcome.value, plan });
107
+ results.push(outcome.value);
108
+ }
109
+ return results;
110
+ };
111
+ return run;
112
+ };
113
+ const createSpawn = (deps) => async (workflow, params, options) => {
114
+ if (params !== void 0 && Object.hasOwn(params, BRANCH_MARKER_KEY)) {
115
+ throw new LunoraError("BAD_REQUEST", `@lunora/workflow: params may not contain the reserved key "${BRANCH_MARKER_KEY}"`);
116
+ }
117
+ const childId = deps.nextChildId(options?.id);
118
+ await deps.step.do(`${SPAWN_STEP_PREFIX}${childId}`, async () => {
119
+ const binding = deps.resolveBinding(workflow);
120
+ await binding.create({ id: childId, params });
121
+ return childId;
122
+ });
123
+ return deps.resolveBinding(workflow).get(childId);
124
+ };
125
+ const extractBranchMarker = (payload) => {
126
+ if (typeof payload !== "object" || payload === null) {
127
+ return void 0;
128
+ }
129
+ const marker = payload[BRANCH_MARKER_KEY];
130
+ if (typeof marker !== "object" || marker === null) {
131
+ return void 0;
132
+ }
133
+ const candidate = marker;
134
+ if (typeof candidate.eventType !== "string" || typeof candidate.parentBinding !== "string" || typeof candidate.parentId !== "string" || typeof candidate.index !== "number") {
135
+ return void 0;
136
+ }
137
+ if (!candidate.parentBinding.startsWith("WORKFLOW_") || !candidate.eventType.startsWith(BRANCH_EVENT_PREFIX)) {
138
+ return void 0;
139
+ }
140
+ return { eventType: candidate.eventType, index: candidate.index, parentBinding: candidate.parentBinding, parentId: candidate.parentId };
141
+ };
142
+ const stripBranchMarker = (payload) => {
143
+ if (typeof payload !== "object" || payload === null) {
144
+ return payload;
145
+ }
146
+ const rest = { ...payload };
147
+ Reflect.deleteProperty(rest, BRANCH_MARKER_KEY);
148
+ return rest;
149
+ };
150
+ const signalBranchParent = async (deps, marker, outcome) => {
151
+ const binding = deps.env[marker.parentBinding];
152
+ if (!binding || typeof binding.get !== "function") {
153
+ return;
154
+ }
155
+ const getParent = binding.get.bind(binding);
156
+ await deps.step.do(`${SIGNAL_STEP_PREFIX}${String(marker.index)}`, async () => {
157
+ const parent = await getParent(marker.parentId);
158
+ await parent.sendEvent({ payload: outcome, type: marker.eventType });
159
+ return marker.eventType;
160
+ });
161
+ };
162
+ const signalBranchParentSafe = async (deps, marker, outcome) => {
163
+ try {
164
+ await signalBranchParent(deps, marker, outcome);
165
+ } catch (signalError) {
166
+ deps.log?.error(`@lunora/workflow: failed to signal branch parent "${marker.parentId}" (event "${marker.eventType}")`, signalError);
167
+ }
168
+ };
169
+
170
+ export { BRANCH_MARKER_KEY, MAX_BRANCHES, branch, createParallel, createSpawn, errorOutcome, extractBranchMarker, okOutcome, signalBranchParent, signalBranchParentSafe, stripBranchMarker };
@@ -1,3 +1,5 @@
1
+ import { LunoraError } from '@lunora/errors';
2
+
1
3
  const API_BASE = "https://api.cloudflare.com/client/v4/accounts";
2
4
  const KNOWN_STATUSES = {
3
5
  complete: true,
@@ -41,12 +43,9 @@ const toStep = (raw) => {
41
43
  type: asString(raw["type"])
42
44
  };
43
45
  };
44
- class WorkflowsRestError extends Error {
45
- status;
46
+ class WorkflowsRestError extends LunoraError {
46
47
  constructor(status, body) {
47
- super(`Cloudflare Workflows REST API returned ${String(status)}: ${body}`);
48
- this.name = "WorkflowsRestError";
49
- this.status = status;
48
+ super("WORKFLOWS_REST_ERROR", `Cloudflare Workflows REST API returned ${String(status)}: ${body}`, { name: "WorkflowsRestError", status });
50
49
  }
51
50
  }
52
51
  const createWorkflowsRestClient = (config) => {
@@ -1,5 +1,5 @@
1
1
  import { parseValidatorMap } from '@lunora/values';
2
- import { convertNonRetryableError, NonRetryableError } from './convertNonRetryableError-Dn2dTyBS.mjs';
2
+ import { convertNonRetryableError, NonRetryableError } from './NonRetryableError-Dn2dTyBS.mjs';
3
3
 
4
4
  const validateStepArgs = (validators, source) => parseValidatorMap(validators, source, "step args");
5
5
  const createRunStep = (deps) => async (step, args, options) => {
@@ -1,4 +1,4 @@
1
- import createWorkflows from './createWorkflows-BoSYVIXg.mjs';
1
+ import createWorkflows from './createWorkflows-wq4fs72q.mjs';
2
2
 
3
3
  const createWorkflowContext = (env, specs) => {
4
4
  const bindings = {};