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