awaitly 2.0.0 → 3.0.0

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 (88) hide show
  1. package/dist/di-Biw_plBn.d.cts +15 -0
  2. package/dist/di-DxyH2N3i.d.ts +15 -0
  3. package/dist/durable.cjs +4670 -0
  4. package/dist/durable.cjs.map +1 -0
  5. package/dist/durable.d.cts +9 -0
  6. package/dist/durable.d.ts +9 -0
  7. package/dist/durable.js +4610 -0
  8. package/dist/durable.js.map +1 -0
  9. package/dist/{di-BbFFfO8y.d.ts → duration-BjVn3QpB.d.cts} +1 -15
  10. package/dist/{di-BDlT7InM.d.cts → duration-BjVn3QpB.d.ts} +1 -15
  11. package/dist/engine.cjs +4501 -0
  12. package/dist/engine.cjs.map +1 -0
  13. package/dist/engine.d.cts +113 -0
  14. package/dist/engine.d.ts +113 -0
  15. package/dist/engine.js +4474 -0
  16. package/dist/engine.js.map +1 -0
  17. package/dist/{errors-DtXvrCiO.d.cts → errors-sDSeaZBO.d.cts} +1 -1
  18. package/dist/{errors-DtXvrCiO.d.ts → errors-sDSeaZBO.d.ts} +1 -1
  19. package/dist/guards-CwQZro1F.d.ts +72 -0
  20. package/dist/guards-DhhOJZda.d.cts +72 -0
  21. package/dist/hitl-BnnnLzh2.d.cts +468 -0
  22. package/dist/hitl-pYfkQMv_.d.ts +468 -0
  23. package/dist/hitl.cjs +646 -0
  24. package/dist/hitl.cjs.map +1 -0
  25. package/dist/hitl.d.cts +440 -0
  26. package/dist/hitl.d.ts +440 -0
  27. package/dist/hitl.js +605 -0
  28. package/dist/hitl.js.map +1 -0
  29. package/dist/index-Bew12SZ8.d.ts +417 -0
  30. package/dist/index-Bwt-iz50.d.cts +417 -0
  31. package/dist/{types-B8NfNRGX.d.ts → index-Cv4K_3sZ.d.ts} +2 -1162
  32. package/dist/{types-BZ2f4MRR.d.cts → index-ICmfQi08.d.cts} +2 -1162
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +11 -1527
  35. package/dist/index.d.ts +11 -1527
  36. package/dist/persistence.cjs +552 -0
  37. package/dist/persistence.cjs.map +1 -0
  38. package/dist/persistence.d.cts +254 -0
  39. package/dist/persistence.d.ts +254 -0
  40. package/dist/persistence.js +499 -0
  41. package/dist/persistence.js.map +1 -0
  42. package/dist/reliability.cjs +1651 -0
  43. package/dist/reliability.cjs.map +1 -0
  44. package/dist/reliability.d.cts +1442 -0
  45. package/dist/reliability.d.ts +1442 -0
  46. package/dist/reliability.js +1589 -0
  47. package/dist/reliability.js.map +1 -0
  48. package/dist/result.d.cts +1 -1
  49. package/dist/result.d.ts +1 -1
  50. package/dist/run.cjs +2283 -0
  51. package/dist/run.cjs.map +1 -0
  52. package/dist/run.d.cts +90 -0
  53. package/dist/run.d.ts +90 -0
  54. package/dist/run.js +2247 -0
  55. package/dist/run.js.map +1 -0
  56. package/dist/saga.cjs +3699 -0
  57. package/dist/saga.cjs.map +1 -0
  58. package/dist/saga.d.cts +162 -0
  59. package/dist/saga.d.ts +162 -0
  60. package/dist/saga.js +3670 -0
  61. package/dist/saga.js.map +1 -0
  62. package/dist/store-contract-BI98VYmX.d.ts +66 -0
  63. package/dist/store-contract-C2HyR_o6.d.cts +66 -0
  64. package/dist/streaming.cjs +895 -0
  65. package/dist/streaming.cjs.map +1 -0
  66. package/dist/streaming.d.cts +594 -0
  67. package/dist/streaming.d.ts +594 -0
  68. package/dist/streaming.js +832 -0
  69. package/dist/streaming.js.map +1 -0
  70. package/dist/testing.d.cts +4 -2
  71. package/dist/testing.d.ts +4 -2
  72. package/dist/types-BDTxgKKc.d.ts +845 -0
  73. package/dist/types-C9Y71dua.d.cts +845 -0
  74. package/dist/types-d8q8iQlk.d.cts +323 -0
  75. package/dist/types-sObbY4mX.d.ts +323 -0
  76. package/dist/webhook.cjs +461 -0
  77. package/dist/webhook.cjs.map +1 -0
  78. package/dist/webhook.d.cts +497 -0
  79. package/dist/webhook.d.ts +497 -0
  80. package/dist/webhook.js +422 -0
  81. package/dist/webhook.js.map +1 -0
  82. package/dist/workflow.cjs +2 -2614
  83. package/dist/workflow.cjs.map +1 -1
  84. package/dist/workflow.d.cts +12 -3023
  85. package/dist/workflow.d.ts +12 -3023
  86. package/dist/workflow.js +2 -2535
  87. package/dist/workflow.js.map +1 -1
  88. package/package.json +46 -1
