@jagreehal/workflow 1.3.0 → 1.4.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.
package/dist/core.d.cts CHANGED
@@ -230,7 +230,125 @@ type StepOptions = {
230
230
  * Must be unique within the workflow.
231
231
  */
232
232
  key?: string;
233
+ /**
234
+ * Retry configuration for transient failures.
235
+ * When specified, the step will retry on errors according to this config.
236
+ */
237
+ retry?: RetryOptions;
238
+ /**
239
+ * Timeout configuration for the operation.
240
+ * When specified, each attempt will be aborted after the timeout duration.
241
+ */
242
+ timeout?: TimeoutOptions;
233
243
  };
244
+ /**
245
+ * Backoff strategy for retry operations.
246
+ */
247
+ type BackoffStrategy = "fixed" | "linear" | "exponential";
248
+ /**
249
+ * Configuration for step retry behavior.
250
+ */
251
+ type RetryOptions = {
252
+ /**
253
+ * Total number of attempts (1 = no retry, 3 = initial + 2 retries).
254
+ * Must be >= 1.
255
+ */
256
+ attempts: number;
257
+ /**
258
+ * Backoff strategy between retries.
259
+ * - 'fixed': Same delay each time (initialDelay)
260
+ * - 'linear': Delay increases linearly (initialDelay * attempt)
261
+ * - 'exponential': Delay doubles each time (initialDelay * 2^(attempt-1))
262
+ * @default 'exponential'
263
+ */
264
+ backoff?: BackoffStrategy;
265
+ /**
266
+ * Initial delay in milliseconds before first retry.
267
+ * @default 100
268
+ */
269
+ initialDelay?: number;
270
+ /**
271
+ * Maximum delay cap in milliseconds.
272
+ * Prevents exponential backoff from growing too large.
273
+ * @default 30000 (30 seconds)
274
+ */
275
+ maxDelay?: number;
276
+ /**
277
+ * Whether to add random jitter (0-25% of delay).
278
+ * Helps prevent thundering herd when multiple workflows retry simultaneously.
279
+ * @default true
280
+ */
281
+ jitter?: boolean;
282
+ /**
283
+ * Predicate to determine if a retry should occur.
284
+ * Receives the error and current attempt number (1-indexed).
285
+ * Return true to retry, false to fail immediately.
286
+ * @default Always retry on any error
287
+ */
288
+ retryOn?: (error: unknown, attempt: number) => boolean;
289
+ /**
290
+ * Callback invoked before each retry attempt.
291
+ * Useful for logging, metrics, or side effects.
292
+ */
293
+ onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
294
+ };
295
+ /**
296
+ * Configuration for step timeout behavior.
297
+ */
298
+ type TimeoutOptions = {
299
+ /**
300
+ * Timeout duration in milliseconds per attempt.
301
+ * When combined with retry, each attempt gets its own timeout.
302
+ */
303
+ ms: number;
304
+ /**
305
+ * Custom error to use when timeout occurs.
306
+ * @default StepTimeoutError with step details
307
+ */
308
+ error?: unknown;
309
+ /**
310
+ * Whether to pass an AbortSignal to the operation.
311
+ * When true, the operation function receives (signal: AbortSignal) as argument.
312
+ * Useful for fetch() and other APIs that support cancellation.
313
+ * @default false
314
+ */
315
+ signal?: boolean;
316
+ };
317
+ /**
318
+ * Standard timeout error type.
319
+ */
320
+ type StepTimeoutError = {
321
+ type: "STEP_TIMEOUT";
322
+ stepName?: string;
323
+ stepKey?: string;
324
+ timeoutMs: number;
325
+ attempt?: number;
326
+ };
327
+ /**
328
+ * Symbol used to mark any error (including custom errors) as a timeout error.
329
+ * This allows detection of timeout errors even when users provide custom error payloads.
330
+ */
331
+ declare const STEP_TIMEOUT_MARKER: unique symbol;
332
+ /**
333
+ * Metadata attached to timeout-marked errors.
334
+ */
335
+ type StepTimeoutMarkerMeta = {
336
+ timeoutMs: number;
337
+ stepName?: string;
338
+ stepKey?: string;
339
+ attempt?: number;
340
+ };
341
+ /**
342
+ * Type guard to check if an error is a StepTimeoutError.
343
+ * This checks both the standard type field AND the timeout marker symbol,
344
+ * so custom errors provided via timeout.error are also detected.
345
+ */
346
+ declare function isStepTimeoutError(e: unknown): e is StepTimeoutError;
347
+ /**
348
+ * Get timeout metadata from a timeout error (works with both standard and custom errors).
349
+ * Returns undefined if the error is not a timeout error.
350
+ */
351
+ declare function getStepTimeoutMeta(e: unknown): StepTimeoutMarkerMeta | undefined;
234
352
  /**
235
353
  * The `step` object passed to the function in `run(async (step) => { ... })`.
236
354
  * acts as the bridge between your business logic and the workflow engine.
@@ -399,6 +517,72 @@ interface RunStep<E = unknown> {
399
517
  * ```
400
518
  */
401
519
  allSettled: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
