@jagreehal/workflow 1.6.0 → 1.8.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.ts CHANGED
@@ -463,23 +463,37 @@ interface RunStep<E = unknown> {
463
463
  key?: string;
464
464
  }) => Promise<T>;
465
465
  /**
466
- * Execute a parallel operation (allAsync) with scope events for visualization.
466
+ * Execute parallel operations with scope events for visualization.
467
467
  *
468
- * This wraps the operation with scope_start and scope_end events, enabling
468
+ * This wraps the operations with scope_start and scope_end events, enabling
469
469
  * visualization of parallel execution branches.
470
470
  *
471
- * @param name - Name for this parallel block (used in visualization)
472
- * @param operation - A function that returns a Result from allAsync or allSettledAsync
473
- * @returns The success value (unwrapped array)
471
+ * @overload Named object form - returns typed object with named results
472
+ * @overload Array form - wraps allAsync result with scope events
474
473
  *
475
- * @example
474
+ * @example Named object form
475
+ * ```typescript
476
+ * const { user, posts } = await step.parallel({
477
+ * user: () => fetchUser(id),
478
+ * posts: () => fetchPosts(id),
479
+ * }, { name: 'Fetch user data' });
480
+ * ```
481
+ *
482
+ * @example Array form
476
483
  * ```typescript
477
484
  * const [user, posts] = await step.parallel('Fetch all data', () =>
478
485
  * allAsync([fetchUser(id), fetchPosts(id)])
479
486
  * );
480
487
  * ```
481
488
  */
482
- parallel: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
489
+ parallel: {
490
+ <TOperations extends Record<string, () => MaybeAsyncResult<unknown, E, unknown>>>(operations: TOperations, options?: {
491
+ name?: string;
492
+ }): Promise<{
493
+ [K in keyof TOperations]: TOperations[K] extends () => MaybeAsyncResult<infer V, E, unknown> ? V : never;
494
+ }>;
495
+ <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>): Promise<T[]>;
496
+ };
483
497
  /**
484
498
  * Execute a race operation (anyAsync) with scope events for visualization.
485
499
  *
@@ -596,21 +610,24 @@ interface RunStep<E = unknown> {
596
610
  * Scope types for parallel and race operations.
597
611
  */
598
612
  type ScopeType = "parallel" | "race" | "allSettled";