package/dist/saga.cjs ADDED
@@ -0,0 +1,3699 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/saga-entry.ts
21
+ var saga_entry_exports = {};
22
+ __export(saga_entry_exports, {
23
+ createSagaWorkflow: () => createSagaWorkflow,
24
+ isSagaCompensationError: () => isSagaCompensationError,
25
+ runSaga: () => runSaga
26
+ });
27
+ module.exports = __toCommonJS(saga_entry_exports);
28
+
29
+ // src/slugs.ts
30
+ var AWAITLY_SLUGS = {
31
+ // --- step-* ---
32
+ "step-require-id": "step-require-id",
33
+ "step-no-immediate-execution": "step-no-immediate-execution",
34
+ "step-require-thunk-for-key": "step-require-thunk-for-key",
35
+ "step-no-bare-await": "step-no-bare-await",
36
+ "step-no-try-catch-wrap": "step-no-try-catch-wrap",
37
+ "step-stable-cache-keys": "step-stable-cache-keys",
38
+ // --- workflow-* ---
39
+ "workflow-no-floating": "workflow-no-floating",
40
+ "workflow-options-position": "workflow-options-position",
41
+ "workflow-callback-shape": "workflow-callback-shape",
42
+ "workflow-no-callable-form": "workflow-no-callable-form",
43
+ "workflow-no-dynamic-import": "workflow-no-dynamic-import",
44
+ "workflow-prefer-step-if": "workflow-prefer-step-if",
45
+ "workflow-prefer-step-foreach": "workflow-prefer-step-foreach",
46
+ // --- result-* ---
47
+ "result-no-floating": "result-no-floating",
48
+ "result-require-handling": "result-require-handling",
49
+ "result-no-double-wrap": "result-no-double-wrap",
50
+ "result-no-manual-propagation": "result-no-manual-propagation",
51
+ "result-no-direct-ok-err": "result-no-direct-ok-err",
52
+ // --- error-* ---
53
+ "error-check-unexpected-first": "error-check-unexpected-first",
54
+ "error-access-cause": "error-access-cause",
55
+ "error-normalize": "error-normalize",
56
+ "error-no-throw-in-deps": "error-no-throw-in-deps",
57
+ // --- concurrency-* ---
58
+ "concurrency-no-promise-all": "concurrency-no-promise-all",
59
+ "concurrency-no-promise-race": "concurrency-no-promise-race",
60
+ "concurrency-no-promise-allsettled": "concurrency-no-promise-allsettled",
61
+ // --- runtime-* ---
62
+ "runtime-step-timeout": "runtime-step-timeout",
63
+ "runtime-step-aborted": "runtime-step-aborted",
64
+ "runtime-retry-exhausted": "runtime-retry-exhausted",
65
+ "runtime-rate-limit": "runtime-rate-limit",
66
+ "runtime-circuit-open": "runtime-circuit-open",
67
+ "runtime-unexpected": "runtime-unexpected",
68
+ "runtime-resolver-not-found": "runtime-resolver-not-found",
69
+ "runtime-saga-compensation": "runtime-saga-compensation"
70
+ };
71
+ function slugDocsUrl(slug) {
72
+ return `https://jagreehal.github.io/awaitly/rules/#${slug}`;
73
+ }
74
+ var ALL_SLUGS = Object.keys(
75
+ AWAITLY_SLUGS
76
+ );
77
+
78
+ // src/tagged-error.ts
79
+ var InternalTaggedErrorBase = class extends Error {
80
+ type;
81
+ /** @deprecated Use `type`. */
82
+ _tag;
83
+ };
84
+ function TaggedError(tag, options) {
85
+ return class extends InternalTaggedErrorBase {
86
+ type = tag;
87
+ /** @deprecated Use `type`. */
88
+ _tag = tag;
89
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
90
+ constructor(props, errorOptions) {
91
+ const message = options?.message ? options.message(props ?? {}) : tag;
92
+ super(message);
93
+ this.name = tag;
94
+ if (options?.slug !== void 0) {
95
+ if (!options.hint) {
96
+ throw new TypeError(
97
+ `TaggedError: 'hint' is required when 'slug' is set (slug: "${options.slug}")`
98
+ );
99
+ }
100
+ Object.defineProperty(this, "code", {
101
+ value: options.slug,
102
+ enumerable: true,
103
+ writable: false,
104
+ configurable: false
105
+ });
106
+ Object.defineProperty(this, "hint", {
107
+ value: options.hint,
108
+ enumerable: true,
109
+ writable: false,
110
+ configurable: false
111
+ });
112
+ Object.defineProperty(this, "docsUrl", {
113
+ value: slugDocsUrl(options.slug),
114
+ enumerable: true,
115
+ writable: false,
116
+ configurable: false
117
+ });
118
+ }
119
+ Object.setPrototypeOf(this, new.target.prototype);
120
+ if (props && typeof props === "object") {
121
+ let safeProps;
122
+ if (options?.slug !== void 0) {
123
+ const {
124
+ _tag: _,
125
+ type: _t,
126
+ name: _n,
127
+ message: _m,
128
+ stack: _s,
129
+ code: _c,
130
+ hint: _h,
131
+ docsUrl: _d,
132
+ ...rest
133
+ } = props;
134
+ safeProps = rest;
135
+ } else {
136
+ const {
137
+ _tag: _,
138
+ type: _t,
139
+ name: _n,
140
+ message: _m,
141
+ stack: _s,
142
+ ...rest
143
+ } = props;
144
+ safeProps = rest;
145
+ }
146
+ const hasUserCause = Object.prototype.hasOwnProperty.call(
147
+ safeProps,
148
+ "cause"
149
+ );
150
+ const userCause = hasUserCause ? safeProps.cause : void 0;
151
+ if (hasUserCause) {
152
+ delete safeProps.cause;
153
+ }
154
+ const hasOptionsCause = errorOptions?.cause !== void 0;
155
+ if (hasUserCause && hasOptionsCause) {
156
+ throw new TypeError(
157
+ "TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause"
158
+ );
159
+ }
160
+ Object.assign(this, safeProps);
161
+ if (hasUserCause) {
162
+ this.cause = userCause;
163
+ }
164
+ if (hasOptionsCause) {
165
+ this.cause = errorOptions?.cause;
166
+ }
167
+ } else if (errorOptions?.cause !== void 0) {
168
+ this.cause = errorOptions.cause;
169
+ }
170
+ }
171
+ };
172
+ }
173
+ Object.defineProperty(TaggedError, Symbol.hasInstance, {
174
+ value: (instance) => instance instanceof InternalTaggedErrorBase
175
+ });
176
+ ((TaggedError2) => {
177
+ function isError(value) {
178
+ return value instanceof Error;
179
+ }
180
+ TaggedError2.isError = isError;
181
+ function isTaggedError(value) {
182
+ return value instanceof InternalTaggedErrorBase;
183
+ }
184
+ TaggedError2.isTaggedError = isTaggedError;
185
+ function match(error, handlers) {
186
+ const tag = error._tag;
187
+ const handler = handlers[tag];
188
+ return handler(
189
+ error
190
+ );
191
+ }
192
+ TaggedError2.match = match;
193
+ function matchPartial(error, handlers, otherwise) {
194
+ const tag = error._tag;
195
+ const handler = handlers[tag];
196
+ if (handler) {
197
+ return handler(
198
+ error
199
+ );
200
+ }
201
+ return otherwise(error);
202
+ }
203
+ TaggedError2.matchPartial = matchPartial;
204
+ })(TaggedError || (TaggedError = {}));
205
+
206
+ // src/errors.ts
207
+ var UnexpectedError = class extends (/* @__PURE__ */ TaggedError("UnexpectedError", {
208
+ slug: "runtime-unexpected",
209
+ hint: "An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",
210
+ message: (p) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? "unknown")}`
211
+ })) {
212
+ };
213
+
214
+ // src/result/index.ts
215
+ function ok(value) {
216
+ return { ok: true, value };
217
+ }
218
+
219
+ // src/core/bound-steps.ts
220
+ var isDepResultShaped = (value) => typeof value === "object" && value !== null && "ok" in value && typeof value.ok === "boolean" && (value.ok ? "value" in value : "error" in value);
221
+ var bindSteps = (deps, step) => {
222
+ const steps = {};
223
+ const invocationCounts = /* @__PURE__ */ new Map();
224
+ for (const key of Object.keys(deps)) {
225
+ const dep = deps[key];
226
+ if (typeof dep !== "function") continue;
227
+ steps[key] = (...args) => {
228
+ const count = (invocationCounts.get(key) ?? 0) + 1;
229
+ invocationCounts.set(key, count);
230
+ const stepKey = count === 1 ? key : `${key}#${count}`;
231
+ return step(stepKey, async () => {
232
+ const value = await dep(...args);
233
+ return isDepResultShaped(value) ? value : ok(value);
234
+ });
235
+ };
236
+ }
237
+ return steps;
238
+ };
239
+
240
+ // src/duration.ts
241
+ function millis(ms) {
242
+ return { _tag: "Duration", millis: ms };
243
+ }
244
+ function seconds(s) {
245
+ return { _tag: "Duration", millis: s * 1e3 };
246
+ }
247
+ function minutes(m) {
248
+ return { _tag: "Duration", millis: m * 60 * 1e3 };
249
+ }
250
+ function hours(h) {
251
+ return { _tag: "Duration", millis: h * 60 * 60 * 1e3 };
252
+ }
253
+ function days(d) {
254
+ return { _tag: "Duration", millis: d * 24 * 60 * 60 * 1e3 };
255
+ }
256
+ function toMillis(duration) {
257
+ return duration.millis;
258
+ }
259
+ function parse(input) {
260
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
261
+ if (!match) return void 0;
262
+ const value = parseFloat(match[1]);
263
+ const unit = match[2].toLowerCase();
264
+ switch (unit) {
265
+ case "ms":
266
+ return millis(value);
267
+ case "s":
268
+ return seconds(value);
269
+ case "m":
270
+ return minutes(value);
271
+ case "h":
272
+ return hours(value);
273
+ case "d":
274
+ return days(value);
275
+ default:
276
+ return void 0;
277
+ }
278
+ }
279
+
280
+ // src/core/index.ts
281
+ function parseDurationString(input) {
282
+ const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
283
+ if (!match) return void 0;
284
+ const value = parseFloat(match[1]);
285
+ const unit = match[2].toLowerCase();
286
+ const multipliers = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
287
+ return { _tag: "Duration", millis: value * (multipliers[unit] ?? 1) };
288
+ }
289
+ function defaultCatchUnexpected(cause) {
290
+ return new UnexpectedError({ cause });
291
+ }
292
+ function ok2(value) {
293
+ return { ok: true, value };
294
+ }
295
+ function err(error, options) {
296
+ const cause = options?.cause;
297
+ return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
298
+ }
299
+ var isUnexpectedError = (e) => e instanceof UnexpectedError || typeof e === "object" && e !== null && "_tag" in e && e._tag === "UnexpectedError";
300
+ function extractErrorTag(error) {
301
+ if (error == null) return "unknown";
302
+ if (typeof error === "string") return error.trim() || "unknown";
303
+ if (typeof error === "object") {
304
+ const tagged = error;
305
+ if (typeof tagged._tag === "string") {
306
+ const trimmed = tagged._tag.trim();
307
+ if (trimmed) return trimmed;
308
+ }
309
+ if (typeof tagged.tag === "string") {
310
+ const trimmed = tagged.tag.trim();
311
+ if (trimmed) return trimmed;
312
+ }
313
+ if (typeof tagged.code === "string") {
314
+ const trimmed = tagged.code.trim();
315
+ if (trimmed) return trimmed;
316
+ } else if (typeof tagged.code === "number") {
317
+ return String(tagged.code);
318
+ }
319
+ if (error instanceof Error && error.name) {
320
+ const trimmed = error.name.trim();
321
+ if (trimmed) return trimmed;
322
+ }
323
+ }
324
+ return "unknown";
325
+ }
326
+ function lookupErrorClassification(tag, errorMeta) {
327
+ if (!errorMeta || !tag) return void 0;
328
+ return errorMeta[tag];
329
+ }
330
+ function extractStepMetadata(options) {
331
+ const { intent, domain, owner, tags, stateChanges, emits, calls } = options;
332
+ if (!intent && !domain && !owner && !tags?.length && !stateChanges?.length && !emits?.length && !calls?.length) {
333
+ return void 0;
334
+ }
335
+ const metadata = {};
336
+ if (intent) metadata.intent = intent;
337
+ if (domain) metadata.domain = domain;
338
+ if (owner) metadata.owner = owner;
339
+ if (tags?.length) metadata.tags = tags;
340
+ if (stateChanges?.length) metadata.stateChanges = stateChanges;
341
+ if (emits?.length) metadata.emits = emits;
342
+ if (calls?.length) metadata.calls = calls;
343
+ return metadata;
344
+ }
345
+ function buildStepErrorPayload(error, errorMeta, origin, attempt, cumulativeDurationMs) {
346
+ const tag = extractErrorTag(error);
347
+ const classification = lookupErrorClassification(tag, errorMeta);
348
+ const diagnostics = { tag, origin };
349
+ if (classification !== void 0) diagnostics.classification = classification;
350
+ if (attempt !== void 0) diagnostics.attempt = attempt;
351
+ if (cumulativeDurationMs !== void 0) diagnostics.cumulativeDurationMs = cumulativeDurationMs;
352
+ return diagnostics;
353
+ }
354
+ var STEP_TIMEOUT_MARKER = /* @__PURE__ */ Symbol.for("step_timeout_marker");
355
+ function isStepTimeoutError(e) {
356
+ if (typeof e !== "object" || e === null) {
357
+ return false;
358
+ }
359
+ if (e.type === "STEP_TIMEOUT") {
360
+ return true;
361
+ }
362
+ return STEP_TIMEOUT_MARKER in e;
363
+ }
364
+ function getStepTimeoutMeta(e) {
365
+ if (typeof e !== "object" || e === null) {
366
+ return void 0;
367
+ }
368
+ if (e.type === "STEP_TIMEOUT") {
369
+ const err2 = e;
370
+ return {
371
+ timeoutMs: err2.timeoutMs,
372
+ stepName: err2.stepName,
373
+ stepKey: err2.stepKey,
374
+ attempt: err2.attempt
375
+ };
376
+ }
377
+ if (STEP_TIMEOUT_MARKER in e) {
378
+ return e[STEP_TIMEOUT_MARKER];
379
+ }
380
+ return void 0;
381
+ }
382
+ var EARLY_EXIT_SYMBOL = /* @__PURE__ */ Symbol("early-exit");
383
+ function createEarlyExit(error, meta) {
384
+ return {
385
+ [EARLY_EXIT_SYMBOL]: true,
386
+ error,
387
+ meta
388
+ };
389
+ }
390
+ function isEarlyExit(e) {
391
+ return typeof e === "object" && e !== null && e[EARLY_EXIT_SYMBOL] === true;
392
+ }
393
+ var MAPPER_EXCEPTION_SYMBOL = /* @__PURE__ */ Symbol("mapper-exception");
394
+ function createMapperException(thrown) {
395
+ return { [MAPPER_EXCEPTION_SYMBOL]: true, thrown };
396
+ }
397
+ function isMapperException(e) {
398
+ return typeof e === "object" && e !== null && e[MAPPER_EXCEPTION_SYMBOL] === true;
399
+ }
400
+ function calculateRetryDelay(attempt, options) {
401
+ const { backoff, initialDelay, maxDelay, jitter } = options;
402
+ let delay;
403
+ switch (backoff) {
404
+ case "fixed":
405
+ delay = initialDelay;
406
+ break;
407
+ case "linear":
408
+ delay = initialDelay * attempt;
409
+ break;
410
+ case "exponential":
411
+ delay = initialDelay * Math.pow(2, attempt - 1);
412
+ break;
413
+ }
414
+ delay = Math.min(delay, maxDelay);
415
+ if (jitter) {
416
+ const jitterAmount = delay * 0.25 * Math.random();
417
+ delay = delay + jitterAmount;
418
+ }
419
+ return Math.floor(delay);
420
+ }
421
+ function sleep(ms) {
422
+ return new Promise((resolve) => setTimeout(resolve, ms));
423
+ }
424
+ var TIMEOUT_SYMBOL = /* @__PURE__ */ Symbol("timeout");
425
+ var TIMEOUT_OPTION_SYMBOL = /* @__PURE__ */ Symbol("timeout-option");
426
+ function isTimeoutOptionMarker(value) {
427
+ return typeof value === "object" && value !== null && value[TIMEOUT_OPTION_SYMBOL] === true;
428
+ }
429
+ async function executeWithTimeout(operation, options, stepInfo, externalSignal) {
430
+ const controller = new AbortController();
431
+ const behavior = options.onTimeout ?? "error";
432
+ const createTimeoutError = () => {
433
+ if (typeof behavior === "function") {
434
+ return behavior({
435
+ name: stepInfo.name,
436
+ key: stepInfo.key,
437
+ ms: options.ms
438
+ });
439
+ }
440
+ return options.error ?? {
441
+ type: "STEP_TIMEOUT",
442
+ stepName: stepInfo.name,
443
+ stepKey: stepInfo.key,
444
+ timeoutMs: options.ms,
445
+ attempt: stepInfo.attempt
446
+ };
447
+ };
448
+ let timeoutId;
449
+ if (externalSignal?.aborted) {
450
+ controller.abort(externalSignal.reason);
451
+ }
452
+ let externalAbortHandler;
453
+ if (externalSignal && !externalSignal.aborted) {
454
+ externalAbortHandler = () => controller.abort(externalSignal.reason);
455
+ externalSignal.addEventListener("abort", externalAbortHandler, { once: true });
456
+ }
457
+ const timeoutPromise = new Promise((_, reject) => {
458
+ timeoutId = setTimeout(() => {
459
+ if (behavior !== "disconnect") {
460
+ controller.abort();
461
+ }
462
+ if (behavior === "option") {
463
+ reject({ [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms });
464
+ return;
465
+ }
466
+ reject({ [TIMEOUT_SYMBOL]: true, error: createTimeoutError() });
467
+ }, options.ms);
468
+ });
469
+ let operationPromise;
470
+ if (options.signal) {
471
+ operationPromise = Promise.resolve(
472
+ operation(controller.signal)
473
+ );
474
+ } else {
475
+ operationPromise = Promise.resolve(operation());
476
+ }
477
+ try {
478
+ const result = await Promise.race([operationPromise, timeoutPromise]);
479
+ return result;
480
+ } catch (error) {
481
+ if (typeof error === "object" && error !== null && error[TIMEOUT_OPTION_SYMBOL] === true) {
482
+ throw { [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms };
483
+ }
484
+ if (typeof error === "object" && error !== null && error[TIMEOUT_SYMBOL] === true) {
485
+ if (behavior === "disconnect") {
486
+ operationPromise.catch(() => {
487
+ });
488
+ }
489
+ const errorToThrow = error.error;
490
+ if (typeof errorToThrow === "object" && errorToThrow !== null && errorToThrow.type !== "STEP_TIMEOUT") {
491
+ const meta = {
492
+ timeoutMs: options.ms,
493
+ stepName: stepInfo.name,
494
+ stepKey: stepInfo.key,
495
+ attempt: stepInfo.attempt
496
+ };
497
+ if (STEP_TIMEOUT_MARKER in errorToThrow) {
498
+ errorToThrow[STEP_TIMEOUT_MARKER] = meta;
499
+ } else {
500
+ Object.defineProperty(errorToThrow, STEP_TIMEOUT_MARKER, {
501
+ value: meta,
502
+ enumerable: false,
503
+ writable: true,
504
+ configurable: false
505
+ });
506
+ }
507
+ }
508
+ throw errorToThrow;
509
+ }
510
+ throw error;
511
+ } finally {
512
+ clearTimeout(timeoutId);
513
+ if (externalAbortHandler && externalSignal) {
514
+ externalSignal.removeEventListener("abort", externalAbortHandler);
515
+ }
516
+ }
517
+ }
518
+ var DEFAULT_RETRY_CONFIG = {
519
+ backoff: "exponential",
520
+ initialDelay: 100,
521
+ maxDelay: 3e4,
522
+ jitter: true,
523
+ shouldRetry: () => true,
524
+ onRetry: () => {
525
+ }
526
+ };
527
+ async function runFn(fnOrDeps, optionsOrFn, maybeOptions) {
528
+ if (typeof fnOrDeps !== "function") {
529
+ const deps = fnOrDeps;
530
+ const boundFn = optionsOrFn;
531
+ if (typeof boundFn !== "function") {
532
+ throw new TypeError(
533
+ "[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))"
534
+ );
535
+ }
536
+ const classicRun = runFn;
537
+ return classicRun(
538
+ ({ step }) => boundFn(bindSteps(deps, step), { step }),
539
+ maybeOptions
540
+ );
541
+ }
542
+ const fn = fnOrDeps;
543
+ const options = optionsOrFn;
544
+ const {
545
+ onError,
546
+ onEvent,
547
+ catchUnexpected,
548
+ workflowId: providedWorkflowId,
549
+ workflowName,
550
+ context,
551
+ graph,
552
+ _workflowSignal
553
+ } = options && typeof options === "object" ? options : {};
554
+ const workflowId = providedWorkflowId ?? crypto.randomUUID();
555
+ const declaredIds = graph ? new Set(
556
+ Array.isArray(graph) ? graph : graph.states.map((state) => state.semanticId ?? state.id)
557
+ ) : void 0;
558
+ const declaredPatterns = declaredIds ? [...declaredIds].filter((id) => id.includes("{")).map(
559
+ (id) => new RegExp(
560
+ `^${id.replaceAll(/[.*+?^$()[\]\\|]/g, String.raw`\$&`).replaceAll(/\{[^}]*\}/g, ".+")}$`
561
+ )
562
+ ) : void 0;
563
+ const assertDeclared = (id, kind) => {
564
+ if (!declaredIds || declaredIds.has(id)) return;
565
+ if (declaredPatterns?.some((re) => re.test(id))) return;
566
+ throw new Error(
567
+ `[awaitly] ${kind} id "${id}" is not in the declared workflow graph. Declared ids: ${[...declaredIds].join(", ")}. Either add it to the graph or remove the graph option.`
568
+ );
569
+ };
570
+ const effectiveCatchUnexpected = catchUnexpected ?? defaultCatchUnexpected;
571
+ const activeScopeStack = [];
572
+ let stepIdCounter = 0;
573
+ const generateStepId = (stepKey) => {
574
+ return stepKey ?? `step_${++stepIdCounter}`;
575
+ };
576
+ const emitEvent = (event) => {
577
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
578
+ const eventWithName = workflowName !== void 0 && eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
579
+ if (eventWithName.type === "step_success") {
580
+ const stepId = eventWithName.stepId;
581
+ for (let i = activeScopeStack.length - 1; i >= 0; i--) {
582
+ const scope = activeScopeStack[i];
583
+ if (scope.type === "race" && !scope.winnerId) {
584
+ scope.winnerId = stepId;
585
+ break;
586
+ }
587
+ }
588
+ }
589
+ onEvent?.(eventWithName, context);
590
+ };
591
+ const earlyExit = createEarlyExit;
592
+ const isEarlyExitE = (e) => isEarlyExit(e);
593
+ const wrapForStep = (error, _meta) => {
594
+ return error;
595
+ };
596
+ const isResultLike = (value) => {
597
+ if (typeof value === "function") return false;
598
+ if (value && typeof value === "object" && "ok" in value) return true;
599
+ if (value && typeof value === "object" && "then" in value && typeof value.then === "function") return true;
600
+ return false;
601
+ };
602
+ try {
603
+ let normalizeParallelOperations2 = function(rawOperations) {
604
+ const out = {};
605
+ for (const [key, value2] of Object.entries(rawOperations)) {
606
+ if (typeof value2 === "function") {
607
+ out[key] = value2;
608
+ } else if (value2 && typeof value2 === "object" && "fn" in value2) {
609
+ out[key] = value2.fn;
610
+ } else {
611
+ throw new TypeError(`step.all: operation "${key}" must be a function or { fn, errors? } object`);
612
+ }
613
+ }
614
+ return out;
615
+ }, executeParallelArray2 = function(name, operation) {
616
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
617
+ return (async () => {
618
+ const startTime = performance.now();
619
+ let scopeEnded = false;
620
+ activeScopeStack.push({ scopeId, type: "parallel" });
621
+ const emitScopeEnd = () => {
622
+ if (scopeEnded) return;
623
+ scopeEnded = true;
624
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
625
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
626
+ emitEvent({
627
+ type: "scope_end",
628
+ workflowId,
629
+ scopeId,
630
+ ts: Date.now(),
631
+ durationMs: performance.now() - startTime
632
+ });
633
+ };
634
+ emitEvent({
635
+ type: "scope_start",
636
+ workflowId,
637
+ scopeId,
638
+ scopeType: "parallel",
639
+ name,
640
+ ts: Date.now()
641
+ });
642
+ try {
643
+ const result = await operation();
644
+ emitScopeEnd();
645
+ if (!result.ok) {
646
+ onError?.(result.error, name, context);
647
+ throw earlyExit(result.error, {
648
+ origin: "result",
649
+ resultCause: result.cause
650
+ });
651
+ }
652
+ return result.value;
653
+ } catch (error) {
654
+ emitScopeEnd();
655
+ throw error;
656
+ }
657
+ })();
658
+ }, executeParallelNamed2 = function(operations, options2) {
659
+ const keys = Object.keys(operations);
660
+ const name = options2.name ?? `Parallel(${keys.join(", ")})`;
661
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
662
+ return (async () => {
663
+ const startTime = performance.now();
664
+ let scopeEnded = false;
665
+ activeScopeStack.push({ scopeId, type: "parallel" });
666
+ const emitScopeEnd = () => {
667
+ if (scopeEnded) return;
668
+ scopeEnded = true;
669
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
670
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
671
+ emitEvent({
672
+ type: "scope_end",
673
+ workflowId,
674
+ scopeId,
675
+ ts: Date.now(),
676
+ durationMs: performance.now() - startTime
677
+ });
678
+ };
679
+ emitEvent({
680
+ type: "scope_start",
681
+ workflowId,
682
+ scopeId,
683
+ scopeType: "parallel",
684
+ name,
685
+ ts: Date.now()
686
+ });
687
+ try {
688
+ const results = await new Promise((resolve) => {
689
+ if (keys.length === 0) {
690
+ resolve([]);
691
+ return;
692
+ }
693
+ let settled = false;
694
+ let pendingCount = keys.length;
695
+ const resultArray = new Array(keys.length);
696
+ for (let i = 0; i < keys.length; i++) {
697
+ const key = keys[i];
698
+ const index = i;
699
+ Promise.resolve(operations[key]()).catch((reason) => err(
700
+ { type: "PROMISE_REJECTED", cause: reason },
701
+ { cause: { type: "PROMISE_REJECTION", reason } }
702
+ )).then((result) => {
703
+ if (settled) return;
704
+ if (!result.ok) {
705
+ settled = true;
706
+ resolve([{ key, result }]);
707
+ return;
708
+ }
709
+ resultArray[index] = { key, result };
710
+ pendingCount--;
711
+ if (pendingCount === 0) {
712
+ resolve(resultArray);
713
+ }
714
+ });
715
+ }
716
+ });
717
+ emitScopeEnd();
718
+ const output = {};
719
+ for (const { key, result } of results) {
720
+ if (!result.ok) {
721
+ onError?.(result.error, key, context);
722
+ throw earlyExit(result.error, {
723
+ origin: "result",
724
+ resultCause: result.cause
725
+ });
726
+ }
727
+ output[key] = result.value;
728
+ }
729
+ return output;
730
+ } catch (error) {
731
+ emitScopeEnd();
732
+ throw error;
733
+ }
734
+ })();
735
+ };
736
+ var normalizeParallelOperations = normalizeParallelOperations2, executeParallelArray = executeParallelArray2, executeParallelNamed = executeParallelNamed2;
737
+ const stepFn = (id, operationOrResult, stepOptions) => {
738
+ return (async () => {
739
+ if (typeof id !== "string" || id.length === 0) {
740
+ throw new Error(
741
+ '[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
742
+ );
743
+ }
744
+ assertDeclared(id, "step");
745
+ const parsedOptions = stepOptions ?? {};
746
+ const stepMetadata = extractStepMetadata(parsedOptions);
747
+ const stepName = id;
748
+ const stepKey = parsedOptions.key ?? id;
749
+ const explicitKey = parsedOptions.key ?? id;
750
+ const { description: stepDescription, retry: retryConfig, timeout: timeoutConfig } = parsedOptions;
751
+ const stepId = generateStepId(stepKey);
752
+ const hasEventListeners = onEvent;
753
+ const overallStartTime = hasEventListeners ? performance.now() : 0;
754
+ const isDirectResult = isResultLike(operationOrResult);
755
+ const operation = isDirectResult ? () => operationOrResult : operationOrResult;
756
+ const maxAttempts = Math.max(1, retryConfig?.attempts ?? 1);
757
+ const effectiveRetry = {
758
+ attempts: maxAttempts,
759
+ backoff: retryConfig?.backoff ?? DEFAULT_RETRY_CONFIG.backoff,
760
+ initialDelay: retryConfig?.initialDelay ?? DEFAULT_RETRY_CONFIG.initialDelay,
761
+ maxDelay: retryConfig?.maxDelay ?? DEFAULT_RETRY_CONFIG.maxDelay,
762
+ jitter: retryConfig?.jitter ?? DEFAULT_RETRY_CONFIG.jitter,
763
+ shouldRetry: retryConfig?.shouldRetry ?? DEFAULT_RETRY_CONFIG.shouldRetry,
764
+ onRetry: retryConfig?.onRetry ?? DEFAULT_RETRY_CONFIG.onRetry
765
+ };
766
+ if (onEvent) {
767
+ emitEvent({
768
+ type: "step_start",
769
+ workflowId,
770
+ stepId,
771
+ stepKey,
772
+ name: stepName,
773
+ description: stepDescription,
774
+ ts: Date.now(),
775
+ ...stepMetadata && { metadata: stepMetadata }
776
+ });
777
+ }
778
+ let lastResult;
779
+ for (let attempt = 1; attempt <= effectiveRetry.attempts; attempt++) {
780
+ const attemptStartTime = hasEventListeners ? performance.now() : 0;
781
+ try {
782
+ let result;
783
+ if (timeoutConfig) {
784
+ result = await executeWithTimeout(
785
+ operation,
786
+ timeoutConfig,
787
+ { name: stepName, key: stepKey, attempt },
788
+ _workflowSignal
789
+ );
790
+ } else {
791
+ result = await operation();
792
+ }
793
+ if (result.ok) {
794
+ const durationMs = performance.now() - overallStartTime;
795
+ emitEvent({
796
+ type: "step_success",
797
+ workflowId,
798
+ stepId,
799
+ stepKey,
800
+ name: stepName,
801
+ description: stepDescription,
802
+ ts: Date.now(),
803
+ durationMs,
804
+ ...stepMetadata && { metadata: stepMetadata }
805
+ });
806
+ if (explicitKey) {
807
+ emitEvent({
808
+ type: "step_complete",
809
+ workflowId,
810
+ stepKey: explicitKey,
811
+ name: stepName,
812
+ description: stepDescription,
813
+ ts: Date.now(),
814
+ durationMs,
815
+ result,
816
+ ...stepMetadata && { metadata: stepMetadata }
817
+ });
818
+ }
819
+ return result.value;
820
+ }
821
+ lastResult = result;
822
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(result.error, attempt)) {
823
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
824
+ emitEvent({
825
+ type: "step_retry",
826
+ workflowId,
827
+ stepId,
828
+ stepKey,
829
+ name: stepName,
830
+ ts: Date.now(),
831
+ attempt: attempt + 1,
832
+ maxAttempts: effectiveRetry.attempts,
833
+ delayMs: delay,
834
+ error: result.error,
835
+ ...stepMetadata && { metadata: stepMetadata },
836
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
837
+ });
838
+ effectiveRetry.onRetry(result.error, attempt, delay);
839
+ await sleep(delay);
840
+ continue;
841
+ }
842
+ if (effectiveRetry.attempts > 1) {
843
+ emitEvent({
844
+ type: "step_retries_exhausted",
845
+ workflowId,
846
+ stepId,
847
+ stepKey,
848
+ name: stepName,
849
+ ts: Date.now(),
850
+ durationMs: performance.now() - overallStartTime,
851
+ attempts: attempt,
852
+ lastError: result.error,
853
+ ...stepMetadata && { metadata: stepMetadata },
854
+ diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
855
+ });
856
+ }
857
+ break;
858
+ } catch (thrown) {
859
+ const durationMs = performance.now() - attemptStartTime;
860
+ if (isTimeoutOptionMarker(thrown)) {
861
+ const timeoutMs = thrown.ms;
862
+ emitEvent({
863
+ type: "step_timeout",
864
+ workflowId,
865
+ stepId,
866
+ stepKey,
867
+ name: stepName,
868
+ ts: Date.now(),
869
+ timeoutMs,
870
+ attempt,
871
+ ...stepMetadata && { metadata: stepMetadata },
872
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
873
+ });
874
+ emitEvent({
875
+ type: "step_success",
876
+ workflowId,
877
+ stepId,
878
+ stepKey,
879
+ name: stepName,
880
+ description: stepDescription,
881
+ ts: Date.now(),
882
+ durationMs: performance.now() - overallStartTime,
883
+ ...stepMetadata && { metadata: stepMetadata }
884
+ });
885
+ if (explicitKey) {
886
+ emitEvent({
887
+ type: "step_complete",
888
+ workflowId,
889
+ stepKey: explicitKey,
890
+ name: stepName,
891
+ description: stepDescription,
892
+ ts: Date.now(),
893
+ durationMs: performance.now() - overallStartTime,
894
+ result: ok2(void 0),
895
+ ...stepMetadata && { metadata: stepMetadata }
896
+ });
897
+ }
898
+ return void 0;
899
+ }
900
+ if (isEarlyExitE(thrown)) {
901
+ emitEvent({
902
+ type: "step_aborted",
903
+ workflowId,
904
+ stepId,
905
+ stepKey,
906
+ name: stepName,
907
+ description: stepDescription,
908
+ ts: Date.now(),
909
+ durationMs,
910
+ ...stepMetadata && { metadata: stepMetadata }
911
+ });
912
+ throw thrown;
913
+ }
914
+ if (isStepTimeoutError(thrown)) {
915
+ const timeoutMeta = getStepTimeoutMeta(thrown);
916
+ const timeoutMs = timeoutConfig?.ms ?? timeoutMeta?.timeoutMs ?? 0;
917
+ emitEvent({
918
+ type: "step_timeout",
919
+ workflowId,
920
+ stepId,
921
+ stepKey,
922
+ name: stepName,
923
+ ts: Date.now(),
924
+ timeoutMs,
925
+ attempt,
926
+ ...stepMetadata && { metadata: stepMetadata },
927
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
928
+ });
929
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
930
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
931
+ emitEvent({
932
+ type: "step_retry",
933
+ workflowId,
934
+ stepId,
935
+ stepKey,
936
+ name: stepName,
937
+ ts: Date.now(),
938
+ attempt: attempt + 1,
939
+ maxAttempts: effectiveRetry.attempts,
940
+ delayMs: delay,
941
+ error: thrown,
942
+ ...stepMetadata && { metadata: stepMetadata },
943
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
944
+ });
945
+ effectiveRetry.onRetry(thrown, attempt, delay);
946
+ await sleep(delay);
947
+ continue;
948
+ }
949
+ if (effectiveRetry.attempts > 1) {
950
+ emitEvent({
951
+ type: "step_retries_exhausted",
952
+ workflowId,
953
+ stepId,
954
+ stepKey,
955
+ name: stepName,
956
+ ts: Date.now(),
957
+ durationMs: performance.now() - overallStartTime,
958
+ attempts: attempt,
959
+ lastError: thrown,
960
+ ...stepMetadata && { metadata: stepMetadata },
961
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
962
+ });
963
+ }
964
+ const totalDurationMs3 = performance.now() - overallStartTime;
965
+ emitEvent({
966
+ type: "step_error",
967
+ workflowId,
968
+ stepId,
969
+ stepKey,
970
+ name: stepName,
971
+ description: stepDescription,
972
+ ts: Date.now(),
973
+ durationMs: totalDurationMs3,
974
+ error: thrown,
975
+ ...stepMetadata && { metadata: stepMetadata },
976
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, totalDurationMs3)
977
+ });
978
+ if (explicitKey) {
979
+ emitEvent({
980
+ type: "step_complete",
981
+ workflowId,
982
+ stepKey: explicitKey,
983
+ name: stepName,
984
+ description: stepDescription,
985
+ ts: Date.now(),
986
+ durationMs: totalDurationMs3,
987
+ result: err(thrown, { cause: thrown }),
988
+ meta: { origin: "throw", thrown },
989
+ ...stepMetadata && { metadata: stepMetadata }
990
+ });
991
+ }
992
+ onError?.(thrown, stepName, context);
993
+ throw earlyExit(thrown, { origin: "throw", thrown });
994
+ }
995
+ if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
996
+ const delay = calculateRetryDelay(attempt, effectiveRetry);
997
+ emitEvent({
998
+ type: "step_retry",
999
+ workflowId,
1000
+ stepId,
1001
+ stepKey,
1002
+ name: stepName,
1003
+ ts: Date.now(),
1004
+ attempt: attempt + 1,
1005
+ maxAttempts: effectiveRetry.attempts,
1006
+ delayMs: delay,
1007
+ error: thrown,
1008
+ ...stepMetadata && { metadata: stepMetadata },
1009
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1010
+ });
1011
+ effectiveRetry.onRetry(thrown, attempt, delay);
1012
+ await sleep(delay);
1013
+ continue;
1014
+ }
1015
+ if (effectiveRetry.attempts > 1 && !isStepTimeoutError(thrown)) {
1016
+ emitEvent({
1017
+ type: "step_retries_exhausted",
1018
+ workflowId,
1019
+ stepId,
1020
+ stepKey,
1021
+ name: stepName,
1022
+ ts: Date.now(),
1023
+ durationMs: performance.now() - overallStartTime,
1024
+ attempts: attempt,
1025
+ lastError: thrown,
1026
+ ...stepMetadata && { metadata: stepMetadata },
1027
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
1028
+ });
1029
+ }
1030
+ const totalDurationMs2 = performance.now() - overallStartTime;
1031
+ let mappedError;
1032
+ try {
1033
+ mappedError = effectiveCatchUnexpected(thrown);
1034
+ } catch (mapperError) {
1035
+ throw createMapperException(mapperError);
1036
+ }
1037
+ emitEvent({
1038
+ type: "step_error",
1039
+ workflowId,
1040
+ stepId,
1041
+ stepKey,
1042
+ name: stepName,
1043
+ description: stepDescription,
1044
+ ts: Date.now(),
1045
+ durationMs: totalDurationMs2,
1046
+ error: mappedError,
1047
+ ...stepMetadata && { metadata: stepMetadata },
1048
+ diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, totalDurationMs2)
1049
+ });
1050
+ if (explicitKey) {
1051
+ emitEvent({
1052
+ type: "step_complete",
1053
+ workflowId,
1054
+ stepKey: explicitKey,
1055
+ name: stepName,
1056
+ description: stepDescription,
1057
+ ts: Date.now(),
1058
+ durationMs: totalDurationMs2,
1059
+ result: err(mappedError, { cause: thrown }),
1060
+ meta: { origin: "throw", thrown },
1061
+ ...stepMetadata && { metadata: stepMetadata }
1062
+ });
1063
+ }
1064
+ onError?.(mappedError, stepName, context);
1065
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1066
+ }
1067
+ }
1068
+ const errorResult = lastResult;
1069
+ const totalDurationMs = performance.now() - overallStartTime;
1070
+ const wrappedError = wrapForStep(errorResult.error, {
1071
+ origin: "result",
1072
+ resultCause: errorResult.cause
1073
+ });
1074
+ emitEvent({
1075
+ type: "step_error",
1076
+ workflowId,
1077
+ stepId,
1078
+ stepKey,
1079
+ name: stepName,
1080
+ description: stepDescription,
1081
+ ts: Date.now(),
1082
+ durationMs: totalDurationMs,
1083
+ error: wrappedError,
1084
+ ...stepMetadata && { metadata: stepMetadata },
1085
+ diagnostics: buildStepErrorPayload(errorResult.error, parsedOptions.errorMeta, "result", effectiveRetry.attempts, totalDurationMs)
1086
+ });
1087
+ if (explicitKey) {
1088
+ emitEvent({
1089
+ type: "step_complete",
1090
+ workflowId,
1091
+ stepKey: explicitKey,
1092
+ name: stepName,
1093
+ description: stepDescription,
1094
+ ts: Date.now(),
1095
+ durationMs: totalDurationMs,
1096
+ result: errorResult,
1097
+ meta: { origin: "result", resultCause: errorResult.cause },
1098
+ ...stepMetadata && { metadata: stepMetadata }
1099
+ });
1100
+ }
1101
+ onError?.(wrappedError, stepName, context);
1102
+ throw earlyExit(wrappedError, {
1103
+ origin: "result",
1104
+ resultCause: errorResult.cause
1105
+ });
1106
+ })();
1107
+ };
1108
+ stepFn.try = (id, operation, opts) => {
1109
+ if (typeof id !== "string" || id.length === 0) {
1110
+ throw new Error(
1111
+ '[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })'
1112
+ );
1113
+ }
1114
+ assertDeclared(id, "step");
1115
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1116
+ if (opts.retry || opts.timeout) {
1117
+ return stepFn.retry(
1118
+ id,
1119
+ async () => {
1120
+ try {
1121
+ return ok2(await operation());
1122
+ } catch (cause) {
1123
+ return err(mapToError(cause), { cause });
1124
+ }
1125
+ },
1126
+ {
1127
+ attempts: opts.retry?.attempts ?? 1,
1128
+ ...opts.retry ?? {},
1129
+ key: opts.key,
1130
+ timeout: opts.timeout
1131
+ }
1132
+ );
1133
+ }
1134
+ const stepKey = opts.key ?? id;
1135
+ const stepName = id;
1136
+ const stepId = id;
1137
+ const hasEventListeners = onEvent;
1138
+ return (async () => {
1139
+ const startTime = hasEventListeners ? performance.now() : 0;
1140
+ if (onEvent) {
1141
+ emitEvent({
1142
+ type: "step_start",
1143
+ workflowId,
1144
+ stepId,
1145
+ stepKey,
1146
+ name: stepName,
1147
+ ts: Date.now()
1148
+ });
1149
+ }
1150
+ try {
1151
+ const value2 = await operation();
1152
+ const durationMs = performance.now() - startTime;
1153
+ emitEvent({
1154
+ type: "step_success",
1155
+ workflowId,
1156
+ stepId,
1157
+ stepKey,
1158
+ name: stepName,
1159
+ ts: Date.now(),
1160
+ durationMs
1161
+ });
1162
+ if (stepKey) {
1163
+ emitEvent({
1164
+ type: "step_complete",
1165
+ workflowId,
1166
+ stepKey,
1167
+ name: stepName,
1168
+ ts: Date.now(),
1169
+ durationMs,
1170
+ result: ok2(value2)
1171
+ });
1172
+ }
1173
+ return value2;
1174
+ } catch (error) {
1175
+ const mapped = mapToError(error);
1176
+ const durationMs = performance.now() - startTime;
1177
+ const wrappedError = wrapForStep(mapped, { origin: "throw", thrown: error });
1178
+ emitEvent({
1179
+ type: "step_error",
1180
+ workflowId,
1181
+ stepId,
1182
+ stepKey,
1183
+ name: stepName,
1184
+ ts: Date.now(),
1185
+ durationMs,
1186
+ error: wrappedError
1187
+ });
1188
+ if (stepKey) {
1189
+ emitEvent({
1190
+ type: "step_complete",
1191
+ workflowId,
1192
+ stepKey,
1193
+ name: stepName,
1194
+ ts: Date.now(),
1195
+ durationMs,
1196
+ result: err(mapped, { cause: error }),
1197
+ meta: { origin: "throw", thrown: error }
1198
+ });
1199
+ }
1200
+ onError?.(wrappedError, stepName, context);
1201
+ throw earlyExit(wrappedError, { origin: "throw", thrown: error });
1202
+ }
1203
+ })();
1204
+ };
1205
+ stepFn.fromResult = (id, operation, opts) => {
1206
+ if (typeof id !== "string" || id.length === 0) {
1207
+ throw new Error(
1208
+ '[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })'
1209
+ );
1210
+ }
1211
+ assertDeclared(id, "step");
1212
+ const stepKey = opts.key ?? id;
1213
+ const stepName = id;
1214
+ const stepId = id;
1215
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
1216
+ const hasEventListeners = onEvent;
1217
+ return (async () => {
1218
+ const startTime = hasEventListeners ? performance.now() : 0;
1219
+ if (onEvent) {
1220
+ emitEvent({
1221
+ type: "step_start",
1222
+ workflowId,
1223
+ stepId,
1224
+ stepKey,
1225
+ name: stepName,
1226
+ ts: Date.now()
1227
+ });
1228
+ }
1229
+ const result = await operation();
1230
+ if (result.ok) {
1231
+ const durationMs = performance.now() - startTime;
1232
+ emitEvent({
1233
+ type: "step_success",
1234
+ workflowId,
1235
+ stepId,
1236
+ stepKey,
1237
+ name: stepName,
1238
+ ts: Date.now(),
1239
+ durationMs
1240
+ });
1241
+ if (stepKey) {
1242
+ emitEvent({
1243
+ type: "step_complete",
1244
+ workflowId,
1245
+ stepKey,
1246
+ name: stepName,
1247
+ ts: Date.now(),
1248
+ durationMs,
1249
+ result: ok2(result.value)
1250
+ });
1251
+ }
1252
+ return result.value;
1253
+ } else {
1254
+ const mapped = mapToError(result.error);
1255
+ const durationMs = performance.now() - startTime;
1256
+ const wrappedError = wrapForStep(mapped, {
1257
+ origin: "result",
1258
+ resultCause: result.error
1259
+ });
1260
+ emitEvent({
1261
+ type: "step_error",
1262
+ workflowId,
1263
+ stepId,
1264
+ stepKey,
1265
+ name: stepName,
1266
+ ts: Date.now(),
1267
+ durationMs,
1268
+ error: wrappedError
1269
+ });
1270
+ if (stepKey) {
1271
+ emitEvent({
1272
+ type: "step_complete",
1273
+ workflowId,
1274
+ stepKey,
1275
+ name: stepName,
1276
+ ts: Date.now(),
1277
+ durationMs,
1278
+ result: err(mapped, { cause: result.error }),
1279
+ meta: { origin: "result", resultCause: result.error }
1280
+ });
1281
+ }
1282
+ onError?.(wrappedError, stepName, context);
1283
+ throw earlyExit(wrappedError, {
1284
+ origin: "result",
1285
+ resultCause: result.error
1286
+ });
1287
+ }
1288
+ })();
1289
+ };
1290
+ stepFn.fromNullable = (id, operation, onNull, options2) => {
1291
+ if (typeof id !== "string" || id.length === 0) {
1292
+ throw new Error(
1293
+ '[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))'
1294
+ );
1295
+ }
1296
+ return stepFn(
1297
+ id,
1298
+ async () => {
1299
+ const value2 = await operation();
1300
+ return value2 != null ? ok2(value2) : err(onNull());
1301
+ },
1302
+ options2
1303
+ );
1304
+ };
1305
+ stepFn.retry = (id, operation, options2) => {
1306
+ if (typeof id !== "string" || id.length === 0) {
1307
+ throw new Error(
1308
+ '[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })'
1309
+ );
1310
+ }
1311
+ return stepFn(id, operation, {
1312
+ key: options2.key ?? id,
1313
+ retry: {
1314
+ attempts: options2.attempts,
1315
+ backoff: options2.backoff,
1316
+ initialDelay: options2.initialDelay,
1317
+ maxDelay: options2.maxDelay,
1318
+ jitter: options2.jitter,
1319
+ shouldRetry: options2.shouldRetry,
1320
+ onRetry: options2.onRetry
1321
+ },
1322
+ timeout: options2.timeout
1323
+ });
1324
+ };
1325
+ stepFn.withTimeout = (id, operation, options2) => {
1326
+ if (typeof id !== "string" || id.length === 0) {
1327
+ throw new Error(
1328
+ '[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })'
1329
+ );
1330
+ }
1331
+ return stepFn(
1332
+ id,
1333
+ operation,
1334
+ {
1335
+ key: options2.key ?? id,
1336
+ timeout: options2
1337
+ }
1338
+ );
1339
+ };
1340
+ stepFn.sleep = (id, duration, options2) => {
1341
+ if (typeof id !== "string" || id.length === 0) {
1342
+ throw new Error(
1343
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
1344
+ );
1345
+ }
1346
+ const d = typeof duration === "string" ? parseDurationString(duration) : duration;
1347
+ if (!d) {
1348
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
1349
+ }
1350
+ const ms = d.millis;
1351
+ const userSignal = options2?.signal;
1352
+ return stepFn(
1353
+ id,
1354
+ async () => {
1355
+ if (_workflowSignal?.aborted || userSignal?.aborted) {
1356
+ const e = new Error("Sleep aborted");
1357
+ e.name = "AbortError";
1358
+ throw e;
1359
+ }
1360
+ return new Promise((resolve, reject) => {
1361
+ const state = { timeoutId: void 0 };
1362
+ const onAbort = () => {
1363
+ if (state.timeoutId) clearTimeout(state.timeoutId);
1364
+ const e = new Error("Sleep aborted");
1365
+ e.name = "AbortError";
1366
+ reject(e);
1367
+ };
1368
+ _workflowSignal?.addEventListener("abort", onAbort, { once: true });
1369
+ userSignal?.addEventListener("abort", onAbort, { once: true });
1370
+ state.timeoutId = setTimeout(() => {
1371
+ _workflowSignal?.removeEventListener("abort", onAbort);
1372
+ userSignal?.removeEventListener("abort", onAbort);
1373
+ resolve(ok2(void 0));
1374
+ }, ms);
1375
+ });
1376
+ },
1377
+ {
1378
+ key: options2?.key ?? id,
1379
+ description: options2?.description
1380
+ }
1381
+ );
1382
+ };
1383
+ stepFn.all = ((...args) => {
1384
+ if (typeof args[0] !== "string") {
1385
+ throw new TypeError(
1386
+ "step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })"
1387
+ );
1388
+ }
1389
+ const name = args[0];
1390
+ const second = args[1];
1391
+ if (typeof second === "function") {
1392
+ return executeParallelArray2(name, second);
1393
+ }
1394
+ if (second && typeof second === "object" && !Array.isArray(second)) {
1395
+ const rawOperations = second;
1396
+ const normalizedOperations = normalizeParallelOperations2(rawOperations);
1397
+ return executeParallelNamed2(normalizedOperations, { name });
1398
+ }
1399
+ throw new TypeError(
1400
+ "step.all(name, ...): second argument must be a function (array form) or an object of operations (object form)."
1401
+ );
1402
+ });
1403
+ stepFn.race = (name, operation) => {
1404
+ const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1405
+ return (async () => {
1406
+ const startTime = performance.now();
1407
+ let scopeEnded = false;
1408
+ const scopeEntry = { scopeId, type: "race", winnerId: void 0 };
1409
+ activeScopeStack.push(scopeEntry);
1410
+ const emitScopeEnd = () => {
1411
+ if (scopeEnded) return;
1412
+ scopeEnded = true;
1413
+ const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
1414
+ if (idx !== -1) activeScopeStack.splice(idx, 1);
1415
+ emitEvent({
1416
+ type: "scope_end",
1417
+ workflowId,
1418
+ scopeId,
1419
+ ts: Date.now(),
1420
+ durationMs: performance.now() - startTime,
1421
+ winnerId: scopeEntry.winnerId
1422
+ });
1423
+ };
1424
+ emitEvent({
1425
+ type: "scope_start",
1426
+ workflowId,
1427
+ scopeId,
1428
+ scopeType: "race",
1429
+ name,
1430
+ ts: Date.now()
1431
+ });
1432
+ try {
1433
+ const result = await operation();
1434
+ emitScopeEnd();
1435
+ if (!result.ok) {
1436
+ onError?.(result.error, name, context);
1437
+ throw earlyExit(result.error, {
1438
+ origin: "result",
1439
+ resultCause: result.cause
1440
+ });
1441
+ }
1442
+ return result.value;
1443
+ } catch (error) {
1444
+ emitScopeEnd();
1445
+ throw error;
1446
+ }
1447
+ })();
1448
+ };
1449
+ stepFn.if = (id, conditionLabel, condition) => {
1450
+ assertDeclared(id, "decision");
1451
+ const value2 = condition();
1452
+ emitEvent({
1453
+ type: "decision",
1454
+ workflowId,
1455
+ decisionId: id,
1456
+ label: conditionLabel,
1457
+ branch: value2 ? "then" : "else",
1458
+ value: value2,
1459
+ ts: Date.now()
1460
+ });
1461
+ return value2;
1462
+ };
1463
+ stepFn.label = stepFn.if;
1464
+ stepFn.branch = async (id, options2) => {
1465
+ const { condition, then: thenFn, else: elseFn } = options2;
1466
+ assertDeclared(id, "decision");
1467
+ const conditionResult = condition();
1468
+ const branch = conditionResult ? "then" : "else";
1469
+ const startTime = performance.now();
1470
+ emitEvent({
1471
+ type: "decision",
1472
+ workflowId,
1473
+ decisionId: id,
1474
+ label: options2.conditionLabel,
1475
+ branch,
1476
+ value: conditionResult,
1477
+ phase: "start",
1478
+ ts: Date.now()
1479
+ });
1480
+ const emitEnd = () => {
1481
+ emitEvent({
1482
+ type: "decision",
1483
+ workflowId,
1484
+ decisionId: id,
1485
+ label: options2.conditionLabel,
1486
+ branch,
1487
+ value: conditionResult,
1488
+ phase: "end",
1489
+ durationMs: performance.now() - startTime,
1490
+ ts: Date.now()
1491
+ });
1492
+ };
1493
+ try {
1494
+ if (conditionResult) {
1495
+ return await thenFn();
1496
+ } else if (elseFn) {
1497
+ return await elseFn();
1498
+ }
1499
+ return void 0;
1500
+ } finally {
1501
+ emitEnd();
1502
+ }
1503
+ };
1504
+ stepFn.arm = (fn2, errors) => {
1505
+ return { fn: fn2, errors };
1506
+ };
1507
+ stepFn.forEach = async (_id, items, options2) => {
1508
+ const results = [];
1509
+ const maxIterations = options2.maxIterations;
1510
+ let index = 0;
1511
+ const isRunForm = "run" in options2;
1512
+ const asyncItems = Symbol.asyncIterator in items ? items : (async function* () {
1513
+ yield* items;
1514
+ })();
1515
+ for await (const item of asyncItems) {
1516
+ if (maxIterations !== void 0 && index >= maxIterations) {
1517
+ break;
1518
+ }
1519
+ let result;
1520
+ if (isRunForm) {
1521
+ const runOptions = options2;
1522
+ result = await runOptions.run(item, index);
1523
+ } else {
1524
+ const itemOptions = options2;
1525
+ result = await itemOptions.item.handler(item, index, stepFn);
1526
+ }
1527
+ results.push(result);
1528
+ index++;
1529
+ }
1530
+ return results;
1531
+ };
1532
+ stepFn.item = (handler) => {
1533
+ return {
1534
+ __forEachItemHandler: true,
1535
+ handler
1536
+ };
1537
+ };
1538
+ stepFn.dep = (_name, fn2) => {
1539
+ return fn2;
1540
+ };
1541
+ stepFn.workflow = (id, getter, options2) => {
1542
+ return stepFn(id, getter, options2);
1543
+ };
1544
+ stepFn.map = async (id, items, mapper, options2) => {
1545
+ const concurrency = options2?.concurrency ?? items.length;
1546
+ return stepFn(
1547
+ id,
1548
+ () => {
1549
+ if (concurrency >= items.length) {
1550
+ return allAsync(items.map((item, index) => mapper(item, index)));
1551
+ } else {
1552
+ return (async () => {
1553
+ const results = [];
1554
+ for (let i = 0; i < items.length; i += concurrency) {
1555
+ const batch = items.slice(i, i + concurrency);
1556
+ const batchResult = await allAsync(
1557
+ batch.map((item, batchIndex) => mapper(item, i + batchIndex))
1558
+ );
1559
+ if (!batchResult.ok) {
1560
+ return batchResult;
1561
+ }
1562
+ results.push(...batchResult.value);
1563
+ }
1564
+ return ok2(results);
1565
+ })();
1566
+ }
1567
+ },
1568
+ { key: options2?.key }
1569
+ );
1570
+ };
1571
+ stepFn.withFallback = (id, operation, options2) => {
1572
+ if (typeof id !== "string" || id.length === 0) {
1573
+ throw new Error(
1574
+ '[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })'
1575
+ );
1576
+ }
1577
+ assertDeclared(id, "step");
1578
+ const stepKey = options2.key ?? id;
1579
+ const stepName = id;
1580
+ const stepId = generateStepId(stepKey);
1581
+ const hasEventListeners = onEvent;
1582
+ return (async () => {
1583
+ const startTime = hasEventListeners ? performance.now() : 0;
1584
+ if (onEvent) {
1585
+ emitEvent({
1586
+ type: "step_start",
1587
+ workflowId,
1588
+ stepId,
1589
+ stepKey,
1590
+ name: stepName,
1591
+ ts: Date.now()
1592
+ });
1593
+ }
1594
+ let primaryResult;
1595
+ try {
1596
+ primaryResult = await operation();
1597
+ } catch (thrown) {
1598
+ if (isEarlyExitE(thrown)) {
1599
+ emitEvent({
1600
+ type: "step_aborted",
1601
+ workflowId,
1602
+ stepId,
1603
+ stepKey,
1604
+ name: stepName,
1605
+ ts: Date.now(),
1606
+ durationMs: performance.now() - startTime
1607
+ });
1608
+ throw thrown;
1609
+ }
1610
+ let mappedError;
1611
+ try {
1612
+ mappedError = effectiveCatchUnexpected(thrown);
1613
+ } catch (mapperError) {
1614
+ throw createMapperException(mapperError);
1615
+ }
1616
+ if (options2.on !== void 0 && options2.on !== mappedError) {
1617
+ const durationMs2 = performance.now() - startTime;
1618
+ emitEvent({
1619
+ type: "step_error",
1620
+ workflowId,
1621
+ stepId,
1622
+ stepKey,
1623
+ name: stepName,
1624
+ ts: Date.now(),
1625
+ durationMs: durationMs2,
1626
+ error: mappedError
1627
+ });
1628
+ if (stepKey) {
1629
+ emitEvent({
1630
+ type: "step_complete",
1631
+ workflowId,
1632
+ stepKey,
1633
+ name: stepName,
1634
+ ts: Date.now(),
1635
+ durationMs: durationMs2,
1636
+ result: err(mappedError, { cause: thrown }),
1637
+ meta: { origin: "throw", thrown }
1638
+ });
1639
+ }
1640
+ onError?.(mappedError, stepName, context);
1641
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1642
+ }
1643
+ let fallbackResultFromThrow;
1644
+ try {
1645
+ fallbackResultFromThrow = await options2.fallback();
1646
+ } catch (fallbackThrown) {
1647
+ if (isEarlyExitE(fallbackThrown)) {
1648
+ emitEvent({
1649
+ type: "step_aborted",
1650
+ workflowId,
1651
+ stepId,
1652
+ stepKey,
1653
+ name: stepName,
1654
+ ts: Date.now(),
1655
+ durationMs: performance.now() - startTime
1656
+ });
1657
+ throw fallbackThrown;
1658
+ }
1659
+ let fallbackMappedError;
1660
+ try {
1661
+ fallbackMappedError = effectiveCatchUnexpected(fallbackThrown);
1662
+ } catch (mapperError) {
1663
+ throw createMapperException(mapperError);
1664
+ }
1665
+ const durationMs2 = performance.now() - startTime;
1666
+ emitEvent({
1667
+ type: "step_error",
1668
+ workflowId,
1669
+ stepId,
1670
+ stepKey,
1671
+ name: stepName,
1672
+ ts: Date.now(),
1673
+ durationMs: durationMs2,
1674
+ error: fallbackMappedError
1675
+ });
1676
+ if (stepKey) {
1677
+ emitEvent({
1678
+ type: "step_complete",
1679
+ workflowId,
1680
+ stepKey,
1681
+ name: stepName,
1682
+ ts: Date.now(),
1683
+ durationMs: durationMs2,
1684
+ result: err(fallbackMappedError, { cause: fallbackThrown }),
1685
+ meta: { origin: "throw", thrown: fallbackThrown }
1686
+ });
1687
+ }
1688
+ onError?.(fallbackMappedError, stepName, context);
1689
+ throw earlyExit(fallbackMappedError, { origin: "throw", thrown: fallbackThrown });
1690
+ }
1691
+ if (fallbackResultFromThrow.ok) {
1692
+ const durationMs2 = performance.now() - startTime;
1693
+ emitEvent({
1694
+ type: "step_success",
1695
+ workflowId,
1696
+ stepId,
1697
+ stepKey,
1698
+ name: stepName,
1699
+ ts: Date.now(),
1700
+ durationMs: durationMs2
1701
+ });
1702
+ if (stepKey) {
1703
+ emitEvent({
1704
+ type: "step_complete",
1705
+ workflowId,
1706
+ stepKey,
1707
+ name: stepName,
1708
+ ts: Date.now(),
1709
+ durationMs: durationMs2,
1710
+ result: fallbackResultFromThrow,
1711
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(mappedError) }
1712
+ });
1713
+ }
1714
+ return fallbackResultFromThrow.value;
1715
+ } else {
1716
+ const durationMs2 = performance.now() - startTime;
1717
+ const wrappedError2 = wrapForStep(fallbackResultFromThrow.error, {
1718
+ origin: "result",
1719
+ resultCause: fallbackResultFromThrow.cause
1720
+ });
1721
+ emitEvent({
1722
+ type: "step_error",
1723
+ workflowId,
1724
+ stepId,
1725
+ stepKey,
1726
+ name: stepName,
1727
+ ts: Date.now(),
1728
+ durationMs: durationMs2,
1729
+ error: wrappedError2
1730
+ });
1731
+ if (stepKey) {
1732
+ emitEvent({
1733
+ type: "step_complete",
1734
+ workflowId,
1735
+ stepKey,
1736
+ name: stepName,
1737
+ ts: Date.now(),
1738
+ durationMs: durationMs2,
1739
+ result: fallbackResultFromThrow,
1740
+ meta: { origin: "result", resultCause: fallbackResultFromThrow.cause }
1741
+ });
1742
+ }
1743
+ onError?.(wrappedError2, stepName, context);
1744
+ throw earlyExit(wrappedError2, {
1745
+ origin: "result",
1746
+ resultCause: fallbackResultFromThrow.cause
1747
+ });
1748
+ }
1749
+ }
1750
+ if (primaryResult.ok) {
1751
+ const durationMs2 = performance.now() - startTime;
1752
+ emitEvent({
1753
+ type: "step_success",
1754
+ workflowId,
1755
+ stepId,
1756
+ stepKey,
1757
+ name: stepName,
1758
+ ts: Date.now(),
1759
+ durationMs: durationMs2
1760
+ });
1761
+ if (stepKey) {
1762
+ emitEvent({
1763
+ type: "step_complete",
1764
+ workflowId,
1765
+ stepKey,
1766
+ name: stepName,
1767
+ ts: Date.now(),
1768
+ durationMs: durationMs2,
1769
+ result: primaryResult
1770
+ });
1771
+ }
1772
+ return primaryResult.value;
1773
+ }
1774
+ const primaryError = primaryResult.error;
1775
+ if (options2.on !== void 0 && options2.on !== primaryError) {
1776
+ const durationMs2 = performance.now() - startTime;
1777
+ const wrappedError2 = wrapForStep(primaryError, {
1778
+ origin: "result",
1779
+ resultCause: primaryResult.cause
1780
+ });
1781
+ emitEvent({
1782
+ type: "step_error",
1783
+ workflowId,
1784
+ stepId,
1785
+ stepKey,
1786
+ name: stepName,
1787
+ ts: Date.now(),
1788
+ durationMs: durationMs2,
1789
+ error: wrappedError2
1790
+ });
1791
+ if (stepKey) {
1792
+ emitEvent({
1793
+ type: "step_complete",
1794
+ workflowId,
1795
+ stepKey,
1796
+ name: stepName,
1797
+ ts: Date.now(),
1798
+ durationMs: durationMs2,
1799
+ result: primaryResult,
1800
+ meta: { origin: "result", resultCause: primaryResult.cause }
1801
+ });
1802
+ }
1803
+ onError?.(wrappedError2, stepName, context);
1804
+ throw earlyExit(wrappedError2, {
1805
+ origin: "result",
1806
+ resultCause: primaryResult.cause
1807
+ });
1808
+ }
1809
+ let fallbackResult;
1810
+ try {
1811
+ fallbackResult = await options2.fallback();
1812
+ } catch (thrown) {
1813
+ if (isEarlyExitE(thrown)) {
1814
+ emitEvent({
1815
+ type: "step_aborted",
1816
+ workflowId,
1817
+ stepId,
1818
+ stepKey,
1819
+ name: stepName,
1820
+ ts: Date.now(),
1821
+ durationMs: performance.now() - startTime
1822
+ });
1823
+ throw thrown;
1824
+ }
1825
+ let mappedError;
1826
+ try {
1827
+ mappedError = effectiveCatchUnexpected(thrown);
1828
+ } catch (mapperError) {
1829
+ throw createMapperException(mapperError);
1830
+ }
1831
+ const durationMs2 = performance.now() - startTime;
1832
+ emitEvent({
1833
+ type: "step_error",
1834
+ workflowId,
1835
+ stepId,
1836
+ stepKey,
1837
+ name: stepName,
1838
+ ts: Date.now(),
1839
+ durationMs: durationMs2,
1840
+ error: mappedError
1841
+ });
1842
+ if (stepKey) {
1843
+ emitEvent({
1844
+ type: "step_complete",
1845
+ workflowId,
1846
+ stepKey,
1847
+ name: stepName,
1848
+ ts: Date.now(),
1849
+ durationMs: durationMs2,
1850
+ result: err(mappedError, { cause: thrown }),
1851
+ meta: { origin: "throw", thrown }
1852
+ });
1853
+ }
1854
+ onError?.(mappedError, stepName, context);
1855
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1856
+ }
1857
+ if (fallbackResult.ok) {
1858
+ const durationMs2 = performance.now() - startTime;
1859
+ emitEvent({
1860
+ type: "step_success",
1861
+ workflowId,
1862
+ stepId,
1863
+ stepKey,
1864
+ name: stepName,
1865
+ ts: Date.now(),
1866
+ durationMs: durationMs2
1867
+ });
1868
+ if (stepKey) {
1869
+ emitEvent({
1870
+ type: "step_complete",
1871
+ workflowId,
1872
+ stepKey,
1873
+ name: stepName,
1874
+ ts: Date.now(),
1875
+ durationMs: durationMs2,
1876
+ result: fallbackResult,
1877
+ meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(primaryError) }
1878
+ });
1879
+ }
1880
+ return fallbackResult.value;
1881
+ }
1882
+ const durationMs = performance.now() - startTime;
1883
+ const wrappedError = wrapForStep(fallbackResult.error, {
1884
+ origin: "result",
1885
+ resultCause: fallbackResult.cause
1886
+ });
1887
+ emitEvent({
1888
+ type: "step_error",
1889
+ workflowId,
1890
+ stepId,
1891
+ stepKey,
1892
+ name: stepName,
1893
+ ts: Date.now(),
1894
+ durationMs,
1895
+ error: wrappedError
1896
+ });
1897
+ if (stepKey) {
1898
+ emitEvent({
1899
+ type: "step_complete",
1900
+ workflowId,
1901
+ stepKey,
1902
+ name: stepName,
1903
+ ts: Date.now(),
1904
+ durationMs,
1905
+ result: fallbackResult,
1906
+ meta: { origin: "result", resultCause: fallbackResult.cause }
1907
+ });
1908
+ }
1909
+ onError?.(wrappedError, stepName, context);
1910
+ throw earlyExit(wrappedError, {
1911
+ origin: "result",
1912
+ resultCause: fallbackResult.cause
1913
+ });
1914
+ })();
1915
+ };
1916
+ stepFn.withResource = (id, options2) => {
1917
+ if (typeof id !== "string" || id.length === 0) {
1918
+ throw new Error(
1919
+ '[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })'
1920
+ );
1921
+ }
1922
+ assertDeclared(id, "step");
1923
+ const stepKey = id;
1924
+ const stepName = id;
1925
+ const stepId = generateStepId(stepKey);
1926
+ const hasEventListeners = onEvent;
1927
+ return (async () => {
1928
+ const startTime = hasEventListeners ? performance.now() : 0;
1929
+ if (onEvent) {
1930
+ emitEvent({
1931
+ type: "step_start",
1932
+ workflowId,
1933
+ stepId,
1934
+ stepKey,
1935
+ name: stepName,
1936
+ ts: Date.now()
1937
+ });
1938
+ }
1939
+ let acquireResult;
1940
+ try {
1941
+ acquireResult = await options2.acquire();
1942
+ } catch (thrown) {
1943
+ if (isEarlyExitE(thrown)) {
1944
+ emitEvent({
1945
+ type: "step_aborted",
1946
+ workflowId,
1947
+ stepId,
1948
+ stepKey,
1949
+ name: stepName,
1950
+ ts: Date.now(),
1951
+ durationMs: performance.now() - startTime
1952
+ });
1953
+ throw thrown;
1954
+ }
1955
+ let mappedError;
1956
+ try {
1957
+ mappedError = effectiveCatchUnexpected(thrown);
1958
+ } catch (mapperError) {
1959
+ throw createMapperException(mapperError);
1960
+ }
1961
+ const durationMs2 = performance.now() - startTime;
1962
+ emitEvent({
1963
+ type: "step_error",
1964
+ workflowId,
1965
+ stepId,
1966
+ stepKey,
1967
+ name: stepName,
1968
+ ts: Date.now(),
1969
+ durationMs: durationMs2,
1970
+ error: mappedError
1971
+ });
1972
+ if (stepKey) {
1973
+ emitEvent({
1974
+ type: "step_complete",
1975
+ workflowId,
1976
+ stepKey,
1977
+ name: stepName,
1978
+ ts: Date.now(),
1979
+ durationMs: durationMs2,
1980
+ result: err(mappedError, { cause: thrown }),
1981
+ meta: { origin: "throw", thrown }
1982
+ });
1983
+ }
1984
+ onError?.(mappedError, stepName, context);
1985
+ throw earlyExit(mappedError, { origin: "throw", thrown });
1986
+ }
1987
+ if (!acquireResult.ok) {
1988
+ const durationMs2 = performance.now() - startTime;
1989
+ const wrappedError2 = wrapForStep(acquireResult.error, {
1990
+ origin: "result",
1991
+ resultCause: acquireResult.cause
1992
+ });
1993
+ emitEvent({
1994
+ type: "step_error",
1995
+ workflowId,
1996
+ stepId,
1997
+ stepKey,
1998
+ name: stepName,
1999
+ ts: Date.now(),
2000
+ durationMs: durationMs2,
2001
+ error: wrappedError2
2002
+ });
2003
+ if (stepKey) {
2004
+ emitEvent({
2005
+ type: "step_complete",
2006
+ workflowId,
2007
+ stepKey,
2008
+ name: stepName,
2009
+ ts: Date.now(),
2010
+ durationMs: durationMs2,
2011
+ result: acquireResult,
2012
+ meta: { origin: "result", resultCause: acquireResult.cause }
2013
+ });
2014
+ }
2015
+ onError?.(wrappedError2, stepName, context);
2016
+ throw earlyExit(wrappedError2, {
2017
+ origin: "result",
2018
+ resultCause: acquireResult.cause
2019
+ });
2020
+ }
2021
+ const resource = acquireResult.value;
2022
+ let useResult;
2023
+ let useThrown;
2024
+ let useThrewNonResult = false;
2025
+ try {
2026
+ useResult = await options2.use(resource);
2027
+ } catch (thrown) {
2028
+ if (isEarlyExitE(thrown)) {
2029
+ try {
2030
+ await options2.release(resource);
2031
+ } catch (releaseErr) {
2032
+ console.warn(
2033
+ `[awaitly] step.withResource("${id}"): release threw after earlyExit:`,
2034
+ releaseErr
2035
+ );
2036
+ }
2037
+ throw thrown;
2038
+ }
2039
+ useThrown = thrown;
2040
+ useThrewNonResult = true;
2041
+ }
2042
+ try {
2043
+ await options2.release(resource);
2044
+ } catch (releaseErr) {
2045
+ console.warn(
2046
+ `[awaitly] step.withResource("${id}"): release threw:`,
2047
+ releaseErr
2048
+ );
2049
+ }
2050
+ if (useThrewNonResult) {
2051
+ let mappedError;
2052
+ try {
2053
+ mappedError = effectiveCatchUnexpected(useThrown);
2054
+ } catch (mapperError) {
2055
+ throw createMapperException(mapperError);
2056
+ }
2057
+ const durationMs2 = performance.now() - startTime;
2058
+ emitEvent({
2059
+ type: "step_error",
2060
+ workflowId,
2061
+ stepId,
2062
+ stepKey,
2063
+ name: stepName,
2064
+ ts: Date.now(),
2065
+ durationMs: durationMs2,
2066
+ error: mappedError
2067
+ });
2068
+ if (stepKey) {
2069
+ emitEvent({
2070
+ type: "step_complete",
2071
+ workflowId,
2072
+ stepKey,
2073
+ name: stepName,
2074
+ ts: Date.now(),
2075
+ durationMs: durationMs2,
2076
+ result: err(mappedError, { cause: useThrown }),
2077
+ meta: { origin: "throw", thrown: useThrown }
2078
+ });
2079
+ }
2080
+ onError?.(mappedError, stepName, context);
2081
+ throw earlyExit(mappedError, { origin: "throw", thrown: useThrown });
2082
+ }
2083
+ const result = useResult;
2084
+ if (result.ok) {
2085
+ const durationMs2 = performance.now() - startTime;
2086
+ emitEvent({
2087
+ type: "step_success",
2088
+ workflowId,
2089
+ stepId,
2090
+ stepKey,
2091
+ name: stepName,
2092
+ ts: Date.now(),
2093
+ durationMs: durationMs2
2094
+ });
2095
+ if (stepKey) {
2096
+ emitEvent({
2097
+ type: "step_complete",
2098
+ workflowId,
2099
+ stepKey,
2100
+ name: stepName,
2101
+ ts: Date.now(),
2102
+ durationMs: durationMs2,
2103
+ result
2104
+ });
2105
+ }
2106
+ return result.value;
2107
+ }
2108
+ const durationMs = performance.now() - startTime;
2109
+ const wrappedError = wrapForStep(result.error, {
2110
+ origin: "result",
2111
+ resultCause: result.cause
2112
+ });
2113
+ emitEvent({
2114
+ type: "step_error",
2115
+ workflowId,
2116
+ stepId,
2117
+ stepKey,
2118
+ name: stepName,
2119
+ ts: Date.now(),
2120
+ durationMs,
2121
+ error: wrappedError
2122
+ });
2123
+ if (stepKey) {
2124
+ emitEvent({
2125
+ type: "step_complete",
2126
+ workflowId,
2127
+ stepKey,
2128
+ name: stepName,
2129
+ ts: Date.now(),
2130
+ durationMs,
2131
+ result,
2132
+ meta: { origin: "result", resultCause: result.cause }
2133
+ });
2134
+ }
2135
+ onError?.(wrappedError, stepName, context);
2136
+ throw earlyExit(wrappedError, {
2137
+ origin: "result",
2138
+ resultCause: result.cause
2139
+ });
2140
+ })();
2141
+ };
2142
+ const step = stepFn;
2143
+ const value = await fn({ step });
2144
+ if (process.env.NODE_ENV !== "production" && value !== null && typeof value === "object" && "ok" in value && typeof value.ok === "boolean") {
2145
+ const maybeResult = value;
2146
+ if (maybeResult.ok === true && "value" in maybeResult || maybeResult.ok === false && "error" in maybeResult) {
2147
+ console.warn(
2148
+ `awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
2149
+
2150
+ Incorrect: return ok({ data });
2151
+ Correct: return { data };
2152
+
2153
+ See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
2154
+ );
2155
+ }
2156
+ }
2157
+ return ok2(value);
2158
+ } catch (error) {
2159
+ if (isMapperException(error)) {
2160
+ throw error.thrown;
2161
+ }
2162
+ if (isEarlyExitE(error)) {
2163
+ const originalCause = error.meta.origin === "throw" ? error.meta.thrown : error.meta.origin === "result" ? error.meta.resultCause : void 0;
2164
+ return err(error.error, { cause: originalCause });
2165
+ }
2166
+ const mapped = effectiveCatchUnexpected(error);
2167
+ onError?.(mapped, "unexpected", context);
2168
+ return err(mapped, { cause: error });
2169
+ }
2170
+ }
2171
+ var runStrict = (fn, options) => {
2172
+ return runFn(fn, options);
2173
+ };
2174
+ var run = /* @__PURE__ */ Object.assign(runFn, { strict: runStrict });
2175
+ async function allAsync(results) {
2176
+ if (results.length === 0) {
2177
+ return ok2([]);
2178
+ }
2179
+ return new Promise((resolve) => {
2180
+ let settled = false;
2181
+ let pendingCount = results.length;
2182
+ const values = new Array(results.length);
2183
+ for (let i = 0; i < results.length; i++) {
2184
+ const index = i;
2185
+ Promise.resolve(results[index]).catch((reason) => err(
2186
+ { type: "PROMISE_REJECTED", cause: reason },
2187
+ { cause: { type: "PROMISE_REJECTION", reason } }
2188
+ )).then((result) => {
2189
+ if (settled) return;
2190
+ if (!result.ok) {
2191
+ settled = true;
2192
+ resolve(result);
2193
+ return;
2194
+ }
2195
+ values[index] = result.value;
2196
+ pendingCount--;
2197
+ if (pendingCount === 0) {
2198
+ resolve(ok2(values));
2199
+ }
2200
+ });
2201
+ }
2202
+ });
2203
+ }
2204
+
2205
+ // src/streaming/types.ts
2206
+ var STREAM_WRITE_ERROR = "STREAM_WRITE_ERROR";
2207
+ var STREAM_READ_ERROR = "STREAM_READ_ERROR";
2208
+ var STREAM_CLOSE_ERROR = "STREAM_CLOSE_ERROR";
2209
+ var STREAM_ENDED = "STREAM_ENDED";
2210
+ function streamWriteError(reason, message, cause) {
2211
+ return {
2212
+ type: STREAM_WRITE_ERROR,
2213
+ reason,
2214
+ message,
2215
+ ...cause !== void 0 ? { cause } : {}
2216
+ };
2217
+ }
2218
+ function streamReadError(reason, message, cause) {
2219
+ return {
2220
+ type: STREAM_READ_ERROR,
2221
+ reason,
2222
+ message,
2223
+ ...cause !== void 0 ? { cause } : {}
2224
+ };
2225
+ }
2226
+ function streamCloseError(reason, message, cause) {
2227
+ return {
2228
+ type: STREAM_CLOSE_ERROR,
2229
+ reason,
2230
+ message,
2231
+ ...cause !== void 0 ? { cause } : {}
2232
+ };
2233
+ }
2234
+ function streamEnded(finalPosition) {
2235
+ return {
2236
+ type: STREAM_ENDED,
2237
+ finalPosition
2238
+ };
2239
+ }
2240
+
2241
+ // src/streaming/backpressure.ts
2242
+ function createBackpressureController(options = {}) {
2243
+ const highWaterMark = options.highWaterMark ?? 16;
2244
+ const lowWaterMark = options.lowWaterMark ?? Math.floor(highWaterMark / 2);
2245
+ const onStateChange = options.onStateChange;
2246
+ let state = "flowing";
2247
+ let bufferedCount = 0;
2248
+ let drainResolvers = [];
2249
+ function updateState(newState) {
2250
+ if (state !== newState) {
2251
+ state = newState;
2252
+ onStateChange?.(newState);
2253
+ if (newState === "flowing" && drainResolvers.length > 0) {
2254
+ const resolvers = drainResolvers;
2255
+ drainResolvers = [];
2256
+ for (const resolve of resolvers) {
2257
+ resolve();
2258
+ }
2259
+ }
2260
+ }
2261
+ }
2262
+ function checkState() {
2263
+ if (state === "flowing" && bufferedCount >= highWaterMark) {
2264
+ updateState("paused");
2265
+ } else if (state === "paused" && bufferedCount <= lowWaterMark) {
2266
+ updateState("flowing");
2267
+ }
2268
+ }
2269
+ return {
2270
+ get state() {
2271
+ return state;
2272
+ },
2273
+ get bufferedCount() {
2274
+ return bufferedCount;
2275
+ },
2276
+ get highWaterMark() {
2277
+ return highWaterMark;
2278
+ },
2279
+ get lowWaterMark() {
2280
+ return lowWaterMark;
2281
+ },
2282
+ increment() {
2283
+ bufferedCount++;
2284
+ checkState();
2285
+ },
2286
+ decrement() {
2287
+ if (bufferedCount > 0) {
2288
+ bufferedCount--;
2289
+ checkState();
2290
+ }
2291
+ },
2292
+ setCount(count) {
2293
+ bufferedCount = Math.max(0, count);
2294
+ checkState();
2295
+ },
2296
+ waitForDrain() {
2297
+ if (state === "flowing") {
2298
+ return Promise.resolve();
2299
+ }
2300
+ return new Promise((resolve) => {
2301
+ drainResolvers.push(resolve);
2302
+ });
2303
+ },
2304
+ reset() {
2305
+ bufferedCount = 0;
2306
+ drainResolvers = [];
2307
+ updateState("flowing");
2308
+ }
2309
+ };
2310
+ }
2311
+
2312
+ // src/workflow/guards.ts
2313
+ function isStepComplete(event) {
2314
+ return event.type === "step_complete";
2315
+ }
2316
+ function isWorkflowCancelled(error) {
2317
+ return typeof error === "object" && error !== null && error.type === "WORKFLOW_CANCELLED";
2318
+ }
2319
+
2320
+ // src/workflow/resume-state.ts
2321
+ function createResumeStateCollector() {
2322
+ const steps = /* @__PURE__ */ new Map();
2323
+ return {
2324
+ handleEvent: (event) => {
2325
+ if (isStepComplete(event)) {
2326
+ steps.set(event.stepKey, { result: event.result, meta: event.meta });
2327
+ }
2328
+ },
2329
+ getResumeState: () => ({ steps: new Map(steps) }),
2330
+ clear: () => steps.clear()
2331
+ };
2332
+ }
2333
+
2334
+ // src/workflow/cache-encoding.ts
2335
+ function isCachedErrorCause(cause) {
2336
+ return typeof cause === "object" && cause !== null && cause.__cachedMeta === true;
2337
+ }
2338
+ function encodeCachedError(error, meta, originalCause) {
2339
+ return err(error, {
2340
+ cause: { __cachedMeta: true, originalCause, meta }
2341
+ });
2342
+ }
2343
+ function decodeCachedMeta(cause) {
2344
+ if (isCachedErrorCause(cause)) {
2345
+ return cause.meta;
2346
+ }
2347
+ return { origin: "result", resultCause: cause };
2348
+ }
2349
+
2350
+ // src/workflow/validation.ts
2351
+ async function validateInput(schema, input) {
2352
+ const result = schema["~standard"].validate(input);
2353
+ const resolved = result instanceof Promise ? await result : result;
2354
+ if (resolved.issues) {
2355
+ return err({
2356
+ type: "INPUT_VALIDATION_ERROR",
2357
+ issues: resolved.issues.map((i) => ({
2358
+ message: i.message,
2359
+ path: i.path?.map(
2360
+ (p) => typeof p === "object" ? p.key : p
2361
+ )
2362
+ })),
2363
+ message: `Input validation failed: ${resolved.issues.map((i) => i.message).join(", ")}`
2364
+ });
2365
+ }
2366
+ return ok2(resolved.value);
2367
+ }
2368
+
2369
+ // src/di.ts
2370
+ function withDeps(workflow, overrides) {
2371
+ const forward = (method) => ((...args) => {
2372
+ const last = args.at(-1);
2373
+ const hasConfig = args.length > 0 && typeof last === "object" && last !== null && !Array.isArray(last) && typeof last !== "function";
2374
+ const config = hasConfig ? last : void 0;
2375
+ const head = hasConfig ? args.slice(0, -1) : args;
2376
+ const mergedDeps = { ...overrides, ...config?.deps ?? {} };
2377
+ const mergedConfig = config ? { ...config, deps: mergedDeps } : { deps: mergedDeps };
2378
+ return workflow[method](...head, mergedConfig);
2379
+ });
2380
+ return {
2381
+ run: forward("run"),
2382
+ runWithState: forward("runWithState"),
2383
+ withDeps(nextOverrides) {
2384
+ return withDeps(workflow, { ...overrides, ...nextOverrides });
2385
+ }
2386
+ };
2387
+ }
2388
+
2389
+ // src/persistence.ts
2390
+ var SnapshotDecodeError = class extends Error {
2391
+ constructor(message, stepId, originalError) {
2392
+ super(message);
2393
+ this.stepId = stepId;
2394
+ this.originalError = originalError;
2395
+ this.name = "SnapshotDecodeError";
2396
+ }
2397
+ stepId;
2398
+ originalError;
2399
+ };
2400
+ function deserializeCauseNew(serialized) {
2401
+ if (serialized.type === "error") {
2402
+ const error = new Error(serialized.message);
2403
+ error.name = serialized.name;
2404
+ if (serialized.stack) {
2405
+ error.stack = serialized.stack;
2406
+ }
2407
+ if (serialized.cause) {
2408
+ error.cause = deserializeCauseNew(serialized.cause);
2409
+ }
2410
+ return error;
2411
+ }
2412
+ return serialized.value !== void 0 ? serialized.value : serialized.stringRepresentation;
2413
+ }
2414
+
2415
+ // src/workflow/execute.ts
2416
+ function createWorkflow(workflowName, deps, options) {
2417
+ if (typeof workflowName !== "string" || workflowName.length === 0) {
2418
+ throw new TypeError(
2419
+ "createWorkflow(workflowName, deps, options?): first argument must be a non-empty string. Example: createWorkflow('checkout', { chargeCard, sendEmail })"
2420
+ );
2421
+ }
2422
+ const depsActual = deps ?? {};
2423
+ const optionsActual = options;
2424
+ async function internalExecute(runName, userFn, config) {
2425
+ const workflowId = runName ?? crypto.randomUUID();
2426
+ const effectiveDeps = config?.deps ? { ...depsActual, ...config.deps } : depsActual;
2427
+ const compensations = [];
2428
+ const createContextFn = config?.createContext ?? optionsActual?.createContext;
2429
+ const context = createContextFn ? await createContextFn() : void 0;
2430
+ const workflowSignal = config?.signal ?? optionsActual?.signal;
2431
+ const onEventHandler = config?.onEvent ?? optionsActual?.onEvent;
2432
+ const onErrorHandler = config?.onError ?? optionsActual?.onError;
2433
+ const shouldRunHook = config?.shouldRun ?? optionsActual?.shouldRun;
2434
+ const onBeforeStartHook = config?.onBeforeStart ?? optionsActual?.onBeforeStart;
2435
+ const onAfterStepHook = config?.onAfterStep ?? optionsActual?.onAfterStep;
2436
+ const resumeStateOption = config?.resumeState ?? optionsActual?.resumeState;
2437
+ const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
2438
+ const declaredGraph = config?.graph ?? optionsActual?.graph;
2439
+ const workflowData = {};
2440
+ const devWarnings = (config?.devWarnings ?? optionsActual?.devWarnings) === true && process.env.NODE_ENV !== "production";
2441
+ const ctxSetWarned = /* @__PURE__ */ new Set();
2442
+ const ctxGetWarned = /* @__PURE__ */ new Set();
2443
+ const workflowContext = {
2444
+ workflowId,
2445
+ onEvent: onEventHandler,
2446
+ context: context !== void 0 ? context : void 0,
2447
+ signal: workflowSignal,
2448
+ // Data store for static analysis
2449
+ input: {},
2450
+ ref: (key) => workflowData[key],
2451
+ set: (key, value) => {
2452
+ if (devWarnings && !ctxSetWarned.has(key)) {
2453
+ ctxSetWarned.add(key);
2454
+ console.warn(
2455
+ `awaitly: ctx.set('${key}', ...) is deprecated for static analysis. Use step('id', fn, { out: '${key}' }) instead.`
2456
+ );
2457
+ }
2458
+ workflowData[key] = value;
2459
+ },
2460
+ get: (key) => {
2461
+ if (devWarnings && !ctxGetWarned.has(key)) {
2462
+ ctxGetWarned.add(key);
2463
+ console.warn(
2464
+ `awaitly: ctx.get('${key}') is deprecated for static analysis. Use ctx.ref('${key}') instead for tracked dependencies.`
2465
+ );
2466
+ }
2467
+ return workflowData[key];
2468
+ }
2469
+ };
2470
+ const emitEvent = (event) => {
2471
+ const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
2472
+ const eventWithName = eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
2473
+ onEventHandler?.(eventWithName, context);
2474
+ };
2475
+ const createCancelledResult = (reason, lastStepKey2) => {
2476
+ const cancelledError = {
2477
+ type: "WORKFLOW_CANCELLED",
2478
+ reason,
2479
+ lastStepKey: lastStepKey2
2480
+ };
2481
+ return err(catchUnexpected(cancelledError), { cause: cancelledError });
2482
+ };
2483
+ if (workflowSignal?.aborted) {
2484
+ const reason = typeof workflowSignal.reason === "string" ? workflowSignal.reason : workflowSignal.reason instanceof Error ? workflowSignal.reason.message : void 0;
2485
+ emitEvent({
2486
+ type: "workflow_cancelled",
2487
+ workflowId,
2488
+ ts: Date.now(),
2489
+ durationMs: 0,
2490
+ reason
2491
+ });
2492
+ return createCancelledResult(reason);
2493
+ }
2494
+ if (shouldRunHook) {
2495
+ const hookStartTime = performance.now();
2496
+ try {
2497
+ const shouldRunResult = await shouldRunHook(workflowId, context);
2498
+ const hookDuration = performance.now() - hookStartTime;
2499
+ emitEvent({
2500
+ type: "hook_should_run",
2501
+ workflowId,
2502
+ ts: Date.now(),
2503
+ durationMs: hookDuration,
2504
+ result: shouldRunResult,
2505
+ skipped: !shouldRunResult
2506
+ });
2507
+ if (!shouldRunResult) {
2508
+ const skipCause = new Error("Workflow skipped by shouldRun hook");
2509
+ return err(catchUnexpected(skipCause), { cause: skipCause });
2510
+ }
2511
+ } catch (thrown) {
2512
+ const hookDuration = performance.now() - hookStartTime;
2513
+ emitEvent({
2514
+ type: "hook_should_run_error",
2515
+ workflowId,
2516
+ ts: Date.now(),
2517
+ durationMs: hookDuration,
2518
+ error: thrown
2519
+ });
2520
+ return err(catchUnexpected(thrown), { cause: thrown });
2521
+ }
2522
+ }
2523
+ if (onBeforeStartHook) {
2524
+ const hookStartTime = performance.now();
2525
+ try {
2526
+ const beforeStartResult = await onBeforeStartHook(workflowId, context);
2527
+ const hookDuration = performance.now() - hookStartTime;
2528
+ emitEvent({
2529
+ type: "hook_before_start",
2530
+ workflowId,
2531
+ ts: Date.now(),
2532
+ durationMs: hookDuration,
2533
+ result: beforeStartResult,
2534
+ skipped: !beforeStartResult
2535
+ });
2536
+ if (!beforeStartResult) {
2537
+ const skipCause = new Error("Workflow skipped by onBeforeStart hook");
2538
+ return err(catchUnexpected(skipCause), { cause: skipCause });
2539
+ }
2540
+ } catch (thrown) {
2541
+ const hookDuration = performance.now() - hookStartTime;
2542
+ emitEvent({
2543
+ type: "hook_before_start_error",
2544
+ workflowId,
2545
+ ts: Date.now(),
2546
+ durationMs: hookDuration,
2547
+ error: thrown
2548
+ });
2549
+ return err(catchUnexpected(thrown), { cause: thrown });
2550
+ }
2551
+ }
2552
+ const inputSchema = optionsActual?.inputSchema;
2553
+ const inputValue = optionsActual?.input;
2554
+ if (inputSchema) {
2555
+ const validationResult = await validateInput(inputSchema, inputValue);
2556
+ if (!validationResult.ok) {
2557
+ return err(validationResult.error);
2558
+ }
2559
+ workflowContext.input = validationResult.value;
2560
+ } else if (inputValue !== void 0) {
2561
+ workflowContext.input = inputValue;
2562
+ }
2563
+ const startTs = Date.now();
2564
+ const startTime = performance.now();
2565
+ emitEvent({
2566
+ type: "workflow_start",
2567
+ workflowId,
2568
+ ts: startTs
2569
+ });
2570
+ let cache = config?.cache ?? optionsActual?.cache;
2571
+ const streamStore = config?.streamStore ?? optionsActual?.streamStore;
2572
+ if (resumeStateOption && !cache) {
2573
+ cache = /* @__PURE__ */ new Map();
2574
+ }
2575
+ if (resumeStateOption && cache) {
2576
+ const resumeState = typeof resumeStateOption === "function" ? await resumeStateOption() : resumeStateOption;
2577
+ if (!(resumeState.steps instanceof Map)) {
2578
+ console.warn(
2579
+ `awaitly: resumeState.steps is not a Map (got ${typeof resumeState.steps}). This usually happens when state is serialized with JSON.stringify() directly.
2580
+ Use serializeResumeState() and deserializeResumeState() from 'awaitly/workflow' instead:
2581
+ import { serializeResumeState, deserializeResumeState } from 'awaitly/workflow';
2582
+ const json = JSON.stringify(serializeResumeState(state)); // Save this
2583
+ const restored = deserializeResumeState(JSON.parse(json)); // Load this`
2584
+ );
2585
+ if (typeof resumeState.steps === "object" && resumeState.steps !== null) {
2586
+ resumeState.steps = new Map(Object.entries(resumeState.steps));
2587
+ }
2588
+ }
2589
+ for (const [key, entry] of resumeState.steps) {
2590
+ const { result: result2, meta } = entry;
2591
+ if (result2.ok) {
2592
+ cache.set(key, result2);
2593
+ } else {
2594
+ const effectiveMeta = meta ?? { origin: "result", resultCause: result2.cause };
2595
+ cache.set(key, encodeCachedError(result2.error, effectiveMeta, result2.cause));
2596
+ }
2597
+ }
2598
+ }
2599
+ const snapshotOption = config?.snapshot ?? optionsActual?.snapshot;
2600
+ const snapshotSerialization = optionsActual?.serialization;
2601
+ if (snapshotOption && !resumeStateOption) {
2602
+ if (!cache) {
2603
+ cache = /* @__PURE__ */ new Map();
2604
+ }
2605
+ const snapshot = snapshotOption;
2606
+ const decode = snapshotSerialization?.decode;
2607
+ for (const [stepId, stepResult] of Object.entries(snapshot.steps)) {
2608
+ if (!Object.prototype.hasOwnProperty.call(snapshot.steps, stepId)) {
2609
+ continue;
2610
+ }
2611
+ try {
2612
+ if (stepResult.ok) {
2613
+ const value = decode ? decode(stepResult.value) : stepResult.value;
2614
+ cache.set(stepId, ok2(value));
2615
+ } else {
2616
+ const errorValue = decode ? decode(stepResult.error) : stepResult.error;
2617
+ const deserializedCause = deserializeCauseNew(stepResult.cause);
2618
+ const meta = stepResult.meta?.origin === "throw" ? { origin: "throw", thrown: deserializedCause } : { origin: "result", resultCause: deserializedCause };
2619
+ cache.set(stepId, encodeCachedError(errorValue, meta, deserializedCause));
2620
+ }
2621
+ } catch (e) {
2622
+ throw new SnapshotDecodeError(
2623
+ `Failed to decode step "${stepId}": ${e instanceof Error ? e.message : String(e)}`,
2624
+ stepId,
2625
+ e instanceof Error ? e : void 0
2626
+ );
2627
+ }
2628
+ }
2629
+ }
2630
+ let abortedDuringExecution = false;
2631
+ let abortReason;
2632
+ let lastStepKey;
2633
+ const abortHandler = () => {
2634
+ abortedDuringExecution = true;
2635
+ abortReason = typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0;
2636
+ };
2637
+ if (workflowSignal && !workflowSignal.aborted) {
2638
+ workflowSignal.addEventListener("abort", abortHandler, { once: true });
2639
+ }
2640
+ const checkCancellation = () => {
2641
+ if (abortedDuringExecution || workflowSignal?.aborted) {
2642
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
2643
+ const cancelledError = {
2644
+ type: "WORKFLOW_CANCELLED",
2645
+ reason,
2646
+ lastStepKey
2647
+ };
2648
+ throw cancelledError;
2649
+ }
2650
+ };
2651
+ const callOnAfterStepHook = async (stepKey, result2, _meta) => {
2652
+ if (!onAfterStepHook) return;
2653
+ const hookStartTime = performance.now();
2654
+ try {
2655
+ await onAfterStepHook(stepKey, result2, workflowId, context);
2656
+ const hookDuration = performance.now() - hookStartTime;
2657
+ emitEvent({
2658
+ type: "hook_after_step",
2659
+ workflowId,
2660
+ stepKey,
2661
+ ts: Date.now(),
2662
+ durationMs: hookDuration
2663
+ });
2664
+ } catch (thrown) {
2665
+ const hookDuration = performance.now() - hookStartTime;
2666
+ emitEvent({
2667
+ type: "hook_after_step_error",
2668
+ workflowId,
2669
+ stepKey,
2670
+ ts: Date.now(),
2671
+ durationMs: hookDuration,
2672
+ error: thrown
2673
+ });
2674
+ throw thrown;
2675
+ }
2676
+ };
2677
+ const createCachedStep = (realStep) => {
2678
+ const cachedStepFn = async (idOrOperationOrResult, operationOrOptions, stepOptions) => {
2679
+ if (typeof idOrOperationOrResult !== "string") {
2680
+ throw new Error(
2681
+ '[awaitly] step() requires a string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
2682
+ );
2683
+ }
2684
+ const id = idOrOperationOrResult;
2685
+ const opts = stepOptions ?? {};
2686
+ const name = id;
2687
+ const key = Object.prototype.hasOwnProperty.call(opts, "key") ? opts.key : id;
2688
+ const { ttl, out } = opts;
2689
+ checkCancellation();
2690
+ const stepMetadata = extractStepMetadata(opts);
2691
+ if (key && cache && cache.has(key)) {
2692
+ emitEvent({
2693
+ type: "step_cache_hit",
2694
+ workflowId,
2695
+ stepKey: key,
2696
+ name,
2697
+ ts: Date.now(),
2698
+ ...stepMetadata && { metadata: stepMetadata }
2699
+ });
2700
+ const cached = cache.get(key);
2701
+ if (cached.ok) {
2702
+ lastStepKey = key;
2703
+ if (out) {
2704
+ workflowData[out] = cached.value;
2705
+ }
2706
+ return cached.value;
2707
+ }
2708
+ const meta = decodeCachedMeta(cached.cause);
2709
+ throw createEarlyExit(cached.error, meta);
2710
+ }
2711
+ if (key && cache) {
2712
+ emitEvent({
2713
+ type: "step_cache_miss",
2714
+ workflowId,
2715
+ stepKey: key,
2716
+ name,
2717
+ ts: Date.now(),
2718
+ ...stepMetadata && { metadata: stepMetadata }
2719
+ });
2720
+ }
2721
+ try {
2722
+ const value = await realStep(
2723
+ id,
2724
+ operationOrOptions,
2725
+ opts
2726
+ );
2727
+ if (out) {
2728
+ workflowData[out] = value;
2729
+ }
2730
+ if (opts.compensate) {
2731
+ compensations.push({
2732
+ stepName: name,
2733
+ value,
2734
+ compensate: opts.compensate
2735
+ });
2736
+ }
2737
+ if (key) {
2738
+ lastStepKey = key;
2739
+ if (cache) {
2740
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2741
+ }
2742
+ await callOnAfterStepHook(key, ok2(value));
2743
+ }
2744
+ return value;
2745
+ } catch (thrown) {
2746
+ if (key && isEarlyExit(thrown)) {
2747
+ const exit = thrown;
2748
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2749
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2750
+ if (cache) {
2751
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2752
+ }
2753
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2754
+ }
2755
+ throw thrown;
2756
+ }
2757
+ };
2758
+ cachedStepFn.try = async (id, operation, opts) => {
2759
+ const { ttl } = opts;
2760
+ const key = opts.key ?? id;
2761
+ const name = id;
2762
+ if (cache && cache.has(key)) {
2763
+ emitEvent({
2764
+ type: "step_cache_hit",
2765
+ workflowId,
2766
+ stepKey: key,
2767
+ name,
2768
+ ts: Date.now()
2769
+ });
2770
+ const cached = cache.get(key);
2771
+ if (cached.ok) {
2772
+ return cached.value;
2773
+ }
2774
+ const meta = decodeCachedMeta(cached.cause);
2775
+ throw createEarlyExit(cached.error, meta);
2776
+ }
2777
+ if (cache) {
2778
+ emitEvent({
2779
+ type: "step_cache_miss",
2780
+ workflowId,
2781
+ stepKey: key,
2782
+ name,
2783
+ ts: Date.now()
2784
+ });
2785
+ }
2786
+ try {
2787
+ const value = await realStep.try(id, operation, { ...opts, key });
2788
+ if (opts.compensate) {
2789
+ compensations.push({
2790
+ stepName: name,
2791
+ value,
2792
+ compensate: opts.compensate
2793
+ });
2794
+ }
2795
+ if (cache) {
2796
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2797
+ }
2798
+ await callOnAfterStepHook(key, ok2(value));
2799
+ return value;
2800
+ } catch (thrown) {
2801
+ if (isEarlyExit(thrown)) {
2802
+ const exit = thrown;
2803
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2804
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2805
+ if (cache) {
2806
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2807
+ }
2808
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2809
+ }
2810
+ throw thrown;
2811
+ }
2812
+ };
2813
+ cachedStepFn.fromResult = async (id, operation, opts) => {
2814
+ const { ttl } = opts;
2815
+ const key = opts.key ?? id;
2816
+ const name = id;
2817
+ if (cache && cache.has(key)) {
2818
+ emitEvent({
2819
+ type: "step_cache_hit",
2820
+ workflowId,
2821
+ stepKey: key,
2822
+ name,
2823
+ ts: Date.now()
2824
+ });
2825
+ const cached = cache.get(key);
2826
+ if (cached.ok) {
2827
+ return cached.value;
2828
+ }
2829
+ const meta = decodeCachedMeta(cached.cause);
2830
+ throw createEarlyExit(cached.error, meta);
2831
+ }
2832
+ if (cache) {
2833
+ emitEvent({
2834
+ type: "step_cache_miss",
2835
+ workflowId,
2836
+ stepKey: key,
2837
+ name,
2838
+ ts: Date.now()
2839
+ });
2840
+ }
2841
+ try {
2842
+ const value = await realStep.fromResult(id, operation, { ...opts, key });
2843
+ if (cache) {
2844
+ cache.set(key, ok2(value), ttl ? { ttl } : void 0);
2845
+ }
2846
+ await callOnAfterStepHook(key, ok2(value));
2847
+ return value;
2848
+ } catch (thrown) {
2849
+ if (isEarlyExit(thrown)) {
2850
+ const exit = thrown;
2851
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2852
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2853
+ if (cache) {
2854
+ cache.set(key, errorResult, ttl ? { ttl } : void 0);
2855
+ }
2856
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2857
+ }
2858
+ throw thrown;
2859
+ }
2860
+ };
2861
+ cachedStepFn.race = realStep.race;
2862
+ cachedStepFn.withFallback = async (id, operation, options2) => {
2863
+ const key = options2.key ?? id;
2864
+ const name = id;
2865
+ if (cache && cache.has(key)) {
2866
+ emitEvent({
2867
+ type: "step_cache_hit",
2868
+ workflowId,
2869
+ stepKey: key,
2870
+ name,
2871
+ ts: Date.now()
2872
+ });
2873
+ const cached = cache.get(key);
2874
+ if (cached.ok) {
2875
+ return cached.value;
2876
+ }
2877
+ const meta = decodeCachedMeta(cached.cause);
2878
+ throw createEarlyExit(cached.error, meta);
2879
+ }
2880
+ if (cache) {
2881
+ emitEvent({
2882
+ type: "step_cache_miss",
2883
+ workflowId,
2884
+ stepKey: key,
2885
+ name,
2886
+ ts: Date.now()
2887
+ });
2888
+ }
2889
+ try {
2890
+ const value = await realStep.withFallback(
2891
+ id,
2892
+ operation,
2893
+ options2
2894
+ );
2895
+ if (cache) {
2896
+ cache.set(key, ok2(value));
2897
+ }
2898
+ await callOnAfterStepHook(key, ok2(value));
2899
+ return value;
2900
+ } catch (thrown) {
2901
+ if (isEarlyExit(thrown)) {
2902
+ const exit = thrown;
2903
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2904
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2905
+ if (cache) {
2906
+ cache.set(key, errorResult);
2907
+ }
2908
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2909
+ }
2910
+ throw thrown;
2911
+ }
2912
+ };
2913
+ cachedStepFn.withResource = async (id, options2) => {
2914
+ const key = id;
2915
+ try {
2916
+ const value = await realStep.withResource(id, options2);
2917
+ await callOnAfterStepHook(key, ok2(value));
2918
+ return value;
2919
+ } catch (thrown) {
2920
+ if (isEarlyExit(thrown)) {
2921
+ const exit = thrown;
2922
+ const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
2923
+ const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
2924
+ await callOnAfterStepHook(key, errorResult, exit.meta);
2925
+ }
2926
+ throw thrown;
2927
+ }
2928
+ };
2929
+ cachedStepFn.retry = (id, operation, options2) => {
2930
+ const stepOptions = {
2931
+ key: options2.key,
2932
+ // explicitly pass so undefined = don't cache
2933
+ retry: {
2934
+ attempts: options2.attempts,
2935
+ backoff: options2.backoff,
2936
+ initialDelay: options2.initialDelay,
2937
+ maxDelay: options2.maxDelay,
2938
+ jitter: options2.jitter,
2939
+ shouldRetry: options2.shouldRetry,
2940
+ onRetry: options2.onRetry
2941
+ },
2942
+ timeout: options2.timeout,
2943
+ ttl: options2.ttl
2944
+ };
2945
+ return cachedStepFn(id, operation, stepOptions);
2946
+ };
2947
+ cachedStepFn.withTimeout = (id, operation, options2) => {
2948
+ const stepOptions = {
2949
+ key: options2.key,
2950
+ timeout: options2,
2951
+ ttl: options2.ttl
2952
+ };
2953
+ return cachedStepFn(
2954
+ id,
2955
+ operation,
2956
+ stepOptions
2957
+ );
2958
+ };
2959
+ cachedStepFn.sleep = (id, duration, options2) => {
2960
+ if (typeof id !== "string" || id.length === 0) {
2961
+ throw new Error(
2962
+ '[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
2963
+ );
2964
+ }
2965
+ const d = typeof duration === "string" ? parse(duration) : duration;
2966
+ if (!d) {
2967
+ throw new Error(`step.sleep: invalid duration '${duration}'`);
2968
+ }
2969
+ const ms = toMillis(d);
2970
+ const userSignal = options2?.signal;
2971
+ const sleepOperation = async () => {
2972
+ if (workflowSignal?.aborted || userSignal?.aborted) {
2973
+ const e = new Error("Sleep aborted");
2974
+ e.name = "AbortError";
2975
+ throw e;
2976
+ }
2977
+ return new Promise((resolve, reject) => {
2978
+ const state = {
2979
+ timeoutId: void 0
2980
+ };
2981
+ const onAbort = () => {
2982
+ if (state.timeoutId) clearTimeout(state.timeoutId);
2983
+ const e = new Error("Sleep aborted");
2984
+ e.name = "AbortError";
2985
+ reject(e);
2986
+ };
2987
+ workflowSignal?.addEventListener("abort", onAbort, { once: true });
2988
+ userSignal?.addEventListener("abort", onAbort, { once: true });
2989
+ state.timeoutId = setTimeout(() => {
2990
+ workflowSignal?.removeEventListener("abort", onAbort);
2991
+ userSignal?.removeEventListener("abort", onAbort);
2992
+ resolve(ok2(void 0));
2993
+ }, ms);
2994
+ });
2995
+ };
2996
+ return cachedStepFn(id, sleepOperation, {
2997
+ key: options2?.key,
2998
+ ttl: options2?.ttl,
2999
+ description: options2?.description
3000
+ });
3001
+ };
3002
+ const activeWriters = /* @__PURE__ */ new Map();
3003
+ const activeReaders = /* @__PURE__ */ new Map();
3004
+ cachedStepFn.getWritable = (options2) => {
3005
+ const namespace = options2?.namespace ?? "default";
3006
+ const highWaterMark = options2?.highWaterMark ?? 16;
3007
+ if (!streamStore) {
3008
+ throw new Error(
3009
+ "streamStore is required to use getWritable(). Pass a streamStore to createWorkflow options."
3010
+ );
3011
+ }
3012
+ const existingKey = `${workflowId}:${namespace}`;
3013
+ const existing = activeWriters.get(existingKey);
3014
+ if (existing && !existing.closed && !existing.aborted) {
3015
+ return existing.writer;
3016
+ }
3017
+ const backpressure = createBackpressureController({
3018
+ highWaterMark,
3019
+ onStateChange: (state) => {
3020
+ emitEvent({
3021
+ type: "stream_backpressure",
3022
+ workflowId,
3023
+ namespace,
3024
+ bufferedCount: backpressure.bufferedCount,
3025
+ state,
3026
+ ts: Date.now()
3027
+ });
3028
+ }
3029
+ });
3030
+ let position = 0;
3031
+ let writable = true;
3032
+ let aborted = false;
3033
+ let closed = false;
3034
+ emitEvent({
3035
+ type: "stream_created",
3036
+ workflowId,
3037
+ namespace,
3038
+ ts: Date.now()
3039
+ });
3040
+ const writer = {
3041
+ async write(value) {
3042
+ if (closed) {
3043
+ return err(streamWriteError("closed", "Stream is closed"));
3044
+ }
3045
+ if (aborted) {
3046
+ return err(streamWriteError("aborted", "Stream was aborted"));
3047
+ }
3048
+ if (backpressure.state === "paused") {
3049
+ await backpressure.waitForDrain();
3050
+ }
3051
+ const item = {
3052
+ value,
3053
+ position,
3054
+ ts: Date.now()
3055
+ };
3056
+ const result2 = await streamStore.append(workflowId, namespace, item);
3057
+ if (!result2.ok) {
3058
+ emitEvent({
3059
+ type: "stream_error",
3060
+ workflowId,
3061
+ namespace,
3062
+ error: result2.error,
3063
+ position,
3064
+ ts: Date.now()
3065
+ });
3066
+ return err(streamWriteError("store_error", result2.error.message, result2.error));
3067
+ }
3068
+ emitEvent({
3069
+ type: "stream_write",
3070
+ workflowId,
3071
+ namespace,
3072
+ position,
3073
+ ts: Date.now()
3074
+ });
3075
+ position++;
3076
+ backpressure.increment();
3077
+ return ok2(void 0);
3078
+ },
3079
+ async close() {
3080
+ if (closed) {
3081
+ return err(streamCloseError("already_closed", "Stream is already closed"));
3082
+ }
3083
+ const result2 = await streamStore.closeStream(workflowId, namespace);
3084
+ if (!result2.ok) {
3085
+ return err(streamCloseError("store_error", result2.error.message, result2.error));
3086
+ }
3087
+ closed = true;
3088
+ writable = false;
3089
+ emitEvent({
3090
+ type: "stream_close",
3091
+ workflowId,
3092
+ namespace,
3093
+ finalPosition: position,
3094
+ ts: Date.now()
3095
+ });
3096
+ activeWriters.delete(existingKey);
3097
+ return ok2(void 0);
3098
+ },
3099
+ abort(reason) {
3100
+ aborted = true;
3101
+ writable = false;
3102
+ closed = true;
3103
+ emitEvent({
3104
+ type: "stream_error",
3105
+ workflowId,
3106
+ namespace,
3107
+ error: reason,
3108
+ position,
3109
+ ts: Date.now()
3110
+ });
3111
+ activeWriters.delete(existingKey);
3112
+ },
3113
+ get writable() {
3114
+ return writable;
3115
+ },
3116
+ get position() {
3117
+ return position;
3118
+ },
3119
+ get namespace() {
3120
+ return namespace;
3121
+ }
3122
+ };
3123
+ activeWriters.set(existingKey, {
3124
+ writer,
3125
+ backpressure,
3126
+ aborted,
3127
+ closed
3128
+ });
3129
+ return writer;
3130
+ };
3131
+ cachedStepFn.getReadable = (options2) => {
3132
+ const namespace = options2?.namespace ?? "default";
3133
+ const startIndex = options2?.startIndex ?? 0;
3134
+ const pollInterval = options2?.pollInterval ?? 10;
3135
+ const pollTimeout = options2?.pollTimeout ?? 3e4;
3136
+ if (!streamStore) {
3137
+ throw new Error(
3138
+ "streamStore is required to use getReadable(). Pass a streamStore to createWorkflow options."
3139
+ );
3140
+ }
3141
+ const existingKey = `${workflowId}:${namespace}:${startIndex}`;
3142
+ const existing = activeReaders.get(existingKey);
3143
+ if (existing && !existing.closed) {
3144
+ return existing.reader;
3145
+ }
3146
+ const decrementBackpressure = () => {
3147
+ const writerKey = `${workflowId}:${namespace}`;
3148
+ const activeWriter = activeWriters.get(writerKey);
3149
+ if (activeWriter) {
3150
+ activeWriter.backpressure.decrement();
3151
+ }
3152
+ };
3153
+ let position = startIndex;
3154
+ let readable = true;
3155
+ let closed = false;
3156
+ let bufferedItems = [];
3157
+ let bufferIndex = 0;
3158
+ const reader = {
3159
+ async read() {
3160
+ if (closed) {
3161
+ return err(streamReadError("closed", "Reader is closed"));
3162
+ }
3163
+ if (bufferIndex < bufferedItems.length) {
3164
+ const item = bufferedItems[bufferIndex++];
3165
+ position = item.position + 1;
3166
+ decrementBackpressure();
3167
+ emitEvent({
3168
+ type: "stream_read",
3169
+ workflowId,
3170
+ namespace,
3171
+ position: item.position,
3172
+ ts: Date.now()
3173
+ });
3174
+ return ok2(item.value);
3175
+ }
3176
+ const writerKey = `${workflowId}:${namespace}`;
3177
+ const pollStart = Date.now();
3178
+ let hasSeenWriter = activeWriters.has(writerKey);
3179
+ const initialMetaResult = await streamStore.getMetadata(workflowId, namespace);
3180
+ let hasSeenMetadata = initialMetaResult.ok && initialMetaResult.value !== void 0;
3181
+ while (Date.now() - pollStart < pollTimeout) {
3182
+ const result2 = await streamStore.read(workflowId, namespace, position, 100);
3183
+ if (!result2.ok) {
3184
+ return err(streamReadError("store_error", result2.error.message, result2.error));
3185
+ }
3186
+ const items = result2.value;
3187
+ if (items.length > 0) {
3188
+ bufferedItems = items;
3189
+ bufferIndex = 1;
3190
+ const item = items[0];
3191
+ position = item.position + 1;
3192
+ decrementBackpressure();
3193
+ emitEvent({
3194
+ type: "stream_read",
3195
+ workflowId,
3196
+ namespace,
3197
+ position: item.position,
3198
+ ts: Date.now()
3199
+ });
3200
+ return ok2(item.value);
3201
+ }
3202
+ const writerActive = activeWriters.has(writerKey);
3203
+ const metaResult = await streamStore.getMetadata(workflowId, namespace);
3204
+ const metadataExists = metaResult.ok && metaResult.value !== void 0;
3205
+ if (writerActive) hasSeenWriter = true;
3206
+ if (metadataExists) hasSeenMetadata = true;
3207
+ if (metaResult.ok && metaResult.value?.closed) {
3208
+ readable = false;
3209
+ return err(streamEnded(position));
3210
+ }
3211
+ if (hasSeenWriter && !writerActive && !metadataExists) {
3212
+ readable = false;
3213
+ return err(streamEnded(position));
3214
+ }
3215
+ if (hasSeenMetadata && !writerActive && metaResult.ok && !metaResult.value?.closed) {
3216
+ }
3217
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
3218
+ }
3219
+ readable = false;
3220
+ return err(streamEnded(position));
3221
+ },
3222
+ close() {
3223
+ closed = true;
3224
+ readable = false;
3225
+ bufferedItems = [];
3226
+ activeReaders.delete(existingKey);
3227
+ },
3228
+ get readable() {
3229
+ return readable;
3230
+ },
3231
+ get position() {
3232
+ return position;
3233
+ },
3234
+ get namespace() {
3235
+ return namespace;
3236
+ }
3237
+ };
3238
+ activeReaders.set(existingKey, {
3239
+ reader,
3240
+ position,
3241
+ closed
3242
+ });
3243
+ return reader;
3244
+ };
3245
+ cachedStepFn.streamForEach = async (source, processor, options2) => {
3246
+ const checkpointInterval = options2?.checkpointInterval ?? 1;
3247
+ const concurrency = options2?.concurrency ?? 1;
3248
+ const results = [];
3249
+ let processedCount = 0;
3250
+ let lastPosition = -1;
3251
+ const isStreamReader = (s) => {
3252
+ return typeof s === "object" && s !== null && "read" in s && typeof s.read === "function";
3253
+ };
3254
+ const processItem = async (item, itemIndex, itemPosition, namespace) => {
3255
+ const shouldCheckpoint = checkpointInterval > 0 && itemIndex % checkpointInterval === 0;
3256
+ const stepKey = shouldCheckpoint ? `stream-foreach:${namespace}:pos-${itemPosition}` : void 0;
3257
+ const stepId = stepKey ?? `stream-item-${itemPosition}`;
3258
+ const stepResult = await cachedStepFn(
3259
+ stepId,
3260
+ () => processor(item, itemIndex),
3261
+ { key: stepKey }
3262
+ );
3263
+ return { index: itemIndex, position: itemPosition, result: stepResult };
3264
+ };
3265
+ if (isStreamReader(source)) {
3266
+ if (concurrency <= 1) {
3267
+ let itemPosition = source.position;
3268
+ let readResult = await source.read();
3269
+ while (readResult.ok) {
3270
+ const item = readResult.value;
3271
+ const { result: result2 } = await processItem(item, processedCount, itemPosition, source.namespace);
3272
+ results.push(result2);
3273
+ lastPosition = itemPosition;
3274
+ processedCount++;
3275
+ itemPosition = source.position;
3276
+ readResult = await source.read();
3277
+ }
3278
+ } else {
3279
+ const resultsMap = /* @__PURE__ */ new Map();
3280
+ let itemIndex = 0;
3281
+ let totalItems = 0;
3282
+ const slots = new Array(concurrency).fill(null);
3283
+ const getSlot = async () => {
3284
+ for (let i = 0; i < slots.length; i++) {
3285
+ if (slots[i] === null) return i;
3286
+ }
3287
+ const activePromises = slots.filter((s) => s !== null);
3288
+ const completed = await Promise.race(activePromises);
3289
+ resultsMap.set(completed.index, { position: completed.position, result: completed.result });
3290
+ slots[completed.slotIndex] = null;
3291
+ return completed.slotIndex;
3292
+ };
3293
+ let itemPosition = source.position;
3294
+ let readResult = await source.read();
3295
+ while (readResult.ok) {
3296
+ const slotIndex = await getSlot();
3297
+ const currentIndex = itemIndex;
3298
+ const currentPosition = itemPosition;
3299
+ const currentItem = readResult.value;
3300
+ const currentSlot = slotIndex;
3301
+ slots[slotIndex] = processItem(currentItem, currentIndex, currentPosition, source.namespace).then((r) => ({ slotIndex: currentSlot, ...r }));
3302
+ totalItems++;
3303
+ itemIndex++;
3304
+ itemPosition = source.position;
3305
+ readResult = await source.read();
3306
+ }
3307
+ for (let i = 0; i < slots.length; i++) {
3308
+ if (slots[i] !== null) {
3309
+ const result2 = await slots[i];
3310
+ resultsMap.set(result2.index, { position: result2.position, result: result2.result });
3311
+ }
3312
+ }
3313
+ for (let i = 0; i < totalItems; i++) {
3314
+ const entry = resultsMap.get(i);
3315
+ if (entry) {
3316
+ results.push(entry.result);
3317
+ lastPosition = entry.position;
3318
+ processedCount++;
3319
+ }
3320
+ }
3321
+ }
3322
+ } else {
3323
+ if (concurrency <= 1) {
3324
+ let index = 0;
3325
+ for await (const item of source) {
3326
+ const { result: result2 } = await processItem(item, index, index, "async-iterable");
3327
+ results.push(result2);
3328
+ lastPosition = index;
3329
+ processedCount++;
3330
+ index++;
3331
+ }
3332
+ } else {
3333
+ const resultsMap = /* @__PURE__ */ new Map();
3334
+ let itemIndex = 0;
3335
+ let totalItems = 0;
3336
+ const slots = new Array(concurrency).fill(null);
3337
+ const getSlot = async () => {
3338
+ for (let i = 0; i < slots.length; i++) {
3339
+ if (slots[i] === null) return i;
3340
+ }
3341
+ const activePromises = slots.filter((s) => s !== null);
3342
+ const completed = await Promise.race(activePromises);
3343
+ resultsMap.set(completed.index, completed.result);
3344
+ slots[completed.slotIndex] = null;
3345
+ return completed.slotIndex;
3346
+ };
3347
+ for await (const item of source) {
3348
+ const slotIndex = await getSlot();
3349
+ const currentIndex = itemIndex;
3350
+ const currentSlot = slotIndex;
3351
+ slots[slotIndex] = processItem(item, currentIndex, currentIndex, "async-iterable").then((r) => ({ slotIndex: currentSlot, ...r }));
3352
+ totalItems++;
3353
+ itemIndex++;
3354
+ }
3355
+ for (let i = 0; i < slots.length; i++) {
3356
+ if (slots[i] !== null) {
3357
+ const result2 = await slots[i];
3358
+ resultsMap.set(result2.index, result2.result);
3359
+ }
3360
+ }
3361
+ for (let i = 0; i < totalItems; i++) {
3362
+ if (resultsMap.has(i)) {
3363
+ results.push(resultsMap.get(i));
3364
+ lastPosition = i;
3365
+ processedCount++;
3366
+ }
3367
+ }
3368
+ }
3369
+ }
3370
+ return {
3371
+ results,
3372
+ processedCount,
3373
+ lastPosition
3374
+ };
3375
+ };
3376
+ cachedStepFn.if = realStep.if;
3377
+ cachedStepFn.label = realStep.label;
3378
+ cachedStepFn.branch = realStep.branch;
3379
+ cachedStepFn.arm = realStep.arm;
3380
+ cachedStepFn.forEach = realStep.forEach;
3381
+ cachedStepFn.item = realStep.item;
3382
+ cachedStepFn.dep = realStep.dep;
3383
+ cachedStepFn.workflow = (id, getter, options2) => cachedStepFn(id, getter, options2);
3384
+ cachedStepFn.all = (id, shape, options2) => {
3385
+ const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
3386
+ return cachedStepFn(id, async () => ok2(await realStep.all(id, shape)), opts);
3387
+ };
3388
+ cachedStepFn.map = (id, items, mapper, options2) => {
3389
+ const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
3390
+ return cachedStepFn(id, async () => ok2(await realStep.map(id, items, mapper, options2)), opts);
3391
+ };
3392
+ return cachedStepFn;
3393
+ };
3394
+ const wrappedFn = ({ step }) => {
3395
+ const cachedStep = createCachedStep(step);
3396
+ return userFn({
3397
+ step: cachedStep,
3398
+ steps: bindSteps(effectiveDeps ?? {}, cachedStep),
3399
+ deps: effectiveDeps,
3400
+ ctx: workflowContext
3401
+ });
3402
+ };
3403
+ let result;
3404
+ try {
3405
+ result = await run(wrappedFn, {
3406
+ onError: onErrorHandler,
3407
+ onEvent: onEventHandler,
3408
+ catchUnexpected,
3409
+ workflowId,
3410
+ workflowName,
3411
+ context,
3412
+ graph: declaredGraph,
3413
+ _workflowSignal: workflowSignal
3414
+ });
3415
+ } finally {
3416
+ if (workflowSignal) {
3417
+ workflowSignal.removeEventListener("abort", abortHandler);
3418
+ }
3419
+ }
3420
+ if (!result.ok && compensations.length > 0) {
3421
+ const compensationErrors = [];
3422
+ for (let i = compensations.length - 1; i >= 0; i--) {
3423
+ const comp = compensations[i];
3424
+ try {
3425
+ await comp.compensate(comp.value);
3426
+ } catch (compErr) {
3427
+ compensationErrors.push({ stepName: comp.stepName, error: compErr });
3428
+ }
3429
+ }
3430
+ if (compensationErrors.length > 0) {
3431
+ const sagaError = {
3432
+ type: "SAGA_COMPENSATION_ERROR",
3433
+ originalError: result.error,
3434
+ compensationErrors
3435
+ };
3436
+ result = err(sagaError, { cause: result.cause });
3437
+ }
3438
+ }
3439
+ const durationMs = performance.now() - startTime;
3440
+ if (!result.ok) {
3441
+ let cancelledError;
3442
+ if (isWorkflowCancelled(result.cause)) {
3443
+ cancelledError = result.cause;
3444
+ }
3445
+ if (!cancelledError && abortedDuringExecution && isUnexpectedError(result.error)) {
3446
+ const thrown = result.cause;
3447
+ const isAbortError = thrown != null && typeof thrown === "object" && "name" in thrown && thrown.name === "AbortError";
3448
+ if (isAbortError) {
3449
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
3450
+ cancelledError = {
3451
+ type: "WORKFLOW_CANCELLED",
3452
+ reason,
3453
+ lastStepKey
3454
+ };
3455
+ }
3456
+ }
3457
+ if (cancelledError) {
3458
+ emitEvent({
3459
+ type: "workflow_cancelled",
3460
+ workflowId,
3461
+ ts: Date.now(),
3462
+ durationMs,
3463
+ reason: cancelledError.reason,
3464
+ lastStepKey: cancelledError.lastStepKey
3465
+ });
3466
+ if (cancelledError && !isWorkflowCancelled(result.cause)) {
3467
+ return err(result.error, { cause: cancelledError });
3468
+ }
3469
+ return result;
3470
+ }
3471
+ }
3472
+ if (result.ok && abortedDuringExecution) {
3473
+ const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
3474
+ emitEvent({
3475
+ type: "workflow_cancelled",
3476
+ workflowId,
3477
+ ts: Date.now(),
3478
+ durationMs,
3479
+ reason,
3480
+ lastStepKey
3481
+ });
3482
+ const cancelledError = {
3483
+ type: "WORKFLOW_CANCELLED",
3484
+ reason,
3485
+ lastStepKey
3486
+ };
3487
+ return err(catchUnexpected(cancelledError), { cause: cancelledError });
3488
+ }
3489
+ if (result.ok) {
3490
+ emitEvent({
3491
+ type: "workflow_success",
3492
+ workflowId,
3493
+ ts: Date.now(),
3494
+ durationMs
3495
+ });
3496
+ } else {
3497
+ emitEvent({
3498
+ type: "workflow_error",
3499
+ workflowId,
3500
+ ts: Date.now(),
3501
+ durationMs,
3502
+ error: result.error
3503
+ });
3504
+ }
3505
+ return result;
3506
+ }
3507
+ function runMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
3508
+ let runName;
3509
+ let fn;
3510
+ let config;
3511
+ if (typeof fnOrName === "string") {
3512
+ runName = fnOrName;
3513
+ fn = maybeFnOrConfig;
3514
+ config = maybeConfig;
3515
+ } else {
3516
+ fn = fnOrName;
3517
+ config = maybeFnOrConfig;
3518
+ }
3519
+ return internalExecute(runName, fn, config);
3520
+ }
3521
+ async function runWithStateMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
3522
+ let runName;
3523
+ let fn;
3524
+ let config;
3525
+ if (typeof fnOrName === "string") {
3526
+ runName = fnOrName;
3527
+ fn = maybeFnOrConfig;
3528
+ config = maybeConfig;
3529
+ } else {
3530
+ fn = fnOrName;
3531
+ config = maybeFnOrConfig;
3532
+ }
3533
+ const collector = createResumeStateCollector();
3534
+ const userOnEvent = config?.onEvent;
3535
+ const mergedOnEvent = (event, ctx) => {
3536
+ collector.handleEvent(event);
3537
+ try {
3538
+ userOnEvent?.(event, ctx);
3539
+ } catch {
3540
+ }
3541
+ };
3542
+ const mergedConfig = {
3543
+ ...config,
3544
+ onEvent: mergedOnEvent
3545
+ };
3546
+ let result;
3547
+ let resumeState;
3548
+ try {
3549
+ result = await internalExecute(runName, fn, mergedConfig);
3550
+ } catch (thrown) {
3551
+ const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
3552
+ result = err(catchUnexpected(thrown), { cause: thrown });
3553
+ } finally {
3554
+ resumeState = collector.getResumeState();
3555
+ }
3556
+ return { result, resumeState };
3557
+ }
3558
+ const workflow = {
3559
+ withDeps: (overrides) => withDeps(workflow, overrides),
3560
+ run: runMethod,
3561
+ runWithState: runWithStateMethod
3562
+ };
3563
+ return workflow;
3564
+ }
3565
+
3566
+ // src/saga.ts
3567
+ function isSagaCompensationError(error) {
3568
+ return typeof error === "object" && error !== null && error.type === "SAGA_COMPENSATION_ERROR";
3569
+ }
3570
+ function createSagaWorkflow(workflowName, deps, options) {
3571
+ return createWorkflow(workflowName, deps, options);
3572
+ }
3573
+ async function runSaga(fn, options) {
3574
+ const sagaId = crypto.randomUUID();
3575
+ const startTime = performance.now();
3576
+ const compensations = [];
3577
+ const emit = (e) => options?.onEvent?.(e);
3578
+ emit({ type: "saga_start", sagaId, ts: Date.now() });
3579
+ const stepFn = async (name, operation, stepOptions) => {
3580
+ if (typeof name !== "string" || name.length === 0) {
3581
+ throw new TypeError(
3582
+ "step(name, operation, options?): first argument must be a string."
3583
+ );
3584
+ }
3585
+ const result = await operation();
3586
+ if (result.ok) {
3587
+ if (stepOptions?.compensate) {
3588
+ compensations.push({
3589
+ name,
3590
+ value: result.value,
3591
+ compensate: stepOptions.compensate
3592
+ });
3593
+ }
3594
+ return result.value;
3595
+ }
3596
+ throw createEarlyExit(result.error, {
3597
+ origin: "result",
3598
+ resultCause: result.cause
3599
+ });
3600
+ };
3601
+ const stepTry = async (name, operation, opts) => {
3602
+ if (typeof name !== "string" || name.length === 0) {
3603
+ throw new TypeError(
3604
+ "step.try(name, operation, options): first argument must be a string."
3605
+ );
3606
+ }
3607
+ const mapToError = "error" in opts ? () => opts.error : opts.onError;
3608
+ try {
3609
+ const value = await operation();
3610
+ if (opts.compensate) {
3611
+ compensations.push({
3612
+ name,
3613
+ value,
3614
+ compensate: opts.compensate
3615
+ });
3616
+ }
3617
+ return value;
3618
+ } catch (thrown) {
3619
+ const mapped = mapToError(thrown);
3620
+ throw createEarlyExit(mapped, { origin: "throw", thrown });
3621
+ }
3622
+ };
3623
+ const step = Object.assign(stepFn, { try: stepTry });
3624
+ try {
3625
+ const value = await fn({ step });
3626
+ emit({
3627
+ type: "saga_success",
3628
+ sagaId,
3629
+ ts: Date.now(),
3630
+ durationMs: performance.now() - startTime
3631
+ });
3632
+ return ok2(value);
3633
+ } catch (thrown) {
3634
+ const durationMs = performance.now() - startTime;
3635
+ const originalError = isEarlyExit(thrown) ? thrown.error : thrown;
3636
+ emit({ type: "saga_error", sagaId, ts: Date.now(), durationMs, error: originalError });
3637
+ emit({
3638
+ type: "saga_compensation_start",
3639
+ sagaId,
3640
+ ts: Date.now(),
3641
+ stepCount: compensations.length
3642
+ });
3643
+ const compensationStart = performance.now();
3644
+ const compensationErrors = [];
3645
+ for (let i = compensations.length - 1; i >= 0; i--) {
3646
+ const comp = compensations[i];
3647
+ try {
3648
+ await comp.compensate(comp.value);
3649
+ emit({
3650
+ type: "saga_compensation_step",
3651
+ sagaId,
3652
+ stepName: comp.name,
3653
+ ts: Date.now(),
3654
+ success: true
3655
+ });
3656
+ } catch (error) {
3657
+ compensationErrors.push({ stepName: comp.name, error });
3658
+ emit({
3659
+ type: "saga_compensation_step",
3660
+ sagaId,
3661
+ stepName: comp.name,
3662
+ ts: Date.now(),
3663
+ success: false,
3664
+ error
3665
+ });
3666
+ }
3667
+ }
3668
+ emit({
3669
+ type: "saga_compensation_end",
3670
+ sagaId,
3671
+ ts: Date.now(),
3672
+ durationMs: performance.now() - compensationStart,
3673
+ success: compensationErrors.length === 0,
3674
+ failedCount: compensationErrors.length
3675
+ });
3676
+ if (compensationErrors.length > 0) {
3677
+ const sagaError = {
3678
+ type: "SAGA_COMPENSATION_ERROR",
3679
+ originalError,
3680
+ compensationErrors
3681
+ };
3682
+ options?.onError?.(sagaError);
3683
+ if (options?.throwOnCompensationFailure) throw sagaError;
3684
+ return err(sagaError);
3685
+ }
3686
+ options?.onError?.(originalError);
3687
+ if (!isEarlyExit(thrown)) {
3688
+ return err(new UnexpectedError({ cause: thrown }));
3689
+ }
3690
+ return err(originalError);
3691
+ }
3692
+ }
3693
+ // Annotate the CommonJS export names for ESM import in node:
3694
+ 0 && (module.exports = {
3695
+ createSagaWorkflow,
3696
+ isSagaCompensationError,
3697
+ runSaga
3698
+ });
3699
+ //# sourceMappingURL=saga.cjs.map