Install
pnpm dlx shadcn@latest add https://archyn.net/r/delay.jsonCopy the files below into the target paths shown in each tab.
import { type Behavior, type RuntimeContext, resultFromSignal, runBehavior } from "./core/runtime";import { type TimingError } from "./timeout";import { wait } from "./wait";
/** * Waits before running a source behavior. * * `delay` models a pause that is part of the workflow itself. Cancellation during the delay returns * a timing cancellation error and the source behavior is not started. * * @typeParam I - Input type. * @typeParam O - Source output type. * @typeParam E - Source domain error type. * @typeParam C - Custom context type. * @param source - Behavior to run after the delay. * @param ms - Delay in milliseconds before source execution. * @returns A behavior with the source result or timing errors. * * @example * ```ts * const delayedLoad = delay(loadUser, 250); * ``` */export function delay<I, O, E, C extends object>( source: Behavior<I, O, E, C>, ms: number,): Behavior<I, O, E | TimingError, C> { return async (input: I, context: RuntimeContext<C>) => { if (context.signal.aborted) { return resultFromSignal(context.signal); }
const delayResult = await wait(ms, context.signal);
if (!delayResult.ok) { return delayResult; }
return runBehavior(source, input, context); };}import { type Awaitable, type Err, type Result, err } from "./result";
/** * Runtime error returned when execution is cancelled through an `AbortSignal`. * * Cancellation is cooperative. Flow helpers check the signal before and after async work and pass * linked signals to child behaviors where appropriate. */export type Cancelled = { kind: "cancelled"; reason?: unknown;};
/** * Runtime error returned when user code throws. * * Thrown exceptions are kept separate from expected domain errors so recovery helpers do not hide * programming or platform failures. */export type Thrown = { kind: "thrown"; error: unknown;};
/** * Runtime-level failure union added around every behavior's domain error type. * * Domain errors describe expected application failures. `RuntimeError` describes cancellation or * unexpected thrown exceptions observed by the Flow runtime. */export type RuntimeError = Cancelled | Thrown;
/** * Execution context passed to every behavior. * * The context always includes an `AbortSignal` and may include application-specific fields. * * @typeParam C - Custom context object type. */export type RuntimeContext<C extends object = {}> = C & { signal: AbortSignal;};
/** * Executable Flow workflow unit. * * A behavior receives typed input, reads runtime context, and resolves to a `Result` containing * either typed output, typed domain error, or a runtime error. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. */export type Behavior<I, O, E = unknown, C extends object = {}> = ( input: I, context: RuntimeContext<C>,) => Promise<Result<O, E | RuntimeError>>;
/** * Extracts the input type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorInput<T> = T extends Behavior<infer I, infer _O, infer _E, infer _C> ? I : never;
/** * Extracts the output type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorOutput<T> = T extends Behavior<infer _I, infer O, infer _E, infer _C> ? O : never;
/** * Extracts the expected domain error type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorError<T> = T extends Behavior<infer _I, infer _O, infer E, infer _C> ? E : never;
/** * Extracts the custom context type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorContext<T> = T extends Behavior<infer _I, infer _O, infer _E, infer C> ? C : never;
/** * Executes a behavior with runtime error protection. * * The runner checks cancellation before and after behavior execution and converts thrown * exceptions into `Thrown` results. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. * @param behavior - Behavior to execute. * @param input - Input passed to the behavior. * @param context - Runtime context containing an `AbortSignal`. * @returns The behavior result, cancellation result, or thrown runtime result. */export async function runBehavior<I, O, E, C extends object>( behavior: Behavior<I, O, E, C>, input: I, context: RuntimeContext<C>,): Promise<Result<O, E | RuntimeError>> { if (context.signal.aborted) { return resultFromSignal(context.signal); }
try { const result = await behavior(input, context);
if (context.signal.aborted) { return resultFromSignal(context.signal); }
return result; } catch (error) { if (context.signal.aborted) { return resultFromSignal(context.signal); }
return thrown(error); }}
/** * Defines a behavior from a callback that returns a `Result`. * * Use `define` for low-level helpers that already operate in the result channel. Most application * code should use `task`, which also accepts plain successful values. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. * @param run - Callback invoked for each behavior execution. * @returns A behavior protected by cancellation and thrown-exception handling. */export function define<I, O, E = unknown, C extends object = {}>( run: (input: I, context: RuntimeContext<C>) => Awaitable<Result<O, E>>,): Behavior<I, O, E, C> { return async (input, context) => { if (context.signal.aborted) { return resultFromSignal(context.signal); }
try { const result = await run(input, context);
if (context.signal.aborted) { return resultFromSignal(context.signal); }
return result; } catch (error) { if (context.signal.aborted) { return cancelled(context.signal.reason); }
return thrown(error); } };}
/** * Runs a behavior with an optional application context. * * If no signal is provided, Flow creates a fresh non-aborted signal. Expected failures remain in * the returned `Result`; thrown exceptions are converted to `Thrown`. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. * @param behavior - Behavior to execute. * @param input - Input passed to the behavior. * @param context - Optional custom context and optional `AbortSignal`. * @returns A result containing behavior output, domain error, or runtime error. * * @example * ```ts * const result = await run(loadUser, "user_1"); * ``` */export async function run<I, O, E, C extends object = {}>( behavior: Behavior<I, O, E, C>, input: I, context: C & { signal?: AbortSignal } = {} as C & { signal?: AbortSignal },): Promise<Result<O, E | RuntimeError>> { const { signal = new AbortController().signal, ...rest } = context;
return runBehavior(behavior, input, { ...(rest as C), signal, });}
/** * Creates a cancellation result. * * @param reason - Optional cancellation reason from an `AbortSignal`. * @returns A failed result containing `Cancelled`. */export function cancelled(reason?: unknown): Err<Cancelled> { if (reason === undefined) { return err({ kind: "cancelled" }); }
return err({ kind: "cancelled", reason });}
/** * Narrows an error value to `Cancelled`. * * @param error - Error value to inspect. * @returns `true` when the value is a cancellation runtime error. */export function isCancelled(error: unknown): error is Cancelled { return ( typeof error === "object" && error !== null && "kind" in error && error.kind === "cancelled" );}
/** * Creates a thrown-exception runtime result. * * @param error - Exception or thrown value. * @returns A failed result containing `Thrown`. */export function thrown(error: unknown): Err<Thrown> { return err({ kind: "thrown", error });}
/** * Narrows an error value to `Thrown`. * * @param error - Error value to inspect. * @returns `true` when the value is a thrown runtime error. */export function isThrown(error: unknown): error is Thrown { return typeof error === "object" && error !== null && "kind" in error && error.kind === "thrown";}
/** * Narrows an error value to a Flow runtime error. * * Recovery helpers use this guard so they only handle expected domain errors. * * @param error - Error value to inspect. * @returns `true` for `Cancelled` or `Thrown`. */export function isRuntimeError(error: unknown): error is RuntimeError { return isCancelled(error) || isThrown(error);}
/** * Converts an aborted signal into a cancellation result. * * @param signal - Aborted signal whose reason should be preserved. * @returns A failed result containing `Cancelled`. */export function resultFromSignal(signal: AbortSignal): Err<Cancelled> { return cancelled(signal.reason);}
/** * Replaces the signal on a runtime context. * * This advanced helper is used by timeout and parallel helpers when they create child abort * controllers. * * @typeParam C - Custom context type. * @param context - Existing runtime context. * @param signal - Replacement signal. * @returns A context with the same custom fields and the replacement signal. */export function contextWithSignal<C extends object>( context: RuntimeContext<C>, signal: AbortSignal,): RuntimeContext<C> { return { ...context, signal };}
/** * Aborts a controller only when it has not already been aborted. * * @param controller - Controller to abort. * @param reason - Optional abort reason. */export function abortController(controller: AbortController, reason?: unknown): void { if (!controller.signal.aborted) { controller.abort(reason); }}
/** * Links a parent signal to a child controller. * * The returned cleanup function removes the listener when the child work has settled. * * @param parent - Parent signal to observe. * @param controller - Child controller to abort when the parent aborts. * @returns Cleanup function that unlinks the abort listener. */export function linkAbortSignal(parent: AbortSignal, controller: AbortController): () => void { if (parent.aborted) { abortController(controller, parent.reason); return () => {}; }
const onAbort = () => abortController(controller, parent.reason); parent.addEventListener("abort", onAbort, { once: true });
return () => parent.removeEventListener("abort", onAbort);}
/** * Creates a child controller linked to a parent signal. * * This advanced helper powers timeout, race, and parallel execution helpers. * * @param parent - Parent signal to link from. * @returns The child controller and an unlink cleanup function. */export function createLinkedController(parent: AbortSignal): { controller: AbortController; unlink: () => void;} { const controller = new AbortController(); const unlink = linkAbortSignal(parent, controller);
return { controller, unlink };}import { type Result, ok } from "./core/result";import { type Cancelled, resultFromSignal } from "./core/runtime";
/** * Waits for a duration while observing an `AbortSignal`. * * Non-positive durations resolve immediately with success. If the signal aborts before the timer * completes, the promise resolves with a cancellation result instead of throwing. * * @param ms - Duration in milliseconds. * @param signal - Signal used to cancel the wait. * @returns A promise resolving to success or cancellation. * * @example * ```ts * const waited = await wait(250, signal); * ``` */export function wait(ms: number, signal: AbortSignal): Promise<Result<void, Cancelled>> { if (signal.aborted) { return Promise.resolve(resultFromSignal(signal)); }
if (ms <= 0) { return Promise.resolve(ok(undefined)); }
return new Promise((resolve) => { const timeout = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(ok(undefined)); }, ms);
const onAbort = () => { clearTimeout(timeout); signal.removeEventListener("abort", onAbort); resolve(resultFromSignal(signal)); };
signal.addEventListener("abort", onAbort, { once: true }); });}/** * Represents a value that may be returned directly or through a Promise. * * Flow helpers accept `Awaitable` callbacks so synchronous and asynchronous logic can share the * same behavior authoring APIs. * * @typeParam T - Value produced either immediately or asynchronously. */export type Awaitable<T> = T | Promise<T>;
/** * Successful `Result` variant. * * `Ok` carries the typed success value through Flow pipelines. Use `ok` to create branded values * that can be detected by `isResult`. * * @typeParam T - Success value type. */export type Ok<T> = { ok: true; value: T;};
/** * Failed `Result` variant. * * `Err` carries expected domain errors. Runtime failures such as cancellation and thrown * exceptions are modeled separately by the runtime helpers. * * @typeParam E - Expected error value type. */export type Err<E> = { ok: false; error: E;};
/** * Explicit success-or-failure outcome used throughout Flow. * * Flow behaviors return `Result` values instead of throwing for expected application failures. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. */export type Result<T, E> = Ok<T> | Err<E>;
/** * Structural result shape accepted by `from`. * * Use this when adapting unbranded result-like values into branded Flow results. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. */export type ResultLike<T, E> = Ok<T> | Err<E>;
const resultBrand = Symbol("archyn.result");
/** * Creates a branded successful result. * * Branded results are recognized by `isResult`, which allows `task` callbacks to distinguish * explicit `Result` returns from plain successful values. * * @typeParam T - Success value type. * @param value - Value to carry in the success variant. * @returns A branded `Ok` result. * * @example * ```ts * const result = ok({ id: "user_1" }); * ``` */export function ok<T>(value: T): Ok<T> { return brandResult({ ok: true, value });}
/** * Creates a branded failed result. * * Use `err` for expected domain failures that should stay typed and recoverable by Flow helpers. * * @typeParam E - Expected error value type. * @param error - Error value to carry in the failure variant. * @returns A branded `Err` result. * * @example * ```ts * const result = err({ kind: "not-found" }); * ``` */export function err<E>(error: E): Err<E> { return brandResult({ ok: false, error });}
/** * Converts a structural result-like value into a branded Flow result. * * This is useful when adapting results from another library or from plain object literals. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Structural success or failure object. * @returns A branded Flow `Result`. */export function from<T, E>(result: ResultLike<T, E>): Result<T, E> { return result.ok ? ok(result.value) : err(result.error);}
/** * Narrows a result to the successful variant. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to inspect. * @returns `true` when the result is `Ok`. */export function isOk<T, E>(result: Result<T, E>): result is Ok<T> { return result.ok;}
/** * Narrows a result to the failed variant. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to inspect. * @returns `true` when the result is `Err`. */export function isErr<T, E>(result: Result<T, E>): result is Err<E> { return !result.ok;}
/** * Exhaustively handles both result variants and returns one value. * * `match` keeps success and error handling explicit without manual branching at the call site. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @typeParam R - Handler return type. * @param result - Result to handle. * @param handlers - Callbacks for the success and failure variants. * @returns The value returned by the matching handler. * * @example * ```ts * const label = match(result, { * ok: (user) => user.name, * err: (error) => error.kind, * }); * ``` */export function match<T, E, R>( result: Result<T, E>, handlers: { ok: (value: T) => R; err: (error: E) => R; },): R { return result.ok ? handlers.ok(result.value) : handlers.err(result.error);}
/** * Returns the success value or throws the error value. * * Prefer typed recovery helpers for expected failures. `unwrap` is best reserved for tests, * boundaries that intentionally throw, or places where a failure is impossible by construction. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to unwrap. * @returns The success value. * @throws The `Err.error` value when the result failed. */export function unwrap<T, E>(result: Result<T, E>): T { if (result.ok) { return result.value; }
throw result.error;}
/** * Returns the success value or a fallback. * * Use this when a failure can be safely collapsed into a default value. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to read. * @param fallback - Value returned when the result failed. * @returns The success value or fallback. * * @example * ```ts * const count = unwrapOr(result, 0); * ``` */export function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T { return result.ok ? result.value : fallback;}
/** * Namespace-style collection of core result helpers. * * This object is convenient when passing the result toolkit as a single value. The individual * named functions remain the preferred imports for tree-shakeable application code. */export const Result = { ok, err, from, isOk, isErr, match, unwrap, unwrapOr,};
/** * Detects branded Flow results created by `ok`, `err`, or `from`. * * `task` uses this guard to preserve explicit results while wrapping plain callback returns in * `ok`. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param value - Plain value or potential result. * @returns `true` when the value is a branded Flow `Result`. */export function isResult<T, E>(value: T | Result<T, E>): value is Result<T, E> { return typeof value === "object" && value !== null && resultBrand in value;}
function brandResult<R extends Ok<unknown> | Err<unknown>>(result: R): R { Object.defineProperty(result, resultBrand, { value: true, });
return result;}import { err, type Result } from "./core/result";import { abortController, createLinkedController, type Behavior, type Cancelled, type RuntimeContext, type Thrown, contextWithSignal, resultFromSignal, runBehavior, thrown,} from "./core/runtime";
/** * Domain error returned when a timeout expires before source completion. */export type TimeoutError = { kind: "timeout";};
/** * Timing-related errors added by timeout and delay helpers. */export type TimingError = TimeoutError | Cancelled;
/** * Wraps a behavior with a timeout. * * The source runs with a child signal linked to the parent. If the timer expires first, the child * is aborted and a timeout domain error is returned. * * @typeParam I - Source input type. * @typeParam O - Source output type. * @typeParam E - Source domain error type. * @typeParam C - Custom context type. * @param source - Behavior to run with a time limit. * @param ms - Timeout in milliseconds. * @returns A behavior with the source result or timing errors. * * @example * ```ts * const boundedLoad = timeout(loadUser, 1000); * ``` */export function timeout<I, O, E, C extends object>( source: Behavior<I, O, E, C>, ms: number,): Behavior<I, O, E | TimingError, C> { return async (input, context) => runWithTimeout(source, input, context, ms);}
/** * Runs one behavior execution with a timeout. * * This advanced helper powers `timeout` and is exported for custom helper authors that need direct * control over input and context. * * @typeParam I - Source input type. * @typeParam O - Source output type. * @typeParam E - Source domain error type. * @typeParam C - Custom context type. * @param source - Behavior to execute. * @param input - Input passed to the behavior. * @param context - Runtime context for this execution. * @param timeoutMs - Timeout in milliseconds. * @returns A result containing source output, source domain error, timing error, or thrown error. */export function runWithTimeout<I, O, E, C extends object>( source: Behavior<I, O, E, C>, input: I, context: RuntimeContext<C>, timeoutMs: number,): Promise<Result<O, E | TimingError | Thrown>> { if (context.signal.aborted) { return Promise.resolve(resultFromSignal(context.signal)); }
const { controller, unlink } = createLinkedController(context.signal); const childContext = contextWithSignal(context, controller.signal);
return new Promise((resolve) => { let settled = false;
const settle = (result: Result<O, E | TimingError | Thrown>) => { if (settled) { return; }
settled = true; clearTimeout(timer); context.signal.removeEventListener("abort", onAbort); unlink(); resolve(result); };
const onAbort = () => { abortController(controller, context.signal.reason); settle(resultFromSignal(context.signal)); };
const timer = setTimeout( () => { settle(err({ kind: "timeout" })); abortController(controller, { kind: "timeout" }); }, Math.max(0, timeoutMs), );
context.signal.addEventListener("abort", onAbort, { once: true });
runBehavior(source, input, childContext) .then(settle) .catch((error: unknown) => settle(thrown(error))); });}Update the import paths to match your project setup.
Delay the start of a Behavior while preserving cancellation and typed errors.
Usage
delay waits before running a source Behavior. It is useful when the pause is part of the workflow contract rather than retry policy.
Use it when:
- Debounce or pace work before a
Behaviorstarts. - Use a typed, cancellable delay without writing custom timer code.
- Keep the source
Behaviortypes unchanged apart from timing errors.
import { delay } from "@/lib/flow/delay";import { task } from "@/lib/flow/task";
const saveDraft = task((draft: { body: string }) => ({ saved: true, draft }));const delayedSave = delay(saveDraft, 300);Behavior
delay calls wait(ms, context.signal) first. If the wait succeeds, it runs the source Behavior with the original input and context.
Source domain errors pass through. Cancellation during the delay returns Cancelled, and cancellation after the delay is handled by the source runtime path.
Types
The source output and error types are preserved, with TimingError added for cancellation during the delay.
Import from @/lib/flow/delay.
Composition Notes
Use delay before a source when the pause is part of the workflow contract.
Do not use delay for backoff after failure; retry delay communicates that intent better.
Related APIs
Source
import { type Behavior, type RuntimeContext, resultFromSignal, runBehavior } from "./core/runtime";import { type TimingError } from "./timeout";import { wait } from "./wait";
/** * Waits before running a source behavior. * * `delay` models a pause that is part of the workflow itself. Cancellation during the delay returns * a timing cancellation error and the source behavior is not started. * * @typeParam I - Input type. * @typeParam O - Source output type. * @typeParam E - Source domain error type. * @typeParam C - Custom context type. * @param source - Behavior to run after the delay. * @param ms - Delay in milliseconds before source execution. * @returns A behavior with the source result or timing errors. * * @example * ```ts * const delayedLoad = delay(loadUser, 250); * ``` */export function delay<I, O, E, C extends object>( source: Behavior<I, O, E, C>, ms: number,): Behavior<I, O, E | TimingError, C> { return async (input: I, context: RuntimeContext<C>) => { if (context.signal.aborted) { return resultFromSignal(context.signal); }
const delayResult = await wait(ms, context.signal);
if (!delayResult.ok) { return delayResult; }
return runBehavior(source, input, context); };}import { type Awaitable, type Err, type Result, err } from "./result";
/** * Runtime error returned when execution is cancelled through an `AbortSignal`. * * Cancellation is cooperative. Flow helpers check the signal before and after async work and pass * linked signals to child behaviors where appropriate. */export type Cancelled = { kind: "cancelled"; reason?: unknown;};
/** * Runtime error returned when user code throws. * * Thrown exceptions are kept separate from expected domain errors so recovery helpers do not hide * programming or platform failures. */export type Thrown = { kind: "thrown"; error: unknown;};
/** * Runtime-level failure union added around every behavior's domain error type. * * Domain errors describe expected application failures. `RuntimeError` describes cancellation or * unexpected thrown exceptions observed by the Flow runtime. */export type RuntimeError = Cancelled | Thrown;
/** * Execution context passed to every behavior. * * The context always includes an `AbortSignal` and may include application-specific fields. * * @typeParam C - Custom context object type. */export type RuntimeContext<C extends object = {}> = C & { signal: AbortSignal;};
/** * Executable Flow workflow unit. * * A behavior receives typed input, reads runtime context, and resolves to a `Result` containing * either typed output, typed domain error, or a runtime error. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. */export type Behavior<I, O, E = unknown, C extends object = {}> = ( input: I, context: RuntimeContext<C>,) => Promise<Result<O, E | RuntimeError>>;
/** * Extracts the input type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorInput<T> = T extends Behavior<infer I, infer _O, infer _E, infer _C> ? I : never;
/** * Extracts the output type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorOutput<T> = T extends Behavior<infer _I, infer O, infer _E, infer _C> ? O : never;
/** * Extracts the expected domain error type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorError<T> = T extends Behavior<infer _I, infer _O, infer E, infer _C> ? E : never;
/** * Extracts the custom context type from a behavior. * * @typeParam T - Behavior type to inspect. */export type BehaviorContext<T> = T extends Behavior<infer _I, infer _O, infer _E, infer C> ? C : never;
/** * Executes a behavior with runtime error protection. * * The runner checks cancellation before and after behavior execution and converts thrown * exceptions into `Thrown` results. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. * @param behavior - Behavior to execute. * @param input - Input passed to the behavior. * @param context - Runtime context containing an `AbortSignal`. * @returns The behavior result, cancellation result, or thrown runtime result. */export async function runBehavior<I, O, E, C extends object>( behavior: Behavior<I, O, E, C>, input: I, context: RuntimeContext<C>,): Promise<Result<O, E | RuntimeError>> { if (context.signal.aborted) { return resultFromSignal(context.signal); }
try { const result = await behavior(input, context);
if (context.signal.aborted) { return resultFromSignal(context.signal); }
return result; } catch (error) { if (context.signal.aborted) { return resultFromSignal(context.signal); }
return thrown(error); }}
/** * Defines a behavior from a callback that returns a `Result`. * * Use `define` for low-level helpers that already operate in the result channel. Most application * code should use `task`, which also accepts plain successful values. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. * @param run - Callback invoked for each behavior execution. * @returns A behavior protected by cancellation and thrown-exception handling. */export function define<I, O, E = unknown, C extends object = {}>( run: (input: I, context: RuntimeContext<C>) => Awaitable<Result<O, E>>,): Behavior<I, O, E, C> { return async (input, context) => { if (context.signal.aborted) { return resultFromSignal(context.signal); }
try { const result = await run(input, context);
if (context.signal.aborted) { return resultFromSignal(context.signal); }
return result; } catch (error) { if (context.signal.aborted) { return cancelled(context.signal.reason); }
return thrown(error); } };}
/** * Runs a behavior with an optional application context. * * If no signal is provided, Flow creates a fresh non-aborted signal. Expected failures remain in * the returned `Result`; thrown exceptions are converted to `Thrown`. * * @typeParam I - Input type. * @typeParam O - Output type. * @typeParam E - Expected domain error type. * @typeParam C - Custom context type. * @param behavior - Behavior to execute. * @param input - Input passed to the behavior. * @param context - Optional custom context and optional `AbortSignal`. * @returns A result containing behavior output, domain error, or runtime error. * * @example * ```ts * const result = await run(loadUser, "user_1"); * ``` */export async function run<I, O, E, C extends object = {}>( behavior: Behavior<I, O, E, C>, input: I, context: C & { signal?: AbortSignal } = {} as C & { signal?: AbortSignal },): Promise<Result<O, E | RuntimeError>> { const { signal = new AbortController().signal, ...rest } = context;
return runBehavior(behavior, input, { ...(rest as C), signal, });}
/** * Creates a cancellation result. * * @param reason - Optional cancellation reason from an `AbortSignal`. * @returns A failed result containing `Cancelled`. */export function cancelled(reason?: unknown): Err<Cancelled> { if (reason === undefined) { return err({ kind: "cancelled" }); }
return err({ kind: "cancelled", reason });}
/** * Narrows an error value to `Cancelled`. * * @param error - Error value to inspect. * @returns `true` when the value is a cancellation runtime error. */export function isCancelled(error: unknown): error is Cancelled { return ( typeof error === "object" && error !== null && "kind" in error && error.kind === "cancelled" );}
/** * Creates a thrown-exception runtime result. * * @param error - Exception or thrown value. * @returns A failed result containing `Thrown`. */export function thrown(error: unknown): Err<Thrown> { return err({ kind: "thrown", error });}
/** * Narrows an error value to `Thrown`. * * @param error - Error value to inspect. * @returns `true` when the value is a thrown runtime error. */export function isThrown(error: unknown): error is Thrown { return typeof error === "object" && error !== null && "kind" in error && error.kind === "thrown";}
/** * Narrows an error value to a Flow runtime error. * * Recovery helpers use this guard so they only handle expected domain errors. * * @param error - Error value to inspect. * @returns `true` for `Cancelled` or `Thrown`. */export function isRuntimeError(error: unknown): error is RuntimeError { return isCancelled(error) || isThrown(error);}
/** * Converts an aborted signal into a cancellation result. * * @param signal - Aborted signal whose reason should be preserved. * @returns A failed result containing `Cancelled`. */export function resultFromSignal(signal: AbortSignal): Err<Cancelled> { return cancelled(signal.reason);}
/** * Replaces the signal on a runtime context. * * This advanced helper is used by timeout and parallel helpers when they create child abort * controllers. * * @typeParam C - Custom context type. * @param context - Existing runtime context. * @param signal - Replacement signal. * @returns A context with the same custom fields and the replacement signal. */export function contextWithSignal<C extends object>( context: RuntimeContext<C>, signal: AbortSignal,): RuntimeContext<C> { return { ...context, signal };}
/** * Aborts a controller only when it has not already been aborted. * * @param controller - Controller to abort. * @param reason - Optional abort reason. */export function abortController(controller: AbortController, reason?: unknown): void { if (!controller.signal.aborted) { controller.abort(reason); }}
/** * Links a parent signal to a child controller. * * The returned cleanup function removes the listener when the child work has settled. * * @param parent - Parent signal to observe. * @param controller - Child controller to abort when the parent aborts. * @returns Cleanup function that unlinks the abort listener. */export function linkAbortSignal(parent: AbortSignal, controller: AbortController): () => void { if (parent.aborted) { abortController(controller, parent.reason); return () => {}; }
const onAbort = () => abortController(controller, parent.reason); parent.addEventListener("abort", onAbort, { once: true });
return () => parent.removeEventListener("abort", onAbort);}
/** * Creates a child controller linked to a parent signal. * * This advanced helper powers timeout, race, and parallel execution helpers. * * @param parent - Parent signal to link from. * @returns The child controller and an unlink cleanup function. */export function createLinkedController(parent: AbortSignal): { controller: AbortController; unlink: () => void;} { const controller = new AbortController(); const unlink = linkAbortSignal(parent, controller);
return { controller, unlink };}import { type Result, ok } from "./core/result";import { type Cancelled, resultFromSignal } from "./core/runtime";
/** * Waits for a duration while observing an `AbortSignal`. * * Non-positive durations resolve immediately with success. If the signal aborts before the timer * completes, the promise resolves with a cancellation result instead of throwing. * * @param ms - Duration in milliseconds. * @param signal - Signal used to cancel the wait. * @returns A promise resolving to success or cancellation. * * @example * ```ts * const waited = await wait(250, signal); * ``` */export function wait(ms: number, signal: AbortSignal): Promise<Result<void, Cancelled>> { if (signal.aborted) { return Promise.resolve(resultFromSignal(signal)); }
if (ms <= 0) { return Promise.resolve(ok(undefined)); }
return new Promise((resolve) => { const timeout = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(ok(undefined)); }, ms);
const onAbort = () => { clearTimeout(timeout); signal.removeEventListener("abort", onAbort); resolve(resultFromSignal(signal)); };
signal.addEventListener("abort", onAbort, { once: true }); });}/** * Represents a value that may be returned directly or through a Promise. * * Flow helpers accept `Awaitable` callbacks so synchronous and asynchronous logic can share the * same behavior authoring APIs. * * @typeParam T - Value produced either immediately or asynchronously. */export type Awaitable<T> = T | Promise<T>;
/** * Successful `Result` variant. * * `Ok` carries the typed success value through Flow pipelines. Use `ok` to create branded values * that can be detected by `isResult`. * * @typeParam T - Success value type. */export type Ok<T> = { ok: true; value: T;};
/** * Failed `Result` variant. * * `Err` carries expected domain errors. Runtime failures such as cancellation and thrown * exceptions are modeled separately by the runtime helpers. * * @typeParam E - Expected error value type. */export type Err<E> = { ok: false; error: E;};
/** * Explicit success-or-failure outcome used throughout Flow. * * Flow behaviors return `Result` values instead of throwing for expected application failures. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. */export type Result<T, E> = Ok<T> | Err<E>;
/** * Structural result shape accepted by `from`. * * Use this when adapting unbranded result-like values into branded Flow results. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. */export type ResultLike<T, E> = Ok<T> | Err<E>;
const resultBrand = Symbol("archyn.result");
/** * Creates a branded successful result. * * Branded results are recognized by `isResult`, which allows `task` callbacks to distinguish * explicit `Result` returns from plain successful values. * * @typeParam T - Success value type. * @param value - Value to carry in the success variant. * @returns A branded `Ok` result. * * @example * ```ts * const result = ok({ id: "user_1" }); * ``` */export function ok<T>(value: T): Ok<T> { return brandResult({ ok: true, value });}
/** * Creates a branded failed result. * * Use `err` for expected domain failures that should stay typed and recoverable by Flow helpers. * * @typeParam E - Expected error value type. * @param error - Error value to carry in the failure variant. * @returns A branded `Err` result. * * @example * ```ts * const result = err({ kind: "not-found" }); * ``` */export function err<E>(error: E): Err<E> { return brandResult({ ok: false, error });}
/** * Converts a structural result-like value into a branded Flow result. * * This is useful when adapting results from another library or from plain object literals. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Structural success or failure object. * @returns A branded Flow `Result`. */export function from<T, E>(result: ResultLike<T, E>): Result<T, E> { return result.ok ? ok(result.value) : err(result.error);}
/** * Narrows a result to the successful variant. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to inspect. * @returns `true` when the result is `Ok`. */export function isOk<T, E>(result: Result<T, E>): result is Ok<T> { return result.ok;}
/** * Narrows a result to the failed variant. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to inspect. * @returns `true` when the result is `Err`. */export function isErr<T, E>(result: Result<T, E>): result is Err<E> { return !result.ok;}
/** * Exhaustively handles both result variants and returns one value. * * `match` keeps success and error handling explicit without manual branching at the call site. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @typeParam R - Handler return type. * @param result - Result to handle. * @param handlers - Callbacks for the success and failure variants. * @returns The value returned by the matching handler. * * @example * ```ts * const label = match(result, { * ok: (user) => user.name, * err: (error) => error.kind, * }); * ``` */export function match<T, E, R>( result: Result<T, E>, handlers: { ok: (value: T) => R; err: (error: E) => R; },): R { return result.ok ? handlers.ok(result.value) : handlers.err(result.error);}
/** * Returns the success value or throws the error value. * * Prefer typed recovery helpers for expected failures. `unwrap` is best reserved for tests, * boundaries that intentionally throw, or places where a failure is impossible by construction. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to unwrap. * @returns The success value. * @throws The `Err.error` value when the result failed. */export function unwrap<T, E>(result: Result<T, E>): T { if (result.ok) { return result.value; }
throw result.error;}
/** * Returns the success value or a fallback. * * Use this when a failure can be safely collapsed into a default value. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param result - Result to read. * @param fallback - Value returned when the result failed. * @returns The success value or fallback. * * @example * ```ts * const count = unwrapOr(result, 0); * ``` */export function unwrapOr<T, E>(result: Result<T, E>, fallback: T): T { return result.ok ? result.value : fallback;}
/** * Namespace-style collection of core result helpers. * * This object is convenient when passing the result toolkit as a single value. The individual * named functions remain the preferred imports for tree-shakeable application code. */export const Result = { ok, err, from, isOk, isErr, match, unwrap, unwrapOr,};
/** * Detects branded Flow results created by `ok`, `err`, or `from`. * * `task` uses this guard to preserve explicit results while wrapping plain callback returns in * `ok`. * * @typeParam T - Success value type. * @typeParam E - Expected error value type. * @param value - Plain value or potential result. * @returns `true` when the value is a branded Flow `Result`. */export function isResult<T, E>(value: T | Result<T, E>): value is Result<T, E> { return typeof value === "object" && value !== null && resultBrand in value;}
function brandResult<R extends Ok<unknown> | Err<unknown>>(result: R): R { Object.defineProperty(result, resultBrand, { value: true, });
return result;}import { err, type Result } from "./core/result";import { abortController, createLinkedController, type Behavior, type Cancelled, type RuntimeContext, type Thrown, contextWithSignal, resultFromSignal, runBehavior, thrown,} from "./core/runtime";
/** * Domain error returned when a timeout expires before source completion. */export type TimeoutError = { kind: "timeout";};
/** * Timing-related errors added by timeout and delay helpers. */export type TimingError = TimeoutError | Cancelled;
/** * Wraps a behavior with a timeout. * * The source runs with a child signal linked to the parent. If the timer expires first, the child * is aborted and a timeout domain error is returned. * * @typeParam I - Source input type. * @typeParam O - Source output type. * @typeParam E - Source domain error type. * @typeParam C - Custom context type. * @param source - Behavior to run with a time limit. * @param ms - Timeout in milliseconds. * @returns A behavior with the source result or timing errors. * * @example * ```ts * const boundedLoad = timeout(loadUser, 1000); * ``` */export function timeout<I, O, E, C extends object>( source: Behavior<I, O, E, C>, ms: number,): Behavior<I, O, E | TimingError, C> { return async (input, context) => runWithTimeout(source, input, context, ms);}
/** * Runs one behavior execution with a timeout. * * This advanced helper powers `timeout` and is exported for custom helper authors that need direct * control over input and context. * * @typeParam I - Source input type. * @typeParam O - Source output type. * @typeParam E - Source domain error type. * @typeParam C - Custom context type. * @param source - Behavior to execute. * @param input - Input passed to the behavior. * @param context - Runtime context for this execution. * @param timeoutMs - Timeout in milliseconds. * @returns A result containing source output, source domain error, timing error, or thrown error. */export function runWithTimeout<I, O, E, C extends object>( source: Behavior<I, O, E, C>, input: I, context: RuntimeContext<C>, timeoutMs: number,): Promise<Result<O, E | TimingError | Thrown>> { if (context.signal.aborted) { return Promise.resolve(resultFromSignal(context.signal)); }
const { controller, unlink } = createLinkedController(context.signal); const childContext = contextWithSignal(context, controller.signal);
return new Promise((resolve) => { let settled = false;
const settle = (result: Result<O, E | TimingError | Thrown>) => { if (settled) { return; }
settled = true; clearTimeout(timer); context.signal.removeEventListener("abort", onAbort); unlink(); resolve(result); };
const onAbort = () => { abortController(controller, context.signal.reason); settle(resultFromSignal(context.signal)); };
const timer = setTimeout( () => { settle(err({ kind: "timeout" })); abortController(controller, { kind: "timeout" }); }, Math.max(0, timeoutMs), );
context.signal.addEventListener("abort", onAbort, { once: true });
runBehavior(source, input, childContext) .then(settle) .catch((error: unknown) => settle(thrown(error))); });}