semola 0.5.4 → 0.6.1

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 (50) hide show
  1. package/README.md +35 -50
  2. package/dist/lib/api/index.cjs +1 -523
  3. package/dist/lib/api/index.d.cts +1 -271
  4. package/dist/lib/api/index.d.mts +80 -84
  5. package/dist/lib/api/index.mjs +1 -521
  6. package/dist/lib/cache/index.cjs +1 -74
  7. package/dist/lib/cache/index.d.cts +1 -48
  8. package/dist/lib/cache/index.d.mts +3 -24
  9. package/dist/lib/cache/index.mjs +1 -73
  10. package/dist/lib/cron/index.cjs +1 -735
  11. package/dist/lib/cron/index.d.cts +1 -146
  12. package/dist/lib/cron/index.d.mts +99 -36
  13. package/dist/lib/cron/index.mjs +1 -726
  14. package/dist/lib/errors/index.cjs +1 -30
  15. package/dist/lib/errors/index.d.cts +1 -2
  16. package/dist/lib/errors/index.d.mts +12 -1
  17. package/dist/lib/errors/index.mjs +1 -26
  18. package/dist/lib/i18n/index.cjs +1 -42
  19. package/dist/lib/i18n/index.d.cts +1 -28
  20. package/dist/lib/i18n/index.mjs +1 -41
  21. package/dist/lib/logging/index.cjs +1 -387
  22. package/dist/lib/logging/index.d.cts +1 -108
  23. package/dist/lib/logging/index.mjs +1 -374
  24. package/dist/lib/orm/index.cjs +1 -0
  25. package/dist/lib/orm/index.d.cts +1 -0
  26. package/dist/lib/orm/index.d.mts +404 -0
  27. package/dist/lib/orm/index.mjs +1 -0
  28. package/dist/lib/policy/index.cjs +1 -285
  29. package/dist/lib/policy/index.d.cts +1 -77
  30. package/dist/lib/policy/index.mjs +1 -265
  31. package/dist/lib/prompts/index.cjs +6 -769
  32. package/dist/lib/prompts/index.d.cts +1 -96
  33. package/dist/lib/prompts/index.d.mts +12 -33
  34. package/dist/lib/prompts/index.mjs +6 -763
  35. package/dist/lib/pubsub/index.cjs +1 -117
  36. package/dist/lib/pubsub/index.d.cts +1 -41
  37. package/dist/lib/pubsub/index.d.mts +3 -18
  38. package/dist/lib/pubsub/index.mjs +1 -116
  39. package/dist/lib/queue/index.cjs +1 -182
  40. package/dist/lib/queue/index.d.cts +1 -74
  41. package/dist/lib/queue/index.d.mts +11 -4
  42. package/dist/lib/queue/index.mjs +1 -181
  43. package/dist/lib/workflow/index.cjs +1 -534
  44. package/dist/lib/workflow/index.d.cts +1 -85
  45. package/dist/lib/workflow/index.d.mts +76 -11
  46. package/dist/lib/workflow/index.mjs +1 -533
  47. package/dist/rolldown-runtime-CMqjfN_6.cjs +1 -0
  48. package/package.json +17 -5
  49. package/dist/index-BhGNDjPq.d.mts +0 -13
  50. package/dist/index-DxSbeGP-.d.cts +0 -13
@@ -1,10 +1,5 @@
1
1
  //#region src/lib/workflow/types.d.ts
2
2
  type WorkflowStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
