@lunora/workflow 1.0.0-alpha.6 → 1.0.0-alpha.61
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/LICENSE.md +6 -0
- package/README.md +25 -2
- package/dist/do/index.d.mts +16 -16
- package/dist/do/index.d.ts +16 -16
- package/dist/do/index.mjs +1 -44
- package/dist/index.d.mts +191 -122
- package/dist/index.d.ts +191 -122
- package/dist/index.mjs +1 -9
- package/dist/packem_shared/MAX_BRANCHES-j59ZUUSu.mjs +1 -0
- package/dist/packem_shared/NonRetryableError-BPu01mU8.mjs +1 -0
- package/dist/packem_shared/WorkflowsRestError-Ccq1FUR1.mjs +1 -0
- package/dist/packem_shared/branch-marker-CCpWfS5k.mjs +1 -0
- package/dist/packem_shared/createRunStep-DITrH01N.mjs +1 -0
- package/dist/packem_shared/createWaitForEvent-D5Ohn2Pz.mjs +1 -0
- package/dist/packem_shared/createWorkflowContext-zQR_9N-v.mjs +1 -0
- package/dist/packem_shared/createWorkflowRunContext-Dk5nhB1e.mjs +1 -0
- package/dist/packem_shared/createWorkflows-LvAyUyKq.mjs +1 -0
- package/dist/packem_shared/defineStep-D1-9eOnA.mjs +1 -0
- package/dist/packem_shared/defineWorkflow-tKaIifbZ.mjs +1 -0
- package/dist/packem_shared/defineWorkflowEvent-suERPEEV.mjs +1 -0
- package/dist/packem_shared/isDuplicateInstanceError-CecnqNAa.mjs +1 -0
- package/dist/packem_shared/run-step-bKFJhP--.mjs +1 -0
- package/dist/packem_shared/types.d-DKvSidAr.d.mts +560 -0
- package/dist/packem_shared/types.d-DKvSidAr.d.ts +560 -0
- package/package.json +3 -3
- package/dist/packem_shared/MAX_BRANCHES-D6cQabJ1.mjs +0 -132
- package/dist/packem_shared/NonRetryableError-Dn2dTyBS.mjs +0 -27
- package/dist/packem_shared/WorkflowsRestError-zmjOxTR1.mjs +0 -117
- package/dist/packem_shared/createRunStep-8jOXxP2o.mjs +0 -54
- package/dist/packem_shared/createWorkflowContext-DfSgBq5I.mjs +0 -14
- package/dist/packem_shared/createWorkflowRunContext-C09mSbgk.mjs +0 -112
- package/dist/packem_shared/createWorkflows-BC1Mwjwe.mjs +0 -25
- package/dist/packem_shared/defineStep-DJQtLw7g.mjs +0 -28
- package/dist/packem_shared/defineWorkflow-DbUC-oCN.mjs +0 -15
- package/dist/packem_shared/types.d-C9W6rEWv.d.mts +0 -425
- package/dist/packem_shared/types.d-C9W6rEWv.d.ts +0 -425
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as Workflows, L as LunoraWorkflowsOptions, S as StepArgsValidator,
|
|
2
|
-
export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionReference, I as InferStepArgs, R as RunFunctionOptions,
|
|
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-DKvSidAr.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-DKvSidAr.js";
|
|
3
|
+
import { Validator } from '@lunora/values';
|
|
3
4
|
import { LunoraError } from '@lunora/errors';
|
|
4
|
-
import '@lunora/values';
|
|
5
5
|
/** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
|
|
6
6
|
interface WorkflowBindingSpec {
|
|
7
7
|
/** The Cloudflare `Workflow` binding name, e.g. `WORKFLOW_ORDER_PIPELINE`. */
|
|
@@ -10,108 +10,152 @@ interface WorkflowBindingSpec {
|
|
|
10
10
|
exportName: string;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
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
|
-
*/
|
|
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
|
+
*/
|
|
19
19
|
declare const createWorkflowContext: (env: Record<string, unknown>, specs: ReadonlyArray<WorkflowBindingSpec>) => Workflows;
|
|
20
20
|
/**
|
|
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
|
-
*/
|
|
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
|
+
*/
|
|
25
25
|
declare const createWorkflows: (options: LunoraWorkflowsOptions) => Workflows;
|
|
26
26
|
/**
|
|
27
|
-
* Declare
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* import {
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
|
|
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
|
+
*/
|
|
54
84
|
declare const defineStep: <A extends StepArgsValidator, Result>(name: string, config: StepConfig<A, Result>) => StepDefinition<A, Result>;
|
|
55
85
|
/** True when a value is a `defineStep` result (the runtime brand check). */
|
|
56
86
|
declare const isStepDefinition: (value: unknown) => value is StepDefinition;
|
|
57
87
|
/**
|
|
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
|
-
*/
|
|
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
|
+
*/
|
|
63
93
|
declare const workflowClassName: (exportName: string) => string;
|
|
64
94
|
/**
|
|
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
|
-
*/
|
|
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
|
+
*/
|
|
70
100
|
declare const workflowBindingName: (exportName: string) => string;
|
|
71
101
|
/**
|
|
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
|
-
*/
|
|
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
|
+
*/
|
|
76
106
|
declare const workflowDefaultName: (exportName: string) => string;
|
|
77
107
|
/**
|
|
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
|
|
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
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
* })
|
|
97
|
-
*
|
|
98
|
-
|
|
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
|
+
* // A raw `step.do` retries its callback in place, so a WRITE made through
|
|
124
|
+
* // it needs an explicit dedup id (or use `ctx.runStep`, which pins one).
|
|
125
|
+
* await ctx.step.do("charge", () =>
|
|
126
|
+
* ctx.run(api.payments.charge, { orderId: ctx.params.orderId }, { dedupId: `charge:${ctx.params.orderId}` }),
|
|
127
|
+
* );
|
|
128
|
+
* return order;
|
|
129
|
+
* },
|
|
130
|
+
* });
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
99
133
|
declare const defineWorkflow: <Params = Record<string, unknown>, Output = unknown>(config: WorkflowConfig<Params, Output>) => WorkflowDefinition<Params, Output>;
|
|
100
134
|
/** True when a value is a `defineWorkflow` result (the runtime brand check). */
|
|
101
135
|
declare const isWorkflowDefinition: (value: unknown) => value is WorkflowDefinition;
|
|
102
136
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
*
|
|
114
|
-
|
|
137
|
+
* Whether a `WorkflowBinding.create()` rejection is a duplicate-instance-id
|
|
138
|
+
* error — the idempotency signal that a *previous* attempt's create already
|
|
139
|
+
* applied — as opposed to a transient or config failure (Workflows service
|
|
140
|
+
* error, instance-creation quota, bad params).
|
|
141
|
+
*
|
|
142
|
+
* Every other failure MUST surface, so the caller retries or fails visibly
|
|
143
|
+
* rather than silently reporting success for work that never started.
|
|
144
|
+
*/
|
|
145
|
+
declare const isDuplicateInstanceError: (error: unknown) => boolean;
|
|
146
|
+
/**
|
|
147
|
+
* Throw from a workflow step (or handler) to fail the instance immediately
|
|
148
|
+
* **without** retrying — the portable mirror of `cloudflare:workflows`'
|
|
149
|
+
* `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
|
|
150
|
+
*
|
|
151
|
+
* ```ts
|
|
152
|
+
* import { NonRetryableError } from "@lunora/workflow";
|
|
153
|
+
*
|
|
154
|
+
* if (order.status === "cancelled") {
|
|
155
|
+
* throw new NonRetryableError("order already cancelled — no point retrying");
|
|
156
|
+
* }
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
115
159
|
declare class NonRetryableError extends Error {
|
|
116
160
|
constructor(message: string, name?: string);
|
|
117
161
|
}
|
|
@@ -120,34 +164,31 @@ declare const isNonRetryableError: (value: unknown) => value is NonRetryableErro
|
|
|
120
164
|
/** Constructor shape of `cloudflare:workflows`' native `NonRetryableError`. */
|
|
121
165
|
type NativeNonRetryableErrorConstructor = new (message: string, name?: string) => Error;
|
|
122
166
|
/**
|
|
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
|
-
*/
|
|
167
|
+
* Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
|
|
168
|
+
* preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
|
|
169
|
+
* boundary where the native constructor is available; everywhere else the
|
|
170
|
+
* portable error is thrown unchanged (and still honored by name).
|
|
171
|
+
*/
|
|
128
172
|
declare const toNativeNonRetryableError: (error: NonRetryableError, NativeNonRetryableError: NativeNonRetryableErrorConstructor) => Error;
|
|
129
173
|
/**
|
|
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
|
-
*/
|
|
174
|
+
* If `error` is a portable {@link NonRetryableError} and a native constructor is
|
|
175
|
+
* available, rethrow it as the native error; otherwise rethrow `error` as-is.
|
|
176
|
+
* Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
|
|
177
|
+
*/
|
|
134
178
|
declare const convertNonRetryableError: (error: unknown, NativeNonRetryableError: NativeNonRetryableErrorConstructor | undefined) => never;
|
|
135
179
|
/** Hard cap on branches per `ctx.parallel` call — auto-scale, never silently spawn unbounded DOs. */
|
|
136
180
|
declare const MAX_BRANCHES = 100;
|
|
137
|
-
/** The params key the parent injects so a child knows to signal completion back. Stripped before the user handler sees `ctx.params`. */
|
|
138
|
-
|
|
139
181
|
/**
|
|
140
|
-
* Build a single fan-out branch: a declared child workflow referenced by its
|
|
141
|
-
* `lunora/workflows.ts` export name, plus the params it is created with. Pass the
|
|
142
|
-
* output type as the generic argument so `ctx.parallel(...)` infers the result
|
|
143
|
-
* tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
|
|
144
|
-
*/
|
|
182
|
+
* Build a single fan-out branch: a declared child workflow referenced by its
|
|
183
|
+
* `lunora/workflows.ts` export name, plus the params it is created with. Pass the
|
|
184
|
+
* output type as the generic argument so `ctx.parallel(...)` infers the result
|
|
185
|
+
* tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
|
|
186
|
+
*/
|
|
145
187
|
declare const branch: <Output = unknown>(workflow: string, params?: Record<string, unknown>, options?: {
|
|
146
188
|
compensateWith?: string;
|
|
147
189
|
id?: string;
|
|
148
190
|
timeout?: number | string;
|
|
149
191
|
}) => WorkflowBranch<Output>;
|
|
150
|
-
/** Build the success outcome a completed branch reports to its parent. */
|
|
151
192
|
/** The lifecycle mutations the REST API exposes via `PATCH .../instances/{id}`. */
|
|
152
193
|
type WorkflowInstanceAction = "pause" | "resume" | "terminate";
|
|
153
194
|
/** Configuration for a {@link WorkflowsRestClient}. */
|
|
@@ -194,7 +235,14 @@ interface WorkflowInstancePage {
|
|
|
194
235
|
perPage: number;
|
|
195
236
|
totalCount?: number;
|
|
196
237
|
}
|
|
197
|
-
/**
|
|
238
|
+
/**
|
|
239
|
+
* Thrown when the REST API responds non-2xx or `success: false`; carries the
|
|
240
|
+
* status plus a capped body preview, with the full body on `cause`.
|
|
241
|
+
*
|
|
242
|
+
* The preview is capped because the Cloudflare API's auth/authorization error
|
|
243
|
+
* text (and its HTML gateway pages) would otherwise ride out verbatim —
|
|
244
|
+
* `WORKFLOWS_REST_ERROR` is non-internal, so the message reaches the browser.
|
|
245
|
+
*/
|
|
198
246
|
declare class WorkflowsRestError extends LunoraError {
|
|
199
247
|
constructor(status: number, body: string);
|
|
200
248
|
}
|
|
@@ -219,11 +267,11 @@ interface WorkflowsRestClient {
|
|
|
219
267
|
}>;
|
|
220
268
|
}
|
|
221
269
|
/**
|
|
222
|
-
* Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
|
|
223
|
-
* endpoint with the bearer token, unwraps Cloudflare's
|
|
224
|
-
* `{ success, errors, result, result_info }` envelope, and normalizes the
|
|
225
|
-
* snake_case payload into the camelCase shapes the studio renders.
|
|
226
|
-
*/
|
|
270
|
+
* Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
|
|
271
|
+
* endpoint with the bearer token, unwraps Cloudflare's
|
|
272
|
+
* `{ success, errors, result, result_info }` envelope, and normalizes the
|
|
273
|
+
* snake_case payload into the camelCase shapes the studio renders.
|
|
274
|
+
*/
|
|
227
275
|
declare const createWorkflowsRestClient: (config: WorkflowsRestConfig) => WorkflowsRestClient;
|
|
228
276
|
interface RunContextOptions<Params> {
|
|
229
277
|
env: Record<string, unknown>;
|
|
@@ -237,15 +285,17 @@ interface RunContextOptions<Params> {
|
|
|
237
285
|
/** Assemble the {@link WorkflowRunContext} passed to a `defineWorkflow` handler. */
|
|
238
286
|
declare const createWorkflowRunContext: <Params = Record<string, unknown>>(options: RunContextOptions<Params>) => WorkflowRunContext<Params>;
|
|
239
287
|
/**
|
|
240
|
-
* Validate a step's args through its validator map, prefixing any
|
|
241
|
-
* `ValidationError` with `step args
|
|
242
|
-
* offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
|
|
243
|
-
* — the same parser the procedure builder and HTTP routes use — so the
|
|
244
|
-
* optional-skip and error-prefix semantics stay in lockstep across the framework.
|
|
245
|
-
*/
|
|
288
|
+
* Validate a step's args through its validator map, prefixing any
|
|
289
|
+
* `ValidationError` with `step args.<key>` so the failure points at the
|
|
290
|
+
* offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
|
|
291
|
+
* — the same parser the procedure builder and HTTP routes use — so the
|
|
292
|
+
* optional-skip and error-prefix semantics stay in lockstep across the framework.
|
|
293
|
+
*/
|
|
246
294
|
declare const validateStepArgs: (validators: StepArgsValidator, source: Record<string, unknown>) => Record<string, unknown>;
|
|
247
295
|
/** Dependencies needed to run a step: the native step API plus the workflow's env / runner / logger. */
|
|
248
296
|
interface RunStepDeps {
|
|
297
|
+
/** The instance's `dedupNamespace(exportName, instanceId)` — the prefix of the replay-dedup ids the steps' dispatches carry (see `dedup-id.ts`). */
|
|
298
|
+
dedupNamespace: string;
|
|
249
299
|
/** The Worker environment bindings, surfaced on the step context. */
|
|
250
300
|
env: Record<string, unknown>;
|
|
251
301
|
/** Structured logger surfaced on the step context. */
|
|
@@ -258,10 +308,29 @@ interface RunStepDeps {
|
|
|
258
308
|
step: WorkflowStepLike;
|
|
259
309
|
}
|
|
260
310
|
/**
|
|
261
|
-
* Build the `ctx.runStep` function bound to one workflow invocation. Each call
|
|
262
|
-
* runs the step through `step.do(...)`: validate args → run body → validate
|
|
263
|
-
* result (when `returns` is declared), with any portable `NonRetryableError`
|
|
264
|
-
* converted to the native one and any declared rollback forwarded to Cloudflare.
|
|
265
|
-
*/
|
|
311
|
+
* Build the `ctx.runStep` function bound to one workflow invocation. Each call
|
|
312
|
+
* runs the step through `step.do(...)`: validate args → run body → validate
|
|
313
|
+
* result (when `returns` is declared), with any portable `NonRetryableError`
|
|
314
|
+
* converted to the native one and any declared rollback forwarded to Cloudflare.
|
|
315
|
+
*/
|
|
266
316
|
declare const createRunStep: (deps: RunStepDeps) => WorkflowRunStepFunction;
|
|
267
|
-
|
|
317
|
+
/** Dependencies one workflow invocation's `ctx.waitForEvent` closes over. */
|
|
318
|
+
interface WaitForEventDeps {
|
|
319
|
+
/** Native `cloudflare:workflows` `NonRetryableError` constructor — injected by `src/do`; absent in Node tests. */
|
|
320
|
+
nonRetryableErrorClass?: NativeNonRetryableErrorConstructor;
|
|
321
|
+
/** The native Cloudflare durable-step API. */
|
|
322
|
+
step: WorkflowStepLike;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Build `ctx.waitForEvent` for one workflow invocation.
|
|
326
|
+
*
|
|
327
|
+
* Every failure here is **non-retryable**. A malformed definition or a reserved
|
|
328
|
+
* step name is a deterministic programmer error, and a payload that fails the
|
|
329
|
+
* validator has already consumed the event — replaying the wait cannot produce a
|
|
330
|
+
* different value, it can only hibernate the instance until its timeout. Each is
|
|
331
|
+
* raised through the shared {@link raiseNonRetryable}, the same classification path
|
|
332
|
+
* `ctx.runStep` uses, so the native error reaches Cloudflare and the instance fails
|
|
333
|
+
* fast.
|
|
334
|
+
*/
|
|
335
|
+
declare const createWaitForEvent: (deps: WaitForEventDeps) => WorkflowWaitForEventFunction;
|
|
336
|
+
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, isDuplicateInstanceError, isNonRetryableError, isStepDefinition, isWorkflowDefinition, isWorkflowEventDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
|
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { default as createWorkflows } from './packem_shared/createWorkflows-BC1Mwjwe.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-D6cQabJ1.mjs';
|
|
7
|
-
export { WorkflowsRestError, createWorkflowsRestClient } from './packem_shared/WorkflowsRestError-zmjOxTR1.mjs';
|
|
8
|
-
export { createWorkflowRunContext } from './packem_shared/createWorkflowRunContext-C09mSbgk.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 w,isWorkflowDefinition as x,workflowBindingName as k,workflowClassName as c,workflowDefaultName as E}from"./packem_shared/defineWorkflow-tKaIifbZ.mjs";import{NonRetryableError as N,convertNonRetryableError as R,isNonRetryableError as v,toNativeNonRetryableError as d}from"./packem_shared/NonRetryableError-BPu01mU8.mjs";import{MAX_BRANCHES as u,branch as C}from"./packem_shared/MAX_BRANCHES-j59ZUUSu.mjs";import{WorkflowsRestError as S,createWorkflowsRestClient as y}from"./packem_shared/WorkflowsRestError-Ccq1FUR1.mjs";import{createWorkflowRunContext as g}from"./packem_shared/createWorkflowRunContext-Dk5nhB1e.mjs";import{c as h,v as F}from"./packem_shared/run-step-bKFJhP--.mjs";import{createWaitForEvent as I}from"./packem_shared/createWaitForEvent-D5Ohn2Pz.mjs";import{isDuplicateInstanceError as X}from"./packem_shared/isDuplicateInstanceError-CecnqNAa.mjs";export{u as MAX_BRANCHES,N as NonRetryableError,S as WorkflowsRestError,C as branch,R as convertNonRetryableError,h as createRunStep,I as createWaitForEvent,e as createWorkflowContext,g as createWorkflowRunContext,f as createWorkflows,y as createWorkflowsRestClient,p as defineStep,w as defineWorkflow,a as defineWorkflowEvent,X as isDuplicateInstanceError,v as isNonRetryableError,s as isStepDefinition,x as isWorkflowDefinition,i as isWorkflowEventDefinition,d as toNativeNonRetryableError,F as validateStepArgs,k as workflowBindingName,c as workflowClassName,E as workflowDefaultName};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{h as x,B as A,a as g}from"./branch-marker-CCpWfS5k.mjs";import{RESERVED_EVENT_TYPE_PREFIX as P}from"./defineWorkflowEvent-suERPEEV.mjs";import{NonRetryableError as f}from"./NonRetryableError-BPu01mU8.mjs";import{isDuplicateInstanceError as N}from"./isDuplicateInstanceError-CecnqNAa.mjs";const p=t=>t.toString(16).padStart(4,"0"),O=t=>{let e=8997,n=33826,a=40164,o=52210;for(let c=0;c<t.length;c+=1){e^=t.charCodeAt(c);const l=e*435,d=n*435,h=a*435+e*256,r=o*435+n*256,s=d+(l>>>16),i=h+(s>>>16),u=r+(i>>>16);e=l&65535,n=s&65535,a=i&65535,o=u&65535}return p(o)+p(a)+p(n)+p(e)},v=100,I=100,b="lunora:spawn:",k="lunora:await:",C="lunora:signal:",W="lunora:compensate:",F=17,w=(t,e="")=>t.length+e.length<=I?`${t}${e}`:`${t.slice(0,I-e.length-F)}-${O(t)}${e}`,S=`${P}branch:`,G=(t,e,n)=>({compensateWith:n?.compensateWith,id:n?.id,params:e,timeout:n?.timeout,workflow:t}),T=t=>t instanceof Error?{message:t.message,name:t.name}:{message:String(t),name:"Error"},M=t=>({status:"ok",value:t}),U=t=>({error:T(t),status:"error"}),$=1048576,X=t=>{try{return String(t instanceof Error?t.message:t).slice(0,200)}catch{return"the failure itself could not be described"}},B=t=>{let e;try{e=new TextEncoder().encode(JSON.stringify(t)).length}catch(n){return{error:{message:`branch outcome cannot be serialised to JSON (${X(n)}) — the parent can never receive it. Return a plain JSON value (no cycles, no BigInt, no class instance that fails to serialise) or a reference the parent can dereference (an R2 key, a row id)`,name:"BranchOutputUnserializable"},status:"error"}}return e<=$?t:{error:{message:`branch outcome serialises to ${String(e)} bytes, over Cloudflare's ${String($)}-byte event payload limit — the parent can never receive it. Return a reference the parent can dereference (an R2 key, a row id) instead of the payload itself`,name:"BranchOutputTooLarge"},status:"error"}},E=async(t,e)=>{try{return{attached:!1,instance:await t.create(e)}}catch(n){if(!N(n))throw n;return{attached:!0,instance:await t.get(e.id)}}},j=async t=>{const{error:e,output:n,status:a}=await t.status();if(a==="complete")return M(n);if(a==="errored"||a==="terminated")return{error:e??{message:`branch instance ${a}`,name:"Error"},status:"error"}},D=t=>{if(typeof t!="object"||t===null)return;const{status:e}=t;return e==="error"||e==="ok"?t:void 0};class m extends Error{branchError;kind;plan;constructor(e,n,a){super(n.message),this.branchError=n,this.kind=a,this.plan=e}}const H=async(t,e,n)=>{for(let a=e.length-1;a>=0;a-=1){const o=e[a],c=o?.plan.item.compensateWith;if(!(o===void 0||c===void 0))try{const l=t.resolveBinding(c);await t.step.do(`${W}${o.plan.childId}`,async()=>{const d=w(o.plan.childId,"-compensate"),h={branch:o.plan.item.workflow,error:n,index:o.plan.index,output:o.output};return await E(l,{id:d,params:h}),d})}catch(l){t.log?.error(`ctx.parallel: group-saga compensation "${c}" for branch "${o.plan.item.workflow}" (#${String(o.plan.index)}) failed`,l)}}},q=t=>async n=>{if(n.length===0)return[];if(n.length>v)throw new f(`ctx.parallel: ${String(n.length)} branches exceeds the cap of ${String(v)} — split the fan-out or raise the work into fewer child workflows`);const a=n.map((r,s)=>{const i=w(t.nextChildId(r.id));return{childId:i,eventType:`${S}${i}`,index:s,item:r}}),o=new Set;for(const r of a){if(o.has(r.childId))throw new f(`ctx.parallel: duplicate branch id "${r.childId}" — each branch in a group must resolve to a unique child instance id (check explicit \`id\` options)`);o.add(r.childId)}const c=await Promise.all(a.map(r=>t.step.do(`${b}${r.childId}`,async()=>{const s=t.resolveBinding(r.item.workflow),i={eventType:r.eventType,index:r.index,parentBinding:t.parentBinding,parentId:t.instanceId},{attached:u,instance:_}=await E(s,{id:r.childId,params:{...r.item.params,[g]:i}});if(!u)return;const y=await j(_);return y===void 0?void 0:B(y)}))),l=Array.from({length:a.length}),d=Array.from({length:a.length}),h=async(r,s)=>{let i;if(s===void 0)try{i=(await t.step.waitForEvent(`${k}${r.childId}`,{timeout:r.item.timeout,type:r.eventType})).payload}catch(u){throw new m(r,T(u),"join failed")}else i=s;if(i.status==="error")throw new m(r,i.error,"failed");d[r.index]={output:i.value,plan:r},l[r.index]=i.value};try{await Promise.all(a.map((r,s)=>h(r,D(c[s]))))}catch(r){throw r instanceof m?(await H(t,d.filter(s=>s!==void 0),r.branchError),new f(`ctx.parallel: branch "${r.plan.item.workflow}" (#${String(r.plan.index)}) ${r.kind}: ${r.branchError.message}`)):r}return l},Q=t=>async(e,n,a)=>{if(x(n))throw new R("BAD_REQUEST",`@lunora/workflow: params ${A}`);const o=w(t.nextChildId(a?.id));return await t.step.do(`${b}${o}`,async()=>{const c=t.resolveBinding(e);return await E(c,{id:o,params:n}),o}),t.resolveBinding(e).get(o)},Z=t=>{if(typeof t!="object"||t===null)return;const e=t[g];if(typeof e!="object"||e===null)return;const n=e;if(!(typeof n.eventType!="string"||typeof n.parentBinding!="string"||typeof n.parentId!="string"||typeof n.index!="number")&&!(!n.parentBinding.startsWith("WORKFLOW_")||!n.eventType.startsWith(S)))return{eventType:n.eventType,index:n.index,parentBinding:n.parentBinding,parentId:n.parentId}},tt=t=>{if(typeof t!="object"||t===null)return t;const e={...t};return Reflect.deleteProperty(e,g),e},L=async(t,e,n)=>{const a=t.env[e.parentBinding];if(!a||typeof a.get!="function")return;const o=a.get.bind(a),c=B(n);await t.step.do(`${C}${String(e.index)}`,async()=>(await(await o(e.parentId)).sendEvent({payload:c,type:e.eventType}),e.eventType))},et=async(t,e,n)=>{try{await L(t,e,n)}catch(a){t.log?.error(`@lunora/workflow: failed to signal branch parent "${e.parentId}" (event "${e.eventType}")`,a)}};export{v as MAX_BRANCHES,G as branch,q as createParallel,Q as createSpawn,U as errorOutcome,Z as extractBranchMarker,M as okOutcome,L as signalBranchParent,et as signalBranchParentSafe,tt as stripBranchMarker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isDuplicateInstanceError as E}from"./isDuplicateInstanceError-CecnqNAa.mjs";const s="__lunoraNonRetryable";class r extends Error{constructor(e,n="NonRetryableError"){super(e),this.name=n,this[s]=!0}}const a=t=>t instanceof Error&&t[s]===!0,c=(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&&a(t)?c(t,e):t},u=(t,e,n)=>{const o=new r(t);return e!==void 0&&(o.cause=e),i(o,n)};export{r as NonRetryableError,i as convertNonRetryableError,E as isDuplicateInstanceError,a as isNonRetryableError,u as raiseNonRetryable,c as toNativeNonRetryableError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";const m=256,A=t=>t.length>m?`${t.slice(0,m)}… (truncated)`:t,$="https://api.cloudflare.com/client/v4/accounts",b={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},S=t=>typeof t=="string"&&Object.hasOwn(b,t)?t:"unknown",u=t=>typeof t=="string"&&t!==""?t:void 0,R=(t,a)=>typeof t=="string"?t:a,O=t=>typeof t=="boolean"?t:void 0,I=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:R(t.id,""),startedOn:u(t.started_on),status:S(t.status)}),C=t=>({attempts:I(t.attempts),end:u(t.end),error:t.error,name:R(t.name,""),output:t.output,start:u(t.start),success:O(t.success),type:u(t.type)});class g extends _{constructor(a,i){super("WORKFLOWS_REST_ERROR",`Cloudflare Workflows REST API returned ${String(a)}: ${A(i)}`,{cause:i,name:"WorkflowsRestError",status:a})}}const E=t=>{const a=t.fetch??globalThis.fetch.bind(globalThis),i=`${$}/${t.accountId}/workflows`,p=async(o,r)=>{const n=await a(`${i}${o}`,{...r,headers:{Authorization:`Bearer ${t.apiToken}`,"Content-Type":"application/json"}}),e=await n.text();let s;try{s=JSON.parse(e)}catch{throw new g(n.status,e)}if(!n.ok||s.success===!1)throw new g(n.status,e);return s};return{getInstance:async({instanceId:o,workflowName:r})=>{const e=(await p(`/${encodeURIComponent(r)}/instances/${encodeURIComponent(o)}`)).result??{},s=Array.isArray(e.steps)?e.steps:[];return{...f(e),error:e.error,output:e.output,params:e.params,steps:s.map(d=>C(d))}},listInstances:async({page:o,perPage:r,status:n,workflowName:e})=>{const s=new URLSearchParams;n!==void 0&&s.set("status",n),o!==void 0&&s.set("page",String(o)),r!==void 0&&s.set("per_page",String(r));const d=s.toString()===""?"":`?${s.toString()}`,l=await p(`/${encodeURIComponent(e)}/instances${d}`),y=Array.isArray(l.result)?l.result:[],c=l.result_info??{};return{instances:y.map(h=>f(h)),page:typeof c.page=="number"?c.page:o??1,perPage:typeof c.per_page=="number"?c.per_page:r??y.length,totalCount:typeof c.total_count=="number"?c.total_count:void 0}},setInstanceStatus:async({action:o,instanceId:r,workflowName:n})=>{const s=(await p(`/${encodeURIComponent(n)}/instances/${encodeURIComponent(r)}/status`,{body:JSON.stringify({status:o}),method:"PATCH"})).result??{};return{status:S(s.status)}}}};export{g as WorkflowsRestError,E 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-bKFJhP--.mjs";import"./defineWorkflowEvent-suERPEEV.mjs";import"./NonRetryableError-BPu01mU8.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-BPu01mU8.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{u as I,I as R,l as C,d as N,c as T,p as k}from"./run-step-bKFJhP--.mjs";import{LunoraError as S}from"@lunora/errors";import{workflowBindingName as y}from"./defineWorkflow-tKaIifbZ.mjs";import{raiseNonRetryable as _}from"./NonRetryableError-BPu01mU8.mjs";import{createSpawn as O,createParallel as v}from"./MAX_BRANCHES-j59ZUUSu.mjs";import{createWaitForEvent as $}from"./createWaitForEvent-D5Ohn2Pz.mjs";const x=e=>({debug:(t,...o)=>{console.debug(e,t,...o)},error:(t,...o)=>{console.error(e,t,...o)},info:(t,...o)=>{console.info(e,t,...o)},warn:(t,...o)=>{console.warn(e,t,...o)}}),j=e=>{let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)},P=e=>{const t=atob(e),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},B="$lunora.wire$",b=64,p=1024,g="__proto__",E={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},h={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=(e,t=0)=>{if(t>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===B)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>l(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=l(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[l(n[0],t+1),l(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>l(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const i=(Object.hasOwn(h,r)?h[r]:void 0)??Error,c=new i(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const f=l(e[4],t+1);if(f===null||typeof f!="object"||Array.isArray(f))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(f))d===g?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:f[d],writable:!0}):c[d]=f[d];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:l(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=P(r);if(j(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const i=e[3]??"Uint8Array";if(i==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(E,i)?E[i]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>l(r,t+1))}return e.map(s=>l(s,t+1))}const o=e,a={};for(const s of Object.keys(o)){const r=l(o[s],t+1);s===g?Object.defineProperty(a,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[s]=r}return a},U=1e3,D=3e4,M=async e=>{await new Promise(t=>{setTimeout(t,e)})},F=e=>async(t,o,a)=>{const s=async(r,n)=>{try{return await e(t,o,a)}catch(i){if(!I(i))throw i;const c=Date.now(),f=r??c,d=f+R-c;if(d<=0)throw i;return await M(Math.min(n,d)),s(f,Math.min(n*2,D))}};return s(void 0,U)},Y=e=>{const t=x(`[workflow:${e.exportName}]`),o=F(C({env:e.env,fetchImpl:e.fetchImpl,label:"@lunora/workflow"})),a=N(e.exportName,e.event.instanceId),s=k(o,`${a}#body`),r=u=>{const m=y(u),w=e.env[m];if(!w||typeof w.create!="function"||typeof w.get!="function")throw new S("INTERNAL",`@lunora/workflow: cannot spawn child workflow "${u}" — no Workflow binding "${m}" on env (is it declared in lunora/workflows.ts?)`);return w},n=e.exportName.replaceAll(/\W/gu,"_");let i=0;const c=u=>{if(u!==void 0)return u;const m=`${e.event.instanceId}-${n}-c${String(i)}`;return i+=1,m},f={env:e.env,instanceId:e.event.instanceId,log:t,nextChildId:c,parentBinding:y(e.exportName),resolveBinding:r,step:e.step},A=(()=>{try{return l(e.event.payload)}catch(u){return _(`@lunora/workflow: workflow "${e.exportName}" params could not be decoded — ${u instanceof Error?u.message:String(u)}`,u,e.nonRetryableErrorClass)}})();return{env:e.env,event:e.event,...e.fetchImpl===void 0?{}:{fetchImpl:e.fetchImpl},log:t,parallel:v(f),params:A,run:s,runStep:T({dedupNamespace:a,env:e.env,log:t,nonRetryableErrorClass:e.nonRetryableErrorClass,run:o,step:e.step}),spawn:O(f),step:e.step,waitForEvent:$({nonRetryableErrorClass:e.nonRetryableErrorClass,step:e.step})}};export{Y 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
|
+
const t=/already[\s_-]?exists/iu,e=s=>t.test(s instanceof Error?s.message:String(s));export{e as isDuplicateInstanceError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as w,isLunoraError as J}from"@lunora/errors";import{parseValidatorMap as H}from"@lunora/values";import{RESERVED_EVENT_TYPE_PREFIX as T}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as R,convertNonRetryableError as K}from"./NonRetryableError-BPu01mU8.mjs";const pr=9e5,V="DISPATCH_IN_PROGRESS",W="x-lunora-dispatch-declined",F=(r,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:r};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},$=r=>{let t="";for(let o=0;o<r.length;o+=32768)t+=String.fromCharCode(...r.subarray(o,o+32768));return btoa(t)},G=r=>{const t=atob(r),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",k=r=>{let t="",o=0;const a=r.length-2;for(;o<a;o+=3){const e=r[o]<<16|r[o+1]<<8|r[o+2];t+=b.charAt(e>>18&63)+b.charAt(e>>12&63)+b.charAt(e>>6&63)+b.charAt(e&63)}const n=r.length-o;if(n===1){const e=r[o]<<16;t+=b.charAt(e>>18&63)+b.charAt(e>>12&63)}else if(n===2){const e=r[o]<<16|r[o+1]<<8;t+=b.charAt(e>>18&63)+b.charAt(e>>12&63)+b.charAt(e>>6&63)}return t};new TextDecoder;const P=new TextEncoder,I="=",z=r=>{for(let t=0;t<r.length;t+=1)if(r.charCodeAt(t)>255)return!1;return!0},X=r=>k(P.encode(JSON.stringify(r))),Y=r=>!r.startsWith(I)&&z(r)?r:`${I}${k(P.encode(r))}`,f="$lunora.wire$",O=64,j=1024,S="__proto__",_={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},U={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},q=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},g=(r,t=0)=>{if(t>O)throw new RangeError(`wire-codec: value nesting exceeds the ${O}-level limit`);if(r===void 0)return[f,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint")return[f,"bigint",r.toString()];if(o==="number"){const e=r;return Number.isNaN(e)?[f,"nan"]:e===1/0?[f,"inf"]:e===-1/0?[f,"-inf"]:e}if(o!=="object")return r;if(r instanceof Date)return[f,"date",g(r.getTime(),t+1)];if(r instanceof Error){const e=r,s={};for(const c of Object.keys(e)){if(e[c]===void 0)continue;const l=g(e[c],t+1);c===S?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:l,writable:!0}):s[c]=l}const i=[f,"error",String(e.name),String(e.message),s];return e.cause!==void 0&&i.push(g(e.cause,t+1)),i}if(r instanceof URL)return[f,"url",r.href];if(r instanceof Map)return[f,"map",[...r.entries()].map(([e,s])=>[g(e,t+1),g(s,t+1)])];if(r instanceof Set)return[f,"set",[...r].map(e=>g(e,t+1))];if(r instanceof ArrayBuffer)return[f,"bytes",$(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,s=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return s==="Uint8Array"?[f,"bytes",$(i)]:[f,"bytes",$(i),s]}if(Array.isArray(r)){const e=r.map(s=>g(s,t+1));return e.length>0&&e[0]===f?[f,"arr",e]:e}if(!q(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,n={};for(const e of Object.keys(a)){const s=a[e];if(s===void 0)continue;const i=g(s,t+1);e===S?Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[e]=i}return n},y=(r,t=0)=>{if(t>O)throw new RangeError(`wire-codec: value nesting exceeds the ${O}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===f)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(n=>y(n,t+1));case"bigint":{const n=r[2];if(typeof n!="string"||n.length>j||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${j} digits)`);return BigInt(n)}case"date":{const n=y(r[2],t+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=r[2];return new Map(n.map(e=>{if(!Array.isArray(e)||e.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(e[0],t+1),y(e[1],t+1)]}))}case"set":return new Set(r[2].map(n=>y(n,t+1)));case"url":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=r[2],e=r[3];if(typeof n!="string"||typeof e!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(U,n)?U[n]:void 0)??Error,i=new s(e);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=y(r[4],t+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const l of Object.keys(c))l===S?Object.defineProperty(i,l,{configurable:!0,enumerable:!0,value:c[l],writable:!0}):i[l]=c[l];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:y(r[5],t+1),writable:!0}),i}case"bytes":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const e=G(n);if($(e)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=r[3]??"Uint8Array";if(s==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const i=Object.hasOwn(_,s)?_[s]:void 0;return i?new i(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(n=>y(n,t+1))}return r.map(n=>y(n,t+1))}const o=r,a={};for(const n of Object.keys(o)){const e=y(o[n],t+1);n===S?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:e,writable:!0}):a[n]=e}return a},Q=(r,t,o)=>{try{return g(o)}catch(a){throw new TypeError(`${r}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},Z="/_lunora/scheduler/dispatch",rr=3e4,tr=r=>{let t=r.length;for(;t>0&&r[t-1]==="/";)t-=1;return r.slice(0,t)},D=Symbol("lunoraDispatchFailure"),x=Symbol("lunoraDispatchDecline"),er=Symbol("lunoraDispatchMessageId"),C=(r,t)=>(t!==void 0&&Object.defineProperty(r,er,{value:t}),r),nr=(r,t)=>(Object.defineProperty(r,D,{value:!0}),C(r,t)),or=(r,t,o,a)=>{const{status:n}=t;try{const e=JSON.parse(o)?.error;if(typeof e=="object"&&e!==null&&typeof e.code=="string"){const{code:s,data:i,message:c}=e,l=nr(new w(s,typeof c=="string"?c:void 0,{data:i,status:n}),a);return t.headers.get(W)==="1"&&Object.defineProperty(l,x,{value:!0}),l}}catch{}return C(new w("INTERNAL",`${r}: function dispatch failed (${String(n)}): ${o}`,{status:n}),a)},ar=new Set([400,403,404,422]),sr=new Set([V,"DISPATCH_UNAUTHENTICATED"]),B=r=>J(r)&&r[D]===!0,ir=r=>B(r)&&ar.has(r.status)&&!sr.has(r.code),br=r=>B(r)&&r[x]===!0,cr=(r,t,o)=>new w("INTERNAL",`${r}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),gr=r=>{const{label:t}=r,o=globalThis.fetch,a=r.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,e,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>r.argsAlreadyEncoded===!0?e??{}:Q(t,n.__lunoraRef,e??{}),c=r.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new w("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const l=r.env.LUNORA_ADMIN_TOKEN;if(typeof l!="string"||l.length===0)throw new w("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const v=`${tr(c)}${Z}`,h={authorization:`Bearer ${l}`,"content-type":"application/json"};r.traceparent!==void 0&&r.traceparent.length>0&&(h.traceparent=r.traceparent),r.identity?.userId!==void 0&&(h["x-lunora-userid"]=Y(r.identity.userId)),r.identity?.claims!==void 0&&(h["x-lunora-identity"]=X(r.identity.claims));const p=s.timeoutMs??rr,N=F(void 0,p,()=>new DOMException(`dispatch timed out after ${String(p)}ms`,"TimeoutError")),m=d=>{throw d instanceof Error&&d.name==="TimeoutError"?cr(t,n.__lunoraRef,p):d};let u;try{try{u=await a(v,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:h,method:"POST",signal:N.signal})}catch(E){return m(E)}if(!u.ok){let E;try{E=await u.text()}catch(M){return m(M)}throw or(t,u,E,s.messageId)}let d;try{d=await u.text()}catch(E){return m(E)}if(d.length===0)return;let A;try{A=JSON.parse(d)}catch{throw new w("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(u.status)}): ${d}`,{status:u.status})}if(A===null||typeof A!="object"||Array.isArray(A)||!("result"in A))throw new w("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(u.status)}): ${d}`,{status:u.status});return y(A.result)}finally{N.dispose()}}},hr=(r,t)=>`${r}/${t}`,L=(r,t)=>{let o=0;return(a,n,e)=>(o+=1,r(a,n,{...e,dedupId:e?.dedupId??`${t}.${String(o)}`}))},ur=(r,t)=>H(r,t,"step args"),mr=r=>{let t=0;return async(o,a,n)=>{const e=`${r.dedupNamespace}#step${String(t)}`;t+=1;const s=n?.config??o.config,i=n?.name??o.name;if(i.startsWith(T))return R(`@lunora/workflow: ctx.runStep step name "${i}" is reserved — the "${T}" prefix is used by the framework's own steps`,void 0,r.nonRetryableErrorClass);const c=ur(o.args,a),l=async p=>{const N={attempt:p.attempt,config:p.config,env:r.env,log:r.log,run:L(r.run,e),step:p.step};let m;try{m=await o.handler(N,c)}catch(u){return ir(u)?R(u.message,u,r.nonRetryableErrorClass):K(u,r.nonRetryableErrorClass)}if(!o.returns)return m;try{return o.returns.parse(m)}catch(u){const d=u instanceof Error?u.message:String(u);return R(`step "${o.name}" returns validation failed: ${d}`,u,r.nonRetryableErrorClass)}},v=o.rollback,h=v?{rollback:async p=>{await v({args:c,env:r.env,error:p.error,log:r.log,output:p.output,run:L(r.run,`${e}rollback`)})},rollbackConfig:o.rollbackConfig}:void 0;return s===void 0?r.step.do(i,l,h):r.step.do(i,s,l,h)}};export{pr as I,mr as c,hr as d,gr as l,L as p,br as u,ur as v};
|