520
+ /**
521
+ * Execute an operation with retry and optional timeout.
522
+ *
523
+ * Use this for operations that may fail transiently (network issues, rate limits)
524
+ * and benefit from automatic retry with backoff.
525
+ *
526
+ * @param operation - A function that returns a Result or AsyncResult
527
+ * @param options - Retry configuration and optional timeout
528
+ * @returns The success value (unwrapped)
529
+ * @throws {EarlyExit} If all retries are exhausted (stops execution safely)
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * const data = await step.retry(
534
+ * () => fetchFromExternalApi(id),
535
+ * {
536
+ * name: 'fetch-external',
537
+ * attempts: 3,
538
+ * backoff: 'exponential',
539
+ * initialDelay: 200,
540
+ * retryOn: (error) => error === 'RATE_LIMITED' || error === 'TRANSIENT',
541
+ * onRetry: (error, attempt, delay) => {
542
+ * console.log(`Retry ${attempt} after ${delay}ms`);
543
+ * },
544
+ * }
545
+ * );
546
+ * ```
547
+ */
548
+ retry: <T, StepE extends E, StepC = unknown>(operation: () => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>, options: RetryOptions & {
549
+ name?: string;
550
+ key?: string;
551
+ timeout?: TimeoutOptions;
552
+ }) => Promise<T>;
553
+ /**
554
+ * Execute an operation with a timeout.
555
+ *
556
+ * Use this for operations that may hang indefinitely (external APIs, connections)
557
+ * and need to be aborted after a certain duration.
558
+ *
559
+ * When `signal: true` is set, an AbortSignal is passed to your operation,
560
+ * which you can use with APIs like fetch() for proper cancellation.
561
+ *
562
+ * @param operation - A function that returns a Result (may receive AbortSignal)
563
+ * @param options - Timeout configuration
564
+ * @returns The success value (unwrapped)
565
+ * @throws {EarlyExit} If the operation times out (stops execution safely)
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * // Without AbortSignal
570
+ * const data = await step.withTimeout(
571
+ * () => fetchData(id),
572
+ * { ms: 5000, name: 'fetch-data' }
573
+ * );
574
+ *
575
+ * // With AbortSignal for fetch()
576
+ * const data = await step.withTimeout(
577
+ * (signal) => fetch(url, { signal }).then(r => ok(r.json())),
578
+ * { ms: 5000, signal: true, name: 'fetch-url' }
579
+ * );
580
+ * ```
581
+ */
582
+ withTimeout: <T, StepE extends E, StepC = unknown>(operation: (() => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>) | ((signal: AbortSignal) => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>), options: TimeoutOptions & {
583
+ name?: string;
584
+ key?: string;
585
+ }) => Promise<T>;
402
586
  }
403
587
  /**
404
588
  * Unified event stream for workflow execution.
@@ -502,6 +686,36 @@ type WorkflowEvent<E> = {
502
686
  ts: number;
503
687
  durationMs: number;
504
688
  winnerId?: string;
689
+ } | {
690
+ type: "step_retry";
691
+ workflowId: string;
692
+ stepId: string;
693
+ stepKey?: string;
694
+ name?: string;
695
+ ts: number;
696
+ attempt: number;
697
+ maxAttempts: number;
698
+ delayMs: number;
699
+ error: E;
700
+ } | {
701
+ type: "step_retries_exhausted";
702
+ workflowId: string;
703
+ stepId: string;
704
+ stepKey?: string;
705
+ name?: string;
706
+ ts: number;
707
+ durationMs: number;
708
+ attempts: number;
709
+ lastError: E;
710
+ } | {
711
+ type: "step_timeout";
712
+ workflowId: string;
713
+ stepId: string;
714
+ stepKey?: string;
715
+ name?: string;
716
+ ts: number;
717
+ timeoutMs: number;
718
+ attempt?: number;
505
719
  };
506
720
  type RunOptionsWithCatch<E, C = void> = {
507
721
  /**
@@ -1778,4 +1992,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
1778
1992
  */
1779
1993
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
1780
1994
 
