@jagreehal/workflow 1.8.0 → 1.10.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
@@ -10,6 +10,39 @@
10
10
  * 2. `run()` function for executing steps with standardized error management
11
11
  * 3. Utilities for transforming and combining Results
12
12
  */
13
+ /**
14
+ * Represents a successful result.
15
+ * Use `ok(value)` to create instances.
16
+ *
17
+ * @template T - The type of the success value
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const success = ok(42);
22
+ * // Type shown: Ok<number>
23
+ * ```
24
+ */
25
+ type Ok<T> = {
26
+ ok: true;
27
+ value: T;
28
+ };
29
+ /**
30
+ * Represents a failed result.
31
+ * Use `err(error)` to create instances.
32
+ *
33
+ * @template E - The type of the error value
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * const failure = err({ type: "NOT_FOUND", message: "User not found" });
38
+ * // Type shown: Err<{ type: string; message: string }>
39
+ * ```
40
+ */
41
+ type Err<E, C = unknown> = {
42
+ ok: false;
43
+ error: E;
44
+ cause?: C;
45
+ };
13
46
  /**
14
47
  * Represents a successful computation or a failed one.
15
48
  * Use this type to represent the outcome of an operation that might fail,
@@ -70,42 +103,41 @@ type MaybeAsyncResult<T, E, C = unknown> = Result<T, E, C> | Promise<Result<T, E
70
103
  * Use this when an operation completes successfully.
71
104
  *
72
105
  * @param value - The success value to wrap
73
- * @returns A Result object with `{ ok: true, value }`
106
+ * @returns An Ok object with `{ ok: true, value }`
74
107
  *
75
108
  * @example
76
109
  * ```typescript
110
+ * const success = ok(42);
111
+ * // Type: Ok<number>
112
+ *
77
113
  * function divide(a: number, b: number): Result<number, string> {
78
114
  * if (b === 0) return err("Division by zero");
79
115
  * return ok(a / b);
80
116
  * }
81
117
  * ```
82
118
  */
83
- declare const ok: <T>(value: T) => Result<T, never, never>;
119
+ declare const ok: <T>(value: T) => Ok<T>;
84
120
  /**
85
121
  * Creates a failed Result.
86
122
  * Use this when an operation fails.
87
123
  *
88
124
  * @param error - The error value describing what went wrong (e.g., error code, object)
89
- * @param options - Optional context about the failure
90
- * @param options.cause - The underlying cause of the error (e.g., a caught exception)
91
- * @returns A Result object with `{ ok: false, error }` (and optional cause)
125
+ * @returns An Err object with `{ ok: false, error }`
92
126
  *
93
127
  * @example
94
128
  * ```typescript
95
129
  * // Simple error
96
130
  * const r1 = err("NOT_FOUND");
131
+ * // Type: Err<"NOT_FOUND">
97
132
  *
98
- * // Error with cause (useful for wrapping exceptions)
99
- * try {
100
- * // ... unsafe code
101
- * } catch (e) {
102
- * return err("PROCESSING_FAILED", { cause: e });
103
- * }
133
+ * // Error with context (include in error object)
134
+ * const r2 = err({ type: "PROCESSING_FAILED", cause: originalError });
135
+ * // Type: Err<{ type: string; cause: Error }>
104
136
  * ```
105
137
  */
106
138
  declare const err: <E, C = unknown>(error: E, options?: {
107
139
  cause?: C;
108
- }) => Result<never, E, C>;
140
+ }) => Err<E, C>;
109
141
  /**
110
142
  * Checks if a Result is successful.
111
143
  * Use this to narrow the type of a Result to the success case.
@@ -2309,4 +2341,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
2309
2341
  */
