@jagreehal/workflow 1.0.0 → 1.2.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
@@ -117,9 +117,11 @@ declare const err: <E, C = unknown>(error: E, options?: {
117
117
  * ```typescript
118
118
  * const r = someOperation();
119
119
  * if (isOk(r)) {
120
- * console.log(r.value); // Type is T
120
+ * // Use r.value (Type is T)
121
+ * processValue(r.value);
121
122
  * } else {
122
- * console.error(r.error); // Type is E
123
+ * // Handle r.error (Type is E)
124
+ * handleError(r.error);
123
125
  * }
124
126
  * ```
125
127
  */
@@ -288,6 +290,97 @@ interface RunStep<E = unknown> {
288
290
  name?: string;
289
291
  key?: string;
290
292
  }) => Promise<T>;
293
+ /**
294
+ * Execute a Result-returning function and map its error to a typed error.
295
+ *
296
+ * Use this when calling functions that return Result<T, E> and you want to
297
+ * map their typed errors to your workflow's error type. Unlike step.try(),
298
+ * the error passed to onError is typed (not unknown).
299
+ *
300
+ * @param operation - A function that returns a Result or AsyncResult
301
+ * @param options - Configuration including error mapping
302
+ * @returns The success value (unwrapped)
303
+ * @throws {EarlyExit} If the result is an error (stops execution safely)
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * const response = await step.fromResult(
308
+ * () => callProvider(input),
309
+ * {
310
+ * name: "call-provider",
311
+ * onError: (providerError) => ({
312
+ * type: "PROVIDER_FAILED",
313
+ * provider: providerError.provider,
314
+ * cause: providerError
315
+ * })
316
+ * }
317
+ * );
318
+ * ```
319
+ */
320
+ fromResult: <T, ResultE, const Err extends E>(operation: () => Result<T, ResultE, unknown> | AsyncResult<T, ResultE, unknown>, options: {
321
+ error: Err;
322
+ name?: string;
323
+ key?: string;
324
+ } | {
325
+ onError: (resultError: ResultE) => Err;
326
+ name?: string;
327
+ key?: string;
328
+ }) => Promise<T>;
329
+ /**
330
+ * Execute a parallel operation (allAsync) with scope events for visualization.
331
+ *
332
+ * This wraps the operation with scope_start and scope_end events, enabling
333
+ * visualization of parallel execution branches.
334
+ *
335
+ * @param name - Name for this parallel block (used in visualization)
336
+ * @param operation - A function that returns a Result from allAsync or allSettledAsync
337
+ * @returns The success value (unwrapped array)
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * const [user, posts] = await step.parallel('Fetch all data', () =>
342
+ * allAsync([fetchUser(id), fetchPosts(id)])
343
+ * );
344
+ * ```
345
+ */
346
+ parallel: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
347
+ /**
348
+ * Execute a race operation (anyAsync) with scope events for visualization.
349
+ *
350
+ * This wraps the operation with scope_start and scope_end events, enabling
351
+ * visualization of racing execution branches.
352
+ *
353
+ * @param name - Name for this race block (used in visualization)
354
+ * @param operation - A function that returns a Result from anyAsync
355
+ * @returns The success value (first to succeed)
356
+ *
357
+ * @example
358
+ * ```typescript
359
+ * const data = await step.race('Fastest API', () =>
360
+ * anyAsync([fetchFromPrimary(id), fetchFromFallback(id)])
361
+ * );
362
+ * ```
363
+ */
364
+ race: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>) => Promise<T>;
365
+ /**
366
+ * Execute an allSettled operation with scope events for visualization.
367
+ *
368
+ * This wraps the operation with scope_start and scope_end events, enabling
369
+ * visualization of allSettled execution branches. Unlike step.parallel,
370
+ * allSettled collects all results even if some fail.
371
+ *
372
+ * @param name - Name for this allSettled block (used in visualization)
373
+ * @param operation - A function that returns a Result from allSettledAsync
374
+ * @returns The success value (unwrapped array)
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const [user, posts] = await step.allSettled('Fetch all data', () =>
379
+ * allSettledAsync([fetchUser(id), fetchPosts(id)])
380
+ * );
381
+ * ```
382
+ */
383
+ allSettled: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
291
384
  }