1781
- export { type AsyncResult, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, type ScopeType, type SettledError, type StepFailureMeta, type StepOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, isEarlyExit, isErr, isOk, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
1995
+ export { type AsyncResult, type BackoffStrategy, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RetryOptions, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, STEP_TIMEOUT_MARKER, type ScopeType, type SettledError, type StepFailureMeta, type StepOptions, type StepTimeoutError, type StepTimeoutMarkerMeta, type TimeoutOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, getStepTimeoutMeta, isEarlyExit, isErr, isOk, isStepTimeoutError, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
package/dist/core.d.ts CHANGED
@@ -230,7 +230,125 @@ type StepOptions = {
230
230
  * Must be unique within the workflow.
231
231
  */
232
232
  key?: string;
233
+ /**
234
+ * Retry configuration for transient failures.
235
+ * When specified, the step will retry on errors according to this config.
236
+ */
237
+ retry?: RetryOptions;
238
+ /**
239
+ * Timeout configuration for the operation.
240
+ * When specified, each attempt will be aborted after the timeout duration.
241
+ */
242
+ timeout?: TimeoutOptions;
233
243
  };
244
+ /**
245
+ * Backoff strategy for retry operations.
246
+ */
247
+ type BackoffStrategy = "fixed" | "linear" | "exponential";
248
+ /**
249
+ * Configuration for step retry behavior.
250
+ */
251
+ type RetryOptions = {
252
+ /**
253
+ * Total number of attempts (1 = no retry, 3 = initial + 2 retries).
254
+ * Must be >= 1.
255
+ */
256
+ attempts: number;
257
+ /**
258
+ * Backoff strategy between retries.
259
+ * - 'fixed': Same delay each time (initialDelay)
260
+ * - 'linear': Delay increases linearly (initialDelay * attempt)
261
+ * - 'exponential': Delay doubles each time (initialDelay * 2^(attempt-1))
262
+ * @default 'exponential'
263
+ */
264
+ backoff?: BackoffStrategy;
265
+ /**
266
+ * Initial delay in milliseconds before first retry.
267
+ * @default 100
268
+ */
269
+ initialDelay?: number;
270
+ /**
271
+ * Maximum delay cap in milliseconds.
272
+ * Prevents exponential backoff from growing too large.
273
+ * @default 30000 (30 seconds)
274
+ */
275
+ maxDelay?: number;
276
+ /**
277
+ * Whether to add random jitter (0-25% of delay).
278
+ * Helps prevent thundering herd when multiple workflows retry simultaneously.
279
+ * @default true
280
+ */
281
+ jitter?: boolean;
282
+ /**
283
+ * Predicate to determine if a retry should occur.
284
+ * Receives the error and current attempt number (1-indexed).
285
+ * Return true to retry, false to fail immediately.
286
+ * @default Always retry on any error
287
+ */
288
+ retryOn?: (error: unknown, attempt: number) => boolean;
289
+ /**
290
+ * Callback invoked before each retry attempt.
291
+ * Useful for logging, metrics, or side effects.
292
+ */
293
+ onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
294
+ };
295
+ /**
296
+ * Configuration for step timeout behavior.
297
+ */
298
+ type TimeoutOptions = {
299
+ /**
300
+ * Timeout duration in milliseconds per attempt.
301
+ * When combined with retry, each attempt gets its own timeout.
302
+ */
303
+ ms: number;
304
+ /**
305
+ * Custom error to use when timeout occurs.
306
+ * @default StepTimeoutError with step details
307
+ */
308
+ error?: unknown;
309
+ /**
310
+ * Whether to pass an AbortSignal to the operation.
311
+ * When true, the operation function receives (signal: AbortSignal) as argument.
312
+ * Useful for fetch() and other APIs that support cancellation.
313
+ * @default false
314
+ */
315
+ signal?: boolean;
316
+ };
317
+ /**
318
+ * Standard timeout error type.
319
+ */
320
+ type StepTimeoutError = {
321
+ type: "STEP_TIMEOUT";
322
+ stepName?: string;
323
+ stepKey?: string;
324
+ timeoutMs: number;
325
+ attempt?: number;
326
+ };
327
+ /**
328
+ * Symbol used to mark any error (including custom errors) as a timeout error.
329
+ * This allows detection of timeout errors even when users provide custom error payloads.
330
+ */
331
+ declare const STEP_TIMEOUT_MARKER: unique symbol;
332
+ /**
333
+ * Metadata attached to timeout-marked errors.
334
+ */
335
+ type StepTimeoutMarkerMeta = {
336
+ timeoutMs: number;
337
+ stepName?: string;
338
+ stepKey?: string;
339
+ attempt?: number;
340
+ };
341
+ /**
342
+ * Type guard to check if an error is a StepTimeoutError.
343
+ * This checks both the standard type field AND the timeout marker symbol,
344
+ * so custom errors provided via timeout.error are also detected.
345
+ */
346
+ declare function isStepTimeoutError(e: unknown): e is StepTimeoutError;
347
+ /**
348
+ * Get timeout metadata from a timeout error (works with both standard and custom errors).
349
+ * Returns undefined if the error is not a timeout error.
350
+ */
351
+ declare function getStepTimeoutMeta(e: unknown): StepTimeoutMarkerMeta | undefined;
234
352
  /**
235
353
  * The `step` object passed to the function in `run(async (step) => { ... })`.
236
354
  * acts as the bridge between your business logic and the workflow engine.
@@ -399,6 +517,72 @@ interface RunStep<E = unknown> {
399
517
  * ```
400
518
  */
401
519
  allSettled: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
520
+ /**
521
+ * Execute an operation with retry and optional timeout.
522
+ *
523
+ * Use this for operations that may fail transiently (network issues, rate limits)
524
+ * and benefit from automatic retry with backoff.
525
+ *
526
+ * @param operation - A function that returns a Result or AsyncResult
527
+ * @param options - Retry configuration and optional timeout
528
+ * @returns The success value (unwrapped)
529
+ * @throws {EarlyExit} If all retries are exhausted (stops execution safely)
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * const data = await step.retry(
534
+ * () => fetchFromExternalApi(id),
535
+ * {
536
+ * name: 'fetch-external',
537
+ * attempts: 3,
538
+ * backoff: 'exponential',
539
+ * initialDelay: 200,
540
+ * retryOn: (error) => error === 'RATE_LIMITED' || error === 'TRANSIENT',
541
+ * onRetry: (error, attempt, delay) => {
542
+ * console.log(`Retry ${attempt} after ${delay}ms`);
543
+ * },
544
+ * }
545
+ * );
546
+ * ```
547
+ */
548
+ retry: <T, StepE extends E, StepC = unknown>(operation: () => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>, options: RetryOptions & {
549
+ name?: string;
550
+ key?: string;
551
+ timeout?: TimeoutOptions;
552
+ }) => Promise<T>;
553
+ /**
554
+ * Execute an operation with a timeout.
555
+ *
556
+ * Use this for operations that may hang indefinitely (external APIs, connections)
557
+ * and need to be aborted after a certain duration.
558
+ *
559
+ * When `signal: true` is set, an AbortSignal is passed to your operation,
560
+ * which you can use with APIs like fetch() for proper cancellation.
561
+ *
562
+ * @param operation - A function that returns a Result (may receive AbortSignal)
563
+ * @param options - Timeout configuration
564
+ * @returns The success value (unwrapped)
565
+ * @throws {EarlyExit} If the operation times out (stops execution safely)
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * // Without AbortSignal
570
+ * const data = await step.withTimeout(
571
+ * () => fetchData(id),
572
+ * { ms: 5000, name: 'fetch-data' }
573
+ * );
574
+ *
575
+ * // With AbortSignal for fetch()
576
+ * const data = await step.withTimeout(
577
+ * (signal) => fetch(url, { signal }).then(r => ok(r.json())),
578
+ * { ms: 5000, signal: true, name: 'fetch-url' }
579
+ * );
580
+ * ```
581
+ */
582
+ withTimeout: <T, StepE extends E, StepC = unknown>(operation: (() => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>) | ((signal: AbortSignal) => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>), options: TimeoutOptions & {
583
+ name?: string;
584
+ key?: string;
585
+ }) => Promise<T>;
402
586
  }
403
587
  /**
404
588
  * Unified event stream for workflow execution.
@@ -502,6 +686,36 @@ type WorkflowEvent<E> = {
502
686
  ts: number;
503
687
  durationMs: number;
504
688
  winnerId?: string;
689
+ } | {
690
+ type: "step_retry";
691
+ workflowId: string;
692
+ stepId: string;
693
+ stepKey?: string;
694
+ name?: string;
695
+ ts: number;
696
+ attempt: number;
697
+ maxAttempts: number;
698
+ delayMs: number;
699
+ error: E;
700
+ } | {
701
+ type: "step_retries_exhausted";
702
+ workflowId: string;
703
+ stepId: string;
704
+ stepKey?: string;
705
+ name?: string;
706
+ ts: number;
707
+ durationMs: number;
708
+ attempts: number;
709
+ lastError: E;
710
+ } | {
711
+ type: "step_timeout";
712
+ workflowId: string;
713
+ stepId: string;
714
+ stepKey?: string;
715
+ name?: string;
716
+ ts: number;
717
+ timeoutMs: number;
718
+ attempt?: number;
505
719
  };
506
720
  type RunOptionsWithCatch<E, C = void> = {
507
721
  /**
@@ -1778,4 +1992,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
1778
1992
  */
1779
1993
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
1780
1994
 
1781
- export { type AsyncResult, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, type ScopeType, type SettledError, type StepFailureMeta, type StepOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, isEarlyExit, isErr, isOk, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
1995
+ export { type AsyncResult, type BackoffStrategy, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RetryOptions, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, STEP_TIMEOUT_MARKER, type ScopeType, type SettledError, type StepFailureMeta, type StepOptions, type StepTimeoutError, type StepTimeoutMarkerMeta, type TimeoutOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, getStepTimeoutMeta, isEarlyExit, isErr, isOk, isStepTimeoutError, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- var f=e=>({ok:!0,value:e}),l=(e,n)=>({ok:!1,error:e,...n?.cause!==void 0?{cause:n.cause}:{}}),G=e=>e.ok,q=e=>!e.ok,L=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",O=Symbol("early-exit");function X(e,n){return{[O]:!0,error:e,meta:n}}function W(e){return typeof e=="object"&&e!==null&&e[O]===!0}var K=Symbol("mapper-exception");function Y(e){return{[K]:!0,thrown:e}}function J(e){return typeof e=="object"&&e!==null&&e[K]===!0}function $(e){return typeof e=="string"?{name:e}:e??{}}async function M(e,n){let{onError:t,onEvent:u,catchUnexpected:w,workflowId:C,context:A}=n&&typeof n=="object"?n:{},a=C??crypto.randomUUID(),D=!t&&!w,g=[],F=0,I=r=>r??`step_${++F}`,c=r=>{if(r.type==="step_success"){let S=r.stepId;for(let x=g.length-1;x>=0;x--){let T=g[x];if(T.type==="race"&&!T.winnerId){T.winnerId=S;break}}}u?.(r,A)},h=X,b=r=>W(r),_=(r,S)=>D?S?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r,...S.resultCause!==void 0?{cause:S.resultCause}:{}}}:S?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:r,thrown:S.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r}}:r,N=r=>r.origin==="result"?r.resultCause:r.thrown,V=r=>({type:"UNEXPECTED_ERROR",cause:r.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:r.error,...r.meta.resultCause!==void 0?{cause:r.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:r.error,thrown:r.meta.thrown}});try{let r=(T,k)=>(async()=>{let{name:o,key:s}=$(k),y=I(s),i=u?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});let p;try{p=await(typeof T=="function"?T():T)}catch(R){let v=performance.now()-i;if(b(R))throw c({type:"step_aborted",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:v}),R;if(w){let P;try{P=w(R)}catch(j){throw Y(j)}throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:v,error:P}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:v,result:l(P,{cause:R}),meta:{origin:"throw",thrown:R}}),t?.(P,o),h(P,{origin:"throw",thrown:R})}else{let P={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:R}};throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:v,error:P}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:v,result:l(P,{cause:R}),meta:{origin:"throw",thrown:R}}),R}}let E=performance.now()-i;if(p.ok)return c({type:"step_success",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:E}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:E,result:p}),p.value;let d=_(p.error,{origin:"result",resultCause:p.cause});throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:E,error:d}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:E,result:p,meta:{origin:"result",resultCause:p.cause}}),t?.(p.error,o),h(p.error,{origin:"result",resultCause:p.cause})})();r.try=(T,k)=>{let o=k.name,s=k.key,y=I(s),m="error"in k?()=>k.error:k.onError,i=u;return(async()=>{let p=i?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});try{let E=await T(),d=performance.now()-p;return c({type:"step_success",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:d}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:d,result:f(E)}),E}catch(E){let d=m(E),R=performance.now()-p,v=_(d,{origin:"throw",thrown:E});throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:R,error:v}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:R,result:l(d,{cause:E}),meta:{origin:"throw",thrown:E}}),t?.(d,o),h(d,{origin:"throw",thrown:E})}})()},r.fromResult=(T,k)=>{let o=k.name,s=k.key,y=I(s),m="error"in k?()=>k.error:k.onError,i=u;return(async()=>{let p=i?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});let E=await T();if(E.ok){let d=performance.now()-p;return c({type:"step_success",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:d}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:d,result:f(E.value)}),E.value}else{let d=m(E.error),R=performance.now()-p,v=_(d,{origin:"result",resultCause:E.error});throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:R,error:v}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:R,result:l(d,{cause:E.error}),meta:{origin:"result",resultCause:E.error}}),t?.(d,o),h(d,{origin:"result",resultCause:E.error})}})()},r.parallel=(T,k)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),y=!1;g.push({scopeId:o,type:"parallel"});let m=()=>{if(y)return;y=!0;let i=g.findIndex(p=>p.scopeId===o);i!==-1&&g.splice(i,1),c({type:"scope_end",workflowId:a,scopeId:o,ts:Date.now(),durationMs:performance.now()-s})};c({type:"scope_start",workflowId:a,scopeId:o,scopeType:"parallel",name:T,ts:Date.now()});try{let i=await k();if(m(),!i.ok)throw t?.(i.error,T),h(i.error,{origin:"result",resultCause:i.cause});return i.value}catch(i){throw m(),i}})()},r.race=(T,k)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),y=!1,m={scopeId:o,type:"race",winnerId:void 0};g.push(m);let i=()=>{if(y)return;y=!0;let p=g.findIndex(E=>E.scopeId===o);p!==-1&&g.splice(p,1),c({type:"scope_end",workflowId:a,scopeId:o,ts:Date.now(),durationMs:performance.now()-s,winnerId:m.winnerId})};c({type:"scope_start",workflowId:a,scopeId:o,scopeType:"race",name:T,ts:Date.now()});try{let p=await k();if(i(),!p.ok)throw t?.(p.error,T),h(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw i(),p}})()},r.allSettled=(T,k)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),y=!1;g.push({scopeId:o,type:"allSettled"});let m=()=>{if(y)return;y=!0;let i=g.findIndex(p=>p.scopeId===o);i!==-1&&g.splice(i,1),c({type:"scope_end",workflowId:a,scopeId:o,ts:Date.now(),durationMs:performance.now()-s})};c({type:"scope_start",workflowId:a,scopeId:o,scopeType:"allSettled",name:T,ts:Date.now()});try{let i=await k();if(m(),!i.ok)throw t?.(i.error,T),h(i.error,{origin:"result",resultCause:i.cause});return i.value}catch(i){throw m(),i}})()};let x=await e(r);return f(x)}catch(r){if(J(r))throw r.thrown;if(b(r)){let x=N(r.meta);if(w||t)return l(r.error,{cause:x});if(L(r.error))return l(r.error,{cause:x});let T=V(r);return l(T,{cause:x})}if(w){let x=w(r);return t?.(x,"unexpected"),l(x,{cause:r})}let S={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:r}};return t?.(S,"unexpected"),l(S,{cause:r})}}M.strict=(e,n)=>M(e,n);var U=class extends Error{constructor(t,u){super(`Unwrap called on an error result: ${String(t)}`);this.error=t;this.cause=u;this.name="UnwrapError"}},B=e=>{if(e.ok)return e.value;throw new U(e.error,e.cause)},H=(e,n)=>e.ok?e.value:n,z=(e,n)=>e.ok?e.value:n(e.error,e.cause);function Q(e,n){try{return f(e())}catch(t){return n?l(n(t),{cause:t}):l(t)}}async function Z(e,n){try{return f(await e)}catch(t){return n?l(n(t),{cause:t}):l(t)}}async function ee(e,n){try{return f(await e())}catch(t){return n?l(n(t),{cause:t}):l(t)}}function ne(e,n){return e!=null?f(e):l(n())}function te(e,n){return e.ok?f(n(e.value)):e}function re(e,n){return e.ok?e:l(n(e.error),{cause:e.cause})}function oe(e,n){return e.ok?n.ok(e.value):n.err(e.error,e.cause)}function se(e,n){return e.ok?n(e.value):e}function ue(e,n){return e.ok&&n(e.value),e}function ae(e,n){return e.ok||n(e.error,e.cause),e}function pe(e,n,t){if(!e.ok)return e;try{return f(n(e.value))}catch(u){return l(t(u),{cause:u})}}function ie(e,n,t){if(e.ok)return e;try{return l(n(e.error),{cause:e.cause})}catch(u){return l(t(u),{cause:u})}}function ce(e){let n=[];for(let t of e){if(!t.ok)return t;n.push(t.value)}return f(n)}async function le(e){return e.length===0?f([]):new Promise(n=>{let t=!1,u=e.length,w=new Array(e.length);for(let C=0;C<e.length;C++){let A=C;Promise.resolve(e[A]).catch(a=>l({type:"PROMISE_REJECTED",cause:a},{cause:{type:"PROMISE_REJECTION",reason:a}})).then(a=>{if(!t){if(!a.ok){t=!0,n(a);return}w[A]=a.value,u--,u===0&&n(f(w))}})}})}function Ee(e){let n=[],t=[];for(let u of e)u.ok?n.push(u.value):t.push({error:u.error,cause:u.cause});return t.length>0?l(t):f(n)}function we(e){let n=[],t=[];for(let u of e)u.ok?n.push(u.value):t.push(u.error);return{values:n,errors:t}}function ye(e){if(e.length===0)return l({type:"EMPTY_INPUT",message:"any() requires at least one Result"});let n=null;for(let t of e){if(t.ok)return t;n||(n=t)}return n}async function Te(e){return e.length===0?l({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(n=>{let t=!1,u=e.length,w=null;for(let C of e)Promise.resolve(C).catch(A=>l({type:"PROMISE_REJECTED",cause:A},{cause:{type:"PROMISE_REJECTION",reason:A}})).then(A=>{if(!t){if(A.ok){t=!0,n(A);return}w||(w=A),u--,u===0&&n(w)}})})}async function ke(e){let n=await Promise.all(e.map(w=>Promise.resolve(w).then(C=>({status:"result",result:C})).catch(C=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:C},cause:{type:"PROMISE_REJECTION",reason:C}})))),t=[],u=[];for(let w of n)w.status==="rejected"?u.push({error:w.error,cause:w.cause}):w.result.ok?t.push(w.result.value):u.push({error:w.result.error,cause:w.result.cause});return u.length>0?l(u):f(t)}export{O as EARLY_EXIT_SYMBOL,U as UnwrapError,ce as all,le as allAsync,Ee as allSettled,ke as allSettledAsync,se as andThen,ye as any,Te as anyAsync,X as createEarlyExit,l as err,Q as from,ne as fromNullable,Z as fromPromise,W as isEarlyExit,q as isErr,G as isOk,L as isUnexpectedError,te as map,re as mapError,ie as mapErrorTry,pe as mapTry,oe as match,f as ok,we as partition,M as run,ue as tap,ae as tapError,ee as tryAsync,B as unwrap,H as unwrapOr,z as unwrapOrElse};
1
+ var P=e=>({ok:!0,value:e}),T=(e,t)=>({ok:!1,error:e,...t?.cause!==void 0?{cause:t.cause}:{}}),Ee=e=>e.ok,ye=e=>!e.ok,oe=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",D=Symbol.for("step_timeout_marker");function G(e){return typeof e!="object"||e===null?!1:e.type==="STEP_TIMEOUT"?!0:D in e}function se(e){if(!(typeof e!="object"||e===null)){if(e.type==="STEP_TIMEOUT"){let t=e;return{timeoutMs:t.timeoutMs,stepName:t.stepName,stepKey:t.stepKey,attempt:t.attempt}}if(D in e)return e[D]}}var Q=Symbol("early-exit");function ue(e,t){return{[Q]:!0,error:e,meta:t}}function ae(e){return typeof e=="object"&&e!==null&&e[Q]===!0}var Z=Symbol("mapper-exception");function ie(e){return{[Z]:!0,thrown:e}}function pe(e){return typeof e=="object"&&e!==null&&e[Z]===!0}function le(e){return typeof e=="string"?{name:e}:e??{}}function X(e,t){let{backoff:n,initialDelay:u,maxDelay:w,jitter:g}=t,k;switch(n){case"fixed":k=u;break;case"linear":k=u*e;break;case"exponential":k=u*Math.pow(2,e-1);break}if(k=Math.min(k,w),g){let o=k*.25*Math.random();k=k+o}return Math.floor(k)}function Y(e){return new Promise(t=>setTimeout(t,e))}var H=Symbol("timeout");async function ce(e,t,n){let u=new AbortController,w=t.error??{type:"STEP_TIMEOUT",stepName:n.name,stepKey:n.key,timeoutMs:t.ms,attempt:n.attempt},g,k=new Promise((v,x)=>{g=setTimeout(()=>{u.abort(),x({[H]:!0,error:w})},t.ms)}),o;t.signal?o=Promise.resolve(e(u.signal)):o=Promise.resolve(e());try{return await Promise.race([o,k])}catch(v){if(typeof v=="object"&&v!==null&&v[H]===!0){let x=v.error;if(typeof x=="object"&&x!==null&&x.type!=="STEP_TIMEOUT"){let K={timeoutMs:t.ms,stepName:n.name,stepKey:n.key,attempt:n.attempt};D in x?x[D]=K:Object.defineProperty(x,D,{value:K,enumerable:!1,writable:!0,configurable:!1})}throw x}throw v}finally{clearTimeout(g)}}var U={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,retryOn:()=>!0,onRetry:()=>{}};async function z(e,t){let{onError:n,onEvent:u,catchUnexpected:w,workflowId:g,context:k}=t&&typeof t=="object"?t:{},o=g??crypto.randomUUID(),v=!n&&!w,x=[],K=0,N=r=>r??`step_${++K}`,l=r=>{if(r.type==="step_success"){let h=r.stepId;for(let b=x.length-1;b>=0;b--){let m=x[b];if(m.type==="race"&&!m.winnerId){m.winnerId=h;break}}}u?.(r,k)},M=ue,q=r=>ae(r),V=(r,h)=>v?h?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r,...h.resultCause!==void 0?{cause:h.resultCause}:{}}}:h?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:r,thrown:h.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r}}:r,ee=r=>r.origin==="result"?r.resultCause:r.thrown,te=r=>({type:"UNEXPECTED_ERROR",cause:r.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:r.error,...r.meta.resultCause!==void 0?{cause:r.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:r.error,thrown:r.meta.thrown}});try{let r=(m,i)=>(async()=>{let y=le(i),{name:s,key:a,retry:d,timeout:c}=y,p=N(a),f=u,R=f?performance.now():0;if(!(typeof m=="function")){if(d&&d.attempts>1)throw new Error("step: retry options require a function operation. Direct Promise/Result values cannot be re-executed on retry. Wrap your operation in a function: step(() => yourOperation, { retry: {...} })");if(c)throw new Error("step: timeout options require a function operation. Direct Promise/Result values cannot be wrapped with timeout after they've started. Wrap your operation in a function: step(() => yourOperation, { timeout: {...} })")}let S={attempts:Math.max(1,d?.attempts??1),backoff:d?.backoff??U.backoff,initialDelay:d?.initialDelay??U.initialDelay,maxDelay:d?.maxDelay??U.maxDelay,jitter:d?.jitter??U.jitter,retryOn:d?.retryOn??U.retryOn,onRetry:d?.onRetry??U.onRetry};u&&l({type:"step_start",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now()});let J;for(let C=1;C<=S.attempts;C++){let re=f?performance.now():0;try{let E;if(typeof m=="function"?c?E=await ce(m,c,{name:s,key:a,attempt:C}):E=await m():E=await m,E.ok){let _=performance.now()-R;return l({type:"step_success",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:_}),a&&l({type:"step_complete",workflowId:o,stepKey:a,name:s,ts:Date.now(),durationMs:_,result:E}),E.value}if(J=E,C<S.attempts&&S.retryOn(E.error,C)){let _=X(C,S);l({type:"step_retry",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),attempt:C+1,maxAttempts:S.attempts,delayMs:_,error:E.error}),S.onRetry(E.error,C,_),await Y(_);continue}S.attempts>1&&l({type:"step_retries_exhausted",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:performance.now()-R,attempts:C,lastError:E.error});break}catch(E){let _=performance.now()-re;if(q(E))throw l({type:"step_aborted",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:_}),E;if(G(E)){let A=se(E),L=c?.ms??A?.timeoutMs??0;if(l({type:"step_timeout",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),timeoutMs:L,attempt:C}),C<S.attempts&&S.retryOn(E,C)){let W=X(C,S);l({type:"step_retry",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),attempt:C+1,maxAttempts:S.attempts,delayMs:W,error:E}),S.onRetry(E,C,W),await Y(W);continue}S.attempts>1&&l({type:"step_retries_exhausted",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:performance.now()-R,attempts:C,lastError:E})}if(C<S.attempts&&S.retryOn(E,C)){let A=X(C,S);l({type:"step_retry",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),attempt:C+1,maxAttempts:S.attempts,delayMs:A,error:E}),S.onRetry(E,C,A),await Y(A);continue}S.attempts>1&&!G(E)&&l({type:"step_retries_exhausted",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:performance.now()-R,attempts:C,lastError:E});let F=performance.now()-R;if(w){let A;try{A=w(E)}catch(L){throw ie(L)}throw l({type:"step_error",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:F,error:A}),a&&l({type:"step_complete",workflowId:o,stepKey:a,name:s,ts:Date.now(),durationMs:F,result:T(A,{cause:E}),meta:{origin:"throw",thrown:E}}),n?.(A,s),M(A,{origin:"throw",thrown:E})}else{let A={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:E}};throw l({type:"step_error",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:F,error:A}),a&&l({type:"step_complete",workflowId:o,stepKey:a,name:s,ts:Date.now(),durationMs:F,result:T(A,{cause:E}),meta:{origin:"throw",thrown:E}}),E}}}let I=J,$=performance.now()-R,ne=V(I.error,{origin:"result",resultCause:I.cause});throw l({type:"step_error",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:$,error:ne}),a&&l({type:"step_complete",workflowId:o,stepKey:a,name:s,ts:Date.now(),durationMs:$,result:I,meta:{origin:"result",resultCause:I.cause}}),n?.(I.error,s),M(I.error,{origin:"result",resultCause:I.cause})})();r.try=(m,i)=>{let y=i.name,s=i.key,a=N(s),d="error"in i?()=>i.error:i.onError,c=u;return(async()=>{let p=c?performance.now():0;u&&l({type:"step_start",workflowId:o,stepId:a,stepKey:s,name:y,ts:Date.now()});try{let f=await m(),R=performance.now()-p;return l({type:"step_success",workflowId:o,stepId:a,stepKey:s,name:y,ts:Date.now(),durationMs:R}),s&&l({type:"step_complete",workflowId:o,stepKey:s,name:y,ts:Date.now(),durationMs:R,result:P(f)}),f}catch(f){let R=d(f),O=performance.now()-p,j=V(R,{origin:"throw",thrown:f});throw l({type:"step_error",workflowId:o,stepId:a,stepKey:s,name:y,ts:Date.now(),durationMs:O,error:j}),s&&l({type:"step_complete",workflowId:o,stepKey:s,name:y,ts:Date.now(),durationMs:O,result:T(R,{cause:f}),meta:{origin:"throw",thrown:f}}),n?.(R,y),M(R,{origin:"throw",thrown:f})}})()},r.fromResult=(m,i)=>{let y=i.name,s=i.key,a=N(s),d="error"in i?()=>i.error:i.onError,c=u;return(async()=>{let p=c?performance.now():0;u&&l({type:"step_start",workflowId:o,stepId:a,stepKey:s,name:y,ts:Date.now()});let f=await m();if(f.ok){let R=performance.now()-p;return l({type:"step_success",workflowId:o,stepId:a,stepKey:s,name:y,ts:Date.now(),durationMs:R}),s&&l({type:"step_complete",workflowId:o,stepKey:s,name:y,ts:Date.now(),durationMs:R,result:P(f.value)}),f.value}else{let R=d(f.error),O=performance.now()-p,j=V(R,{origin:"result",resultCause:f.error});throw l({type:"step_error",workflowId:o,stepId:a,stepKey:s,name:y,ts:Date.now(),durationMs:O,error:j}),s&&l({type:"step_complete",workflowId:o,stepKey:s,name:y,ts:Date.now(),durationMs:O,result:T(R,{cause:f.error}),meta:{origin:"result",resultCause:f.error}}),n?.(R,y),M(R,{origin:"result",resultCause:f.error})}})()},r.retry=(m,i)=>r(m,{name:i.name,key:i.key,retry:{attempts:i.attempts,backoff:i.backoff,initialDelay:i.initialDelay,maxDelay:i.maxDelay,jitter:i.jitter,retryOn:i.retryOn,onRetry:i.onRetry},timeout:i.timeout}),r.withTimeout=(m,i)=>r(m,{name:i.name,key:i.key,timeout:i}),r.parallel=(m,i)=>{let y=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),a=!1;x.push({scopeId:y,type:"parallel"});let d=()=>{if(a)return;a=!0;let c=x.findIndex(p=>p.scopeId===y);c!==-1&&x.splice(c,1),l({type:"scope_end",workflowId:o,scopeId:y,ts:Date.now(),durationMs:performance.now()-s})};l({type:"scope_start",workflowId:o,scopeId:y,scopeType:"parallel",name:m,ts:Date.now()});try{let c=await i();if(d(),!c.ok)throw n?.(c.error,m),M(c.error,{origin:"result",resultCause:c.cause});return c.value}catch(c){throw d(),c}})()},r.race=(m,i)=>{let y=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),a=!1,d={scopeId:y,type:"race",winnerId:void 0};x.push(d);let c=()=>{if(a)return;a=!0;let p=x.findIndex(f=>f.scopeId===y);p!==-1&&x.splice(p,1),l({type:"scope_end",workflowId:o,scopeId:y,ts:Date.now(),durationMs:performance.now()-s,winnerId:d.winnerId})};l({type:"scope_start",workflowId:o,scopeId:y,scopeType:"race",name:m,ts:Date.now()});try{let p=await i();if(c(),!p.ok)throw n?.(p.error,m),M(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw c(),p}})()},r.allSettled=(m,i)=>{let y=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),a=!1;x.push({scopeId:y,type:"allSettled"});let d=()=>{if(a)return;a=!0;let c=x.findIndex(p=>p.scopeId===y);c!==-1&&x.splice(c,1),l({type:"scope_end",workflowId:o,scopeId:y,ts:Date.now(),durationMs:performance.now()-s})};l({type:"scope_start",workflowId:o,scopeId:y,scopeType:"allSettled",name:m,ts:Date.now()});try{let c=await i();if(d(),!c.ok)throw n?.(c.error,m),M(c.error,{origin:"result",resultCause:c.cause});return c.value}catch(c){throw d(),c}})()};let b=await e(r);return P(b)}catch(r){if(pe(r))throw r.thrown;if(q(r)){let b=ee(r.meta);if(w||n)return T(r.error,{cause:b});if(oe(r.error))return T(r.error,{cause:b});let m=te(r);return T(m,{cause:b})}if(w){let b=w(r);return n?.(b,"unexpected"),T(b,{cause:r})}let h={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:r}};return n?.(h,"unexpected"),T(h,{cause:r})}}z.strict=(e,t)=>z(e,t);var B=class extends Error{constructor(n,u){super(`Unwrap called on an error result: ${String(n)}`);this.error=n;this.cause=u;this.name="UnwrapError"}},me=e=>{if(e.ok)return e.value;throw new B(e.error,e.cause)},we=(e,t)=>e.ok?e.value:t,Te=(e,t)=>e.ok?e.value:t(e.error,e.cause);function ke(e,t){try{return P(e())}catch(n){return t?T(t(n),{cause:n}):T(n)}}async function de(e,t){try{return P(await e)}catch(n){return t?T(t(n),{cause:n}):T(n)}}async function fe(e,t){try{return P(await e())}catch(n){return t?T(t(n),{cause:n}):T(n)}}function Re(e,t){return e!=null?P(e):T(t())}function Ce(e,t){return e.ok?P(t(e.value)):e}function xe(e,t){return e.ok?e:T(t(e.error),{cause:e.cause})}function Se(e,t){return e.ok?t.ok(e.value):t.err(e.error,e.cause)}function ge(e,t){return e.ok?t(e.value):e}function Ae(e,t){return e.ok&&t(e.value),e}function Pe(e,t){return e.ok||t(e.error,e.cause),e}function be(e,t,n){if(!e.ok)return e;try{return P(t(e.value))}catch(u){return T(n(u),{cause:u})}}function he(e,t,n){if(e.ok)return e;try{return T(t(e.error),{cause:e.cause})}catch(u){return T(n(u),{cause:u})}}function ve(e){let t=[];for(let n of e){if(!n.ok)return n;t.push(n.value)}return P(t)}async function _e(e){return e.length===0?P([]):new Promise(t=>{let n=!1,u=e.length,w=new Array(e.length);for(let g=0;g<e.length;g++){let k=g;Promise.resolve(e[k]).catch(o=>T({type:"PROMISE_REJECTED",cause:o},{cause:{type:"PROMISE_REJECTION",reason:o}})).then(o=>{if(!n){if(!o.ok){n=!0,t(o);return}w[k]=o.value,u--,u===0&&t(P(w))}})}})}function Me(e){let t=[],n=[];for(let u of e)u.ok?t.push(u.value):n.push({error:u.error,cause:u.cause});return n.length>0?T(n):P(t)}function Ie(e){let t=[],n=[];for(let u of e)u.ok?t.push(u.value):n.push(u.error);return{values:t,errors:n}}function Oe(e){if(e.length===0)return T({type:"EMPTY_INPUT",message:"any() requires at least one Result"});let t=null;for(let n of e){if(n.ok)return n;t||(t=n)}return t}async function Ue(e){return e.length===0?T({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(t=>{let n=!1,u=e.length,w=null;for(let g of e)Promise.resolve(g).catch(k=>T({type:"PROMISE_REJECTED",cause:k},{cause:{type:"PROMISE_REJECTION",reason:k}})).then(k=>{if(!n){if(k.ok){n=!0,t(k);return}w||(w=k),u--,u===0&&t(w)}})})}async function De(e){let t=await Promise.all(e.map(w=>Promise.resolve(w).then(g=>({status:"result",result:g})).catch(g=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:g},cause:{type:"PROMISE_REJECTION",reason:g}})))),n=[],u=[];for(let w of t)w.status==="rejected"?u.push({error:w.error,cause:w.cause}):w.result.ok?n.push(w.result.value):u.push({error:w.result.error,cause:w.result.cause});return u.length>0?T(u):P(n)}export{Q as EARLY_EXIT_SYMBOL,D as STEP_TIMEOUT_MARKER,B as UnwrapError,ve as all,_e as allAsync,Me as allSettled,De as allSettledAsync,ge as andThen,Oe as any,Ue as anyAsync,ue as createEarlyExit,T as err,ke as from,Re as fromNullable,de as fromPromise,se as getStepTimeoutMeta,ae as isEarlyExit,ye as isErr,Ee as isOk,G as isStepTimeoutError,oe as isUnexpectedError,Ce as map,xe as mapError,he as mapErrorTry,be as mapTry,Se as match,P as ok,Ie as partition,z as run,Ae as tap,Pe as tapError,fe as tryAsync,me as unwrap,we as unwrapOr,Te as unwrapOrElse};
2
2
  //# sourceMappingURL=core.js.map