2310
2342
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
2311
2343
 
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 };
2344
+ export { type AsyncResult, type BackoffStrategy, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type Err, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type Ok, 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.d.ts CHANGED
@@ -10,6 +10,39 @@
10
10
  * 2. `run()` function for executing steps with standardized error management
11
11
  * 3. Utilities for transforming and combining Results
12
12
  */
13
+ /**
14
+ * Represents a successful result.
15
+ * Use `ok(value)` to create instances.
16
+ *
17
+ * @template T - The type of the success value
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const success = ok(42);
22
+ * // Type shown: Ok<number>
23
+ * ```
24
+ */
25
+ type Ok<T> = {
26
+ ok: true;
27
+ value: T;
28
+ };
29
+ /**
30
+ * Represents a failed result.
31
+ * Use `err(error)` to create instances.
32
+ *
33
+ * @template E - The type of the error value
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * const failure = err({ type: "NOT_FOUND", message: "User not found" });
38
+ * // Type shown: Err<{ type: string; message: string }>
39
+ * ```
40
+ */
41
+ type Err<E, C = unknown> = {
42
+ ok: false;
43
+ error: E;
44
+ cause?: C;
45
+ };
13
46
  /**
14
47
  * Represents a successful computation or a failed one.
15
48
  * Use this type to represent the outcome of an operation that might fail,
@@ -70,42 +103,41 @@ type MaybeAsyncResult<T, E, C = unknown> = Result<T, E, C> | Promise<Result<T, E
70
103
  * Use this when an operation completes successfully.
71
104
  *
72
105
  * @param value - The success value to wrap
73
- * @returns A Result object with `{ ok: true, value }`
106
+ * @returns An Ok object with `{ ok: true, value }`
74
107
  *
75
108
  * @example
76
109
  * ```typescript
110
+ * const success = ok(42);
111
+ * // Type: Ok<number>
112
+ *
77
113
  * function divide(a: number, b: number): Result<number, string> {
78
114
  * if (b === 0) return err("Division by zero");
79
115
  * return ok(a / b);
80
116
  * }
81
117
  * ```
82
118
  */
83
- declare const ok: <T>(value: T) => Result<T, never, never>;
119
+ declare const ok: <T>(value: T) => Ok<T>;
84
120
  /**
85
121
  * Creates a failed Result.
86
122
  * Use this when an operation fails.
87
123
  *
88
124
  * @param error - The error value describing what went wrong (e.g., error code, object)
89
- * @param options - Optional context about the failure
90
- * @param options.cause - The underlying cause of the error (e.g., a caught exception)
91
- * @returns A Result object with `{ ok: false, error }` (and optional cause)
125
+ * @returns An Err object with `{ ok: false, error }`
92
126
  *
93
127
  * @example
94
128
  * ```typescript
95
129
  * // Simple error
96
130
  * const r1 = err("NOT_FOUND");
131
+ * // Type: Err<"NOT_FOUND">
97
132
  *
98
- * // Error with cause (useful for wrapping exceptions)
99
- * try {
100
- * // ... unsafe code
101
- * } catch (e) {
102
- * return err("PROCESSING_FAILED", { cause: e });
103
- * }
133
+ * // Error with context (include in error object)
134
+ * const r2 = err({ type: "PROCESSING_FAILED", cause: originalError });
135
+ * // Type: Err<{ type: string; cause: Error }>
104
136
  * ```
105
137
  */
106
138
  declare const err: <E, C = unknown>(error: E, options?: {
107
139
  cause?: C;
108
- }) => Result<never, E, C>;
140
+ }) => Err<E, C>;
109
141
  /**
110
142
  * Checks if a Result is successful.
111
143
  * Use this to narrow the type of a Result to the success case.
@@ -2309,4 +2341,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
2309
2341
  */
