API Reference
This page is generated from the awaitly package JSDoc and TypeScript types. For workflow and step options, see Options reference below.
Entry points
Section titled “Entry points”The package has task-shaped entry points. All imports are named imports (tree-shake friendly); there is no namespace object:
// The front door: Result primitives, run() + step engine, per-dep policies,// TaggedError, pre-built errors, pattern matching, durations, reliabilityimport { ok, err, run, map, type AsyncResult } from 'awaitly';
// The size guarantee: Result primitives only (minifies under ~10KB)import { ok, err, map, andThen, type AsyncResult } from 'awaitly/result';
// Focused async composition and reliabilityimport { run } from 'awaitly';import { retry, createCircuitBreaker } from 'awaitly';
// Workflow composition, resources, and batchingimport { createWorkflow } from 'awaitly';
// Independent production capabilitiesimport { durable } from 'awaitly/durable';import { type SnapshotStore } from 'awaitly/durable';import { createSagaWorkflow } from 'awaitly/durable';import { createApprovalStep } from 'awaitly/durable';import { createMemoryStreamStore } from 'awaitly/durable';import { createWebhookHandler } from 'awaitly/durable';import { createEngine } from 'awaitly/durable';
// Test utilitiesimport { createWorkflowHarness, createTestClock } from 'awaitly/testing';import { systemClock, type Clock, isRetryableFailure } from 'awaitly';Results
Section titled “Results”Constructors
Section titled “Constructors”err(error: E, options?: { cause?: C }): Err<E, C>ok(): Ok<void>Type guards
Section titled “Type guards”Checks if a Result is a failure.
When to use: Prefer functional-style checks or array filtering over result.ok.
isErr(r: Result<T, E>): (value: Err<E, unknown>) => booleanChecks if a Result is successful.
When to use: Prefer functional-style checks or array filtering over result.ok.
isOk(r: Result<T, E>): (value: Ok<T>) => booleanisRetryableFailure
Section titled “isRetryableFailure”awaitly/errors entry point
Pre-built error types for common failure scenarios.
isRetryableFailure(failure: unknown): booleanisUnexpectedError
Section titled “isUnexpectedError”Checks if an error is an UnexpectedError.
When to use: Distinguish unexpected failures from your typed error union.
isUnexpectedError(e: unknown): (value: UnexpectedError) => booleanisWorkflowCancelled
Section titled “isWorkflowCancelled”Type guard to check if an error is a WorkflowCancelledError.
isWorkflowCancelled(error: unknown): (value: WorkflowCancelledError) => booleanUnwrap
Section titled “Unwrap”unwrap
Section titled “unwrap”Extracts the value from an Ok result, or throws UnwrapError if it’s an Err.
When to use: Only at boundaries or tests where a failure should be fatal.
unwrap(r: Result<T, E>): TunwrapOr
Section titled “unwrapOr”Extracts the value from an Ok result, or returns a default value if it’s an Err.
When to use: Provide a safe fallback without branching.
unwrapOr(r: Result<T, E>, defaultValue: T): TunwrapOrElse
Section titled “unwrapOrElse”Extracts the value from an Ok result, or calls a function to get a default value if it’s an Err.
When to use: Compute a fallback from the error (logging, metrics, or derived defaults).
unwrapOrElse(r: Result<T, E>, fn: (error: E, cause?: unknown) => T): Tfrom(fn: () => T): Err<unknown, unknown> | Ok<T>fromNullable
Section titled “fromNullable”fromNullable(value: T | unknown | undefined, onNull: () => E): Result<T, E>fromPromise
Section titled “fromPromise”fromPromise(promise: PromiseLike<T>): Promise<Err<unknown, unknown> | Ok<T>>tryAsync
Section titled “tryAsync”tryAsync(fn: () => PromiseLike<T>): AsyncResult<T, unknown>Transform
Section titled “Transform”andThen
Section titled “andThen”andThen(r: Ok<T>, fn: (value: T) => Ok<U>): Ok<U>map(r: Ok<T>, fn: (value: T) => U): Ok<U>mapError
Section titled “mapError”mapError(r: Result<T, E>, fn: (error: E, cause?: unknown) => F): Result<T, F>mapErrorTry
Section titled “mapErrorTry”mapErrorTry(r: Result<T, E>, fn: (error: E) => F, onError: (thrown: unknown) => G): Result<T, F | G>mapTry
Section titled “mapTry”mapTry(r: Result<T, E>, fn: (value: T) => U, onError: (thrown: unknown) => F): Result<U, E | F>Exhaustively matches on a tagged error, requiring handlers for all variants.
TypeScript will error if any variant in the error union is not handled.
When to use: You want compile-time enforcement that every tagged variant is handled.
match(handlers: unknown): (r: Result<T, E>) => MatchResult<H>orElse
Section titled “orElse”orElse(r: Result<T, E>, fn: (error: E, cause?: unknown) => Result<T, E2>): Result<T, E2>recover
Section titled “recover”recover(r: Result<T, E>, fn: (error: E, cause?: unknown) => T): Ok<T>recoverAsync
Section titled “recoverAsync”recoverAsync(r: Result<T, E> | Promise<Result<T, E>>, fn: (error: E, cause?: unknown) => T | Promise<T>): Promise<Ok<T>>tap(r: Result<T, E>, fn: (value: T) => void): Result<T, E>tapError
Section titled “tapError”tapError(r: Result<T, E>, fn: (error: E, cause?: unknown) => void): Result<T, E>Policies
Section titled “Policies”fallback
Section titled “fallback”Recover from a dependency’s failure. The handler receives the failure
(the typed Result error, or UnexpectedError wrapping a throw) plus the
original arguments, and its result becomes the outcome. The base
function’s errors are consumed; only the handler’s errors remain in the
union — fallback(fn, () => defaultValue) has no typed errors at all.
fallback(fn: F, onFailure: FB): (args: Parameters<F>) => AsyncResult<DepValueOfReturn<ReturnType<F>> | DepValueOfReturn<ReturnType<FB>>, ErrorOf<FB>>Retry a dependency. The error union is unchanged: if all attempts fail, the last failure propagates exactly as it would have without the policy (typed err for Result functions, throw for plain functions). By default, returned Result errors retry unless they are UnexpectedError. Tagged throws retry; untagged throws stop after the first attempt. Pass a clock at wrap time when tests need to control retry delays.
retry(fn: F, options: RetryPolicyOptions): PolicyFn<F, ErrorOf<F>>timeout
Section titled “timeout”Bound a dependency’s execution time. A timeout returns err(TimeoutError)
and adds TimeoutError to the error union. The wrapper does not cancel the
operation because it does not pass an AbortSignal. It discards any result
that arrives after the timeout.
timeout(fn: F, after: PolicyDelay, options?: { clock?: Clock }): PolicyFn<F, TimeoutError | ErrorOf<F>>Options reference
Section titled “Options reference”Single place for all workflow and step option keys (for docs and static analysis).
Workflow — The value returned by createWorkflow has a single method: workflow.run(name?, fn, config?). Overloads: run(fn), run(fn, config), run(name, fn), run(name, fn, config). Creation overloads: createWorkflow(deps, options?) (deps-first; name inferred from the variable in static analysis) and createWorkflow('name', deps, options?) (explicit label for traces and diagrams). Options can be passed at creation or per-run in RunConfig (workflow.run(fn, config)).
| Option | Type | Purpose |
|---|---|---|
description |
string? |
Short description for labels/tooltips and doc generation |
markdown |
string? |
Full markdown documentation for static analysis and docs |
strict |
boolean? |
Closed error union |
catchUnexpected |
function? |
Map unexpected errors to typed union |
onEvent |
function? |
Event stream callback |
createContext |
function? |
Custom context factory |
cache |
StepCache? |
Step caching backend (creation-time only) |
resumeState |
ResumeState? |
Resume from saved state |
deps |
Partial<Deps>? |
Per-run override of creation-time deps (RunConfig only) |
signal |
AbortSignal? |
Workflow cancellation |
clock |
Clock? |
Time source for retry delays, step.sleep, and step.withTimeout. Per-run overrides creation-time. Pass createTestClock() in tests. |
streamStore |
StreamStore? |
Streaming backend |
snapshot |
WorkflowSnapshot? |
Restore from saved snapshot (RunConfig or creation) |
onUnknownSteps |
`‘warn’ | ‘error’ |
onDefinitionChange |
`‘warn’ | ‘error’ |
Persistence: Use createResumeStateCollector(), pass collector.handleEvent to onEvent, then call collector.getResumeState() after a run to persist. Restore with workflow.run(fn, { resumeState }) or creation-time resumeState (or snapshot where supported).
Step (step, step.sleep, step.retry, step.withTimeout) — in options object:
| Option | Type | Purpose |
|---|---|---|
name |
string? |
Human-readable step name for tracing |
key |
string? |
Cache key for resume/caching |
description |
string? |
Short description for docs and static analysis |
markdown |
string? |
Full markdown for step documentation |
ttl |
number? |
Cache TTL (step.sleep and cached steps) |
retry |
object? |
Retry config (step.retry) |
timeout |
object? |
Timeout config (step.withTimeout) |
signal |
AbortSignal? |
Step cancellation (e.g. step.sleep) |
Compensation (step / step.try inside any workflow) — pass { compensate } on any step. If a later step or the user callback fails, every step that recorded a compensate runs in reverse:
| Option | Type | Purpose |
|---|---|---|
compensate |
(value: T) => void | Promise<void> |
Rollback action; receives the value the step returned |
When at least one compensation throws, the workflow result is a SagaCompensationError carrying the original error and per-step compensation failures.
Injectable time for retry delays, step.sleep, step.withTimeout, and circuit-breaker windows. Production uses systemClock. Tests pass createTestClock() from awaitly/testing as clock on run, createWorkflow / workflow.run, retry, timeout, and createCircuitBreaker.
interface Clock { now(): number sleep(ms: number, signal?: AbortSignal): Promise<void>}
systemClock: Clocksleep resolves on abort (it does not reject). Policy wrappers need clock at wrap time.