599
- type WorkflowEvent<E> = {
613
+ type WorkflowEvent<E, C = unknown> = {
600
614
  type: "workflow_start";
601
615
  workflowId: string;
602
616
  ts: number;
617
+ context?: C;
603
618
  } | {
604
619
  type: "workflow_success";
605
620
  workflowId: string;
606
621
  ts: number;
607
622
  durationMs: number;
623
+ context?: C;
608
624
  } | {
609
625
  type: "workflow_error";
610
626
  workflowId: string;
611
627
  ts: number;
612
628
  durationMs: number;
613
629
  error: E;
630
+ context?: C;
614
631
  } | {
615
632
  type: "step_start";
616
633
  workflowId: string;
@@ -618,6 +635,7 @@ type WorkflowEvent<E> = {
618
635
  stepKey?: string;
619
636
  name?: string;
620
637
  ts: number;
638
+ context?: C;
621
639
  } | {
622
640
  type: "step_success";
623
641
  workflowId: string;
@@ -626,6 +644,7 @@ type WorkflowEvent<E> = {
626
644
  name?: string;
627
645
  ts: number;
628
646
  durationMs: number;
647
+ context?: C;
629
648
  } | {
630
649
  type: "step_error";
631
650
  workflowId: string;
@@ -635,6 +654,7 @@ type WorkflowEvent<E> = {
635
654
  ts: number;
636
655
  durationMs: number;
637
656
  error: E;
657
+ context?: C;
638
658
  } | {
639
659
  type: "step_aborted";
640
660
  workflowId: string;
@@ -643,6 +663,7 @@ type WorkflowEvent<E> = {
643
663
  name?: string;
644
664
  ts: number;
645
665
  durationMs: number;
666
+ context?: C;
646
667
  } | {
647
668
  type: "step_complete";
648
669
  workflowId: string;
@@ -652,18 +673,21 @@ type WorkflowEvent<E> = {
652
673
  durationMs: number;
653
674
  result: Result<unknown, unknown, unknown>;
654
675
  meta?: StepFailureMeta;
676
+ context?: C;
655
677
  } | {
656
678
  type: "step_cache_hit";
657
679
  workflowId: string;
658
680
  stepKey: string;
659
681
  name?: string;
660
682
  ts: number;
683
+ context?: C;
661
684
  } | {
662
685
  type: "step_cache_miss";
663
686
  workflowId: string;
664
687
  stepKey: string;
665
688
  name?: string;
666
689
  ts: number;
690
+ context?: C;
667
691
  } | {
668
692
  type: "step_skipped";
669
693
  workflowId: string;
@@ -672,6 +696,7 @@ type WorkflowEvent<E> = {
672
696
  reason?: string;
673
697
  decisionId?: string;
674
698
  ts: number;
699
+ context?: C;
675
700
  } | {
676
701
  type: "scope_start";
677
702
  workflowId: string;
@@ -679,6 +704,7 @@ type WorkflowEvent<E> = {
679
704
  scopeType: ScopeType;
680
705
  name?: string;
681
706
  ts: number;
707
+ context?: C;
682
708
  } | {
683
709
  type: "scope_end";
684
710
  workflowId: string;
@@ -686,6 +712,7 @@ type WorkflowEvent<E> = {
686
712
  ts: number;
687
713
  durationMs: number;
688
714
  winnerId?: string;
715
+ context?: C;
689
716
  } | {
690
717
  type: "step_retry";
691
718
  workflowId: string;
@@ -697,6 +724,7 @@ type WorkflowEvent<E> = {
697
724
  maxAttempts: number;
698
725
  delayMs: number;
699
726
  error: E;
727
+ context?: C;
700
728
  } | {
701
729
  type: "step_retries_exhausted";
702
730
  workflowId: string;
@@ -707,6 +735,7 @@ type WorkflowEvent<E> = {
707
735
  durationMs: number;
708
736
  attempts: number;
709
737
  lastError: E;
738
+ context?: C;
710
739
  } | {
711
740
  type: "step_timeout";
712
741
  workflowId: string;
@@ -716,18 +745,67 @@ type WorkflowEvent<E> = {
716
745
  ts: number;
717
746
  timeoutMs: number;
718
747
  attempt?: number;
748
+ context?: C;
749
+ } | {
750
+ type: "hook_should_run";
751
+ workflowId: string;
752
+ ts: number;
753
+ durationMs: number;
754
+ result: boolean;
755
+ skipped: boolean;
756
+ context?: C;
757
+ } | {
758
+ type: "hook_should_run_error";
759
+ workflowId: string;
760
+ ts: number;
761
+ durationMs: number;
762
+ error: E;
763
+ context?: C;
764
+ } | {
765
+ type: "hook_before_start";
766
+ workflowId: string;
767
+ ts: number;
768
+ durationMs: number;
769
+ result: boolean;
770
+ skipped: boolean;
771
+ context?: C;
772
+ } | {
773
+ type: "hook_before_start_error";
774
+ workflowId: string;
775
+ ts: number;
776
+ durationMs: number;
777
+ error: E;
778
+ context?: C;
779
+ } | {
780
+ type: "hook_after_step";
781
+ workflowId: string;
782
+ stepKey: string;
783
+ ts: number;
784
+ durationMs: number;
785
+ context?: C;
786
+ } | {
787
+ type: "hook_after_step_error";
788
+ workflowId: string;
789
+ stepKey: string;
790
+ ts: number;
791
+ durationMs: number;
792
+ error: E;
793
+ context?: C;
719
794
  };
720
795
  type RunOptionsWithCatch<E, C = void> = {
721
796
  /**
722
797
  * Handler for expected errors.
723
798
  * Called when a step fails with a known error type.
724
799
  */
725
- onError?: (error: E, stepName?: string) => void;
800
+ onError?: (error: E, stepName?: string, ctx?: C) => void;
726
801
  /**
727
802
  * Listener for workflow events (start, success, error, step events).
728
803
  * Use this for logging, telemetry, or debugging.
804
+ *
805
+ * Context is automatically included in `event.context` when provided via the `context` option.
806
+ * The separate `ctx` parameter is provided for convenience.
729
807
  */
730
- onEvent?: (event: WorkflowEvent<E | UnexpectedError>, ctx: C) => void;
808
+ onEvent?: (event: WorkflowEvent<E | UnexpectedError, C>, ctx: C) => void;
731
809
  /**
732
810
  * Catch-all mapper for unexpected exceptions.
733
811
  * Required for "Strict Mode".
@@ -741,7 +819,7 @@ type RunOptionsWithCatch<E, C = void> = {
741
819
  */
742
820
  workflowId?: string;
743
821
  /**
744
- * Arbitrary context object passed to onEvent.
822
+ * Arbitrary context object passed to onEvent and onError.
745
823
  * Useful for passing request IDs, user IDs, or loggers.
746
824
  */
747
825
  context?: C;
@@ -751,8 +829,14 @@ type RunOptionsWithoutCatch<E, C = void> = {
751
829
  * Handler for expected errors AND unexpected errors.
752
830
  * Unexpected errors will be wrapped in `UnexpectedError`.
753
831
  */
754
- onError?: (error: E | UnexpectedError, stepName?: string) => void;
755
- onEvent?: (event: WorkflowEvent<E | UnexpectedError>, ctx: C) => void;
832
+ onError?: (error: E | UnexpectedError, stepName?: string, ctx?: C) => void;
833
+ /**
834
+ * Listener for workflow events (start, success, error, step events).
835
+ *
836
+ * Note: Context is available both on `event.context` and as the separate `ctx` parameter.
837
+ * The `ctx` parameter is provided for convenience and backward compatibility.
838
+ */
839
+ onEvent?: (event: WorkflowEvent<E | UnexpectedError, C>, ctx: C) => void;
756
840
  catchUnexpected?: undefined;
757
841
  workflowId?: string;
758
842
  context?: C;
@@ -862,8 +946,8 @@ declare function run<T, E, C = void>(fn: (step: RunStep<E>) => Promise<T> | T, o
862
946
  * @returns A Promise resolving to `Result<T, E | UnexpectedError>`
863
947
  */
864
948
  declare function run<T, E, C = void>(fn: (step: RunStep<E | UnexpectedError>) => Promise<T> | T, options: {
865
- onError: (error: E | UnexpectedError, stepName?: string) => void;
866
- onEvent?: (event: WorkflowEvent<E | UnexpectedError>, ctx: C) => void;
949
+ onError: (error: E | UnexpectedError, stepName?: string, ctx?: C) => void;
950
+ onEvent?: (event: WorkflowEvent<E | UnexpectedError, C>, ctx: C) => void;
867
951
  workflowId?: string;
868
952
  context?: C;
869
953
  }): AsyncResult<T, E | UnexpectedError, unknown>;
@@ -886,14 +970,20 @@ declare function run<T, E, C = void>(fn: (step: RunStep<E | UnexpectedError>) =>
886
970
  * ```
887
971
  */
888
972
  declare function run<T, C = void>(fn: (step: RunStep) => Promise<T> | T, options?: {
889
- onEvent?: (event: WorkflowEvent<UnexpectedError>, ctx: C) => void;
973
+ onEvent?: (event: WorkflowEvent<UnexpectedError, C>, ctx: C) => void;
890
974
  workflowId?: string;
891
975
  context?: C;
892
976
  }): AsyncResult<T, UnexpectedError, unknown>;
893
977
  declare namespace run {
894
978
  var strict: <T, E, C = void>(fn: (step: RunStep<E>) => Promise<T> | T, options: {
895
- onError?: (error: E, stepName?: string) => void;
896
- onEvent?: (event: WorkflowEvent<E | UnexpectedError>, ctx: C) => void;
979
+ onError?: (error: E, stepName?: string, ctx?: C) => void;
980
+ /**
981
+ * Listener for workflow events (start, success, error, step events).
982
+ *
983
+ * Note: Context is available both on `event.context` and as the separate `ctx` parameter.
984
+ * The `ctx` parameter is provided for convenience and backward compatibility.
985
+ */
986
+ onEvent?: (event: WorkflowEvent<E | UnexpectedError, C>, ctx: C) => void;
897
987
  catchUnexpected: (cause: unknown) => E;
898
988
  workflowId?: string;
899
989
  context?: C;
@@ -1783,6 +1873,55 @@ declare function recover<T, E, C>(r: Result<T, E, C>, fn: (error: E, cause?: C)
1783
1873
  * ```
1784
1874
  */
1785
1875
  declare function recoverAsync<T, E, C>(r: Result<T, E, C> | Promise<Result<T, E, C>>, fn: (error: E, cause?: C) => T | Promise<T>): Promise<Result<T, never, never>>;
1876
+ /**
1877
+ * Validates and type-narrows a value to a Result.
1878
+ *
1879
+ * Since this library uses plain objects for Results, serialization is trivial -
1880
+ * the serialized form IS the Result. This function validates the structure and
1881
+ * provides type-safe narrowing.
1882
+ *
1883
+ * ## When to Use
1884
+ *
1885
+ * Use `hydrate()` when:
1886
+ * - Receiving Results over RPC/network
1887
+ * - Deserializing Results from storage
1888
+ * - Validating untrusted data as Results
1889
+ *
1890
+ * @param value - The unknown value to validate as a Result
1891
+ * @returns The value as a typed Result, or null if invalid
1892
+ *
1893
+ * @example
1894
+ * ```typescript
1895
+ * // Deserialize from JSON
1896
+ * const parsed = JSON.parse(jsonString);
1897
+ * const result = hydrate<User, ApiError>(parsed);
1898
+ * if (result) {
1899
+ * // result is Result<User, ApiError>
1900
+ * }
1901
+ *
1902
+ * // Validate RPC response
1903
+ * const rpcResponse = await fetchFromService();
1904
+ * const result = hydrate<Data, ServiceError>(rpcResponse);
1905
+ * ```
1906
+ */
1907
+ declare function hydrate<T, E, C = unknown>(value: unknown): Result<T, E, C> | null;
1908
+ /**
1909
+ * Type guard to check if a value is a valid serialized Result.
1910
+ *
1911
+ * @param value - The value to check
1912
+ * @returns True if the value is a valid Result structure
1913
+ *
1914
+ * @example
1915
+ * ```typescript
1916
+ * if (isSerializedResult(data)) {
1917
+ * // data is Result<unknown, unknown, unknown>
1918
+ * if (data.ok) {
1919
+ * console.log(data.value);
1920
+ * }
1921
+ * }
1922
+ * ```
1923
+ */
1924
+ declare function isSerializedResult(value: unknown): value is Result<unknown, unknown, unknown>;
1786
1925
  type AllValues<T extends readonly Result<unknown, unknown, unknown>[]> = {
1787
1926
  [K in keyof T]: T[K] extends Result<infer V, unknown, unknown> ? V : never;
1788
1927
  };
@@ -2170,4 +2309,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
2170
2309
  */
2171
2310
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
2172
2311
 
2173
- 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, bimap, createEarlyExit, err, from, fromNullable, fromPromise, getStepTimeoutMeta, isEarlyExit, isErr, isOk, isStepTimeoutError, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, orElse, orElseAsync, partition, recover, recoverAsync, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
2312
+ 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, bimap, createEarlyExit, err, from, fromNullable, fromPromise, getStepTimeoutMeta, hydrate, isEarlyExit, isErr, isOk, isSerializedResult, isStepTimeoutError, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, orElse, orElseAsync, partition, recover, recoverAsync, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- var g=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:A}=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),A){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},A,k=new Promise((h,x)=>{A=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(h){if(typeof h=="object"&&h!==null&&h[H]===!0){let x=h.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 h}finally{clearTimeout(A)}}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:A,context:k}=t&&typeof t=="object"?t:{},o=A??crypto.randomUUID(),h=!n&&!w,x=[],K=0,N=r=>r??`step_${++K}`,l=r=>{if(r.type==="step_success"){let b=r.stepId;for(let v=x.length-1;v>=0;v--){let m=x[v];if(m.type==="race"&&!m.winnerId){m.winnerId=b;break}}}u?.(r,k)},M=ue,q=r=>ae(r),V=(r,b)=>h?b?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r,...b.resultCause!==void 0?{cause:b.resultCause}:{}}}:b?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:r,thrown:b.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 P=se(E),L=c?.ms??P?.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 P=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:P,error:E}),S.onRetry(E,C,P),await Y(P);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 j=performance.now()-R;if(w){let P;try{P=w(E)}catch(L){throw ie(L)}throw l({type:"step_error",workflowId:o,stepId:p,stepKey:a,name:s,ts:Date.now(),durationMs:j,error:P}),a&&l({type:"step_complete",workflowId:o,stepKey:a,name:s,ts:Date.now(),durationMs:j,result:T(P,{cause:E}),meta:{origin:"throw",thrown:E}}),n?.(P,s),M(P,{origin:"throw",thrown:E})}else{let P={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:j,error:P}),a&&l({type:"step_complete",workflowId:o,stepKey:a,name:s,ts:Date.now(),durationMs:j,result:T(P,{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:g(f)}),f}catch(f){let R=d(f),O=performance.now()-p,F=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:F}),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:g(f.value)}),f.value}else{let R=d(f.error),O=performance.now()-p,F=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:F}),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 v=await e(r);return g(v)}catch(r){if(pe(r))throw r.thrown;if(q(r)){let v=ee(r.meta);if(w||n)return T(r.error,{cause:v});if(oe(r.error))return T(r.error,{cause:v});let m=te(r);return T(m,{cause:v})}if(w){let v=w(r);return n?.(v,"unexpected"),T(v,{cause:r})}let b={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:r}};return n?.(b,"unexpected"),T(b,{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 g(e())}catch(n){return t?T(t(n),{cause:n}):T(n)}}async function de(e,t){try{return g(await e)}catch(n){return t?T(t(n),{cause:n}):T(n)}}async function fe(e,t){try{return g(await e())}catch(n){return t?T(t(n),{cause:n}):T(n)}}function Re(e,t){return e!=null?g(e):T(t())}function Ce(e,t){return e.ok?g(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 ve(e,t,n){if(!e.ok)return e;try{return g(t(e.value))}catch(u){return T(n(u),{cause:u})}}function be(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 he(e,t,n){return e.ok?g(t(e.value)):T(n(e.error),{cause:e.cause})}function _e(e,t){return e.ok?e:t(e.error,e.cause)}async function Me(e,t){let n=await e;return n.ok?n:t(n.error,n.cause)}function Ie(e,t){return e.ok?g(e.value):g(t(e.error,e.cause))}async function Oe(e,t){let n=await e;return n.ok?g(n.value):g(await t(n.error,n.cause))}function Ue(e){let t=[];for(let n of e){if(!n.ok)return n;t.push(n.value)}return g(t)}async function De(e){return e.length===0?g([]):new Promise(t=>{let n=!1,u=e.length,w=new Array(e.length);for(let A=0;A<e.length;A++){let k=A;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(g(w))}})}})}function Ke(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):g(t)}function Fe(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 je(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 Ne(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 A of e)Promise.resolve(A).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 Ve(e){let t=await Promise.all(e.map(w=>Promise.resolve(w).then(A=>({status:"result",result:A})).catch(A=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:A},cause:{type:"PROMISE_REJECTION",reason:A}})))),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):g(n)}export{Q as EARLY_EXIT_SYMBOL,D as STEP_TIMEOUT_MARKER,B as UnwrapError,Ue as all,De as allAsync,Ke as allSettled,Ve as allSettledAsync,ge as andThen,je as any,Ne as anyAsync,he as bimap,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,be as mapErrorTry,ve as mapTry,Se as match,g as ok,_e as orElse,Me as orElseAsync,Fe as partition,Ie as recover,Oe as recoverAsync,z as run,Ae as tap,Pe as tapError,fe as tryAsync,me as unwrap,we as unwrapOr,Te as unwrapOrElse};
1
+ var g=e=>({ok:!0,value:e}),d=(e,t)=>({ok:!1,error:e,...t?.cause!==void 0?{cause:t.cause}:{}}),ke=e=>e.ok,de=e=>!e.ok,ue=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",F=Symbol.for("step_timeout_marker");function Q(e){return typeof e!="object"||e===null?!1:e.type==="STEP_TIMEOUT"?!0:F in e}function ae(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(F in e)return e[F]}}var te=Symbol("early-exit");function ie(e,t){return{[te]:!0,error:e,meta:t}}function pe(e){return typeof e=="object"&&e!==null&&e[te]===!0}var ne=Symbol("mapper-exception");function le(e){return{[ne]:!0,thrown:e}}function ce(e){return typeof e=="object"&&e!==null&&e[ne]===!0}function Ee(e){return typeof e=="string"?{name:e}:e??{}}function q(e,t){let{backoff:n,initialDelay:a,maxDelay:f,jitter:A}=t,E;switch(n){case"fixed":E=a;break;case"linear":E=a*e;break;case"exponential":E=a*Math.pow(2,e-1);break}if(E=Math.min(E,f),A){let r=E*.25*Math.random();E=E+r}return Math.floor(E)}function G(e){return new Promise(t=>setTimeout(t,e))}var Z=Symbol("timeout");async function ye(e,t,n){let a=new AbortController,f=t.error??{type:"STEP_TIMEOUT",stepName:n.name,stepKey:n.key,timeoutMs:t.ms,attempt:n.attempt},A,E=new Promise((I,C)=>{A=setTimeout(()=>{a.abort(),C({[Z]:!0,error:f})},t.ms)}),r;t.signal?r=Promise.resolve(e(a.signal)):r=Promise.resolve(e());try{return await Promise.race([r,E])}catch(I){if(typeof I=="object"&&I!==null&&I[Z]===!0){let C=I.error;if(typeof C=="object"&&C!==null&&C.type!=="STEP_TIMEOUT"){let L={timeoutMs:t.ms,stepName:n.name,stepKey:n.key,attempt:n.attempt};F in C?C[F]=L:Object.defineProperty(C,F,{value:L,enumerable:!1,writable:!0,configurable:!1})}throw C}throw I}finally{clearTimeout(A)}}var j={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,retryOn:()=>!0,onRetry:()=>{}};async function ee(e,t){let{onError:n,onEvent:a,catchUnexpected:f,workflowId:A,context:E}=t&&typeof t=="object"?t:{},r=A??crypto.randomUUID(),I=!n&&!f,C=[],L=0,X=o=>o??`step_${++L}`,y=o=>{let b=o.context!==void 0||E===void 0?o:{...o,context:E};if(b.type==="step_success"){let M=b.stepId;for(let D=C.length-1;D>=0;D--){let N=C[D];if(N.type==="race"&&!N.winnerId){N.winnerId=M;break}}}a?.(b,E)},O=ie,z=o=>pe(o),Y=(o,b)=>I?b?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:o,...b.resultCause!==void 0?{cause:b.resultCause}:{}}}:b?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:o,thrown:b.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:o}}:o,re=o=>o.origin==="result"?o.resultCause:o.thrown,oe=o=>({type:"UNEXPECTED_ERROR",cause:o.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:o.error,...o.meta.resultCause!==void 0?{cause:o.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:o.error,thrown:o.meta.thrown}});try{let b=function(m,p){let i=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),u=!1;C.push({scopeId:i,type:"parallel"});let x=()=>{if(u)return;u=!0;let c=C.findIndex(l=>l.scopeId===i);c!==-1&&C.splice(c,1),y({type:"scope_end",workflowId:r,scopeId:i,ts:Date.now(),durationMs:performance.now()-s})};y({type:"scope_start",workflowId:r,scopeId:i,scopeType:"parallel",name:m,ts:Date.now()});try{let c=await p();if(x(),!c.ok)throw n?.(c.error,m,E),O(c.error,{origin:"result",resultCause:c.cause});return c.value}catch(c){throw x(),c}})()},M=function(m,p){let i=Object.keys(m),s=p.name??`Parallel(${i.join(", ")})`,u=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let x=performance.now(),c=!1;C.push({scopeId:u,type:"parallel"});let l=()=>{if(c)return;c=!0;let T=C.findIndex(R=>R.scopeId===u);T!==-1&&C.splice(T,1),y({type:"scope_end",workflowId:r,scopeId:u,ts:Date.now(),durationMs:performance.now()-x})};y({type:"scope_start",workflowId:r,scopeId:u,scopeType:"parallel",name:s,ts:Date.now()});try{let T=await new Promise(h=>{if(i.length===0){h([]);return}let _=!1,S=i.length,V=new Array(i.length);for(let v=0;v<i.length;v++){let K=i[v],$=v;Promise.resolve(m[K]()).catch(k=>d({type:"PROMISE_REJECTED",cause:k},{cause:{type:"PROMISE_REJECTION",reason:k}})).then(k=>{if(!_){if(!k.ok){_=!0,h([{key:K,result:k}]);return}V[$]={key:K,result:k},S--,S===0&&h(V)}})}});l();let R={};for(let{key:h,result:_}of T){if(!_.ok)throw n?.(_.error,h,E),O(_.error,{origin:"result",resultCause:_.cause});R[h]=_.value}return R}catch(T){throw l(),T}})()};var me=b,Te=M;let o=(m,p)=>(async()=>{let i=Ee(p),{name:s,key:u,retry:x,timeout:c}=i,l=X(u),T=a,R=T?performance.now():0;if(!(typeof m=="function")){if(x&&x.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,x?.attempts??1),backoff:x?.backoff??j.backoff,initialDelay:x?.initialDelay??j.initialDelay,maxDelay:x?.maxDelay??j.maxDelay,jitter:x?.jitter??j.jitter,retryOn:x?.retryOn??j.retryOn,onRetry:x?.onRetry??j.onRetry};a&&y({type:"step_start",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now()});let V;for(let k=1;k<=S.attempts;k++){let se=T?performance.now():0;try{let w;if(typeof m=="function"?c?w=await ye(m,c,{name:s,key:u,attempt:k}):w=await m():w=await m,w.ok){let U=performance.now()-R;return y({type:"step_success",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:U}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:s,ts:Date.now(),durationMs:U,result:w}),w.value}if(V=w,k<S.attempts&&S.retryOn(w.error,k)){let U=q(k,S);y({type:"step_retry",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),attempt:k+1,maxAttempts:S.attempts,delayMs:U,error:w.error}),S.onRetry(w.error,k,U),await G(U);continue}S.attempts>1&&y({type:"step_retries_exhausted",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:performance.now()-R,attempts:k,lastError:w.error});break}catch(w){let U=performance.now()-se;if(z(w))throw y({type:"step_aborted",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:U}),w;if(Q(w)){let P=ae(w),J=c?.ms??P?.timeoutMs??0;if(y({type:"step_timeout",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),timeoutMs:J,attempt:k}),k<S.attempts&&S.retryOn(w,k)){let B=q(k,S);y({type:"step_retry",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),attempt:k+1,maxAttempts:S.attempts,delayMs:B,error:w}),S.onRetry(w,k,B),await G(B);continue}S.attempts>1&&y({type:"step_retries_exhausted",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:performance.now()-R,attempts:k,lastError:w})}if(k<S.attempts&&S.retryOn(w,k)){let P=q(k,S);y({type:"step_retry",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),attempt:k+1,maxAttempts:S.attempts,delayMs:P,error:w}),S.onRetry(w,k,P),await G(P);continue}S.attempts>1&&!Q(w)&&y({type:"step_retries_exhausted",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:performance.now()-R,attempts:k,lastError:w});let W=performance.now()-R;if(f){let P;try{P=f(w)}catch(J){throw le(J)}throw y({type:"step_error",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:W,error:P}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:s,ts:Date.now(),durationMs:W,result:d(P,{cause:w}),meta:{origin:"throw",thrown:w}}),n?.(P,s,E),O(P,{origin:"throw",thrown:w})}else{let P={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:w}};throw y({type:"step_error",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:W,error:P}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:s,ts:Date.now(),durationMs:W,result:d(P,{cause:w}),meta:{origin:"throw",thrown:w}}),w}}}let v=V,K=performance.now()-R,$=Y(v.error,{origin:"result",resultCause:v.cause});throw y({type:"step_error",workflowId:r,stepId:l,stepKey:u,name:s,ts:Date.now(),durationMs:K,error:$}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:s,ts:Date.now(),durationMs:K,result:v,meta:{origin:"result",resultCause:v.cause}}),n?.(v.error,s,E),O(v.error,{origin:"result",resultCause:v.cause})})();o.try=(m,p)=>{let i=p.name,s=p.key,u=X(s),x="error"in p?()=>p.error:p.onError,c=a;return(async()=>{let l=c?performance.now():0;a&&y({type:"step_start",workflowId:r,stepId:u,stepKey:s,name:i,ts:Date.now()});try{let T=await m(),R=performance.now()-l;return y({type:"step_success",workflowId:r,stepId:u,stepKey:s,name:i,ts:Date.now(),durationMs:R}),s&&y({type:"step_complete",workflowId:r,stepKey:s,name:i,ts:Date.now(),durationMs:R,result:g(T)}),T}catch(T){let R=x(T),h=performance.now()-l,_=Y(R,{origin:"throw",thrown:T});throw y({type:"step_error",workflowId:r,stepId:u,stepKey:s,name:i,ts:Date.now(),durationMs:h,error:_}),s&&y({type:"step_complete",workflowId:r,stepKey:s,name:i,ts:Date.now(),durationMs:h,result:d(R,{cause:T}),meta:{origin:"throw",thrown:T}}),n?.(R,i,E),O(R,{origin:"throw",thrown:T})}})()},o.fromResult=(m,p)=>{let i=p.name,s=p.key,u=X(s),x="error"in p?()=>p.error:p.onError,c=a;return(async()=>{let l=c?performance.now():0;a&&y({type:"step_start",workflowId:r,stepId:u,stepKey:s,name:i,ts:Date.now()});let T=await m();if(T.ok){let R=performance.now()-l;return y({type:"step_success",workflowId:r,stepId:u,stepKey:s,name:i,ts:Date.now(),durationMs:R}),s&&y({type:"step_complete",workflowId:r,stepKey:s,name:i,ts:Date.now(),durationMs:R,result:g(T.value)}),T.value}else{let R=x(T.error),h=performance.now()-l,_=Y(R,{origin:"result",resultCause:T.error});throw y({type:"step_error",workflowId:r,stepId:u,stepKey:s,name:i,ts:Date.now(),durationMs:h,error:_}),s&&y({type:"step_complete",workflowId:r,stepKey:s,name:i,ts:Date.now(),durationMs:h,result:d(R,{cause:T.error}),meta:{origin:"result",resultCause:T.error}}),n?.(R,i,E),O(R,{origin:"result",resultCause:T.error})}})()},o.retry=(m,p)=>o(m,{name:p.name,key:p.key,retry:{attempts:p.attempts,backoff:p.backoff,initialDelay:p.initialDelay,maxDelay:p.maxDelay,jitter:p.jitter,retryOn:p.retryOn,onRetry:p.onRetry},timeout:p.timeout}),o.withTimeout=(m,p)=>o(m,{name:p.name,key:p.key,timeout:p}),o.parallel=((...m)=>{if(typeof m[0]=="string"){let p=m[0],i=m[1];return b(p,i)}else{let p=m[0],i=m[1]??{};return M(p,i)}}),o.race=(m,p)=>{let i=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),u=!1,x={scopeId:i,type:"race",winnerId:void 0};C.push(x);let c=()=>{if(u)return;u=!0;let l=C.findIndex(T=>T.scopeId===i);l!==-1&&C.splice(l,1),y({type:"scope_end",workflowId:r,scopeId:i,ts:Date.now(),durationMs:performance.now()-s,winnerId:x.winnerId})};y({type:"scope_start",workflowId:r,scopeId:i,scopeType:"race",name:m,ts:Date.now()});try{let l=await p();if(c(),!l.ok)throw n?.(l.error,m,E),O(l.error,{origin:"result",resultCause:l.cause});return l.value}catch(l){throw c(),l}})()},o.allSettled=(m,p)=>{let i=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),u=!1;C.push({scopeId:i,type:"allSettled"});let x=()=>{if(u)return;u=!0;let c=C.findIndex(l=>l.scopeId===i);c!==-1&&C.splice(c,1),y({type:"scope_end",workflowId:r,scopeId:i,ts:Date.now(),durationMs:performance.now()-s})};y({type:"scope_start",workflowId:r,scopeId:i,scopeType:"allSettled",name:m,ts:Date.now()});try{let c=await p();if(x(),!c.ok)throw n?.(c.error,m,E),O(c.error,{origin:"result",resultCause:c.cause});return c.value}catch(c){throw x(),c}})()};let N=await e(o);return g(N)}catch(o){if(ce(o))throw o.thrown;if(z(o)){let M=re(o.meta);if(f||n)return d(o.error,{cause:M});if(ue(o.error))return d(o.error,{cause:M});let D=oe(o);return d(D,{cause:M})}if(f){let M=f(o);return n?.(M,"unexpected",E),d(M,{cause:o})}let b={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:o}};return n?.(b,"unexpected",E),d(b,{cause:o})}}ee.strict=(e,t)=>ee(e,t);var H=class extends Error{constructor(n,a){super(`Unwrap called on an error result: ${String(n)}`);this.error=n;this.cause=a;this.name="UnwrapError"}},fe=e=>{if(e.ok)return e.value;throw new H(e.error,e.cause)},Re=(e,t)=>e.ok?e.value:t,Ce=(e,t)=>e.ok?e.value:t(e.error,e.cause);function xe(e,t){try{return g(e())}catch(n){return t?d(t(n),{cause:n}):d(n)}}async function Se(e,t){try{return g(await e)}catch(n){return t?d(t(n),{cause:n}):d(n)}}async function ge(e,t){try{return g(await e())}catch(n){return t?d(t(n),{cause:n}):d(n)}}function Ae(e,t){return e!=null?g(e):d(t())}function be(e,t){return e.ok?g(t(e.value)):e}function Pe(e,t){return e.ok?e:d(t(e.error),{cause:e.cause})}function he(e,t){return e.ok?t.ok(e.value):t.err(e.error,e.cause)}function _e(e,t){return e.ok?t(e.value):e}function ve(e,t){return e.ok&&t(e.value),e}function Me(e,t){return e.ok||t(e.error,e.cause),e}function Ie(e,t,n){if(!e.ok)return e;try{return g(t(e.value))}catch(a){return d(n(a),{cause:a})}}function Oe(e,t,n){if(e.ok)return e;try{return d(t(e.error),{cause:e.cause})}catch(a){return d(n(a),{cause:a})}}function Ue(e,t,n){return e.ok?g(t(e.value)):d(n(e.error),{cause:e.cause})}function De(e,t){return e.ok?e:t(e.error,e.cause)}async function Ke(e,t){let n=await e;return n.ok?n:t(n.error,n.cause)}function je(e,t){return e.ok?g(e.value):g(t(e.error,e.cause))}async function Fe(e,t){let n=await e;return n.ok?g(n.value):g(await t(n.error,n.cause))}function we(e){return e!==null&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&(e.ok===!0&&"value"in e||e.ok===!1&&"error"in e)?e:null}function Ne(e){return we(e)!==null}function Ve(e){let t=[];for(let n of e){if(!n.ok)return n;t.push(n.value)}return g(t)}async function Le(e){return e.length===0?g([]):new Promise(t=>{let n=!1,a=e.length,f=new Array(e.length);for(let A=0;A<e.length;A++){let E=A;Promise.resolve(e[E]).catch(r=>d({type:"PROMISE_REJECTED",cause:r},{cause:{type:"PROMISE_REJECTION",reason:r}})).then(r=>{if(!n){if(!r.ok){n=!0,t(r);return}f[E]=r.value,a--,a===0&&t(g(f))}})}})}function We(e){let t=[],n=[];for(let a of e)a.ok?t.push(a.value):n.push({error:a.error,cause:a.cause});return n.length>0?d(n):g(t)}function Xe(e){let t=[],n=[];for(let a of e)a.ok?t.push(a.value):n.push(a.error);return{values:t,errors:n}}function Ye(e){if(e.length===0)return d({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 $e(e){return e.length===0?d({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(t=>{let n=!1,a=e.length,f=null;for(let A of e)Promise.resolve(A).catch(E=>d({type:"PROMISE_REJECTED",cause:E},{cause:{type:"PROMISE_REJECTION",reason:E}})).then(E=>{if(!n){if(E.ok){n=!0,t(E);return}f||(f=E),a--,a===0&&t(f)}})})}async function Je(e){let t=await Promise.all(e.map(f=>Promise.resolve(f).then(A=>({status:"result",result:A})).catch(A=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:A},cause:{type:"PROMISE_REJECTION",reason:A}})))),n=[],a=[];for(let f of t)f.status==="rejected"?a.push({error:f.error,cause:f.cause}):f.result.ok?n.push(f.result.value):a.push({error:f.result.error,cause:f.result.cause});return a.length>0?d(a):g(n)}export{te as EARLY_EXIT_SYMBOL,F as STEP_TIMEOUT_MARKER,H as UnwrapError,Ve as all,Le as allAsync,We as allSettled,Je as allSettledAsync,_e as andThen,Ye as any,$e as anyAsync,Ue as bimap,ie as createEarlyExit,d as err,xe as from,Ae as fromNullable,Se as fromPromise,ae as getStepTimeoutMeta,we as hydrate,pe as isEarlyExit,de as isErr,ke as isOk,Ne as isSerializedResult,Q as isStepTimeoutError,ue as isUnexpectedError,be as map,Pe as mapError,Oe as mapErrorTry,Ie as mapTry,he as match,g as ok,De as orElse,Ke as orElseAsync,Xe as partition,je as recover,Fe as recoverAsync,ee as run,ve as tap,Me as tapError,ge as tryAsync,fe as unwrap,Re as unwrapOr,Ce as unwrapOrElse};
2
2
  //# sourceMappingURL=core.js.map