2310
2342
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
2311
2343
 
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 };
2344
+ export { type AsyncResult, type BackoffStrategy, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type Err, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type Ok, 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}),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};
1
+ var g=e=>({ok:!0,value:e}),d=(e,t)=>({ok:!1,error:e,...t?.cause!==void 0?{cause:t.cause}:{}}),Te=e=>e.ok,ke=e=>!e.ok,se=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 ue(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 ae(e,t){return{[te]:!0,error:e,meta:t}}function ie(e){return typeof e=="object"&&e!==null&&e[te]===!0}var ne=Symbol("mapper-exception");function pe(e){return{[ne]:!0,thrown:e}}function le(e){return typeof e=="object"&&e!==null&&e[ne]===!0}function ce(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 Ee(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=s=>s??`step_${++L}`,y=s=>{let b=s.context!==void 0||E===void 0?s:{...s,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=ae,z=s=>ie(s),Y=(s,b)=>I?b?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:s,...b.resultCause!==void 0?{cause:b.resultCause}:{}}}:b?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:s,thrown:b.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:s}}:s,re=s=>({type:"UNEXPECTED_ERROR",cause:s.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:s.error,...s.meta.resultCause!==void 0?{cause:s.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:s.error,thrown:s.meta.thrown}});try{let b=function(m,p){let i=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=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()-o})};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),o=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:o,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 we=b,me=M;let s=(m,p)=>(async()=>{let i=ce(p),{name:o,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:o,ts:Date.now()});let V;for(let k=1;k<=S.attempts;k++){let oe=T?performance.now():0;try{let w;if(typeof m=="function"?c?w=await Ee(m,c,{name:o,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:o,ts:Date.now(),durationMs:U}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:o,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:o,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:o,ts:Date.now(),durationMs:performance.now()-R,attempts:k,lastError:w.error});break}catch(w){let U=performance.now()-oe;if(z(w))throw y({type:"step_aborted",workflowId:r,stepId:l,stepKey:u,name:o,ts:Date.now(),durationMs:U}),w;if(Q(w)){let P=ue(w),J=c?.ms??P?.timeoutMs??0;if(y({type:"step_timeout",workflowId:r,stepId:l,stepKey:u,name:o,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:o,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:o,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:o,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:o,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 pe(J)}throw y({type:"step_error",workflowId:r,stepId:l,stepKey:u,name:o,ts:Date.now(),durationMs:W,error:P}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:o,ts:Date.now(),durationMs:W,result:d(P,{cause:w}),meta:{origin:"throw",thrown:w}}),n?.(P,o,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:o,ts:Date.now(),durationMs:W,error:P}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:o,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:o,ts:Date.now(),durationMs:K,error:$}),u&&y({type:"step_complete",workflowId:r,stepKey:u,name:o,ts:Date.now(),durationMs:K,result:v,meta:{origin:"result",resultCause:v.cause}}),n?.(v.error,o,E),O(v.error,{origin:"result",resultCause:v.cause})})();s.try=(m,p)=>{let i=p.name,o=p.key,u=X(o),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:o,name:i,ts:Date.now()});try{let T=await m(),R=performance.now()-l;return y({type:"step_success",workflowId:r,stepId:u,stepKey:o,name:i,ts:Date.now(),durationMs:R}),o&&y({type:"step_complete",workflowId:r,stepKey:o,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:o,name:i,ts:Date.now(),durationMs:h,error:_}),o&&y({type:"step_complete",workflowId:r,stepKey:o,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})}})()},s.fromResult=(m,p)=>{let i=p.name,o=p.key,u=X(o),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:o,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:o,name:i,ts:Date.now(),durationMs:R}),o&&y({type:"step_complete",workflowId:r,stepKey:o,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:o,name:i,ts:Date.now(),durationMs:h,error:_}),o&&y({type:"step_complete",workflowId:r,stepKey:o,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})}})()},s.retry=(m,p)=>s(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}),s.withTimeout=(m,p)=>s(m,{name:p.name,key:p.key,timeout:p}),s.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)}}),s.race=(m,p)=>{let i=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=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()-o,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}})()},s.allSettled=(m,p)=>{let i=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=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()-o})};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(s);return g(N)}catch(s){if(le(s))throw s.thrown;if(z(s)){let M=s.meta.origin==="throw"?s.meta.thrown:s.meta.resultCause;if(f||n)return d(s.error,{cause:M});if(se(s.error))return d(s.error,{cause:M});let D=re(s);return d(D,{cause:M})}if(f){let M=f(s);return n?.(M,"unexpected",E),d(M,{cause:s})}let b={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:s}};return n?.(b,"unexpected",E),d(b,{cause:s})}}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"}},de=e=>{if(e.ok)return e.value;throw new H(e.error,e.cause)},fe=(e,t)=>e.ok?e.value:t,Re=(e,t)=>e.ok?e.value:t(e.error,e.cause);function Ce(e,t){try{return g(e())}catch(n){return t?d(t(n),{cause:n}):d(n)}}async function xe(e,t){try{return g(await 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)}}function ge(e,t){return e!=null?g(e):d(t())}function Ae(e,t){return e.ok?g(t(e.value)):e}function be(e,t){return e.ok?e:d(t(e.error),{cause:e.cause})}function Pe(e,t){return e.ok?t.ok(e.value):t.err(e.error,e.cause)}function he(e,t){return e.ok?t(e.value):e}function _e(e,t){return e.ok&&t(e.value),e}function ve(e,t){return e.ok||t(e.error,e.cause),e}function Me(e,t,n){if(!e.ok)return e;try{return g(t(e.value))}catch(a){return d(n(a),{cause:a})}}function Ie(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 Oe(e,t,n){return e.ok?g(t(e.value)):d(n(e.error),{cause:e.cause})}function Ue(e,t){return e.ok?e:t(e.error,e.cause)}async function De(e,t){let n=await e;return n.ok?n:t(n.error,n.cause)}function Ke(e,t){return e.ok?g(e.value):g(t(e.error,e.cause))}async function je(e,t){let n=await e;return n.ok?g(n.value):g(await t(n.error,n.cause))}function ye(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 Fe(e){return ye(e)!==null}function Ne(e){let t=[];for(let n of e){if(!n.ok)return n;t.push(n.value)}return g(t)}async function Ve(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 Le(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 We(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 Xe(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 Ye(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 $e(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,Ne as all,Ve as allAsync,Le as allSettled,$e as allSettledAsync,he as andThen,Xe as any,Ye as anyAsync,Oe as bimap,ae as createEarlyExit,d as err,Ce as from,ge as fromNullable,xe as fromPromise,ue as getStepTimeoutMeta,ye as hydrate,ie as isEarlyExit,ke as isErr,Te as isOk,Fe as isSerializedResult,Q as isStepTimeoutError,se as isUnexpectedError,Ae as map,be as mapError,Ie as mapErrorTry,Me as mapTry,Pe as match,g as ok,Ue as orElse,De as orElseAsync,We as partition,Ke as recover,je as recoverAsync,ee as run,_e as tap,ve as tapError,Se as tryAsync,de as unwrap,fe as unwrapOr,Re as unwrapOrElse};
2
2
  //# sourceMappingURL=core.js.map