292
385
  /**
293
386
  * Unified event stream for workflow execution.
@@ -297,6 +390,10 @@ interface RunStep<E = unknown> {
297
390
  * preserves its original types, but the event type cannot statically represent them.
298
391
  * Use runtime checks or the meta field to interpret cause values.
299
392
  */
393
+ /**
394
+ * Scope types for parallel and race operations.
395
+ */
396
+ type ScopeType = "parallel" | "race" | "allSettled";
300
397
  type WorkflowEvent<E> = {
301
398
  type: "workflow_start";
302
399
  workflowId: string;
@@ -315,12 +412,14 @@ type WorkflowEvent<E> = {
315
412
  } | {
316
413
  type: "step_start";
317
414
  workflowId: string;
415
+ stepId: string;
318
416
  stepKey?: string;
319
417
  name?: string;
320
418
  ts: number;
321
419
  } | {
322
420
  type: "step_success";
323
421
  workflowId: string;
422
+ stepId: string;
324
423
  stepKey?: string;
325
424
  name?: string;
326
425
  ts: number;
@@ -328,6 +427,7 @@ type WorkflowEvent<E> = {
328
427
  } | {
329
428
  type: "step_error";
330
429
  workflowId: string;
430
+ stepId: string;
331
431
  stepKey?: string;
332
432
  name?: string;
333
433
  ts: number;
@@ -336,6 +436,7 @@ type WorkflowEvent<E> = {
336
436
  } | {
337
437
  type: "step_aborted";
338
438
  workflowId: string;
439
+ stepId: string;
339
440
  stepKey?: string;
340
441
  name?: string;
341
442
  ts: number;
@@ -361,6 +462,28 @@ type WorkflowEvent<E> = {
361
462
  stepKey: string;
362
463
  name?: string;
363
464
  ts: number;
465
+ } | {
466
+ type: "step_skipped";
467
+ workflowId: string;
468
+ stepKey?: string;
469
+ name?: string;
470
+ reason?: string;
471
+ decisionId?: string;
472
+ ts: number;
473
+ } | {
474
+ type: "scope_start";
475
+ workflowId: string;
476
+ scopeId: string;
477
+ scopeType: ScopeType;
478
+ name?: string;
479
+ ts: number;
480
+ } | {
481
+ type: "scope_end";
482
+ workflowId: string;
483
+ scopeId: string;
484
+ ts: number;
485
+ durationMs: number;
486
+ winnerId?: string;
364
487
  };
365
488
  type RunOptionsWithCatch<E, C = void> = {
366
489
  /**
@@ -440,6 +563,40 @@ declare function createEarlyExit<E>(error: E, meta: StepFailureMeta): EarlyExit<
440
563
  * @internal
441
564
  */
442
565
  declare function isEarlyExit<E>(e: unknown): e is EarlyExit<E>;
566
+ /**
567
+ * Execute a workflow with step-based error handling.
568
+ *
569
+ * ## When to Use run()
570
+ *
571
+ * Use `run()` when:
572
+ * - Dependencies are dynamic (passed at runtime, not known at compile time)
573
+ * - You don't need step caching or resume state
574
+ * - Error types are known upfront and can be specified manually
575
+ * - Building lightweight, one-off workflows
576
+ *
577
+ * For automatic error type inference from static dependencies, use `createWorkflow()`.
578
+ *
579
+ * ## Modes
580
+ *
581
+ * `run()` has three modes based on options:
582
+ * - **Strict Mode** (`catchUnexpected`): Returns `Result<T, E>` (closed union)
583
+ * - **Typed Mode** (`onError`): Returns `Result<T, E | UnexpectedError>`
584
+ * - **Safe Default** (no options): Returns `Result<T, UnexpectedError>`
585
+ *
586
+ * @example
587
+ * ```typescript
588
+ * // Typed mode with explicit error union
589
+ * const result = await run<Output, 'NOT_FOUND' | 'FETCH_ERROR'>(
590
+ * async (step) => {
591
+ * const user = await step(fetchUser(userId));
592
+ * return user;
593
+ * },
594
+ * { onError: (e) => console.log('Failed:', e) }
595
+ * );
596
+ * ```
597
+ *
598
+ * @see createWorkflow - For static dependencies with auto error inference
599
+ */
443
600
  /**
444
601
  * Execute a workflow with "Strict Mode" error handling.
445
602
  *
@@ -971,9 +1128,9 @@ declare function mapError<T, E, F, C>(r: Result<T, E, C>, fn: (error: E) => F):
971
1128
  * });
972
1129
  *
973
1130
  * // Handle with cause
974
- * const log = match(result, {
975
- * ok: (value) => console.log('Success:', value),
976
- * err: (error, cause) => console.error('Error:', error, cause),
1131
+ * const response = match(result, {
1132
+ * ok: (value) => ({ status: 'success', data: value }),
1133
+ * err: (error, cause) => ({ status: 'error', error, cause }),
977
1134
  * });
978
1135
  * ```
979
1136
  */
@@ -1603,4 +1760,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
1603
1760
  */
1604
1761
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
1605
1762
 
1606
- 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 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 };
1763
+ 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 };
package/dist/core.d.ts CHANGED
@@ -117,9 +117,11 @@ declare const err: <E, C = unknown>(error: E, options?: {
117
117
  * ```typescript
118
118
  * const r = someOperation();
119
119
  * if (isOk(r)) {
120
- * console.log(r.value); // Type is T
120
+ * // Use r.value (Type is T)
121
+ * processValue(r.value);
121
122
  * } else {
122
- * console.error(r.error); // Type is E
123
+ * // Handle r.error (Type is E)
124
+ * handleError(r.error);
123
125
  * }
124
126
  * ```
125
127
  */
@@ -288,6 +290,97 @@ interface RunStep<E = unknown> {
288
290
  name?: string;
289
291
  key?: string;
290
292
  }) => Promise<T>;
293
+ /**
294
+ * Execute a Result-returning function and map its error to a typed error.
295
+ *
296
+ * Use this when calling functions that return Result<T, E> and you want to
297
+ * map their typed errors to your workflow's error type. Unlike step.try(),
298
+ * the error passed to onError is typed (not unknown).
299
+ *
300
+ * @param operation - A function that returns a Result or AsyncResult
301
+ * @param options - Configuration including error mapping
302
+ * @returns The success value (unwrapped)
303
+ * @throws {EarlyExit} If the result is an error (stops execution safely)
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * const response = await step.fromResult(
308
+ * () => callProvider(input),
309
+ * {
310
+ * name: "call-provider",
311
+ * onError: (providerError) => ({
312
+ * type: "PROVIDER_FAILED",
313
+ * provider: providerError.provider,
314
+ * cause: providerError
315
+ * })
316
+ * }
317
+ * );
318
+ * ```
319
+ */
320
+ fromResult: <T, ResultE, const Err extends E>(operation: () => Result<T, ResultE, unknown> | AsyncResult<T, ResultE, unknown>, options: {
321
+ error: Err;
322
+ name?: string;
323
+ key?: string;
324
+ } | {
325
+ onError: (resultError: ResultE) => Err;
326
+ name?: string;
327
+ key?: string;
328
+ }) => Promise<T>;
329
+ /**
330
+ * Execute a parallel operation (allAsync) with scope events for visualization.
331
+ *
332
+ * This wraps the operation with scope_start and scope_end events, enabling
333
+ * visualization of parallel execution branches.
334
+ *
335
+ * @param name - Name for this parallel block (used in visualization)
336
+ * @param operation - A function that returns a Result from allAsync or allSettledAsync
337
+ * @returns The success value (unwrapped array)
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * const [user, posts] = await step.parallel('Fetch all data', () =>
342
+ * allAsync([fetchUser(id), fetchPosts(id)])
343
+ * );
344
+ * ```
345
+ */
346
+ parallel: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
347
+ /**
348
+ * Execute a race operation (anyAsync) with scope events for visualization.
349
+ *
350
+ * This wraps the operation with scope_start and scope_end events, enabling
351
+ * visualization of racing execution branches.
352
+ *
353
+ * @param name - Name for this race block (used in visualization)
354
+ * @param operation - A function that returns a Result from anyAsync
355
+ * @returns The success value (first to succeed)
356
+ *
357
+ * @example
358
+ * ```typescript
359
+ * const data = await step.race('Fastest API', () =>
360
+ * anyAsync([fetchFromPrimary(id), fetchFromFallback(id)])
361
+ * );
362
+ * ```
363
+ */
364
+ race: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>) => Promise<T>;
365
+ /**
366
+ * Execute an allSettled operation with scope events for visualization.
367
+ *
368
+ * This wraps the operation with scope_start and scope_end events, enabling
369
+ * visualization of allSettled execution branches. Unlike step.parallel,
370
+ * allSettled collects all results even if some fail.
371
+ *
372
+ * @param name - Name for this allSettled block (used in visualization)
373
+ * @param operation - A function that returns a Result from allSettledAsync
374
+ * @returns The success value (unwrapped array)
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const [user, posts] = await step.allSettled('Fetch all data', () =>
379
+ * allSettledAsync([fetchUser(id), fetchPosts(id)])
380
+ * );
381
+ * ```
382
+ */
383
+ allSettled: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
291
384
  }
292
385
  /**
293
386
  * Unified event stream for workflow execution.
@@ -297,6 +390,10 @@ interface RunStep<E = unknown> {
297
390
  * preserves its original types, but the event type cannot statically represent them.
298
391
  * Use runtime checks or the meta field to interpret cause values.
299
392
  */
393
+ /**
394
+ * Scope types for parallel and race operations.
395
+ */
396
+ type ScopeType = "parallel" | "race" | "allSettled";
300
397
  type WorkflowEvent<E> = {
301
398
  type: "workflow_start";
302
399
  workflowId: string;
@@ -315,12 +412,14 @@ type WorkflowEvent<E> = {
315
412
  } | {
316
413
  type: "step_start";
317
414
  workflowId: string;
415
+ stepId: string;
318
416
  stepKey?: string;
319
417
  name?: string;
320
418
  ts: number;
321
419
  } | {
322
420
  type: "step_success";
323
421
  workflowId: string;
422
+ stepId: string;
324
423
  stepKey?: string;
325
424
  name?: string;
326
425
  ts: number;
@@ -328,6 +427,7 @@ type WorkflowEvent<E> = {
328
427
  } | {
329
428
  type: "step_error";
330
429
  workflowId: string;
430
+ stepId: string;
331
431
  stepKey?: string;
332
432
  name?: string;
333
433
  ts: number;
@@ -336,6 +436,7 @@ type WorkflowEvent<E> = {
336
436
  } | {
337
437
  type: "step_aborted";
338
438
  workflowId: string;
439
+ stepId: string;
339
440
  stepKey?: string;
340
441
  name?: string;
341
442
  ts: number;
@@ -361,6 +462,28 @@ type WorkflowEvent<E> = {
361
462
  stepKey: string;
362
463
  name?: string;
363
464
  ts: number;
465
+ } | {
466
+ type: "step_skipped";
467
+ workflowId: string;
468
+ stepKey?: string;
469
+ name?: string;
470
+ reason?: string;
471
+ decisionId?: string;
472
+ ts: number;
473
+ } | {
474
+ type: "scope_start";
475
+ workflowId: string;
476
+ scopeId: string;
477
+ scopeType: ScopeType;
478
+ name?: string;
479
+ ts: number;
480
+ } | {
481
+ type: "scope_end";
482
+ workflowId: string;
483
+ scopeId: string;
484
+ ts: number;
485
+ durationMs: number;
486
+ winnerId?: string;
364
487
  };
365
488
  type RunOptionsWithCatch<E, C = void> = {
366
489
  /**
@@ -440,6 +563,40 @@ declare function createEarlyExit<E>(error: E, meta: StepFailureMeta): EarlyExit<
440
563
  * @internal
441
564
  */
442
565
  declare function isEarlyExit<E>(e: unknown): e is EarlyExit<E>;
566
+ /**
567
+ * Execute a workflow with step-based error handling.
568
+ *
569
+ * ## When to Use run()
570
+ *
571
+ * Use `run()` when:
572
+ * - Dependencies are dynamic (passed at runtime, not known at compile time)
573
+ * - You don't need step caching or resume state
574
+ * - Error types are known upfront and can be specified manually
575
+ * - Building lightweight, one-off workflows
576
+ *
577
+ * For automatic error type inference from static dependencies, use `createWorkflow()`.
578
+ *
579
+ * ## Modes
580
+ *
581
+ * `run()` has three modes based on options:
582
+ * - **Strict Mode** (`catchUnexpected`): Returns `Result<T, E>` (closed union)
583
+ * - **Typed Mode** (`onError`): Returns `Result<T, E | UnexpectedError>`
584
+ * - **Safe Default** (no options): Returns `Result<T, UnexpectedError>`
585
+ *
586
+ * @example
587
+ * ```typescript
588
+ * // Typed mode with explicit error union
589
+ * const result = await run<Output, 'NOT_FOUND' | 'FETCH_ERROR'>(
590
+ * async (step) => {
591
+ * const user = await step(fetchUser(userId));
592
+ * return user;
593
+ * },
594
+ * { onError: (e) => console.log('Failed:', e) }
595
+ * );
596
+ * ```
597
+ *
598
+ * @see createWorkflow - For static dependencies with auto error inference
599
+ */
443
600
  /**
444
601
  * Execute a workflow with "Strict Mode" error handling.
445
602
  *
@@ -971,9 +1128,9 @@ declare function mapError<T, E, F, C>(r: Result<T, E, C>, fn: (error: E) => F):
971
1128
  * });
972
1129
  *
973
1130
  * // Handle with cause
974
- * const log = match(result, {
975
- * ok: (value) => console.log('Success:', value),
976
- * err: (error, cause) => console.error('Error:', error, cause),
1131
+ * const response = match(result, {
1132
+ * ok: (value) => ({ status: 'success', data: value }),
1133
+ * err: (error, cause) => ({ status: 'error', error, cause }),
977
1134
  * });
978
1135
  * ```
979
1136
  */
@@ -1603,4 +1760,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
1603
1760
  */
1604
1761
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
1605
1762
 
1606
- 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 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 };
1763
+ 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 };
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- var y=e=>({ok:!0,value:e}),s=(e,n)=>({ok:!1,error:e,...n?.cause!==void 0?{cause:n.cause}:{}}),W=e=>e.ok,Y=e=>!e.ok,N=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",b=Symbol("early-exit");function V(e,n){return{[b]:!0,error:e,meta:n}}function D(e){return typeof e=="object"&&e!==null&&e[b]===!0}var I=Symbol("mapper-exception");function j(e){return{[I]:!0,thrown:e}}function L(e){return typeof e=="object"&&e!==null&&e[I]===!0}function X(e){return typeof e=="string"?{name:e}:e??{}}async function _(e,n){let{onError:r,onEvent:o,catchUnexpected:u,workflowId:T,context:k}=n&&typeof n=="object"?n:{},a=T??crypto.randomUUID(),O=!r&&!u,E=t=>{o?.(t,k)},P=V,h=t=>D(t),S=(t,R)=>O?R?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:t,...R.resultCause!==void 0?{cause:R.resultCause}:{}}}:R?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:t,thrown:R.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:t}}:t,M=t=>t.origin==="result"?t.resultCause:t.thrown,K=t=>({type:"UNEXPECTED_ERROR",cause:t.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:t.error,...t.meta.resultCause!==void 0?{cause:t.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:t.error,thrown:t.meta.thrown}});try{let t=(m,x)=>(async()=>{let{name:l,key:i}=X(x),v=o?performance.now():0;o&&E({type:"step_start",workflowId:a,stepKey:i,name:l,ts:Date.now()});let c;try{c=await(typeof m=="function"?m():m)}catch(w){let A=performance.now()-v;if(h(w))throw E({type:"step_aborted",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:A}),w;if(u){let C;try{C=u(w)}catch(F){throw j(F)}throw E({type:"step_error",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:A,error:C}),i&&E({type:"step_complete",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:A,result:s(C,{cause:w}),meta:{origin:"throw",thrown:w}}),r?.(C,l),P(C,{origin:"throw",thrown:w})}else{let C={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:w}};throw E({type:"step_error",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:A,error:C}),i&&E({type:"step_complete",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:A,result:s(C,{cause:w}),meta:{origin:"throw",thrown:w}}),w}}let p=performance.now()-v;if(c.ok)return E({type:"step_success",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:p}),i&&E({type:"step_complete",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:p,result:c}),c.value;let d=S(c.error,{origin:"result",resultCause:c.cause});throw E({type:"step_error",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:p,error:d}),i&&E({type:"step_complete",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:p,result:c,meta:{origin:"result",resultCause:c.cause}}),r?.(c.error,l),P(c.error,{origin:"result",resultCause:c.cause})})();t.try=(m,x)=>{let l=x.name,i=x.key,U="error"in x?()=>x.error:x.onError,v=o;return(async()=>{let c=v?performance.now():0;o&&E({type:"step_start",workflowId:a,stepKey:i,name:l,ts:Date.now()});try{let p=await m(),d=performance.now()-c;return E({type:"step_success",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:d}),i&&E({type:"step_complete",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:d,result:y(p)}),p}catch(p){let d=U(p),w=performance.now()-c,A=S(d,{origin:"throw",thrown:p});throw E({type:"step_error",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:w,error:A}),i&&E({type:"step_complete",workflowId:a,stepKey:i,name:l,ts:Date.now(),durationMs:w,result:s(d,{cause:p}),meta:{origin:"throw",thrown:p}}),r?.(d,l),P(d,{origin:"throw",thrown:p})}})()};let f=await e(t);return y(f)}catch(t){if(L(t))throw t.thrown;if(h(t)){let f=M(t.meta);if(u||r)return s(t.error,{cause:f});if(N(t.error))return s(t.error,{cause:f});let m=K(t);return s(m,{cause:f})}if(u){let f=u(t);return r?.(f,"unexpected"),s(f,{cause:t})}let R={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:t}};return r?.(R,"unexpected"),s(R,{cause:t})}}_.strict=(e,n)=>_(e,n);var g=class extends Error{constructor(r,o){super(`Unwrap called on an error result: ${String(r)}`);this.error=r;this.cause=o;this.name="UnwrapError"}},J=e=>{if(e.ok)return e.value;throw new g(e.error,e.cause)},G=(e,n)=>e.ok?e.value:n,q=(e,n)=>e.ok?e.value:n(e.error,e.cause);function B(e,n){try{return y(e())}catch(r){return n?s(n(r),{cause:r}):s(r)}}async function H(e,n){try{return y(await e)}catch(r){return n?s(n(r),{cause:r}):s(r)}}async function $(e,n){try{return y(await e())}catch(r){return n?s(n(r),{cause:r}):s(r)}}function z(e,n){return e!=null?y(e):s(n())}function Q(e,n){return e.ok?y(n(e.value)):e}function Z(e,n){return e.ok?e:s(n(e.error),{cause:e.cause})}function ee(e,n){return e.ok?n.ok(e.value):n.err(e.error,e.cause)}function ne(e,n){return e.ok?n(e.value):e}function re(e,n){return e.ok&&n(e.value),e}function te(e,n){return e.ok||n(e.error,e.cause),e}function oe(e,n,r){if(!e.ok)return e;try{return y(n(e.value))}catch(o){return s(r(o),{cause:o})}}function se(e,n,r){if(e.ok)return e;try{return s(n(e.error),{cause:e.cause})}catch(o){return s(r(o),{cause:o})}}function ue(e){let n=[];for(let r of e){if(!r.ok)return r;n.push(r.value)}return y(n)}async function ae(e){return e.length===0?y([]):new Promise(n=>{let r=!1,o=e.length,u=new Array(e.length);for(let T=0;T<e.length;T++){let k=T;Promise.resolve(e[k]).catch(a=>s({type:"PROMISE_REJECTED",cause:a},{cause:{type:"PROMISE_REJECTION",reason:a}})).then(a=>{if(!r){if(!a.ok){r=!0,n(a);return}u[k]=a.value,o--,o===0&&n(y(u))}})}})}function ie(e){let n=[],r=[];for(let o of e)o.ok?n.push(o.value):r.push({error:o.error,cause:o.cause});return r.length>0?s(r):y(n)}function le(e){let n=[],r=[];for(let o of e)o.ok?n.push(o.value):r.push(o.error);return{values:n,errors:r}}function Ee(e){if(e.length===0)return s({type:"EMPTY_INPUT",message:"any() requires at least one Result"});let n=null;for(let r of e){if(r.ok)return r;n||(n=r)}return n}async function ce(e){return e.length===0?s({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(n=>{let r=!1,o=e.length,u=null;for(let T of e)Promise.resolve(T).catch(k=>s({type:"PROMISE_REJECTED",cause:k},{cause:{type:"PROMISE_REJECTION",reason:k}})).then(k=>{if(!r){if(k.ok){r=!0,n(k);return}u||(u=k),o--,o===0&&n(u)}})})}async function pe(e){let n=await Promise.all(e.map(u=>Promise.resolve(u).then(T=>({status:"result",result:T})).catch(T=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:T},cause:{type:"PROMISE_REJECTION",reason:T}})))),r=[],o=[];for(let u of n)u.status==="rejected"?o.push({error:u.error,cause:u.cause}):u.result.ok?r.push(u.result.value):o.push({error:u.result.error,cause:u.result.cause});return o.length>0?s(o):y(r)}export{b as EARLY_EXIT_SYMBOL,g as UnwrapError,ue as all,ae as allAsync,ie as allSettled,pe as allSettledAsync,ne as andThen,Ee as any,ce as anyAsync,V as createEarlyExit,s as err,B as from,z as fromNullable,H as fromPromise,D as isEarlyExit,Y as isErr,W as isOk,N as isUnexpectedError,Q as map,Z as mapError,se as mapErrorTry,oe as mapTry,ee as match,y as ok,le as partition,_ as run,re as tap,te as tapError,$ as tryAsync,J as unwrap,G as unwrapOr,q as unwrapOrElse};
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),p=u?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});let i;try{i=await(typeof T=="function"?T():T)}catch(R){let v=performance.now()-p;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()-p;if(i.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:i}),i.value;let d=_(i.error,{origin:"result",resultCause:i.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:i,meta:{origin:"result",resultCause:i.cause}}),t?.(i.error,o),h(i.error,{origin:"result",resultCause:i.cause})})();r.try=(T,k)=>{let o=k.name,s=k.key,y=I(s),m="error"in k?()=>k.error:k.onError,p=u;return(async()=>{let i=p?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()-i;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()-i,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,p=u;return(async()=>{let i=p?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()-i;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()-i,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 p=g.findIndex(i=>i.scopeId===o);p!==-1&&g.splice(p,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 p=await k();if(m(),!p.ok)throw t?.(p.error,T),h(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw m(),p}})()},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 p=()=>{if(y)return;y=!0;let i=g.findIndex(E=>E.scopeId===o);i!==-1&&g.splice(i,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 i=await k();if(p(),!i.ok)throw t?.(i.error,T),h(i.error,{origin:"result",resultCause:i.cause});return i.value}catch(i){throw p(),i}})()},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 p=g.findIndex(i=>i.scopeId===o);p!==-1&&g.splice(p,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 p=await k();if(m(),!p.ok)throw t?.(p.error,T),h(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw m(),p}})()};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 ie(e,n,t){if(!e.ok)return e;try{return f(n(e.value))}catch(u){return l(t(u),{cause:u})}}function pe(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,pe as mapErrorTry,ie 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};
2
2
  //# sourceMappingURL=core.js.map