3
- type WorkflowErrorType = "WorkflowError" | "WorkflowNotFoundError" | "WorkflowStateError" | "WorkflowSerializationError" | "WorkflowLockError" | "WorkflowExecutionError" | "WorkflowCancelledError";
4
- type WorkflowError = {
5
- type: WorkflowErrorType;
6
- message: string;
7
- };
8
3
  type StepSnapshot = {
9
4
  name: string;
10
5
  completedAt: number;
@@ -32,10 +27,57 @@ type WorkflowHandlerContext<TInput> = {
32
27
  };
33
28
  type SerializeValue<T> = (value: T) => string;
34
29
  type DeserializeValue<T> = (raw: string) => T;
30
+ type WorkflowStepErrorRecord = {
31
+ attempt: number;
32
+ error: string;
33
+ timestamp: number;
34
+ };
35
+ type WorkflowStepRetryContext<TInput> = {
36
+ executionId: string;
37
+ input: TInput;
38
+ stepName: string;
39
+ error: string;
40
+ attempt: number;
41
+ nextRetryDelayMs: number;
42
+ retriesRemaining: number;
43
+ };
44
+ type WorkflowStepErrorContext<TInput> = {
45
+ executionId: string;
46
+ input: TInput;
47
+ stepName: string;
48
+ error: string;
49
+ totalAttempts: number;
50
+ errorHistory: WorkflowStepErrorRecord[];
51
+ };
52
+ type WorkflowHooks<TInput, TResult> = {
53
+ onStart?: (context: {
54
+ executionId: string;
55
+ input: TInput;
56
+ }) => void | Promise<void>;
57
+ onRetry?: (context: WorkflowStepRetryContext<TInput>) => void | Promise<void>;
58
+ onError?: (context: WorkflowStepErrorContext<TInput>) => void | Promise<void>;
59
+ onComplete?: (context: {
60
+ executionId: string;
61
+ input: TInput;
62
+ result: TResult;
63
+ }) => void | Promise<void>;
64
+ onCancel?: (context: {
65
+ executionId: string;
66
+ input: TInput;
67
+ }) => void | Promise<void>;
68
+ };
69
+ type WorkflowRetryBackoff = {
70
+ baseDelay?: number;
71
+ multiplier?: number;
72
+ maxDelay?: number;
73
+ };
35
74
  type WorkflowOptions<TInput, TResult> = {
36
75
  name: string;
37
76
  redis: Bun.RedisClient;
38
77
  handler: (context: WorkflowHandlerContext<TInput>) => TResult | Promise<TResult>;
78
+ retries?: number;
79
+ retryBackoff?: WorkflowRetryBackoff;
80
+ hooks?: WorkflowHooks<TInput, TResult>;
39
81
  lockTTL?: number;
40
82
  serializeInput?: SerializeValue<TInput>;
41
83
  deserializeInput?: DeserializeValue<TInput>;
@@ -72,14 +114,37 @@ type WorkflowMeta = {
72
114
  };
73
115
  type WorkflowMetaField = keyof WorkflowMeta;
74
116
  type Workflow<TInput, TResult> = {
75
- start: (input: TInput, options?: WorkflowStartOptions) => Promise<readonly [WorkflowError | null, WorkflowStartResult | null]>;
76
- run: (input: TInput, options?: WorkflowStartOptions) => Promise<readonly [WorkflowError | null, TResult | null]>;
77
- resume: (executionId: string) => Promise<readonly [WorkflowError | null, WorkflowStartResult | null]>;
78
- get: (executionId: string) => Promise<readonly [WorkflowError | null, WorkflowExecution<TInput, TResult> | null]>;
79
- cancel: (executionId: string) => Promise<readonly [WorkflowError | null, WorkflowCancelResult | null]>;
117
+ start: (input: TInput, options?: WorkflowStartOptions) => Promise<WorkflowStartResult>;
118
+ run: (input: TInput, options?: WorkflowStartOptions) => Promise<TResult | null>;
119
+ resume: (executionId: string) => Promise<WorkflowStartResult>;
120
+ get: (executionId: string) => Promise<WorkflowExecution<TInput, TResult>>;
121
+ cancel: (executionId: string) => Promise<WorkflowCancelResult>;
80
122
  };
81
123
  //#endregion
124
+ //#region src/lib/workflow/errors.d.ts
125
+ declare class WorkflowError extends Error {
126
+ constructor(message: string);
127
+ }
128
+ declare class NotFoundError extends Error {
129
+ constructor(message: string);
130
+ }
131
+ declare class StateError extends Error {
132
+ constructor(message: string);
133
+ }
134
+ declare class SerializationError extends Error {
135
+ constructor(message: string);
136
+ }
137
+ declare class ExecutionError extends Error {
138
+ constructor(message: string);
139
+ }
140
+ declare class LockError extends Error {
141
+ constructor(message: string);
142
+ }
143
+ declare class CancelledError extends Error {
144
+ constructor(message: string);
145
+ }
146
+ //#endregion
82
147
  //#region src/lib/workflow/index.d.ts
83
148
  declare const defineWorkflow: <TInput, TResult = void>(options: WorkflowOptions<TInput, TResult>) => Workflow<TInput, TResult>;
84
149
  //#endregion
85
- export { type StepHandler, type Workflow, type WorkflowError, type WorkflowExecution, type WorkflowHandlerContext, type WorkflowMeta, type WorkflowMetaField, type WorkflowOptions, type WorkflowStartOptions, type WorkflowStartResult, type WorkflowStatus, defineWorkflow };
150
+ export { CancelledError, ExecutionError, LockError, NotFoundError, SerializationError, StateError, type StepHandler, type Workflow, WorkflowError, type WorkflowExecution, type WorkflowHandlerContext, type WorkflowHooks, type WorkflowMeta, type WorkflowMetaField, type WorkflowOptions, type WorkflowRetryBackoff, type WorkflowStartOptions, type WorkflowStartResult, type WorkflowStatus, type WorkflowStepErrorContext, type WorkflowStepErrorRecord, type WorkflowStepRetryContext, defineWorkflow };
@@ -1,533 +1 @@
1
- import { err, mightThrow, mightThrowSync, ok } from "../errors/index.mjs";
2
- //#region src/lib/workflow/index.ts
3
- const DEFAULT_LOCK_TTL = 300 * 1e3;
4
- const now = () => Date.now();
5
- const toErrorMessage = (error) => {
6
- if (error instanceof Error) return error.message;
7
- return String(error);
8
- };
9
- const envelopeSerialize = (value) => {
10
- return JSON.stringify({ value });
11
- };
12
- const envelopeDeserialize = (raw) => {
13
- const [parseError, parsed] = mightThrowSync(() => JSON.parse(raw));
14
- if (parseError) throw parseError;
15
- if (parsed === null) return;
16
- if (typeof parsed !== "object") return;
17
- if ("value" in parsed) return parsed.value;
18
- };
19
- const knownStatuses = [
20
- "pending",
21
- "running",
22
- "completed",
23
- "failed",
24
- "cancelled"
25
- ];
26
- var WorkflowDefinition = class {
27
- options;
28
- lockTTL;
29
- constructor(options) {
30
- this.options = options;
31
- this.lockTTL = options.lockTTL ?? DEFAULT_LOCK_TTL;
32
- }
33
- async start(input, options) {
34
- const executionId = options?.executionId ?? crypto.randomUUID();
35
- const [createError] = await this.createExecution(executionId, input);
36
- if (createError) return err(createError.type, createError.message);
37
- return this.execute(executionId, input);
38
- }
39
- async run(input, options) {
40
- const [startError, startData] = await this.start(input, options);
41
- if (startError) return err(startError.type, startError.message);
42
- if (!startData) return err("WorkflowError", "Unexpected empty start result");
43
- if (startData.status === "cancelled") return err("WorkflowCancelledError", `Workflow execution ${startData.executionId} was cancelled`);
44
- if (startData.status !== "completed") return err("WorkflowExecutionError", `Workflow execution ${startData.executionId} did not complete`);
45
- const [getError, execution] = await this.get(startData.executionId);
46
- if (getError) return err(getError.type, getError.message);
47
- if (!execution) return err("WorkflowError", "Unexpected empty execution");
48
- return ok(execution.result);
49
- }
50
- async resume(executionId) {
51
- const [getError, execution] = await this.get(executionId);
52
- if (getError) return err(getError.type, getError.message);
53
- if (!execution) return err("WorkflowNotFoundError", `Workflow execution ${executionId} not found`);
54
- if (execution.status === "completed") return ok({
55
- executionId,
56
- status: execution.status
57
- });
58
- if (execution.status === "cancelled") return ok({
59
- executionId,
60
- status: execution.status
61
- });
62
- return this.execute(executionId, execution.input);
63
- }
64
- async get(executionId) {
65
- const [statusError, status] = await this.getMeta(executionId, "status");
66
- if (statusError) return err(statusError.type, statusError.message);
67
- if (!status) return err("WorkflowNotFoundError", `Workflow execution ${executionId} not found`);
68
- const normalizedStatus = this.normalizeStatus(status);
69
- if (!normalizedStatus) return err("WorkflowStateError", `Workflow execution ${executionId} has invalid status ${status}`);
70
- const [inputError, input] = await this.readInput(executionId);
71
- if (inputError) return err(inputError.type, inputError.message);
72
- if (input === null) return err("WorkflowStateError", `Workflow execution ${executionId} has invalid input`);
73
- const [resultError, result] = await this.readResult(executionId);
74
- if (resultError) return err(resultError.type, resultError.message);
75
- const [stepsError, steps] = await this.readStepSnapshots(executionId);
76
- if (stepsError) return err(stepsError.type, stepsError.message);
77
- const [createdAtError, createdAt] = await this.readNumberMeta(executionId, "createdAt");
78
- if (createdAtError) return err(createdAtError.type, createdAtError.message);
79
- if (createdAt === null) return err("WorkflowStateError", `Workflow execution ${executionId} is missing createdAt`);
80
- const [updatedAtError, updatedAt] = await this.readNumberMeta(executionId, "updatedAt");
81
- if (updatedAtError) return err(updatedAtError.type, updatedAtError.message);
82
- if (updatedAt === null) return err("WorkflowStateError", `Workflow execution ${executionId} is missing updatedAt`);
83
- const [metaError, errorMessage] = await this.getMeta(executionId, "error");
84
- if (metaError) return err(metaError.type, metaError.message);
85
- const [completedAtError, completedAt] = await this.readNumberMeta(executionId, "completedAt");
86
- if (completedAtError) return err(completedAtError.type, completedAtError.message);
87
- const [failedAtError, failedAt] = await this.readNumberMeta(executionId, "failedAt");
88
- if (failedAtError) return err(failedAtError.type, failedAtError.message);
89
- const [cancelledAtError, cancelledAt] = await this.readNumberMeta(executionId, "cancelledAt");
90
- if (cancelledAtError) return err(cancelledAtError.type, cancelledAtError.message);
91
- return ok({
92
- id: executionId,
93
- name: this.options.name,
94
- status: normalizedStatus,
95
- input,
96
- result,
97
- error: errorMessage,
98
- createdAt,
99
- updatedAt,
100
- completedAt,
101
- failedAt,
102
- cancelledAt,
103
- steps
104
- });
105
- }
106
- async cancel(executionId) {
107
- const [getError, execution] = await this.get(executionId);
108
- if (getError) return err(getError.type, getError.message);
109
- if (!execution) return err("WorkflowNotFoundError", `Workflow execution ${executionId} not found`);
110
- if (execution.status === "completed") return err("WorkflowStateError", `Workflow execution ${executionId} is already completed`);
111
- const timestamp = now();
112
- const [statusError] = await this.setMeta(executionId, "status", "cancelled");
113
- if (statusError) return err(statusError.type, statusError.message);
114
- const [updatedAtError] = await this.setMeta(executionId, "updatedAt", String(timestamp));
115
- if (updatedAtError) return err(updatedAtError.type, updatedAtError.message);
116
- const [cancelledAtError] = await this.setMeta(executionId, "cancelledAt", String(timestamp));
117
- if (cancelledAtError) return err(cancelledAtError.type, cancelledAtError.message);
118
- const [clearErrorError] = await this.setMeta(executionId, "error", "");
119
- if (clearErrorError) return err(clearErrorError.type, clearErrorError.message);
120
- const [clearFailedAtError] = await this.setMeta(executionId, "failedAt", "");
121
- if (clearFailedAtError) return err(clearFailedAtError.type, clearFailedAtError.message);
122
- return ok({
123
- executionId,
124
- createdAt: execution.createdAt,
125
- cancelledAt: timestamp,
126
- updatedAt: timestamp,
127
- status: "cancelled"
128
- });
129
- }
130
- executionKey(executionId) {
131
- return `workflow:${this.options.name}:execution:${executionId}`;
132
- }
133
- metaKey(executionId) {
134
- return `${this.executionKey(executionId)}:meta`;
135
- }
136
- stepsKey(executionId) {
137
- return `${this.executionKey(executionId)}:steps`;
138
- }
139
- lockKey(executionId) {
140
- return `${this.executionKey(executionId)}:lock`;
141
- }
142
- async createExecution(executionId, input) {
143
- const [serializeError, serializedInput] = this.serializeInput(input);
144
- if (serializeError) return err("WorkflowSerializationError", `Unable to serialize workflow input for ${executionId}`);
145
- const timestamp = now();
146
- const [statusReadError, existingStatus] = await this.getMeta(executionId, "status");
147
- if (statusReadError) return err(statusReadError.type, statusReadError.message);
148
- if (existingStatus) return err("WorkflowStateError", `Workflow execution ${executionId} already exists`);
149
- const metadata = {
150
- status: "pending",
151
- input: serializedInput,
152
- result: "",
153
- error: "",
154
- createdAt: String(timestamp),
155
- updatedAt: String(timestamp),
156
- completedAt: "",
157
- failedAt: "",
158
- cancelledAt: "",
159
- steps: "[]"
160
- };
161
- const [writeError] = await mightThrow(this.options.redis.hset(this.metaKey(executionId), metadata));
162
- if (writeError) return err("WorkflowError", `Unable to persist metadata for execution ${executionId}`);
163
- return ok(null);
164
- }
165
- async execute(executionId, input) {
166
- const token = crypto.randomUUID();
167
- const [lockError] = await this.acquireLock(executionId, token);
168
- if (lockError) return err(lockError.type, lockError.message);
169
- const [statusCheckError, currentStatus] = await this.getMeta(executionId, "status");
170
- if (statusCheckError) {
171
- await this.releaseLock(executionId, token);
172
- return err(statusCheckError.type, statusCheckError.message);
173
- }
174
- if (currentStatus === "cancelled") {
175
- await this.releaseLock(executionId, token);
176
- return err("WorkflowStateError", `Workflow execution ${executionId} was cancelled`);
177
- }
178
- const timestamp = now();
179
- const [runningStatusError] = await this.setMeta(executionId, "status", "running");
180
- if (runningStatusError) {
181
- await this.releaseLock(executionId, token);
182
- return err(runningStatusError.type, runningStatusError.message);
183
- }
184
- const [runningUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(timestamp));
185
- if (runningUpdatedAtError) {
186
- await this.releaseLock(executionId, token);
187
- return err(runningUpdatedAtError.type, runningUpdatedAtError.message);
188
- }
189
- const controller = new AbortController();
190
- const renewInterval = Math.floor(this.lockTTL / 3);
191
- let lockLost = false;
192
- const renewTimer = setInterval(async () => {
193
- const [renewError] = await this.extendLock(executionId, token);
194
- if (renewError) {
195
- lockLost = true;
196
- controller.abort();
197
- clearInterval(renewTimer);
198
- }
199
- }, renewInterval);
200
- const step = async (name, handler) => {
201
- const [cancelledError, cancelled] = await this.isCancelled(executionId);
202
- if (cancelledError) return Promise.reject(new Error(cancelledError.message));
203
- if (cancelled) {
204
- controller.abort();
205
- return Promise.reject(/* @__PURE__ */ new Error("Workflow cancelled"));
206
- }
207
- const [readError, cachedStep] = await this.readStepOutput(executionId, name);
208
- if (readError) return Promise.reject(new Error(readError.message));
209
- if (cachedStep.found) return cachedStep.value;
210
- const [stepError, output] = await mightThrow(Promise.resolve(handler(input, controller.signal)));
211
- if (stepError) return Promise.reject(stepError);
212
- const [writeError] = await this.writeStepOutput(executionId, name, output);
213
- if (writeError) return Promise.reject(new Error(writeError.message));
214
- return output;
215
- };
216
- const [handlerError, result] = await mightThrow(Promise.resolve(this.options.handler({
217
- input,
218
- executionId,
219
- signal: controller.signal,
220
- step
221
- })));
222
- clearInterval(renewTimer);
223
- if (lockLost) {
224
- await this.releaseLock(executionId, token);
225
- return err("WorkflowLockError", `Lock expired during execution ${executionId}`);
226
- }
227
- const [cancelledError, cancelled] = await this.isCancelled(executionId);
228
- if (cancelledError) {
229
- await this.releaseLock(executionId, token);
230
- return err(cancelledError.type, cancelledError.message);
231
- }
232
- if (cancelled) {
233
- const cancelledAt = now();
234
- const [cancelledStatusError] = await this.setMeta(executionId, "status", "cancelled");
235
- if (cancelledStatusError) {
236
- await this.releaseLock(executionId, token);
237
- return err(cancelledStatusError.type, cancelledStatusError.message);
238
- }
239
- const [cancelledUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(cancelledAt));
240
- if (cancelledUpdatedAtError) {
241
- await this.releaseLock(executionId, token);
242
- return err(cancelledUpdatedAtError.type, cancelledUpdatedAtError.message);
243
- }
244
- const [cancelledAtError] = await this.setMeta(executionId, "cancelledAt", String(cancelledAt));
245
- if (cancelledAtError) {
246
- await this.releaseLock(executionId, token);
247
- return err(cancelledAtError.type, cancelledAtError.message);
248
- }
249
- await this.releaseLock(executionId, token);
250
- return ok({
251
- executionId,
252
- status: "cancelled"
253
- });
254
- }
255
- if (handlerError) {
256
- const failedAt = now();
257
- const [failedStatusError] = await this.setMeta(executionId, "status", "failed");
258
- if (failedStatusError) {
259
- await this.releaseLock(executionId, token);
260
- return err(failedStatusError.type, failedStatusError.message);
261
- }
262
- const [failedMessageError] = await this.setMeta(executionId, "error", toErrorMessage(handlerError));
263
- if (failedMessageError) {
264
- await this.releaseLock(executionId, token);
265
- return err(failedMessageError.type, failedMessageError.message);
266
- }
267
- const [failedUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(failedAt));
268
- if (failedUpdatedAtError) {
269
- await this.releaseLock(executionId, token);
270
- return err(failedUpdatedAtError.type, failedUpdatedAtError.message);
271
- }
272
- const [failedAtError] = await this.setMeta(executionId, "failedAt", String(failedAt));
273
- if (failedAtError) {
274
- await this.releaseLock(executionId, token);
275
- return err(failedAtError.type, failedAtError.message);
276
- }
277
- await this.releaseLock(executionId, token);
278
- return err("WorkflowExecutionError", `Workflow execution ${executionId} failed: ${toErrorMessage(handlerError)}`);
279
- }
280
- const [serializeResultError, serializedResult] = this.serializeResult(result);
281
- if (serializeResultError) {
282
- const failedAt = now();
283
- const [failedStatusError] = await this.setMeta(executionId, "status", "failed");
284
- if (failedStatusError) {
285
- await this.releaseLock(executionId, token);
286
- return err(failedStatusError.type, failedStatusError.message);
287
- }
288
- const [failedMessageError] = await this.setMeta(executionId, "error", serializeResultError.message);
289
- if (failedMessageError) {
290
- await this.releaseLock(executionId, token);
291
- return err(failedMessageError.type, failedMessageError.message);
292
- }
293
- const [failedUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(failedAt));
294
- if (failedUpdatedAtError) {
295
- await this.releaseLock(executionId, token);
296
- return err(failedUpdatedAtError.type, failedUpdatedAtError.message);
297
- }
298
- const [failedAtError] = await this.setMeta(executionId, "failedAt", String(failedAt));
299
- if (failedAtError) {
300
- await this.releaseLock(executionId, token);
301
- return err(failedAtError.type, failedAtError.message);
302
- }
303
- await this.releaseLock(executionId, token);
304
- return err("WorkflowSerializationError", `Unable to serialize workflow result for ${executionId}`);
305
- }
306
- const completedAt = now();
307
- const [completedResultError] = await this.setMeta(executionId, "result", serializedResult);
308
- if (completedResultError) {
309
- await this.releaseLock(executionId, token);
310
- return err(completedResultError.type, completedResultError.message);
311
- }
312
- const [completedStatusError] = await this.setMeta(executionId, "status", "completed");
313
- if (completedStatusError) {
314
- await this.releaseLock(executionId, token);
315
- return err(completedStatusError.type, completedStatusError.message);
316
- }
317
- const [completedClearErrorError] = await this.setMeta(executionId, "error", "");
318
- if (completedClearErrorError) {
319
- await this.releaseLock(executionId, token);
320
- return err(completedClearErrorError.type, completedClearErrorError.message);
321
- }
322
- const [completedClearFailedAtError] = await this.setMeta(executionId, "failedAt", "");
323
- if (completedClearFailedAtError) {
324
- await this.releaseLock(executionId, token);
325
- return err(completedClearFailedAtError.type, completedClearFailedAtError.message);
326
- }
327
- const [completedUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(completedAt));
328
- if (completedUpdatedAtError) {
329
- await this.releaseLock(executionId, token);
330
- return err(completedUpdatedAtError.type, completedUpdatedAtError.message);
331
- }
332
- const [completedAtError] = await this.setMeta(executionId, "completedAt", String(completedAt));
333
- if (completedAtError) {
334
- await this.releaseLock(executionId, token);
335
- return err(completedAtError.type, completedAtError.message);
336
- }
337
- await this.releaseLock(executionId, token);
338
- return ok({
339
- executionId,
340
- status: "completed"
341
- });
342
- }
343
- async acquireLock(executionId, token) {
344
- const [lockError, lockResult] = await mightThrow(this.options.redis.set(this.lockKey(executionId), token, "PX", String(this.lockTTL), "NX"));
345
- if (lockError) return err("WorkflowLockError", `Unable to acquire lock for execution ${executionId}`);
346
- if (lockResult !== "OK") return err("WorkflowLockError", `Workflow execution ${executionId} is already running`);
347
- return ok(null);
348
- }
349
- async releaseLock(executionId, token) {
350
- const [evalError] = await mightThrow(this.options.redis.send("EVAL", [
351
- "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end",
352
- "1",
353
- this.lockKey(executionId),
354
- token
355
- ]));
356
- if (evalError) return err("WorkflowLockError", `Unable to release lock for execution ${executionId}`);
357
- return ok(null);
358
- }
359
- async extendLock(executionId, token) {
360
- const [evalError, result] = await mightThrow(this.options.redis.send("EVAL", [
361
- "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end",
362
- "1",
363
- this.lockKey(executionId),
364
- token,
365
- String(this.lockTTL)
366
- ]));
367
- if (evalError) return err("WorkflowLockError", `Unable to extend lock for execution ${executionId}`);
368
- if (result === 0) return err("WorkflowLockError", `Lock ownership lost for execution ${executionId}`);
369
- return ok(null);
370
- }
371
- async isCancelled(executionId) {
372
- const [statusError, status] = await this.getMeta(executionId, "status");
373
- if (statusError) return err(statusError.type, statusError.message);
374
- return ok(status === "cancelled");
375
- }
376
- async setMeta(executionId, field, value) {
377
- const [writeError] = await mightThrow(this.options.redis.hset(this.metaKey(executionId), field, value));
378
- if (writeError) return err("WorkflowError", `Unable to persist ${field} for execution ${executionId}`);
379
- return ok(null);
380
- }
381
- async getMeta(executionId, field) {
382
- const [readError, value] = await mightThrow(this.options.redis.hget(this.metaKey(executionId), field));
383
- if (readError) return err("WorkflowError", `Unable to read ${field} for execution ${executionId}`);
384
- if (value === null || value === void 0) return ok(null);
385
- if (typeof value !== "string") return err("WorkflowStateError", `Invalid ${field} value for execution ${executionId}`);
386
- if (value.length === 0) return ok(null);
387
- return ok(value);
388
- }
389
- async readNumberMeta(executionId, field) {
390
- const [readError, value] = await this.getMeta(executionId, field);
391
- if (readError) return err(readError.type, readError.message);
392
- if (!value) return ok(null);
393
- const parsed = Number(value);
394
- if (!Number.isFinite(parsed)) return err("WorkflowStateError", `Invalid ${field} value for execution ${executionId}`);
395
- return ok(parsed);
396
- }
397
- runSerializer(value, serializer, label) {
398
- const [serializeError, serialized] = mightThrowSync(() => serializer(value));
399
- if (serializeError) return err("WorkflowSerializationError", `Unable to serialize ${label}: ${toErrorMessage(serializeError)}`);
400
- if (typeof serialized !== "string") return err("WorkflowSerializationError", `${label} serializer must return a string`);
401
- return ok(serialized);
402
- }
403
- runDeserializer(raw, deserializer, label) {
404
- const [deserializeError, value] = mightThrowSync(() => deserializer(raw));
405
- if (deserializeError) return err("WorkflowSerializationError", `Unable to deserialize ${label}: ${toErrorMessage(deserializeError)}`);
406
- return ok(value);
407
- }
408
- serializeInput(input) {
409
- return this.runSerializer(input, this.options.serializeInput ?? envelopeSerialize, "workflow input");
410
- }
411
- deserializeInput(raw) {
412
- const deserializer = this.options.deserializeInput ?? ((value) => envelopeDeserialize(value));
413
- return this.runDeserializer(raw, deserializer, "workflow input");
414
- }
415
- serializeResult(result) {
416
- if (result === null) return ok(envelopeSerialize(null));
417
- return this.runSerializer(result, this.options.serializeResult ?? envelopeSerialize, "workflow result");
418
- }
419
- deserializeResult(raw) {
420
- const deserializer = this.options.deserializeResult ?? ((value) => envelopeDeserialize(value));
421
- return this.runDeserializer(raw, deserializer, "workflow result");
422
- }
423
- serializeStepOutput(output) {
424
- return this.runSerializer(output, this.options.serializeStepOutput ?? envelopeSerialize, "step output");
425
- }
426
- deserializeStepOutput(raw) {
427
- const deserializer = this.options.deserializeStepOutput ?? ((value) => envelopeDeserialize(value));
428
- return this.runDeserializer(raw, deserializer, "step output");
429
- }
430
- async readInput(executionId) {
431
- const [readError, raw] = await this.getMeta(executionId, "input");
432
- if (readError) return err(readError.type, readError.message);
433
- if (!raw) return err("WorkflowStateError", `Workflow execution ${executionId} input not found`);
434
- return this.deserializeInput(raw);
435
- }
436
- async readResult(executionId) {
437
- const [readError, raw] = await this.getMeta(executionId, "result");
438
- if (readError) return err(readError.type, readError.message);
439
- if (!raw) return ok(null);
440
- const [deserializeError, result] = this.deserializeResult(raw);
441
- if (deserializeError) return err(deserializeError.type, deserializeError.message);
442
- return ok(result);
443
- }
444
- async writeStepOutput(executionId, stepName, output) {
445
- const [serializeError, serializedOutput] = this.serializeStepOutput(output);
446
- if (serializeError) return err("WorkflowSerializationError", `Unable to serialize step ${stepName} output`);
447
- const payload = {
448
- output: serializedOutput,
449
- completedAt: now()
450
- };
451
- const [payloadError, payloadRaw] = mightThrowSync(() => JSON.stringify(payload));
452
- if (payloadError || typeof payloadRaw !== "string") return err("WorkflowSerializationError", `Unable to persist step ${stepName} output`);
453
- const [writeError] = await mightThrow(this.options.redis.hset(this.stepsKey(executionId), stepName, payloadRaw));
454
- if (writeError) return err("WorkflowError", `Unable to persist step ${stepName} for execution ${executionId}`);
455
- const [stepNamesError, stepNames] = await this.readStepNames(executionId);
456
- if (stepNamesError) return err(stepNamesError.type, stepNamesError.message);
457
- if (!stepNames.includes(stepName)) {
458
- const nextStepNames = [...stepNames, stepName];
459
- const [serializeStepsError, serializedSteps] = mightThrowSync(() => JSON.stringify(nextStepNames));
460
- if (serializeStepsError || typeof serializedSteps !== "string") return err("WorkflowSerializationError", `Unable to persist step history for execution ${executionId}`);
461
- const [updateStepsError] = await this.setMeta(executionId, "steps", serializedSteps);
462
- if (updateStepsError) return err(updateStepsError.type, updateStepsError.message);
463
- }
464
- const [updatedError] = await this.setMeta(executionId, "updatedAt", String(now()));
465
- if (updatedError) return err(updatedError.type, updatedError.message);
466
- return ok(null);
467
- }
468
- async readStepOutput(executionId, stepName) {
469
- const [readError, payloadRaw] = await mightThrow(this.options.redis.hget(this.stepsKey(executionId), stepName));
470
- if (readError) return err("WorkflowError", `Unable to read step ${stepName} for execution ${executionId}`);
471
- if (!payloadRaw) return ok({
472
- found: false,
473
- value: null
474
- });
475
- if (typeof payloadRaw !== "string") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
476
- const [parseError, parsed] = mightThrowSync(() => JSON.parse(payloadRaw));
477
- if (parseError || parsed === null || typeof parsed !== "object") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
478
- if (typeof parsed.output !== "string") return err("WorkflowStateError", `Invalid step output for ${stepName} in execution ${executionId}`);
479
- const outputRaw = parsed.output;
480
- const [deserializeError, value] = this.deserializeStepOutput(outputRaw);
481
- if (deserializeError) return err(deserializeError.type, deserializeError.message);
482
- return ok({
483
- found: true,
484
- value
485
- });
486
- }
487
- async readStepNames(executionId) {
488
- const [readError, stepsRaw] = await this.getMeta(executionId, "steps");
489
- if (readError) return [readError, []];
490
- if (!stepsRaw) return ok([]);
491
- const [parseError, values] = mightThrowSync(() => JSON.parse(stepsRaw));
492
- if (parseError || !Array.isArray(values)) return err("WorkflowStateError", `Invalid step index for execution ${executionId}`);
493
- const stepNames = [];
494
- for (const value of values) if (typeof value === "string") stepNames.push(value);
495
- return ok(stepNames);
496
- }
497
- async readStepSnapshots(executionId) {
498
- const [stepNamesError, stepNames] = await this.readStepNames(executionId);
499
- if (stepNamesError) return [stepNamesError, []];
500
- const steps = [];
501
- for (const stepName of stepNames) {
502
- const [readError, payloadRaw] = await mightThrow(this.options.redis.hget(this.stepsKey(executionId), stepName));
503
- if (readError) return err("WorkflowError", `Unable to read step ${stepName} for execution ${executionId}`);
504
- if (!payloadRaw) continue;
505
- if (typeof payloadRaw !== "string") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
506
- const [parseError, parsed] = mightThrowSync(() => JSON.parse(payloadRaw));
507
- if (parseError || parsed === null || typeof parsed !== "object") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
508
- if (typeof parsed.completedAt !== "number") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
509
- const completedAt = parsed.completedAt;
510
- steps.push({
511
- name: stepName,
512
- completedAt
513
- });
514
- }
515
- return ok(steps);
516
- }
517
- normalizeStatus(value) {
518
- for (const status of knownStatuses) if (status === value) return status;
519
- return null;
520
- }
521
- };
522
- const defineWorkflow = (options) => {
523
- const workflow = new WorkflowDefinition(options);
524
- return {
525
- start: (input, startOptions) => workflow.start(input, startOptions),
526
- run: (input, startOptions) => workflow.run(input, startOptions),
527
- resume: (executionId) => workflow.resume(executionId),
528
- get: (executionId) => workflow.get(executionId),
529
- cancel: (executionId) => workflow.cancel(executionId)
530
- };
531
- };
532
- //#endregion
533
- export { defineWorkflow };
1
+ import{mightThrow as e,mightThrowSync as t}from"../errors/index.mjs";import n from"node:assert";var r=class extends Error{constructor(e){super(e),this.name=`WorkflowError`}},i=class extends Error{constructor(e){super(e),this.name=`NotFoundError`}},a=class extends Error{constructor(e){super(e),this.name=`StateError`}},o=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},s=class extends Error{constructor(e){super(e),this.name=`ExecutionError`}},c=class extends Error{constructor(e){super(e),this.name=`LockError`}},l=class extends Error{constructor(e){super(e),this.name=`CancelledError`}};const u=()=>Date.now(),d=async(e,t,n)=>{if(t.aborted)throw new l(`Workflow execution was aborted during retry backoff`);let r=u()+e;for(;u()<r;){if(t.aborted)throw new l(`Workflow execution was aborted during retry backoff`);if(n&&await n())throw new l(`Workflow execution was cancelled during retry backoff`);let e=r-u();await new Promise(t=>{setTimeout(t,Math.min(50,e))})}},f=e=>JSON.stringify({value:e}),p=e=>{let[n,r]=t(()=>JSON.parse(e));if(n)throw n;if(typeof r==`object`&&r&&`value`in r)return r.value},m=[`pending`,`running`,`completed`,`failed`,`cancelled`];var h=class{options;lockTTL;retries;retryBaseDelay;retryMultiplier;retryMaxDelay;constructor(e){this.options=e,this.lockTTL=e.lockTTL??3e5,this.retries=e.retries??3,this.retryBaseDelay=e.retryBackoff?.baseDelay??1e3,this.retryMultiplier=e.retryBackoff?.multiplier??2,this.retryMaxDelay=e.retryBackoff?.maxDelay??3e4,n.ok(Number.isFinite(this.retries)&&this.retries>=0,`Invalid retries: must be a non-negative finite number`),n.ok(Number.isFinite(this.retryBaseDelay)&&this.retryBaseDelay>0,`Invalid retryBackoff.baseDelay: must be a positive finite number`),n.ok(Number.isFinite(this.retryMultiplier)&&this.retryMultiplier>0,`Invalid retryBackoff.multiplier: must be a positive finite number`),n.ok(Number.isFinite(this.retryMaxDelay)&&this.retryMaxDelay>0,`Invalid retryBackoff.maxDelay: must be a positive finite number`)}runHook(t){return e(Promise.resolve().then(()=>t()))}computeBackoffDelay(e){return Math.min(this.retryBaseDelay*this.retryMultiplier**(e-1),this.retryMaxDelay)}async start(e,t){let n=t?.executionId??crypto.randomUUID();return await this.createExecution(n,e),this.execute(n,e)}async run(e,t){let n=await this.start(e,t);if(n.status===`cancelled`)throw new l(`Workflow execution ${n.executionId} was cancelled`);return(await this.get(n.executionId)).result}async resume(e){let t=await this.get(e);return t.status===`completed`||t.status===`cancelled`?{executionId:e,status:t.status}:this.execute(e,t.input)}async get(e){let t=await this.getMeta(e,`status`);if(!t)throw new i(`Workflow execution ${e} not found`);let n=this.normalizeStatus(t);if(!n)throw new a(`Workflow execution ${e} has invalid status ${t}`);let r=await this.readInput(e),o=await this.readResult(e),s=await this.readStepSnapshots(e),c=await this.readNumberMeta(e,`createdAt`),l=await this.readNumberMeta(e,`updatedAt`),u=await this.getMeta(e,`error`),d=await this.readNumberMeta(e,`completedAt`),f=await this.readNumberMeta(e,`failedAt`),p=await this.readNumberMeta(e,`cancelledAt`);if(c===null)throw new a(`Workflow execution ${e} is missing createdAt`);if(l===null)throw new a(`Workflow execution ${e} is missing updatedAt`);return{id:e,name:this.options.name,status:n,input:r,result:o,error:u,createdAt:c,updatedAt:l,completedAt:d,failedAt:f,cancelledAt:p,steps:s}}async cancel(e){let t=await this.get(e);if(t.status===`completed`)throw new a(`Workflow execution ${e} is already completed`);let n=u();return await this.setMeta(e,`status`,`cancelled`),await this.setMeta(e,`updatedAt`,String(n)),await this.setMeta(e,`cancelledAt`,String(n)),await this.setMeta(e,`error`,``),await this.setMeta(e,`failedAt`,``),{executionId:e,createdAt:t.createdAt,cancelledAt:n,updatedAt:n,status:`cancelled`}}executionKey(e){return`workflow:${this.options.name}:execution:${e}`}metaKey(e){return`${this.executionKey(e)}:meta`}stepsKey(e){return`${this.executionKey(e)}:steps`}lockKey(e){return`${this.executionKey(e)}:lock`}async createExecution(t,n){let i=this.serializeInput(n),o=u();if(await this.getMeta(t,`status`))throw new a(`Workflow execution ${t} already exists`);let s={status:`pending`,input:i,result:``,error:``,createdAt:String(o),updatedAt:String(o),completedAt:``,failedAt:``,cancelledAt:``,steps:`[]`},[c]=await e(this.options.redis.hset(this.metaKey(t),s));if(c)throw new r(`Unable to persist metadata for execution ${t}`)}async execute(n,r){let i=crypto.randomUUID();if(await this.acquireLock(n,i),await this.getMeta(n,`status`)===`cancelled`)throw await this.releaseLock(n,i),new a(`Workflow execution ${n} was cancelled`);let l=u();await this.setMeta(n,`status`,`running`),await this.setMeta(n,`updatedAt`,String(l));let d=new AbortController,f=Math.floor(this.lockTTL/3),p=!1,m=setInterval(async()=>{let[t]=await e(this.extendLock(n,i));t&&(p=!0,d.abort(),clearInterval(m))},f);this.options.hooks?.onStart&&await this.runHook(()=>this.options.hooks?.onStart?.({executionId:n,input:r}));let h=await e(Promise.resolve(this.options.handler({input:r,executionId:n,signal:d.signal,step:async(e,t)=>{await this.throwIfCancelled(n,()=>{d.abort()});let i=await this.readStepOutput(n,e);return i.found?i.value:this.runStepWithRetries(n,r,e,t,d.signal,()=>{d.abort()})}})));if(clearInterval(m),p)throw await this.releaseLock(n,i),new c(`Lock expired during execution ${n}`);if(await this.isCancelled(n)){let e=u();return await this.setMeta(n,`status`,`cancelled`),await this.setMeta(n,`updatedAt`,String(e)),await this.setMeta(n,`cancelledAt`,String(e)),this.options.hooks?.onCancel&&await this.runHook(()=>this.options.hooks?.onCancel?.({executionId:n,input:r})),await this.releaseLock(n,i),{executionId:n,status:`cancelled`}}let[g,_]=h;if(g){let e=u();throw await this.setMeta(n,`status`,`failed`),await this.setMeta(n,`error`,g.message),await this.setMeta(n,`updatedAt`,String(e)),await this.setMeta(n,`failedAt`,String(e)),await this.releaseLock(n,i),new s(`Workflow execution ${n} failed: ${g.message}`)}let[v,y]=t(()=>this.serializeResult(_));if(v){let e=u();throw await this.setMeta(n,`status`,`failed`),await this.setMeta(n,`error`,v.message),await this.setMeta(n,`updatedAt`,String(e)),await this.setMeta(n,`failedAt`,String(e)),await this.releaseLock(n,i),new o(`Unable to serialize workflow result for ${n}`)}let b=u();return await this.setMeta(n,`result`,y),await this.setMeta(n,`status`,`completed`),await this.setMeta(n,`error`,``),await this.setMeta(n,`failedAt`,``),await this.setMeta(n,`updatedAt`,String(b)),await this.setMeta(n,`completedAt`,String(b)),this.options.hooks?.onComplete&&await this.runHook(()=>this.options.hooks?.onComplete?.({executionId:n,input:r,result:_})),await this.releaseLock(n,i),{executionId:n,status:`completed`}}async throwIfCancelled(e,t){if(await this.isCancelled(e))throw t(),new l(`Workflow execution ${e} was cancelled`)}async runStepWithRetries(t,n,r,i,a,o){let s=1,c=[];for(;;){await this.throwIfCancelled(t,o);let[l,f]=await e(Promise.resolve(i(n,a)));if(!l)return await this.writeStepOutput(t,r,f),f;let p=l.message;if(c.push({attempt:s,error:p,timestamp:u()}),s<=this.retries){let i=this.computeBackoffDelay(s);this.options.hooks?.onRetry&&await this.runHook(()=>this.options.hooks?.onRetry?.({executionId:t,input:n,stepName:r,error:p,attempt:s,nextRetryDelayMs:i,retriesRemaining:this.retries-s}));let[o]=await e(d(i,a,()=>this.isCancelled(t)));if(o)throw o;s++;continue}throw this.options.hooks?.onError&&await this.runHook(()=>this.options.hooks?.onError?.({executionId:t,input:n,stepName:r,error:p,totalAttempts:s,errorHistory:c})),l}}async acquireLock(t,n){let[r,i]=await e(this.options.redis.set(this.lockKey(t),n,`PX`,String(this.lockTTL),`NX`));if(r)throw new c(`Unable to acquire lock for execution ${t}`);if(i!==`OK`)throw new c(`Workflow execution ${t} is already running`)}async releaseLock(t,n){await e(this.options.redis.send(`EVAL`,[`if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end`,`1`,this.lockKey(t),n]))}async extendLock(t,n){let[r,i]=await e(this.options.redis.send(`EVAL`,[`if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end`,`1`,this.lockKey(t),n,String(this.lockTTL)]));if(r)throw new c(`Unable to extend lock for execution ${t}`);if(i===0)throw new c(`Lock ownership lost for execution ${t}`)}async isCancelled(e){return await this.getMeta(e,`status`)===`cancelled`}async setMeta(t,n,i){let[a]=await e(this.options.redis.hset(this.metaKey(t),n,i));if(a)throw new r(`Unable to persist ${n} for execution ${t}`)}async getMeta(t,n){let[i,o]=await e(this.options.redis.hget(this.metaKey(t),n));if(i)throw new r(`Unable to read ${n} for execution ${t}`);if(o==null)return null;if(typeof o!=`string`)throw new a(`Invalid ${n} value for execution ${t}`);return o.length===0?null:o}async readNumberMeta(e,t){let n=await this.getMeta(e,t);if(!n)return null;let r=Number(n);if(!Number.isFinite(r))throw new a(`Invalid ${t} value for execution ${e}`);return r}runSerializer(e,n,r){let[i,a]=t(()=>n(e));if(i)throw new o(`Unable to serialize ${r}: ${i.message}`);if(typeof a!=`string`)throw new o(`${r} serializer must return a string`);return a}runDeserializer(e,n,r){let i=t(()=>n(e));if(i[0])throw new o(`Unable to deserialize ${r}: ${i[0].message}`);return i[1]}serializeInput(e){return this.runSerializer(e,this.options.serializeInput??f,`workflow input`)}deserializeInput(e){let t=this.options.deserializeInput??(e=>p(e));return this.runDeserializer(e,t,`workflow input`)}serializeResult(e){return e===null?f(null):this.runSerializer(e,this.options.serializeResult??f,`workflow result`)}deserializeResult(e){let t=this.options.deserializeResult??(e=>p(e));return this.runDeserializer(e,t,`workflow result`)}serializeStepOutput(e){return this.runSerializer(e,this.options.serializeStepOutput??f,`step output`)}deserializeStepOutput(e){let t=this.options.deserializeStepOutput??(e=>p(e));return this.runDeserializer(e,t,`step output`)}async readInput(e){let t=await this.getMeta(e,`input`);if(!t)throw new a(`Workflow execution ${e} input not found`);return this.deserializeInput(t)}async readResult(e){let t=await this.getMeta(e,`result`);return t?this.deserializeResult(t):null}async writeStepOutput(n,i,a){let s={output:this.serializeStepOutput(a),completedAt:u()},[c,l]=t(()=>JSON.stringify(s));if(c||typeof l!=`string`)throw new o(`Unable to persist step ${i} output`);let[d]=await e(this.options.redis.hset(this.stepsKey(n),i,l));if(d)throw new r(`Unable to persist step ${i} for execution ${n}`);let f=await this.readStepNames(n);if(!f.includes(i)){let e=[...f,i],[r,a]=t(()=>JSON.stringify(e));if(r||typeof a!=`string`)throw new o(`Unable to persist step history for execution ${n}`);await this.setMeta(n,`steps`,a)}await this.setMeta(n,`updatedAt`,String(u()))}async readStepOutput(n,i){let[o,s]=await e(this.options.redis.hget(this.stepsKey(n),i));if(o)throw new r(`Unable to read step ${i} for execution ${n}`);if(!s)return{found:!1,value:null};if(typeof s!=`string`)throw new a(`Invalid step payload for ${i} in execution ${n}`);let[c,l]=t(()=>JSON.parse(s));if(c||typeof l!=`object`||!l)throw new a(`Invalid step payload for ${i} in execution ${n}`);if(typeof l.output!=`string`)throw new a(`Invalid step output for ${i} in execution ${n}`);let u=l.output;return{found:!0,value:this.deserializeStepOutput(u)}}async readStepNames(e){let n=await this.getMeta(e,`steps`);if(!n)return[];let[r,i]=t(()=>JSON.parse(n));if(r||!Array.isArray(i))throw new a(`Invalid step index for execution ${e}`);let o=[];for(let e of i)typeof e==`string`&&o.push(e);return o}async readStepSnapshots(n){let i=await this.readStepNames(n),o=[];for(let s of i){let[i,c]=await e(this.options.redis.hget(this.stepsKey(n),s));if(i)throw new r(`Unable to read step ${s} for execution ${n}`);if(!c)continue;if(typeof c!=`string`)throw new a(`Invalid step payload for ${s} in execution ${n}`);let[l,u]=t(()=>JSON.parse(c));if(l||typeof u!=`object`||!u||typeof u.completedAt!=`number`)throw new a(`Invalid step payload for ${s} in execution ${n}`);o.push({name:s,completedAt:u.completedAt})}return o}normalizeStatus(e){for(let t of m)if(t===e)return t;return null}};const g=e=>{let t=new h(e);return{start:(e,n)=>t.start(e,n),run:(e,n)=>t.run(e,n),resume:e=>t.resume(e),get:e=>t.get(e),cancel:e=>t.cancel(e)}};export{l as CancelledError,s as ExecutionError,c as LockError,i as NotFoundError,o as SerializationError,a as StateError,r as WorkflowError,g as defineWorkflow};
@@ -0,0 +1 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});