@onrails/result 0.2.0 → 0.3.1
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/DESIGN.md +11 -18
- package/README.md +14 -59
- package/RECIPES.md +12 -25
- package/dist/{async-1fIhfzFu.d.ts → async-Ci6WSL5-.d.ts} +60 -18
- package/dist/{async-u8U5P2EH.d.cts → async-DcXR7k9K.d.cts} +60 -18
- package/dist/compat/neverthrow.cjs +42 -51
- package/dist/compat/neverthrow.cjs.map +1 -1
- package/dist/compat/neverthrow.d.cts +3 -3
- package/dist/compat/neverthrow.d.ts +3 -3
- package/dist/compat/neverthrow.js +42 -51
- package/dist/compat/neverthrow.js.map +1 -1
- package/dist/extra.cjs +1 -1
- package/dist/extra.cjs.map +1 -1
- package/dist/extra.d.cts +5 -11
- package/dist/extra.d.ts +5 -11
- package/dist/extra.js +1 -1
- package/dist/extra.js.map +1 -1
- package/dist/fluent.cjs +66 -28
- package/dist/fluent.cjs.map +1 -1
- package/dist/fluent.d.cts +41 -6
- package/dist/fluent.d.ts +41 -6
- package/dist/fluent.js +66 -28
- package/dist/fluent.js.map +1 -1
- package/dist/index.cjs +95 -95
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +168 -44
- package/dist/index.d.ts +168 -44
- package/dist/index.js +90 -95
- package/dist/index.js.map +1 -1
- package/dist/railway.cjs +101 -172
- package/dist/railway.cjs.map +1 -1
- package/dist/railway.d.cts +25 -179
- package/dist/railway.d.ts +25 -179
- package/dist/railway.js +102 -162
- package/dist/railway.js.map +1 -1
- package/dist/try-gen.cjs +1 -1
- package/dist/try-gen.cjs.map +1 -1
- package/dist/try-gen.js +1 -1
- package/dist/try-gen.js.map +1 -1
- package/package.json +1 -16
- package/skills/railway-do-notation/SKILL.md +29 -68
- package/skills/result-composition/SKILL.md +2 -4
- package/dist/$.cjs +0 -40
- package/dist/$.cjs.map +0 -1
- package/dist/$.js +0 -36
- package/dist/$.js.map +0 -1
- package/dist/_.d.cts +0 -2
- package/dist/_.d.ts +0 -2
- package/dist/interop.cjs +0 -433
- package/dist/interop.cjs.map +0 -1
- package/dist/interop.d.cts +0 -75
- package/dist/interop.d.ts +0 -75
- package/dist/interop.js +0 -429
- package/dist/interop.js.map +0 -1
- package/dist/validation.cjs +0 -53
- package/dist/validation.cjs.map +0 -1
- package/dist/validation.d.cts +0 -72
- package/dist/validation.d.ts +0 -72
- package/dist/validation.js +0 -48
- package/dist/validation.js.map +0 -1
package/dist/railway.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/result.ts","../src/types.ts","../src/async.ts","../src/railway-core.ts","../src/railway-steps.ts"],"names":[],"mappings":";;;AAaO,IAAM,EAAA,GAAK,CAAe,KAAA,MAA4B;AAAA,EAC3D,IAAA,EAAM,IAAA;AAAA,EACN;AACF,CAAA,CAAA;AAWO,IAAM,GAAA,GAAM,CAAyB,KAAA,MAA4B;AAAA,EACtE,IAAA,EAAM,KAAA;AAAA,EACN;AACF,CAAA,CAAA;AAYO,IAAM,IAAA,GAAO,CAAO,MAAA,KAA6C,MAAA,CAAO,IAAA,KAAS,IAAA;AAYjF,IAAM,KAAA,GAAQ,CAAO,MAAA,KAA8C,MAAA,CAAO,IAAA,KAAS,KAAA;AAS1F,IAAM,OAAA,GAAU,CAAU,MAAA,EAAsB,EAAA,KAC9C,KAAK,MAAM,CAAA,GAAI,EAAA,CAAG,EAAA,CAAG,OAAO,KAAK,CAAC,CAAA,GAAI,GAAA,CAAI,OAAO,KAAK,CAAA;AAcjD,SAAS,OACX,IAAA,EACM;AACT,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,OAAA,CAAQ,KAAK,CAAC,CAAA,EAAG,IAAA,CAAK,CAAC,CAAC,CAAA;AACtD,EAAA,MAAM,EAAA,GAAK,KAAK,CAAC,CAAA;AACjB,EAAA,OAAO,CAAC,MAAA,KAAqC,OAAA,CAAQ,MAAA,EAAQ,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,QAAA,KAEA,QAAA,CAAS,UAAA,CAAW,GAAA,EAAK,EAAE;AAMxB,IAAM,gBAAA,GACX,CACE,GAAA,EACA,EAAA,EACA,QAAA,KAEF,CACE,QAAA,KAEA,QAAA,CAAS,WAAA,CAAY,GAAA,EAAK,EAAA,EAAI,QAAQ;AAGnC,IAAM,cAAA,GACX,CAA2C,GAAA,EAAQ,EAAA,KACnD,CACE,QAAA,KAEA,QAAA,CAAS,SAAA,CAAU,GAAA,EAAK,EAAE;AAGvB,IAAM,WAAA,GACX,CAAwC,GAAA,EAAQ,EAAA,KAChD,CACE,QAAA,KAEA,QAAA,CAAS,MAAA,CAAO,GAAA,EAAK,EAAE;AAGpB,IAAM,YAAA,GACX,CACE,GAAA,EACA,MAAA,EACA,SAAA,KAEF,CACE,QAAA,KAEA,QAAA,CAAS,OAAA,CAAQ,GAAA,EAAK,MAAA,EAAQ,SAAS;AAMpC,IAAM,aAAA,GACX,CAAyB,QAAA,KACzB,CACE,QAAA,KACkE;AAElE,EAAA,MAAM,aAAA,GAAgB,QAAA;AACtB,EAAA,OAAO,QAAA,CAAS,SAAS,aAAa,CAAA;AAKxC;AAMK,IAAM,SACX,CAAsB,EAAA,KACtB,CAA2B,QAAA,KACzB,QAAA,CAAS,OAAO,EAAE","file":"railway.cjs","sourcesContent":["import type { Err, Ok, Result } from \"./types.js\";\n\nexport type { Err, Ok, Result } from \"./types.js\";\n\n/**\n * Lifts a value into the success track.\n *\n * @example\n * ```ts\n * const r = ok(42); // Result<number, never>\n * const typed: Result<number, \"parse\"> = ok(1);\n * ```\n */\nexport const ok = <T, E = never>(value: T): Result<T, E> => ({\n _tag: \"Ok\",\n value,\n});\n\n/**\n * Lifts a value into the error track.\n *\n * @example\n * ```ts\n * const r = err({ kind: \"parse\", message: \"bad json\" });\n * // Result<never, { kind: \"parse\"; message: string }>\n * ```\n */\nexport const err = <T = never, E = unknown>(error: E): Result<T, E> => ({\n _tag: \"Err\",\n error,\n});\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Ok`.\n *\n * @example\n * ```ts\n * if (isOk(r)) {\n * console.log(r.value); // narrowed to Ok branch\n * }\n * ```\n */\nexport const isOk = <T, E>(result: Result<T, E>): result is Ok<T, E> => result._tag === \"Ok\";\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Err`.\n *\n * @example\n * ```ts\n * if (isErr(r)) {\n * metrics.inc(\"error\", { kind: r.error.kind });\n * }\n * ```\n */\nexport const isErr = <T, E>(result: Result<T, E>): result is Err<T, E> => result._tag === \"Err\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dual-form helpers — each export accepts either shape:\n// data-first: `map(result, fn)`\n// curried: `map(fn)(result)`\n// Arity at the call site selects the overload.\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst mapImpl = <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> =>\n isOk(result) ? ok(fn(result.value)) : err(result.error);\n\n/**\n * Transform the `Ok` value, passing `Err` through unchanged. Dual-form:\n * call data-first or curried (for use with {@link pipe}).\n *\n * @example\n * ```ts\n * map(ok(2), (n) => n * 3); // Ok 6 — data-first\n * pipe(ok(\"x\"), map((s) => s.length));// Ok 1 — curried\n * ```\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;\nexport function map<T, U>(fn: (value: T) => U): <E>(result: Result<T, E>) => Result<U, E>;\nexport function map(\n ...args: [Result<unknown, unknown>, (value: unknown) => unknown] | [(value: unknown) => unknown]\n): unknown {\n if (args.length === 2) return mapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => mapImpl(result, fn);\n}\n\nconst mapErrImpl = <T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> =>\n isErr(result) ? err(fn(result.error)) : ok(result.value);\n\n/**\n * Transform the `Err` value, passing `Ok` through unchanged. Useful for\n * unifying heterogeneous failure types into one app-level union.\n *\n * @example\n * ```ts\n * type AppError = { kind: \"http\"; status: number } | { kind: \"parse\" };\n * pipe(\n * fetchSync(url), // Result<Body, { status: number }>\n * mapErr((e): AppError => ({ kind: \"http\", status: e.status })),\n * );\n * ```\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;\nexport function mapErr<E, F>(fn: (error: E) => F): <T>(result: Result<T, E>) => Result<T, F>;\nexport function mapErr(\n ...args: [Result<unknown, unknown>, (error: unknown) => unknown] | [(error: unknown) => unknown]\n): unknown {\n if (args.length === 2) return mapErrImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => mapErrImpl(result, fn);\n}\n\nconst bimapImpl = <T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): Result<U, F> => (isOk(result) ? ok(onOk(result.value)) : err(onErr(result.error)));\n\n/**\n * Transform both tracks at once — `Ok` via `onOk`, `Err` via `onErr`.\n * Equivalent to `mapErr(onErr)(map(onOk)(result))` but in one pass.\n *\n * @example\n * ```ts\n * bimap(parsed, (cfg) => cfg.name, (e) => ({ kind: \"input\", cause: e }));\n * ```\n */\nexport function bimap<T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): Result<U, F>;\nexport function bimap<T, U, E, F>(\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n): (result: Result<T, E>) => Result<U, F>;\nexport function bimap(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => unknown, (error: unknown) => unknown]\n | [(value: unknown) => unknown, (error: unknown) => unknown]\n): unknown {\n if (args.length === 3) return bimapImpl(args[0], args[1], args[2]);\n const [onOk, onErr] = args;\n return (result: Result<unknown, unknown>) => bimapImpl(result, onOk, onErr);\n}\n\nconst flatMapImpl = <T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, F>,\n): Result<U, E | F> => (isOk(result) ? fn(result.value) : err(result.error));\n\n/**\n * Canonical bind (Fantasy Land `chain`). Chains a Result-returning step,\n * widening the error union to `E | F`. Short-circuits on `Err`.\n *\n * @example\n * ```ts\n * flatMap(parseInput(raw), (data) =>\n * data.id != null ? ok(data) : err({ kind: \"missing_id\" as const }),\n * );\n * // Result<Data, ParseError | { kind: \"missing_id\" }>\n * ```\n */\nexport function flatMap<T, U, E, F>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, F>,\n): Result<U, E | F>;\nexport function flatMap<T, U, F>(\n fn: (value: T) => Result<U, F>,\n): <E>(result: Result<T, E>) => Result<U, E | F>;\nexport function flatMap(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => Result<unknown, unknown>]\n | [(value: unknown) => Result<unknown, unknown>]\n): unknown {\n if (args.length === 2) return flatMapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => flatMapImpl(result, fn);\n}\n\nconst recoverImpl = <T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F> => (isErr(result) ? fn(result.error) : ok(result.value));\n\n/**\n * Error-track bind — runs `fn` only when the result is `Err`, allowing\n * a failed workflow to recover to `Ok` or remap the failure. Mirror of\n * {@link flatMap} on the error channel.\n *\n * @example\n * ```ts\n * recover(networkResult, (e) =>\n * e.kind === \"rate_limit\" ? ok(cachedBody) : err(e),\n * );\n * ```\n */\nexport function recover<T, E, F>(\n result: Result<T, E>,\n fn: (error: E) => Result<T, F>,\n): Result<T, F>;\nexport function recover<T, E, F>(\n fn: (error: E) => Result<T, F>,\n): (result: Result<T, E>) => Result<T, F>;\nexport function recover(\n ...args:\n | [Result<unknown, unknown>, (error: unknown) => Result<unknown, unknown>]\n | [(error: unknown) => Result<unknown, unknown>]\n): unknown {\n if (args.length === 2) return recoverImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => recoverImpl(result, fn);\n}\n\nconst tapImpl = <T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> => {\n if (isOk(result)) fn(result.value);\n return result;\n};\n\n/**\n * Observe the `Ok` value for side effects (logging, metrics) without\n * changing the carried value. Passes `Err` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * tap((cfg) => log.info({ msg: \"parsed\", name: cfg.name })),\n * flatMap(validate),\n * );\n * ```\n */\nexport function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E>;\nexport function tap<T>(fn: (value: T) => void): <E>(result: Result<T, E>) => Result<T, E>;\nexport function tap(\n ...args: [Result<unknown, unknown>, (value: unknown) => void] | [(value: unknown) => void]\n): unknown {\n if (args.length === 2) return tapImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => tapImpl(result, fn);\n}\n\nconst tapErrImpl = <T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> => {\n if (isErr(result)) fn(result.error);\n return result;\n};\n\n/**\n * Observe the `Err` value for side effects (logging, metrics) without\n * changing the carried error. Passes `Ok` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * loadUser(id),\n * tapErr((e) => metrics.inc(\"user.load.fail\", { kind: e.kind })),\n * );\n * ```\n */\nexport function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E>;\nexport function tapErr<E>(fn: (error: E) => void): <T>(result: Result<T, E>) => Result<T, E>;\nexport function tapErr(\n ...args: [Result<unknown, unknown>, (error: unknown) => void] | [(error: unknown) => void]\n): unknown {\n if (args.length === 2) return tapErrImpl(args[0], args[1]);\n const fn = args[0];\n return (result: Result<unknown, unknown>) => tapErrImpl(result, fn);\n}\n\nconst matchImpl = <T, E, U>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): U => (isOk(result) ? onOk(result.value) : onErr(result.error));\n\n/**\n * Terminal collapse — fold both tracks into a single value. Dual-form:\n * 3-args data-first, 2-args curried for {@link pipe}. Returns whatever\n * the handlers return.\n *\n * For files that also import `match` from `ts-pattern`, use a namespace\n * import (`import * as R from \"@onrails/result\"` → `R.match`) to dissolve\n * the collision.\n *\n * @example\n * ```ts\n * const html = match(parsed, (cfg) => render(cfg), (e) => renderError(e));\n * ```\n */\nexport function match<T, E, U>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): U;\nexport function match<T, E, U>(\n onOk: (value: T) => U,\n onErr: (error: E) => U,\n): (result: Result<T, E>) => U;\nexport function match(\n ...args:\n | [Result<unknown, unknown>, (value: unknown) => unknown, (error: unknown) => unknown]\n | [(value: unknown) => unknown, (error: unknown) => unknown]\n): unknown {\n if (args.length === 3) return matchImpl(args[0], args[1], args[2]);\n const [onOk, onErr] = args;\n return (result: Result<unknown, unknown>) => matchImpl(result, onOk, onErr);\n}\n\n/**\n * Returns the `Ok` value, or `defaultValue` when the result is `Err`.\n *\n * @example\n * ```ts\n * unwrapOr(parsedSetting, \"default-value\");\n * ```\n */\nexport const unwrapOr = <T, E>(result: Result<T, E>, defaultValue: T): T =>\n isOk(result) ? result.value : defaultValue;\n\n/**\n * Test/assert helper — returns the `Ok` value, or **throws the original `Err`\n * value** when called on an `Err`. This is the assertion tier (RFC 0001 §4):\n * intended for `*.spec.ts` / `*.test.ts`, where throwing fails the test loudly.\n * In business logic prefer {@link match} or {@link unwrapOr}; the lint plugins\n * flag `unwrapOk` outside test files.\n *\n * @returns the unwrapped `Ok` value\n * @throws the carried `Err` value when the result is `Err`\n *\n * @example\n * ```ts\n * // in a *.spec.ts\n * expect(unwrapOk(ok(5))).toBe(5);\n * expect(() => unwrapOk(err(error))).toThrow(error);\n * ```\n */\nexport function unwrapOk<T, E>(result: Result<T, E>): T {\n if (isErr(result)) throw result.error;\n return result.value;\n}\n\n/**\n * Test/assert helper — returns the `Err` value, or **throws a `TypeError`**\n * when called on an `Ok`. Mirror of {@link unwrapOk} on the error track and\n * part of the same assertion tier (RFC 0001 §4): intended for `*.spec.ts` /\n * `*.test.ts`. Prefer {@link match} / {@link unwrapOr} in business logic; the\n * lint plugins flag `unwrapErr` outside test files.\n *\n * @returns the unwrapped `Err` value\n * @throws `TypeError` when the result is `Ok`\n *\n * @example\n * ```ts\n * // in a *.spec.ts\n * expect(unwrapErr(err(\"x\"))).toBe(\"x\");\n * expect(() => unwrapErr(ok(5))).toThrow(TypeError);\n * ```\n */\nexport function unwrapErr<T, E>(result: Result<T, E>): E {\n if (isOk(result)) throw new TypeError(\"unwrapErr called on Ok\");\n return result.error;\n}\n\n/**\n * Wraps a throwing sync function, returning a function that produces a\n * {@link Result} instead of throwing. Thrown errors pass through `onThrow` to\n * become a typed `Err`; a normal return becomes `Ok`. The neverthrow analogue\n * is `Result.fromThrowable`.\n *\n * @param fn - the throwing function to wrap\n * @param onThrow - maps a thrown value to the `Err` channel\n * @returns a function with `fn`'s parameters that returns `Result<ReturnType, E>`\n *\n * @example\n * ```ts\n * type ParseError = { kind: \"parse\"; message: string };\n * const parse = trySync(\n * JSON.parse,\n * (e): ParseError => ({ kind: \"parse\", message: String(e) }),\n * );\n * parse(\"{}\"); // Ok({})\n * parse(\"nope\"); // Err({ kind: \"parse\", … })\n * ```\n */\nexport function trySync<A extends readonly unknown[], T, E>(\n fn: (...args: A) => T,\n onThrow: (error: unknown) => E,\n): (...args: A) => Result<T, E>;\nexport function trySync<F extends (...args: never) => unknown, E>(\n fn: F,\n onThrow: (error: unknown) => E,\n): (...args: Parameters<F>) => Result<ReturnType<F>, E>;\nexport function trySync(\n fn: (...args: never) => unknown,\n onThrow: (error: unknown) => unknown,\n): (...args: never) => Result<unknown, unknown> {\n return (...args: never) => {\n try {\n return ok(fn(...args));\n } catch (error) {\n return err(onThrow(error));\n }\n };\n}\n\n/**\n * Variadic value-first pipe — threads `value` through up to nine unary fns,\n * left-to-right. Use {@link pipe} when you already have a starting value;\n * use {@link flow} to define a reusable composed function with no value yet.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * map((cfg) => cfg.name),\n * flatMap((name) => (name ? ok(name) : err({ kind: \"empty\" as const }))),\n * tap(log),\n * );\n * ```\n */\nexport function pipe<A>(value: A): A;\nexport function pipe<A, B>(value: A, ab: (a: A) => B): B;\nexport function pipe<A, B, C>(value: A, ab: (a: A) => B, bc: (b: B) => C): C;\nexport function pipe<A, B, C, D>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D;\nexport function pipe<A, B, C, D, E>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): E;\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): F;\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): G;\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): H;\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): I;\nexport function pipe(value: unknown, ...fns: ReadonlyArray<(x: unknown) => unknown>): unknown {\n let acc = value;\n for (const fn of fns) {\n acc = fn(acc);\n }\n return acc;\n}\n","/**\n * The core railway type: a tagged union carrying either a success value\n * (`Ok<T>`) or a failure value (`Err<E>`). It is a plain discriminated union\n * on `_tag` — no classes — so it is immutable and tree-shake friendly. Narrow\n * with {@link isOk} / {@link isErr} to read `.value` / `.error`.\n *\n * @typeParam T - the `Ok` value type\n * @typeParam E - the `Err` error type\n *\n * @example\n * ```ts\n * function parse(raw: string): Result<number, \"nan\"> {\n * const n = Number(raw);\n * return Number.isNaN(n) ? err(\"nan\") : ok(n);\n * }\n * ```\n */\nexport type Result<T, E> =\n | { readonly _tag: \"Ok\"; readonly value: T }\n | { readonly _tag: \"Err\"; readonly error: E };\n\n/**\n * The success branch of a {@link Result} — `{ _tag: \"Ok\"; value: T }`.\n * The `E` parameter keeps the type assignable to `Result<T, E>`.\n */\nexport type Ok<T, E = never> = Extract<Result<T, E>, { _tag: \"Ok\" }>;\n\n/**\n * The failure branch of a {@link Result} — `{ _tag: \"Err\"; error: E }`.\n */\nexport type Err<T, E> = Extract<Result<T, E>, { _tag: \"Err\" }>;\n\n/**\n * Error subclass representing an **unexpected** defect — a thrown exception or\n * promise rejection that was not part of the modelled `Err` union. Used as the\n * default mapping when {@link fromAsync} is called without an `onDefect`\n * handler; the original cause is preserved on `.cause`.\n *\n * @example\n * ```ts\n * const defect = new UnexpectedError(\"Unexpected async defect\", caught);\n * defect.cause; // the original thrown value\n * ```\n */\nexport class UnexpectedError extends Error {\n constructor(\n message: string,\n override readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"UnexpectedError\";\n }\n}\n","import { err, isErr, map, mapErr, ok } from \"./result.js\";\nimport type { Result } from \"./types.js\";\nimport { UnexpectedError } from \"./types.js\";\n\ntype PromiseFactory<T, E> = () => Promise<Result<T, E>>;\ntype AsyncOk<R> = R extends ResultAsync<infer T, unknown> ? T : never;\ntype AsyncErr<R> = R extends ResultAsync<unknown, infer E> ? E : never;\ntype CombineTupleAsync<R extends readonly ResultAsync<unknown, unknown>[]> = ResultAsync<\n { [K in keyof R]: AsyncOk<R[K]> },\n { [K in keyof R]: AsyncErr<R[K]> }[number]\n>;\n\nconst liftPromiseResult = async <T, E>(\n promise: Promise<Result<T, E>>,\n onDefect: (error: unknown) => E | UnexpectedError,\n): Promise<Result<T, E | UnexpectedError>> => {\n try {\n const result = await promise;\n if (isErr(result)) {\n return result;\n }\n // Auto-flatten one level: Ok<Result<…>> from double-wrapped interop.\n return isResultLike<T, E | UnexpectedError>(result.value) ? result.value : result;\n } catch (error) {\n return err(onDefect(error));\n }\n};\n\n/** Collapses settled results left-to-right, short-circuiting on the first `Err`. */\nconst sequenceSettled = (\n settled: readonly Result<unknown, unknown>[],\n): Result<unknown[], unknown> => {\n const values: unknown[] = [];\n for (const result of settled) {\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n};\n\n/**\n * Async railway carrier. Wraps a deferred `Promise<Result<T, E>>` and exposes\n * the same dual-track transforms as the sync {@link Result} — `map`, `flatMap`,\n * `recover`, `tap`, `match`. The public API never surfaces `Promise<Result<…>>`\n * directly: `await` the instance (it is thenable) or call {@link resolve} /\n * {@link match} to settle it.\n *\n * Construct via the static factories ({@link ok}, {@link err}, {@link fromPromise},\n * {@link defer}, …) rather than `new` — the constructor is `protected`.\n *\n * @typeParam T - the `Ok` value type\n * @typeParam E - the `Err` error type\n *\n * @example\n * ```ts\n * const user = ResultAsync.fromPromise(api.getUser(id), toAppError)\n * .map((u) => u.profile)\n * .recover(() => ResultAsync.ok(guestProfile));\n *\n * const r = await user; // Result<Profile, AppError>\n * ```\n */\nexport class ResultAsync<T, E> {\n private promise: Promise<Result<T, E>> | null = null;\n\n protected constructor(protected readonly run: PromiseFactory<T, E>) {}\n\n /**\n * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}.\n *\n * @example\n * ```ts\n * const ra = ResultAsync.fromResult(ok(42)); // ResultAsync<number, never>\n * ```\n */\n static fromResult<T, E>(result: Result<T, E>): ResultAsync<T, E> {\n return new ResultAsync(async () => result);\n }\n\n /**\n * Wraps a `PromiseLike<T>` that may reject. Rejections pass through `onReject`\n * to become a typed `Err`; resolution becomes `Ok<T>`.\n *\n * @param promise - the promise to wrap\n * @param onReject - maps a rejection reason to the `Err` channel\n *\n * @example\n * ```ts\n * const body = ResultAsync.fromPromise(\n * fetch(url).then((r) => r.text()),\n * (e): NetError => ({ kind: \"net\", cause: String(e) }),\n * );\n * ```\n */\n static fromPromise<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n ): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n try {\n return ok(await promise);\n } catch (error) {\n return err(onReject(error));\n }\n });\n }\n\n /**\n * Wraps a `PromiseLike<T>` that is **guaranteed not to reject**, skipping the\n * `onReject` mapper. Use only when rejection is provably impossible.\n *\n * @example\n * ```ts\n * const now = ResultAsync.fromSafePromise(Promise.resolve(Date.now()));\n * ```\n */\n static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(await promise));\n }\n\n /**\n * Defers work until {@link resolve}. Unlike {@link fromPromise}, the factory\n * does not run until the `ResultAsync` is resolved (e.g. by `combineTuple` /\n * `combineTupleParallel`). The factory runs at most once — `resolve` memoizes.\n *\n * @example\n * ```ts\n * const insert = ResultAsync.defer(() => db.orders.insert(row));\n * // nothing has run yet\n * const r = await insert; // factory runs exactly once here\n * ```\n */\n static defer<T, E>(fn: () => Promise<Result<T, E>>): ResultAsync<T, E> {\n return new ResultAsync(fn);\n }\n\n /**\n * Lifts a value into an `Ok` async result.\n *\n * @example\n * ```ts\n * const r = ResultAsync.ok(42); // ResultAsync<number, never>\n * ```\n */\n static ok<T>(value: T): ResultAsync<T, never>;\n static ok<T, E>(value: T): ResultAsync<T, E>;\n static ok<T, E = never>(value: T): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(value));\n }\n\n /**\n * Lifts an error into an `Err` async result.\n *\n * @example\n * ```ts\n * const r = ResultAsync.err({ kind: \"not_found\" as const });\n * ```\n */\n static err<T = never, E = unknown>(error: E): ResultAsync<T, E> {\n return new ResultAsync(async () => err(error));\n }\n\n /**\n * Lifts an existing `Promise<Result<T, E>>` (e.g. from interop code) into a\n * {@link ResultAsync}, auto-flattening one level of double-wrapping. A thrown\n * defect is routed through `onDefect`, defaulting to {@link UnexpectedError}.\n *\n * @param promise - a promise that already yields a `Result`\n * @param onDefect - maps an unexpected throw to the `Err` channel\n * @see {@link fromAsync} from `@onrails/result/interop`\n */\n static fromResultPromise<T, E>(\n promise: Promise<Result<T, E>>,\n onDefect?: (error: unknown) => E | UnexpectedError,\n ): ResultAsync<T, E | UnexpectedError> {\n const mapDefect =\n onDefect ?? ((error: unknown) => new UnexpectedError(\"Unexpected async defect\", error));\n return new ResultAsync(() => liftPromiseResult(promise, mapDefect));\n }\n\n /**\n * Combines a homogeneous array of async results into one. Resolves\n * **sequentially** in input order, short-circuiting on the first `Err`.\n * For heterogeneous tuples that preserve per-index types, use\n * {@link combineTuple}; for wall-clock overlap, {@link combineTupleParallel}.\n *\n * @example\n * ```ts\n * const all = ResultAsync.combine([loadA(), loadB(), loadC()]);\n * // ResultAsync<Item[], LoadError>\n * ```\n */\n static combine<T, E>(results: readonly ResultAsync<T, E>[]): ResultAsync<T[], E> {\n return new ResultAsync(async () => {\n const values: T[] = [];\n for (const ra of results) {\n const result = await ra.resolve();\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n });\n }\n\n /**\n * Heterogeneous async tuple combine — resolves branches **sequentially**\n * (left-to-right), returning the first `Err` in input order. Preserves each\n * branch's `Ok` type by position, so the result destructures type-safely.\n * This is the canonical sequential async combine (replaces the former\n * `sequenceTupleAsync`).\n *\n * @example\n * ```ts\n * const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()] as const);\n * // ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>\n * const r = await combined;\n * if (isOk(r)) {\n * const [cfg, catalog] = r.value; // typed per position\n * }\n * ```\n */\n static combineTuple<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Runtime identical to combine; the cast restores per-index tuple types.\n return ResultAsync.combine(\n results as readonly ResultAsync<unknown, unknown>[],\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Like {@link combineTuple}, but starts every branch before awaiting (wall-clock\n * parallel for independent IO). On failure, returns the first `Err` in input order.\n *\n * @example\n * ```ts\n * // independent IO — overlap them\n * const combined = ResultAsync.combineTupleParallel([\n * loadProfile(id),\n * loadMetrics(id),\n * ] as const);\n * ```\n */\n static combineTupleParallel<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Cast restores per-index tuple types over the untyped sequence core.\n return new ResultAsync(async () =>\n sequenceSettled(await Promise.all(results.map((ra) => ra.resolve()))),\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Transforms the `Ok` value, passing `Err` through unchanged.\n *\n * @example\n * ```ts\n * ResultAsync.ok(2).map((n) => n * 3); // ResultAsync<number> → Ok 6\n * ```\n */\n map<U>(fn: (value: T) => U): ResultAsync<U, E> {\n return new ResultAsync(async () => map(await this.resolve(), fn));\n }\n\n /**\n * Transforms the `Err` value, passing `Ok` through unchanged — useful for\n * unifying heterogeneous failures into one app-level union.\n *\n * @example\n * ```ts\n * load(id).mapErr((e): AppError => ({ kind: \"load\", cause: e }));\n * ```\n */\n mapErr<F>(fn: (error: E) => F): ResultAsync<T, F> {\n return new ResultAsync(async () => mapErr(await this.resolve(), fn));\n }\n\n /**\n * Canonical bind — chains a step that itself returns a `ResultAsync` or sync\n * `Result`, short-circuiting on `Err`. Error types accumulate (`E | F`).\n *\n * @example\n * ```ts\n * authenticate(req)\n * .flatMap((user) => loadProfile(user.id)) // ResultAsync\n * .flatMap((p) => validate(p)); // sync Result also accepted\n * ```\n */\n flatMap<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return new ResultAsync<U, E | F>(async () => {\n const first = await this.resolve();\n if (isErr(first)) {\n return first;\n }\n const next = fn(first.value);\n if (next instanceof ResultAsync) {\n return next.resolve();\n }\n if (isResultLike<U, F>(next)) {\n return next;\n }\n return isCompatLike<U, F>(next) ? next.inner : next;\n });\n }\n\n /**\n * neverthrow-compat alias of {@link flatMap}. Kept as the documented compat\n * tier; prefer `flatMap` in new code.\n *\n * @example\n * ```ts\n * authenticate(req).andThen((user) => loadProfile(user.id));\n * ```\n */\n andThen<U, F = E>(\n fn: (value: T) => ResultAsync<U, F> | Result<U, F> | { inner: Result<U, F> },\n ): ResultAsync<U, E | F> {\n return this.flatMap(fn);\n }\n\n /**\n * Error-channel bind — runs `fn` only on `Err`, swapping in a recovery\n * `ResultAsync` or sync `Result`. `Ok` passes through. The mirror of\n * {@link flatMap} on the error track.\n *\n * @example\n * ```ts\n * loadFromCache(id).recover(() => loadFromOrigin(id));\n * ```\n */\n recover<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return new ResultAsync<T, F>(async () => {\n const first = await this.resolve();\n if (!isErr(first)) {\n return first;\n }\n const next = fn(first.error);\n return next instanceof ResultAsync ? next.resolve() : next;\n });\n }\n\n /**\n * neverthrow-compat alias of {@link recover}. Kept as the documented compat\n * tier; prefer `recover` in new code.\n *\n * @example\n * ```ts\n * loadFromCache(id).orElse(() => loadFromOrigin(id));\n * ```\n */\n orElse<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return this.recover(fn);\n }\n\n /**\n * Runs a side effect on the `Ok` value and passes the result through\n * unchanged; a no-op on `Err`. Mirrors {@link tapErr}.\n *\n * @example\n * ```ts\n * saveUser(u).tap((saved) => analytics.track(\"user_saved\", saved.id));\n * ```\n */\n tap(fn: (value: T) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (!isErr(result)) {\n fn(result.value);\n }\n return result;\n });\n }\n\n /**\n * Runs a side effect on the `Err` value and passes the result through\n * unchanged; a no-op on `Ok`. The error-track mirror of {@link tap}.\n *\n * @example\n * ```ts\n * saveUser(u).tapErr((e) => logger.warn(\"save failed\", e));\n * ```\n */\n tapErr(fn: (error: E) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (isErr(result)) {\n fn(result.error);\n }\n return result;\n });\n }\n\n /**\n * Settles to the `Ok` value, or `defaultValue` if `Err`. Terminal — returns a\n * plain `Promise`, not a `ResultAsync`.\n *\n * @example\n * ```ts\n * const profile = await loadProfile(id).unwrapOr(guestProfile);\n * ```\n */\n unwrapOr<U>(defaultValue: U): Promise<T | U> {\n return this.resolve().then((result) => (isErr(result) ? defaultValue : result.value));\n }\n\n /**\n * Terminal collapse — folds both tracks into a single awaited value. Returns\n * a plain `Promise`, settling the carrier exactly once.\n *\n * @param onOk - handles the `Ok` value\n * @param onErr - handles the `Err` value\n *\n * @example\n * ```ts\n * const status = await save(row).match(\n * () => 200,\n * (e) => (e.kind === \"conflict\" ? 409 : 500),\n * );\n * ```\n */\n match<U1, U2 = U1>(onOk: (value: T) => U1, onErr: (error: E) => U2): Promise<U1 | U2> {\n return this.resolve().then((result) =>\n isErr(result) ? onErr(result.error) : onOk(result.value),\n );\n }\n\n /**\n * Settles the carrier to a bare sync {@link Result}, memoizing so the\n * underlying factory runs at most once. Prefer `await ra` (the thenable) or\n * {@link match} in app code; use `resolve` when you need the tagged union back.\n *\n * @example\n * ```ts\n * const r = await load(id).resolve(); // Result<Data, LoadError>\n * if (isOk(r)) use(r.value);\n * ```\n */\n resolve(): Promise<Result<T, E>> {\n if (!this.promise) {\n this.promise = this.run();\n }\n return this.promise;\n }\n\n /**\n * Thenable shim — `await ra` resolves to a bare tagged-union `Result<T, E>`.\n * Narrow with `isOk(r)` / `isErr(r)` to read `.value` / `.error`.\n */\n // biome-ignore lint/suspicious/noThenProperty: makes ResultAsync awaitable\n then<R1 = Result<T, E>, R2 = never>(\n onfulfilled?: ((value: Result<T, E>) => R1 | PromiseLike<R1>) | undefined | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | undefined | null,\n ): Promise<R1 | R2> {\n return this.resolve().then(\n // Safe: without onfulfilled, R1 stays at its Result<T, E> default.\n (r) => (onfulfilled ? onfulfilled(r) : (r as unknown as R1)),\n onrejected ?? undefined,\n );\n }\n}\n\nfunction isResultLike<U, F>(v: unknown): v is Result<U, F> {\n return (\n typeof v === \"object\" &&\n v !== null &&\n \"_tag\" in v &&\n ((v as { _tag: unknown })._tag === \"Ok\" || (v as { _tag: unknown })._tag === \"Err\")\n );\n}\n\nfunction isCompatLike<U, F>(v: unknown): v is { inner: Result<U, F> } {\n return (\n typeof v === \"object\" &&\n v !== null &&\n \"inner\" in v &&\n isResultLike((v as { inner: unknown }).inner)\n );\n}\n\n/**\n * The free-function lift helpers (`okAsync`, `errAsync`, `fromPromise`,\n * `fromSafePromise`, `parallelTupleAsync`, `tryAsync`) live in `./async-lift.ts`\n * and are re-exported from the package index.\n */\n","import { ResultAsync } from \"./async.js\";\nimport { err, isErr, ok, trySync } from \"./result.js\";\nimport type { Result } from \"./types.js\";\n\n/**\n * Tracks whether a {@link Railway} workflow has crossed an async boundary.\n * Sync workflows return {@link Result}; async workflows return {@link ResultAsync}.\n */\nexport type RailwayMode = \"sync\" | \"async\";\n\n/**\n * Mode-aware output type for a {@link Railway} workflow: sync mode →\n * `Result<T, E>`, async mode → `ResultAsync<T, E>`.\n */\nexport type RailwayOutput<T, E, M extends RailwayMode> = M extends \"async\"\n ? ResultAsync<T, E>\n : Result<T, E>;\n\n/**\n * Initial context shape for a `railway` functional pipeline.\n * Wraps the raw input under the `input` key so subsequent named steps\n * can reference it via `ctx.input`.\n */\nexport type RailwayInput<I> = { readonly input: I };\n\ntype RailwayState<C extends object, E> =\n | { readonly mode: \"sync\"; readonly result: Result<C, E> }\n | { readonly mode: \"async\"; readonly result: ResultAsync<C, E> };\n\nexport type BranchFn<C extends object> = (ctx: C) => ResultAsync<unknown, unknown>;\nexport type BranchRecord = Record<string, (ctx: never) => ResultAsync<unknown, unknown>>;\ntype BranchOk<R> = R extends (ctx: never) => ResultAsync<infer T, infer _E> ? T : never;\ntype BranchErr<R> = R extends (ctx: never) => ResultAsync<infer _T, infer E> ? E : never;\ntype BranchInput<R> = R extends (ctx: infer C) => ResultAsync<unknown, unknown> ? C : never;\nexport type ParallelInput<R extends BranchRecord> = BranchInput<R[keyof R]> & object;\nexport type ParallelOutput<R extends BranchRecord> = {\n [K in keyof R]: BranchOk<R[K]>;\n};\nexport type ParallelError<R extends BranchRecord> = BranchErr<R[keyof R]>;\n\nconst addField = <C extends object, K extends string, T>(\n ctx: C,\n key: K,\n value: T,\n): C & Record<K, T> => ({ ...ctx, [key]: value }) as C & Record<K, T>;\n\nconst liftResult = <C extends object, E>(result: Result<C, E>): ResultAsync<C, E> =>\n ResultAsync.fromResult(result);\n\n/**\n * Named-context workflow builder. Each step appends a typed field to the\n * accumulating context object; the workflow tracks sync/async mode so the\n * final output type ({@link RailwayOutput}) is correct.\n *\n * Use `Railway` when a service workflow has 4+ named steps, mixed sync and\n * async boundaries, or independent async branches that should run in\n * parallel. For 1–2 step flows, prefer `flatMap` / `asyncAfter` directly.\n *\n * @example\n * ```ts\n * const summary = Railway\n * .fromSync(\"id\", () => IdSchema.parse(raw), toError)\n * .fromPromise(\"row\", ({ id }) => db.profiles.findFirst({ where: eq(profiles.id, id) }), toError)\n * .require(\"profile\", \"row\", ({ id }) => ({ kind: \"not_found\" as const, id }))\n * .derive(\"normalized\", ({ profile }) => normalizeProfile(profile))\n * .parallel({\n * artifacts: ({ normalized }) => loadArtifacts(normalized.id),\n * metrics: ({ normalized }) => loadMetrics(normalized.id),\n * })\n * .select(({ normalized, artifacts, metrics }) =>\n * toProfileSummary({ profile: normalized, artifacts, metrics }),\n * );\n * // ResultAsync<ProfileSummary, ParseError | DbError | NotFound>\n * ```\n */\nexport class Railway<C extends object, E, M extends RailwayMode> {\n private constructor(private readonly state: RailwayState<C, E>) {}\n\n /** Start an empty sync workflow with no fields in context. */\n static empty(): Railway<Record<never, never>, never, \"sync\"> {\n return new Railway({ mode: \"sync\", result: ok({}) });\n }\n\n /** Start a sync workflow with the given context as the initial state. */\n static context<C extends object>(context: C): Railway<C, never, \"sync\"> {\n return new Railway({ mode: \"sync\", result: ok(context) });\n }\n\n /**\n * Start a sync workflow with a throwing function — `onThrow` maps any\n * exception to a typed error.\n */\n static fromSync<K extends string, T, E>(\n key: K,\n fn: () => T,\n onThrow: (error: unknown) => E,\n ): Railway<Record<K, T>, E, \"sync\"> {\n return Railway.empty().fromSync(key, fn, onThrow);\n }\n\n /** Start a sync workflow with a `Result`-returning function. */\n static fromResult<K extends string, T, E>(\n key: K,\n fn: () => Result<T, E>,\n ): Railway<Record<K, T>, E, \"sync\"> {\n return Railway.empty().fromResult(key, fn);\n }\n\n /** Start an async workflow with a `PromiseLike`-returning function. */\n static fromPromise<K extends string, T, E>(\n key: K,\n fn: () => PromiseLike<T>,\n onReject: (error: unknown) => E,\n ): Railway<Record<K, T>, E, \"async\"> {\n return Railway.empty().fromPromise(key, fn, onReject);\n }\n\n /** Start an async workflow with a `ResultAsync`-returning function. */\n static fromAsync<K extends string, T, E>(\n key: K,\n fn: () => ResultAsync<T, E>,\n ): Railway<Record<K, T>, E, \"async\"> {\n return Railway.empty().fromAsync(key, fn);\n }\n\n /**\n * Pure sync derivation — `fn` must not throw. Use {@link fromSync} for\n * throwing transforms.\n */\n derive<K extends string, T>(key: K, fn: (ctx: C) => T): Railway<C & Record<K, T>, E, M> {\n return this.fromResult(key, (ctx) => ok(fn(ctx)));\n }\n\n /**\n * Throwing sync transform. Adds `{ [key]: T }` to context; converts any\n * exception to `Err<F>` via `onThrow`.\n */\n fromSync<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => T,\n onThrow: (error: unknown) => F,\n ): Railway<C & Record<K, T>, E | F, M> {\n return this.fromResult(key, (ctx) => trySync(fn, onThrow)(ctx));\n }\n\n /**\n * Sync `Result`-returning step. Adds `{ [key]: T }` to context on `Ok`;\n * short-circuits the workflow on `Err`. Error union widens to `E | F`.\n */\n fromResult<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => Result<T, F>,\n ): Railway<C & Record<K, T>, E | F, M> {\n if (this.state.mode === \"sync\") {\n const current = this.state.result;\n if (isErr(current)) {\n return new Railway({ mode: \"sync\", result: err(current.error) });\n }\n const next = fn(current.value);\n return isErr(next)\n ? new Railway({ mode: \"sync\", result: err(next.error) })\n : new Railway({\n mode: \"sync\",\n result: ok(addField(current.value, key, next.value)),\n });\n }\n\n return new Railway({\n mode: \"async\",\n result: this.state.result.flatMap((ctx) =>\n ResultAsync.fromResult(fn(ctx)).map((value) => addField(ctx, key, value)),\n ),\n }) as Railway<C & Record<K, T>, E | F, M>;\n }\n\n /**\n * Promise-returning step — upgrades the workflow to async mode. Reject\n * reasons go through `onReject` to become typed `Err<F>`.\n */\n fromPromise<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => PromiseLike<T>,\n onReject: (error: unknown) => F,\n ): Railway<C & Record<K, T>, E | F, \"async\"> {\n return this.fromAsync(key, (ctx) => ResultAsync.fromPromise(fn(ctx), onReject));\n }\n\n /**\n * `ResultAsync`-returning step — upgrades the workflow to async mode.\n * Already-typed error: no mapper needed.\n */\n fromAsync<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => ResultAsync<T, F>,\n ): Railway<C & Record<K, T>, E | F, \"async\"> {\n const current = this.state.mode === \"sync\" ? liftResult(this.state.result) : this.state.result;\n\n return new Railway({\n mode: \"async\",\n result: current.flatMap((ctx) => fn(ctx).map((value) => addField(ctx, key, value))),\n });\n }\n\n /**\n * Narrow a nullable context field into a required non-null field. If the\n * source field is `null` / `undefined`, the workflow short-circuits with\n * `onMissing(ctx)`.\n *\n * @example\n * ```ts\n * .fromPromise(\"row\", ({ id }) => db.users.findFirst({ where: eq(users.id, id) }))\n * .require(\"user\", \"row\", ({ id }) => ({ kind: \"not_found\" as const, id }))\n * // user is now User (non-null), not User | null\n * ```\n */\n require<K extends string, S extends keyof C, F>(\n key: K,\n source: S,\n onMissing: (ctx: C) => F,\n ): Railway<C & Record<K, NonNullable<C[S]>>, E | F, M> {\n return this.fromResult(key, (ctx) => {\n const value = ctx[source];\n return value == null ? err(onMissing(ctx)) : ok(value as NonNullable<C[S]>);\n });\n }\n\n /**\n * Run independent `ResultAsync` branches concurrently and merge their\n * named outputs back into context. Upgrades the workflow to async mode.\n * On multiple failures, the first `Err` in record-iteration order wins.\n *\n * @example\n * ```ts\n * .parallel({\n * recent: ({ userId }) => loadRecent(userId),\n * metrics: ({ userId }) => loadMetrics(userId),\n * })\n * // ctx now has { ..., recent, metrics }\n * ```\n */\n parallel<R extends Record<string, BranchFn<C>>>(\n branches: R,\n ): Railway<C & ParallelOutput<R>, E | ParallelError<R>, \"async\"> {\n const current = this.state.mode === \"sync\" ? liftResult(this.state.result) : this.state.result;\n\n return new Railway({\n mode: \"async\",\n result: current.flatMap((ctx) =>\n ResultAsync.combineTupleParallel(\n Object.entries(branches).map(([, branch]) => branch(ctx)),\n ).map((values) => {\n const next = { ...ctx } as C & ParallelOutput<R>;\n Object.keys(branches).forEach((key, index) => {\n (next as Record<string, unknown>)[key] = values[index];\n });\n return next;\n }),\n ),\n }) as Railway<C & ParallelOutput<R>, E | ParallelError<R>, \"async\">;\n }\n\n /**\n * Project the final context into the workflow's output type. Hides the\n * internal context shape from callers.\n */\n select<T>(fn: (ctx: C) => T): RailwayOutput<T, E, M> {\n if (this.state.mode === \"sync\") {\n const current = this.state.result;\n return (isErr(current) ? err(current.error) : ok(fn(current.value))) as RailwayOutput<\n T,\n E,\n M\n >;\n }\n\n return this.state.result.map(fn) as RailwayOutput<T, E, M>;\n }\n\n /**\n * Return the accumulated context as-is. Use when downstream code needs\n * every named field; prefer {@link select} when you can project to a DTO.\n */\n done(): RailwayOutput<C, E, M> {\n return this.state.result as RailwayOutput<C, E, M>;\n }\n}\n","import type { ResultAsync } from \"./async.js\";\nimport type {\n BranchFn,\n BranchRecord,\n ParallelError,\n ParallelInput,\n ParallelOutput,\n RailwayInput,\n RailwayMode,\n RailwayOutput,\n} from \"./railway-core.js\";\nimport { Railway } from \"./railway-core.js\";\nimport type { Result } from \"./types.js\";\n\ntype ParserLike<I, T> = { readonly parse: (input: I) => T } | ((input: I) => T);\ntype UnaryStep<I, O> = (input: I) => O;\n\nconst parseWithParser = <I, T>(parser: ParserLike<I, T>, input: I): T =>\n typeof parser === \"function\" ? parser(input) : parser.parse(input);\n\n/**\n * Functional companion to {@link Railway} — point-free composition of\n * reusable workflow steps. Starts from `Railway.context({ input })` and\n * applies each step in order. Step factories live below: {@link parseWith},\n * {@link fromSyncNamed}, {@link fromResultNamed}, {@link fromPromiseNamed},\n * {@link fromAsyncNamed}, {@link deriveNamed}, {@link requireNamed},\n * {@link parallelNamed}, {@link select}.\n *\n * @example\n * ```ts\n * const summary = railway(\n * rawId,\n * parseWith(IdSchema, toError).as(\"id\"),\n * fromPromiseNamed(\"row\", ({ id }) => db.profiles.findFirst({ where: eq(profiles.id, id) }), toError),\n * requireNamed(\"profile\", \"row\", ({ id }) => ({ kind: \"not_found\" as const, id })),\n * deriveNamed(\"normalized\", ({ profile }) => normalizeProfile(profile)),\n * select(({ normalized }) => toProfileSummary(normalized)),\n * );\n * ```\n */\nexport function railway<I, A>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n): A;\nexport function railway<I, A, B>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n): B;\nexport function railway<I, A, B, C>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n step3: UnaryStep<B, C>,\n): C;\nexport function railway<I, A, B, C, D>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n step3: UnaryStep<B, C>,\n step4: UnaryStep<C, D>,\n): D;\nexport function railway<I, A, B, C, D, E>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n step3: UnaryStep<B, C>,\n step4: UnaryStep<C, D>,\n step5: UnaryStep<D, E>,\n): E;\nexport function railway<I, A, B, C, D, E, F>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n step3: UnaryStep<B, C>,\n step4: UnaryStep<C, D>,\n step5: UnaryStep<D, E>,\n step6: UnaryStep<E, F>,\n): F;\nexport function railway<I, A, B, C, D, E, F, G>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n step3: UnaryStep<B, C>,\n step4: UnaryStep<C, D>,\n step5: UnaryStep<D, E>,\n step6: UnaryStep<E, F>,\n step7: UnaryStep<F, G>,\n): G;\nexport function railway<I, A, B, C, D, E, F, G, H>(\n input: I,\n step1: UnaryStep<Railway<RailwayInput<I>, never, \"sync\">, A>,\n step2: UnaryStep<A, B>,\n step3: UnaryStep<B, C>,\n step4: UnaryStep<C, D>,\n step5: UnaryStep<D, E>,\n step6: UnaryStep<E, F>,\n step7: UnaryStep<F, G>,\n step8: UnaryStep<G, H>,\n): H;\nexport function railway<I>(input: I, ...steps: readonly ((input: never) => unknown)[]): unknown {\n return steps.reduce<unknown>(\n (current, step) => (step as (input: unknown) => unknown)(current),\n Railway.context({ input }),\n );\n}\n\n/**\n * Step factory: parse the workflow input with a Zod-like schema (or a\n * unary parse function). Call `.as(key)` to name the output field.\n *\n * @example\n * ```ts\n * parseWith(IdSchema, toError).as(\"id\");\n * // Used as the first step in `railway(rawId, parseId, ...)`\n * ```\n */\nexport const parseWith = <I, T, E>(parser: ParserLike<I, T>, onThrow: (error: unknown) => E) => ({\n as:\n <K extends string>(key: K) =>\n <F, M extends RailwayMode>(\n workflow: Railway<RailwayInput<I>, F, M>,\n ): Railway<RailwayInput<I> & Record<K, T>, F | E, M> =>\n workflow.fromSync(key, ({ input }) => parseWithParser(parser, input), onThrow),\n});\n\n/**\n * Name-first companion to {@link parseWith}: parse the workflow input with a\n * Zod-like schema (or unary parse fn), naming the output field in the same\n * `(key, ...)` shape as {@link fromSyncNamed}, {@link deriveNamed}, et al.\n * Prefer this in `railway(...)` pipelines so every step's name aligns at the\n * left edge.\n *\n * @example\n * ```ts\n * railway(\n * rawId,\n * parseNamed(\"id\", IdSchema, toError),\n * fromPromiseNamed(\"profile\", ({ id }) => fetchProfile(id), toError),\n * );\n * ```\n */\nexport const parseNamed =\n <K extends string, I, T, E>(key: K, parser: ParserLike<I, T>, onThrow: (error: unknown) => E) =>\n <F, M extends RailwayMode>(\n workflow: Railway<RailwayInput<I>, F, M>,\n ): Railway<RailwayInput<I> & Record<K, T>, F | E, M> =>\n workflow.fromSync(key, ({ input }) => parseWithParser(parser, input), onThrow);\n\n/**\n * Reusable wrapper around {@link Railway.fromSync}. Captures key + fn +\n * onThrow once; applies to any compatible workflow.\n */\nexport const fromSyncNamed =\n <K extends string, C extends object, T, E>(\n key: K,\n fn: (ctx: C) => T,\n onThrow: (error: unknown) => E,\n ) =>\n <I extends C, F, M extends RailwayMode>(\n workflow: Railway<I, F, M>,\n ): Railway<I & Record<K, T>, F | E, M> =>\n workflow.fromSync(key, fn, onThrow);\n\n/** Reusable wrapper around {@link Railway.fromResult}. */\nexport const fromResultNamed =\n <K extends string, C extends object, T, E>(key: K, fn: (ctx: C) => Result<T, E>) =>\n <I extends C, F, M extends RailwayMode>(\n workflow: Railway<I, F, M>,\n ): Railway<I & Record<K, T>, F | E, M> =>\n workflow.fromResult(key, fn);\n\n/**\n * Reusable wrapper around {@link Railway.fromPromise}. Upgrades the\n * workflow to async mode when applied.\n */\nexport const fromPromiseNamed =\n <K extends string, C extends object, T, E>(\n key: K,\n fn: (ctx: C) => PromiseLike<T>,\n onReject: (error: unknown) => E,\n ) =>\n <I extends C, F, M extends RailwayMode>(\n workflow: Railway<I, F, M>,\n ): Railway<I & Record<K, T>, F | E, \"async\"> =>\n workflow.fromPromise(key, fn, onReject);\n\n/** Reusable wrapper around {@link Railway.fromAsync}. */\nexport const fromAsyncNamed =\n <K extends string, C extends object, T, E>(key: K, fn: (ctx: C) => ResultAsync<T, E>) =>\n <I extends C, F, M extends RailwayMode>(\n workflow: Railway<I, F, M>,\n ): Railway<I & Record<K, T>, F | E, \"async\"> =>\n workflow.fromAsync(key, fn);\n\n/** Reusable wrapper around {@link Railway.derive} — pure sync derivation. */\nexport const deriveNamed =\n <K extends string, C extends object, T>(key: K, fn: (ctx: C) => T) =>\n <I extends C, E, M extends RailwayMode>(\n workflow: Railway<I, E, M>,\n ): Railway<I & Record<K, T>, E, M> =>\n workflow.derive(key, fn);\n\n/** Reusable wrapper around {@link Railway.require} — narrows a nullable field. */\nexport const requireNamed =\n <K extends string, S extends string, C extends object, E>(\n key: K,\n source: S,\n onMissing: (ctx: C & Record<S, unknown>) => E,\n ) =>\n <I extends C & Record<S, unknown>, F, M extends RailwayMode>(\n workflow: Railway<I, F, M>,\n ): Railway<I & Record<K, NonNullable<I[S]>>, F | E, M> =>\n workflow.require(key, source, onMissing);\n\n/**\n * Reusable wrapper around {@link Railway.parallel}. Branches run\n * concurrently and merge their named outputs back into context.\n */\nexport const parallelNamed =\n <R extends BranchRecord>(branches: R) =>\n <I extends ParallelInput<R>, E, M extends RailwayMode>(\n workflow: Railway<I, E, M>,\n ): Railway<I & ParallelOutput<R>, E | ParallelError<R>, \"async\"> => {\n // TS cannot prove contravariant branch params after storing reusable steps.\n const typedBranches = branches as unknown as Record<string, BranchFn<I>>;\n return workflow.parallel(typedBranches) as unknown as Railway<\n I & ParallelOutput<R>,\n E | ParallelError<R>,\n \"async\"\n >;\n };\n\n/**\n * Reusable wrapper around {@link Railway.select} — projects the final\n * context into the workflow's output type.\n */\nexport const select =\n <C extends object, T>(fn: (ctx: C) => T) =>\n <E, M extends RailwayMode>(workflow: Railway<C, E, M>): RailwayOutput<T, E, M> =>\n workflow.select(fn);\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/dual.ts","../src/result.ts","../src/types.ts","../src/async.ts","../src/railway.ts"],"names":[],"mappings":";;;AA0CO,IAAM,IAAA,GAAO,CAAI,KAAA,EAAe,IAAA,KAA2C;AAMhF,EAAA,MAAM,GAAA,GAAM,IAAA;AACZ,EAAA,MAAM,UAAA,GAAa,CAAA,GAAI,IAAA,KACrB,IAAA,CAAK,UAAU,KAA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AAAA,MAAQ,CAAC,QACrC,WAAA,CAAY,oBAAA;AAAA,QACV,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,CAAE,GAAA,CAAI,CAAC,GAAG,MAAM,CAAA,KAAM,MAAA,CAAO,GAAG,CAAC;AAAA,OAC1D,CAAE,GAAA;AAAA,QACA,CAAC,MAAA;AAAA;AAAA;AAAA,UAGE;AAAA,YACC,GAAG,GAAA;AAAA,YACH,GAAG,MAAA,CAAO,WAAA,CAAY,MAAA,CAAO,IAAA,CAAK,QAAQ,CAAA,CAAE,GAAA,CAAI,CAAC,GAAA,EAAK,UAAU,CAAC,GAAA,EAAK,OAAO,KAAK,CAAC,CAAC,CAAC;AAAA;AACvF;AAAA;AACJ,KACF;AACA,IAAA,OAAO,IAAI,QAAA,CAAQ;AAAA,MACjB,IAAA,EAAM,OAAA;AAAA;AAAA;AAAA;AAAA,MAIN,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AAAA;AAAA,EAGA,OAAU,EAAA,EAA2C;AACnD,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,MACV,CAAC,MAAA,KAAW,GAAA,CAAI,MAAA,EAAQ,EAAE,CAAA;AAAA,MAC1B,CAAC,MAAA,KAAW,MAAA,CAAO,GAAA,CAAI,EAAE;AAAA,KAC3B;AAAA,EACF;AAAA;AAAA,EAGA,IAAA,GAA+B;AAC7B,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,MACV,CAAC,MAAA,KAAW,MAAA;AAAA,MACZ,CAAC,MAAA,KAAW;AAAA,KACd;AAAA,EACF;AACF","file":"railway.cjs","sourcesContent":["/**\n * @onrails/result internal — owning module for the **dual-form idiom**.\n *\n * Every dual-form transform in this package (`map`, `flatMap`, `match`, …)\n * accepts either shape:\n *\n * data-first: `map(result, fn)` — full arity, runs immediately\n * curried: `map(fn)(result)` — arity minus the leading `self`, returns\n * a unary function awaiting the data\n *\n * {@link dual} is the single arity dispatcher those transforms derive from;\n * hand-rolled `args.length` checks are not allowed elsewhere.\n *\n * NOTE: a twin copy of this module lives at `packages/maybe/src/internal/dual.ts`\n * — keep the two in sync when editing.\n *\n * Internal only: not listed in package.json `exports` or tsup entries.\n */\n\n/**\n * Derive a dual-form (data-first / curried) function from a single\n * data-first `body`.\n *\n * When called with `args.length >= arity` the wrapper runs `body(...args)`\n * (data-first). With fewer arguments it returns `(self) => body(self, ...args)`\n * — the curried, data-last-`self` form used with `pipe`/`flow`.\n *\n * The public type is supplied entirely by the caller: annotate the exported\n * const with the exact overload set and let `F` be inferred from it.\n *\n * @example\n * ```ts\n * export const map: {\n * <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;\n * <T, U>(fn: (value: T) => U): <E>(result: Result<T, E>) => Result<U, E>;\n * } = dual(\n * 2,\n * <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> =>\n * isOk(result) ? ok(fn(result.value)) : err(result.error),\n * );\n * ```\n */\nexport const dual = <F>(arity: number, body: (...args: never[]) => unknown): F => {\n // `(...args: never[]) => unknown` is the top function type, so every typed\n // body is assignable to the parameter — but it cannot be invoked with\n // `unknown` arguments. Re-view it through the variadic shape the dispatcher\n // actually forwards; the constraint is that `body` only ever receives the\n // arguments the caller's overload annotation admitted.\n const run = body as (...args: readonly unknown[]) => unknown;\n const dispatcher = (...args: readonly unknown[]): unknown =>\n args.length >= arity ? run(...args) : (self: unknown) => run(self, ...args);\n // The caller's overload annotation on the exported const supplies the real\n // public type; internally the dispatcher stays `unknown`-typed.\n return dispatcher as F;\n};\n","import { dual } from \"./internal/dual.js\";\nimport type { Err, Ok, Result } from \"./types.js\";\n\nexport type { Err, Ok, Result } from \"./types.js\";\n\n/**\n * Lifts a value into the success track.\n *\n * @example\n * ```ts\n * const r = ok(42); // Result<number, never>\n * const typed: Result<number, \"parse\"> = ok(1);\n * ```\n */\nexport const ok = <T, E = never>(value: T): Result<T, E> => ({\n _tag: \"Ok\",\n value,\n});\n\n/**\n * Fantasy Land `pure` — alias of {@link ok}. One lift name shared across the\n * trio (`of` / `Maybe.of` / `ResultAsync.of`) for generic and FL-style code.\n *\n * @example\n * ```ts\n * const r = of(42); // Result<number, never> — identical to ok(42)\n * ```\n */\nexport const of = ok;\n\n/**\n * Lifts a value into the error track.\n *\n * @example\n * ```ts\n * const r = err({ kind: \"parse\", message: \"bad json\" });\n * // Result<never, { kind: \"parse\"; message: string }>\n * ```\n */\nexport const err = <T = never, E = unknown>(error: E): Result<T, E> => ({\n _tag: \"Err\",\n error,\n});\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Ok`.\n *\n * @example\n * ```ts\n * if (isOk(r)) {\n * console.log(r.value); // narrowed to Ok branch\n * }\n * ```\n */\nexport const isOk = <T, E>(result: Result<T, E>): result is Ok<T, E> => result._tag === \"Ok\";\n\n/**\n * Type-narrowing predicate: returns `true` when the result is `Err`.\n *\n * @example\n * ```ts\n * if (isErr(r)) {\n * metrics.inc(\"error\", { kind: r.error.kind });\n * }\n * ```\n */\nexport const isErr = <T, E>(result: Result<T, E>): result is Err<T, E> => result._tag === \"Err\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dual-form helpers — each export accepts either shape:\n// data-first: `map(result, fn)`\n// curried: `map(fn)(result)`\n// Arity dispatch is derived from the internal `dual` combinator\n// (src/internal/dual.ts); the const annotation carries the public overloads.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Transform the `Ok` value, passing `Err` through unchanged. Dual-form:\n * call data-first or curried (for use with {@link pipe}).\n *\n * @example\n * ```ts\n * map(ok(2), (n) => n * 3); // Ok 6 — data-first\n * pipe(ok(\"x\"), map((s) => s.length));// Ok 1 — curried\n * ```\n */\nexport const map: {\n <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>;\n <T, U>(fn: (value: T) => U): <E>(result: Result<T, E>) => Result<U, E>;\n} = dual(\n 2,\n <T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> =>\n isOk(result) ? ok(fn(result.value)) : err(result.error),\n);\n\n/**\n * Transform the `Err` value, passing `Ok` through unchanged. Useful for\n * unifying heterogeneous failure types into one app-level union.\n *\n * @example\n * ```ts\n * type AppError = { kind: \"http\"; status: number } | { kind: \"parse\" };\n * pipe(\n * fetchSync(url), // Result<Body, { status: number }>\n * mapErr((e): AppError => ({ kind: \"http\", status: e.status })),\n * );\n * ```\n */\nexport const mapErr: {\n <T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>;\n <E, F>(fn: (error: E) => F): <T>(result: Result<T, E>) => Result<T, F>;\n} = dual(\n 2,\n <T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> =>\n isErr(result) ? err(fn(result.error)) : ok(result.value),\n);\n\n/**\n * Transform both tracks at once — `Ok` via `onOk`, `Err` via `onErr`.\n * Equivalent to `mapErr(onErr)(map(onOk)(result))` but in one pass.\n *\n * @example\n * ```ts\n * bimap(parsed, (cfg) => cfg.name, (e) => ({ kind: \"input\", cause: e }));\n * ```\n */\nexport const bimap: {\n <T, U, E, F>(result: Result<T, E>, onOk: (value: T) => U, onErr: (error: E) => F): Result<U, F>;\n <T, U, E, F>(\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n ): (result: Result<T, E>) => Result<U, F>;\n} = dual(\n 3,\n <T, U, E, F>(\n result: Result<T, E>,\n onOk: (value: T) => U,\n onErr: (error: E) => F,\n ): Result<U, F> => (isOk(result) ? ok(onOk(result.value)) : err(onErr(result.error))),\n);\n\n/**\n * Canonical bind (Fantasy Land `chain`). Chains a Result-returning step,\n * widening the error union to `E | F`. Short-circuits on `Err`.\n *\n * @example\n * ```ts\n * flatMap(parseInput(raw), (data) =>\n * data.id != null ? ok(data) : err({ kind: \"missing_id\" as const }),\n * );\n * // Result<Data, ParseError | { kind: \"missing_id\" }>\n * ```\n */\nexport const flatMap: {\n <T, U, E, F>(result: Result<T, E>, fn: (value: T) => Result<U, F>): Result<U, E | F>;\n <T, U, F>(fn: (value: T) => Result<U, F>): <E>(result: Result<T, E>) => Result<U, E | F>;\n} = dual(\n 2,\n <T, U, E, F>(result: Result<T, E>, fn: (value: T) => Result<U, F>): Result<U, E | F> =>\n isOk(result) ? fn(result.value) : err(result.error),\n);\n\n/**\n * Error-track bind — runs `fn` only when the result is `Err`, allowing\n * a failed workflow to recover to `Ok` or remap the failure. Mirror of\n * {@link flatMap} on the error channel.\n *\n * @example\n * ```ts\n * recover(networkResult, (e) =>\n * e.kind === \"rate_limit\" ? ok(cachedBody) : err(e),\n * );\n * ```\n */\nexport const recover: {\n <T, E, F>(result: Result<T, E>, fn: (error: E) => Result<T, F>): Result<T, F>;\n <T, E, F>(fn: (error: E) => Result<T, F>): (result: Result<T, E>) => Result<T, F>;\n} = dual(\n 2,\n <T, E, F>(result: Result<T, E>, fn: (error: E) => Result<T, F>): Result<T, F> =>\n isErr(result) ? fn(result.error) : ok(result.value),\n);\n\n/**\n * Observe the `Ok` value for side effects (logging, metrics) without\n * changing the carried value. Passes `Err` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * tap((cfg) => log.info({ msg: \"parsed\", name: cfg.name })),\n * flatMap(validate),\n * );\n * ```\n */\nexport const tap: {\n <T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E>;\n <T>(fn: (value: T) => void): <E>(result: Result<T, E>) => Result<T, E>;\n} = dual(2, <T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E> => {\n if (isOk(result)) fn(result.value);\n return result;\n});\n\n/**\n * Observe the `Err` value for side effects (logging, metrics) without\n * changing the carried error. Passes `Ok` through untouched.\n *\n * @example\n * ```ts\n * pipe(\n * loadUser(id),\n * tapErr((e) => metrics.inc(\"user.load.fail\", { kind: e.kind })),\n * );\n * ```\n */\nexport const tapErr: {\n <T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E>;\n <E>(fn: (error: E) => void): <T>(result: Result<T, E>) => Result<T, E>;\n} = dual(2, <T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E> => {\n if (isErr(result)) fn(result.error);\n return result;\n});\n\n/**\n * Terminal collapse — fold both tracks into a single value. Dual-form:\n * 3-args data-first, 2-args curried for {@link pipe}. Returns whatever\n * the handlers return.\n *\n * For files that also import `match` from `ts-pattern`, use a namespace\n * import (`import * as R from \"@onrails/result\"` → `R.match`) to dissolve\n * the collision.\n *\n * @example\n * ```ts\n * const html = match(parsed, (cfg) => render(cfg), (e) => renderError(e));\n * ```\n */\nexport const match: {\n <T, E, U>(result: Result<T, E>, onOk: (value: T) => U, onErr: (error: E) => U): U;\n <T, E, U>(onOk: (value: T) => U, onErr: (error: E) => U): (result: Result<T, E>) => U;\n} = dual(\n 3,\n <T, E, U>(result: Result<T, E>, onOk: (value: T) => U, onErr: (error: E) => U): U =>\n isOk(result) ? onOk(result.value) : onErr(result.error),\n);\n\n/**\n * Returns the `Ok` value, or `defaultValue` when the result is `Err`.\n *\n * @example\n * ```ts\n * unwrapOr(parsedSetting, \"default-value\");\n * ```\n */\nexport const unwrapOr: {\n <T, E>(result: Result<T, E>, defaultValue: T): T;\n <T>(defaultValue: T): <E>(result: Result<T, E>) => T;\n} = dual(\n 2,\n <T, E>(result: Result<T, E>, defaultValue: T): T => (isOk(result) ? result.value : defaultValue),\n);\n\n/**\n * Test/assert helper — returns the `Ok` value, or **throws the original `Err`\n * value** when called on an `Err`. This is the assertion tier (RFC 0001 §4):\n * intended for `*.spec.ts` / `*.test.ts`, where throwing fails the test loudly.\n * In business logic prefer {@link match} or {@link unwrapOr}; the lint plugins\n * flag `unwrapOk` outside test files.\n *\n * @returns the unwrapped `Ok` value\n * @throws the carried `Err` value when the result is `Err`\n *\n * @example\n * ```ts\n * // in a *.spec.ts\n * expect(unwrapOk(ok(5))).toBe(5);\n * expect(() => unwrapOk(err(error))).toThrow(error);\n * ```\n */\nexport function unwrapOk<T, E>(result: Result<T, E>): T {\n if (isErr(result)) throw result.error;\n return result.value;\n}\n\n/** Alias of {@link unwrapOk} for syntax cohesion with `@onrails/maybe`. */\nexport const unwrap = unwrapOk;\n\n/**\n * Test/assert helper — returns the `Err` value, or **throws a `TypeError`**\n * when called on an `Ok`. Mirror of {@link unwrapOk} on the error track and\n * part of the same assertion tier (RFC 0001 §4): intended for `*.spec.ts` /\n * `*.test.ts`. Prefer {@link match} / {@link unwrapOr} in business logic; the\n * lint plugins flag `unwrapErr` outside test files.\n *\n * @returns the unwrapped `Err` value\n * @throws `TypeError` when the result is `Ok`\n *\n * @example\n * ```ts\n * // in a *.spec.ts\n * expect(unwrapErr(err(\"x\"))).toBe(\"x\");\n * expect(() => unwrapErr(ok(5))).toThrow(TypeError);\n * ```\n */\nexport function unwrapErr<T, E>(result: Result<T, E>): E {\n if (isOk(result)) throw new TypeError(\"unwrapErr called on Ok\");\n return result.error;\n}\n\n/**\n * Wraps a throwing sync function, returning a function that produces a\n * {@link Result} instead of throwing. Thrown errors pass through `onThrow` to\n * become a typed `Err`; a normal return becomes `Ok`. The neverthrow analogue\n * is `Result.fromThrowable`.\n *\n * @param fn - the throwing function to wrap\n * @param onThrow - maps a thrown value to the `Err` channel\n * @returns a function with `fn`'s parameters that returns `Result<ReturnType, E>`\n *\n * @example\n * ```ts\n * type ParseError = { kind: \"parse\"; message: string };\n * const parse = trySync(\n * JSON.parse,\n * (e): ParseError => ({ kind: \"parse\", message: String(e) }),\n * );\n * parse(\"{}\"); // Ok({})\n * parse(\"nope\"); // Err({ kind: \"parse\", … })\n * ```\n */\nexport function trySync<A extends readonly unknown[], T, E>(\n fn: (...args: A) => T,\n onThrow: (error: unknown) => E,\n): (...args: A) => Result<T, E>;\nexport function trySync<F extends (...args: never) => unknown, E>(\n fn: F,\n onThrow: (error: unknown) => E,\n): (...args: Parameters<F>) => Result<ReturnType<F>, E>;\nexport function trySync(\n fn: (...args: never) => unknown,\n onThrow: (error: unknown) => unknown,\n): (...args: never) => Result<unknown, unknown> {\n return (...args: never) => {\n try {\n return ok(fn(...args));\n } catch (error) {\n return err(onThrow(error));\n }\n };\n}\n\n/**\n * Variadic value-first pipe — threads `value` through up to nine unary fns,\n * left-to-right. Use {@link pipe} when you already have a starting value;\n * use {@link flow} to define a reusable composed function with no value yet.\n *\n * @example\n * ```ts\n * pipe(\n * parseConfig(raw),\n * map((cfg) => cfg.name),\n * flatMap((name) => (name ? ok(name) : err({ kind: \"empty\" as const }))),\n * tap(log),\n * );\n * ```\n */\nexport function pipe<A>(value: A): A;\nexport function pipe<A, B>(value: A, ab: (a: A) => B): B;\nexport function pipe<A, B, C>(value: A, ab: (a: A) => B, bc: (b: B) => C): C;\nexport function pipe<A, B, C, D>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D;\nexport function pipe<A, B, C, D, E>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): E;\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n): F;\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n): G;\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n): H;\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n ab: (a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n ef: (e: E) => F,\n fg: (f: F) => G,\n gh: (g: G) => H,\n hi: (h: H) => I,\n): I;\nexport function pipe(value: unknown, ...fns: ReadonlyArray<(x: unknown) => unknown>): unknown {\n let acc = value;\n for (const fn of fns) {\n acc = fn(acc);\n }\n return acc;\n}\n\nconst printPayload = (payload: unknown): string => {\n try {\n return JSON.stringify(payload) ?? String(payload);\n } catch {\n // cyclic or non-JSON payload — a debug printer must not throw\n return String(payload);\n }\n};\n\n/**\n * Debug printer — renders a result as `Ok(…)` / `Err(…)` for logs. Payloads\n * print as JSON (values are plain data by design); non-JSON payloads fall\n * back to `String(...)`.\n *\n * @example\n * ```ts\n * show(ok(1)); // 'Ok(1)'\n * show(err({ kind: \"e\" })); // 'Err({\"kind\":\"e\"})'\n * ```\n */\nexport const show = <T, E>(result: Result<T, E>): string =>\n isOk(result) ? `Ok(${printPayload(result.value)})` : `Err(${printPayload(result.error)})`;\n","/**\n * The core railway type: a tagged union carrying either a success value\n * (`Ok<T>`) or a failure value (`Err<E>`). It is a plain discriminated union\n * on `_tag` — no classes — so it is immutable and tree-shake friendly. Narrow\n * with {@link isOk} / {@link isErr} to read `.value` / `.error`.\n *\n * @typeParam T - the `Ok` value type\n * @typeParam E - the `Err` error type\n *\n * @example\n * ```ts\n * function parse(raw: string): Result<number, \"nan\"> {\n * const n = Number(raw);\n * return Number.isNaN(n) ? err(\"nan\") : ok(n);\n * }\n * ```\n */\nexport type Result<T, E> =\n | { readonly _tag: \"Ok\"; readonly value: T }\n | { readonly _tag: \"Err\"; readonly error: E };\n\n/**\n * The success branch of a {@link Result} — `{ _tag: \"Ok\"; value: T }`.\n * The `E` parameter keeps the type assignable to `Result<T, E>`.\n */\nexport type Ok<T, E = never> = Extract<Result<T, E>, { _tag: \"Ok\" }>;\n\n/**\n * The failure branch of a {@link Result} — `{ _tag: \"Err\"; error: E }`.\n */\nexport type Err<T, E> = Extract<Result<T, E>, { _tag: \"Err\" }>;\n\n/**\n * Error subclass representing an **unexpected** defect — a thrown exception or\n * promise rejection that was not part of the modelled `Err` union. Used as the\n * default mapping when {@link fromAsync} is called without an `onDefect`\n * handler; the original cause is preserved on `.cause`.\n *\n * @example\n * ```ts\n * const defect = new UnexpectedError(\"Unexpected async defect\", caught);\n * defect.cause; // the original thrown value\n * ```\n */\nexport class UnexpectedError extends Error {\n constructor(\n message: string,\n override readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"UnexpectedError\";\n }\n}\n","import type { InferErr, InferOk } from \"./internal/infer.js\";\nimport { err, isErr, map, mapErr, ok } from \"./result.js\";\nimport type { Result } from \"./types.js\";\nimport { UnexpectedError } from \"./types.js\";\n\ntype PromiseFactory<T, E> = () => Promise<Result<T, E>>;\ntype CombineTupleAsync<R extends readonly ResultAsync<unknown, unknown>[]> = ResultAsync<\n { [K in keyof R]: InferOk<R[K]> },\n { [K in keyof R]: InferErr<R[K]> }[number]\n>;\n\n/** Collapses settled results left-to-right, short-circuiting on the first `Err`. */\nconst sequenceSettled = (\n settled: readonly Result<unknown, unknown>[],\n): Result<unknown[], unknown> => {\n const values: unknown[] = [];\n for (const result of settled) {\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n};\n\n/**\n * Async railway carrier. Wraps a deferred `Promise<Result<T, E>>` and exposes\n * the same dual-track transforms as the sync {@link Result} — `map`, `flatMap`,\n * `recover`, `tap`, `match`. The public API never surfaces `Promise<Result<…>>`\n * directly: `await` the instance (it is thenable) or call {@link resolve} /\n * {@link match} to settle it.\n *\n * Construct via the static factories ({@link ok}, {@link err}, {@link fromPromise},\n * {@link defer}, …) rather than `new` — the constructor is `protected`.\n *\n * @typeParam T - the `Ok` value type\n * @typeParam E - the `Err` error type\n *\n * @example\n * ```ts\n * const user = ResultAsync.fromPromise(api.getUser(id), toAppError)\n * .map((u) => u.profile)\n * .recover(() => ResultAsync.ok(guestProfile));\n *\n * const r = await user; // Result<Profile, AppError>\n * ```\n */\nexport class ResultAsync<T, E> {\n private promise: Promise<Result<T, E>> | null = null;\n\n protected constructor(protected readonly run: PromiseFactory<T, E>) {}\n\n /**\n * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}.\n *\n * @example\n * ```ts\n * const ra = ResultAsync.fromResult(ok(42)); // ResultAsync<number, never>\n * ```\n */\n static fromResult<T, E>(result: Result<T, E>): ResultAsync<T, E> {\n return new ResultAsync(async () => result);\n }\n\n /**\n * Wraps a `PromiseLike<T>` that may reject. Rejections pass through `onReject`\n * to become a typed `Err`; resolution becomes `Ok<T>`.\n *\n * @param promise - the promise to wrap\n * @param onReject - maps a rejection reason to the `Err` channel\n *\n * @example\n * ```ts\n * const body = ResultAsync.fromPromise(\n * fetch(url).then((r) => r.text()),\n * (e): NetError => ({ kind: \"net\", cause: String(e) }),\n * );\n * ```\n */\n static fromPromise<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n ): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n try {\n return ok(await promise);\n } catch (error) {\n return err(onReject(error));\n }\n });\n }\n\n /**\n * Wraps a `PromiseLike<T>` that is **guaranteed not to reject**, skipping the\n * `onReject` mapper. Use only when rejection is provably impossible.\n *\n * @example\n * ```ts\n * const now = ResultAsync.fromSafePromise(Promise.resolve(Date.now()));\n * ```\n */\n static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(await promise));\n }\n\n /**\n * Defers work until {@link resolve}. Unlike {@link fromPromise}, the factory\n * does not run until the `ResultAsync` is resolved (e.g. by `combineTuple` /\n * `combineTupleParallel`). The factory runs at most once — `resolve` memoizes.\n *\n * @example\n * ```ts\n * const insert = ResultAsync.defer(() => db.orders.insert(row));\n * // nothing has run yet\n * const r = await insert; // factory runs exactly once here\n * ```\n */\n static defer<T, E>(fn: () => Promise<Result<T, E>>): ResultAsync<T, E> {\n return new ResultAsync(fn);\n }\n\n /**\n * Lifts a value into an `Ok` async result.\n *\n * @example\n * ```ts\n * const r = ResultAsync.ok(42); // ResultAsync<number, never>\n * ```\n */\n static ok<T>(value: T): ResultAsync<T, never>;\n static ok<T, E>(value: T): ResultAsync<T, E>;\n static ok<T, E = never>(value: T): ResultAsync<T, E> {\n return new ResultAsync(async () => ok(value));\n }\n\n /**\n * Fantasy Land `pure` — alias of {@link ResultAsync.ok}. One lift name\n * shared across the trio (`of` / `Maybe.of` / `ResultAsync.of`).\n */\n static of<T>(value: T): ResultAsync<T, never>;\n static of<T, E>(value: T): ResultAsync<T, E>;\n static of<T, E = never>(value: T): ResultAsync<T, E> {\n return ResultAsync.ok(value);\n }\n\n /**\n * Lifts an error into an `Err` async result.\n *\n * @example\n * ```ts\n * const r = ResultAsync.err({ kind: \"not_found\" as const });\n * ```\n */\n static err<T = never, E = unknown>(error: E): ResultAsync<T, E> {\n return new ResultAsync(async () => err(error));\n }\n\n /**\n * Lifts an existing `Promise<Result<T, E>>` (e.g. from interop code) into a\n * {@link ResultAsync}. A thrown defect is routed through `onDefect`,\n * defaulting to {@link UnexpectedError}. The `Ok` value passes through\n * verbatim — even when it happens to be Result-shaped.\n *\n * @param promise - a promise that already yields a `Result`\n * @param onDefect - maps an unexpected throw to the `Err` channel\n * @see {@link fromAsync} from `@onrails/result`\n */\n static fromResultPromise<T, E>(\n promise: Promise<Result<T, E>>,\n onDefect?: (error: unknown) => E | UnexpectedError,\n ): ResultAsync<T, E | UnexpectedError> {\n const mapDefect =\n onDefect ?? ((error: unknown) => new UnexpectedError(\"Unexpected async defect\", error));\n return new ResultAsync<T, E | UnexpectedError>(async () => {\n try {\n return await promise;\n } catch (error) {\n return err(mapDefect(error));\n }\n });\n }\n\n /**\n * Combines a homogeneous array of async results into one. Resolves\n * **sequentially** in input order, short-circuiting on the first `Err`.\n * For heterogeneous tuples that preserve per-index types, use\n * {@link combineTuple}; for wall-clock overlap, {@link combineTupleParallel}.\n *\n * @example\n * ```ts\n * const all = ResultAsync.combine([loadA(), loadB(), loadC()]);\n * // ResultAsync<Item[], LoadError>\n * ```\n */\n static combine<T, E>(results: readonly ResultAsync<T, E>[]): ResultAsync<T[], E> {\n return new ResultAsync(async () => {\n const values: T[] = [];\n for (const ra of results) {\n const result = await ra.resolve();\n if (isErr(result)) {\n return err(result.error);\n }\n values.push(result.value);\n }\n return ok(values);\n });\n }\n\n /**\n * Heterogeneous async tuple combine — resolves branches **sequentially**\n * (left-to-right), returning the first `Err` in input order. Preserves each\n * branch's `Ok` type by position, so the result destructures type-safely.\n * This is the canonical sequential async combine (replaces the former\n * `sequenceTupleAsync`).\n *\n * @example\n * ```ts\n * const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()] as const);\n * // ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>\n * const r = await combined;\n * if (isOk(r)) {\n * const [cfg, catalog] = r.value; // typed per position\n * }\n * ```\n */\n static combineTuple<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Runtime identical to combine; the cast restores per-index tuple types.\n return ResultAsync.combine(\n results as readonly ResultAsync<unknown, unknown>[],\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Like {@link combineTuple}, but starts every branch before awaiting (wall-clock\n * parallel for independent IO). On failure, returns the first `Err` in input order.\n *\n * @example\n * ```ts\n * // independent IO — overlap them\n * const combined = ResultAsync.combineTupleParallel([\n * loadProfile(id),\n * loadMetrics(id),\n * ] as const);\n * ```\n */\n static combineTupleParallel<const R extends readonly ResultAsync<unknown, unknown>[]>(\n results: R,\n ): CombineTupleAsync<R> {\n // Cast restores per-index tuple types over the untyped sequence core.\n return new ResultAsync(async () =>\n sequenceSettled(await Promise.all(results.map((ra) => ra.resolve()))),\n ) as CombineTupleAsync<R>;\n }\n\n /**\n * Transforms the `Ok` value, passing `Err` through unchanged.\n *\n * @example\n * ```ts\n * ResultAsync.ok(2).map((n) => n * 3); // ResultAsync<number> → Ok 6\n * ```\n */\n map<U>(fn: (value: T) => U): ResultAsync<U, E> {\n return new ResultAsync(async () => map(await this.resolve(), fn));\n }\n\n /**\n * Transforms the `Err` value, passing `Ok` through unchanged — useful for\n * unifying heterogeneous failures into one app-level union.\n *\n * @example\n * ```ts\n * load(id).mapErr((e): AppError => ({ kind: \"load\", cause: e })); // ResultAsync<T, AppError>\n * ```\n */\n mapErr<F>(fn: (error: E) => F): ResultAsync<T, F> {\n return new ResultAsync(async () => mapErr(await this.resolve(), fn));\n }\n\n /**\n * Canonical bind — chains a step that itself returns a `ResultAsync` or sync\n * `Result`, short-circuiting on `Err`. Error types accumulate (`E | F`).\n *\n * @example\n * ```ts\n * authenticate(req)\n * .flatMap((user) => loadProfile(user.id)) // ResultAsync\n * .flatMap((p) => validate(p)); // sync Result also accepted\n * ```\n */\n flatMap<U, F = E>(fn: (value: T) => ResultAsync<U, F> | Result<U, F>): ResultAsync<U, E | F> {\n return new ResultAsync<U, E | F>(async () => {\n const first = await this.resolve();\n if (isErr(first)) {\n return first;\n }\n const next = fn(first.value);\n return next instanceof ResultAsync ? next.resolve() : next;\n });\n }\n\n /**\n * neverthrow-compat alias of {@link flatMap}. Kept as the documented compat\n * tier; prefer {@link flatMap} in new code.\n *\n * @example\n * ```ts\n * authenticate(req).andThen((user) => loadProfile(user.id));\n * ```\n */\n andThen<U, F = E>(fn: (value: T) => ResultAsync<U, F> | Result<U, F>): ResultAsync<U, E | F> {\n return this.flatMap(fn);\n }\n\n /**\n * Error-channel bind — runs `fn` only on `Err`, swapping in a recovery\n * `ResultAsync` or sync `Result`. `Ok` passes through. The mirror of\n * {@link flatMap} on the error track.\n *\n * @example\n * ```ts\n * loadFromCache(id).recover(() => loadFromOrigin(id)); // ResultAsync<T, F>\n * ```\n */\n recover<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return new ResultAsync<T, F>(async () => {\n const first = await this.resolve();\n if (!isErr(first)) {\n return first;\n }\n const next = fn(first.error);\n return next instanceof ResultAsync ? next.resolve() : next;\n });\n }\n\n /**\n * neverthrow-compat alias of {@link recover}. Kept as the documented compat\n * tier; prefer {@link recover} in new code.\n *\n * @example\n * ```ts\n * loadFromCache(id).orElse(() => loadFromOrigin(id));\n * ```\n */\n orElse<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F> {\n return this.recover(fn);\n }\n\n /**\n * Runs a side effect on the `Ok` value and passes the result through\n * unchanged; a no-op on `Err`. Mirrors {@link tapErr}.\n *\n * @example\n * ```ts\n * saveUser(u).tap((saved) => analytics.track(\"user_saved\", saved.id));\n * ```\n */\n tap(fn: (value: T) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (!isErr(result)) {\n fn(result.value);\n }\n return result;\n });\n }\n\n /**\n * Runs a side effect on the `Err` value and passes the result through\n * unchanged; a no-op on `Ok`. The error-track mirror of {@link tap}.\n *\n * @example\n * ```ts\n * saveUser(u).tapErr((e) => logger.warn(\"save failed\", e));\n * ```\n */\n tapErr(fn: (error: E) => void): ResultAsync<T, E> {\n return new ResultAsync(async () => {\n const result = await this.resolve();\n if (isErr(result)) {\n fn(result.error);\n }\n return result;\n });\n }\n\n /**\n * Settles to the `Ok` value, or `defaultValue` if `Err`. Terminal — returns a\n * plain `Promise`, not a `ResultAsync`.\n *\n * @example\n * ```ts\n * const profile = await loadProfile(id).unwrapOr(guestProfile);\n * ```\n */\n unwrapOr<U>(defaultValue: U): Promise<T | U> {\n return this.resolve().then((result) => (isErr(result) ? defaultValue : result.value));\n }\n\n /**\n * Terminal collapse — folds both tracks into a single awaited value. Returns\n * a plain `Promise`, settling the carrier exactly once.\n *\n * @param onOk - handles the `Ok` value\n * @param onErr - handles the `Err` value\n *\n * @example\n * ```ts\n * const status = await save(row).match(\n * () => 200,\n * (e) => (e.kind === \"conflict\" ? 409 : 500),\n * );\n * ```\n */\n match<U1, U2 = U1>(onOk: (value: T) => U1, onErr: (error: E) => U2): Promise<U1 | U2> {\n return this.resolve().then((result) =>\n isErr(result) ? onErr(result.error) : onOk(result.value),\n );\n }\n\n /**\n * Settles the carrier to a bare sync {@link Result}, memoizing so the\n * underlying factory runs at most once. Prefer `await ra` (the thenable) or\n * {@link match} in app code; use `resolve` when you need the tagged union back.\n *\n * @example\n * ```ts\n * const r = await load(id).resolve(); // Result<Data, LoadError>\n * if (isOk(r)) use(r.value);\n * ```\n */\n resolve(): Promise<Result<T, E>> {\n if (!this.promise) {\n this.promise = this.run();\n }\n return this.promise;\n }\n\n /**\n * Thenable shim — `await ra` resolves to a bare tagged-union `Result<T, E>`.\n * Narrow with `isOk(r)` / `isErr(r)` to read `.value` / `.error`.\n */\n // biome-ignore lint/suspicious/noThenProperty: makes ResultAsync awaitable\n then<R1 = Result<T, E>, R2 = never>(\n onfulfilled?: ((value: Result<T, E>) => R1 | PromiseLike<R1>) | undefined | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | undefined | null,\n ): Promise<R1 | R2> {\n return this.resolve().then(\n // Safe: without onfulfilled, R1 stays at its Result<T, E> default.\n (r) => (onfulfilled ? onfulfilled(r) : (r as unknown as R1)),\n onrejected ?? undefined,\n );\n }\n}\n\n/**\n * The free-function lift helpers (`okAsync`, `errAsync`, `fromPromise`,\n * `fromSafePromise`, `fromResult`, `fromAsync`, `asyncAfter`, `tryAsync`)\n * live in `./async-lift.ts` and are re-exported from the package index.\n */\n","import { ResultAsync } from \"./async.js\";\nimport { err, flatMap, map, ok, trySync } from \"./result.js\";\nimport type { Result } from \"./types.js\";\n\n/**\n * Tracks whether a {@link Railway} workflow has crossed an async boundary.\n * Sync workflows return {@link Result}; async workflows return {@link ResultAsync}.\n */\nexport type RailwayMode = \"sync\" | \"async\";\n\n/**\n * Mode-aware output type for a {@link Railway} workflow: sync mode →\n * `Result<T, E>`, async mode → `ResultAsync<T, E>`.\n */\nexport type RailwayOutput<T, E, M extends RailwayMode> = M extends \"async\"\n ? ResultAsync<T, E>\n : Result<T, E>;\n\n/**\n * Runtime carrier for a workflow. Invariant: the `mode` tag mirrors the\n * phantom `M` on {@link Railway} — every construction site writes matching\n * tag and type parameter, and {@link Railway.step} / {@link Railway.out}\n * are the only places that re-link the two.\n */\ntype RailwayState<C extends object, E> =\n | { readonly mode: \"sync\"; readonly result: Result<C, E> }\n | { readonly mode: \"async\"; readonly result: ResultAsync<C, E> };\n\nexport type BranchFn<C extends object> = (ctx: C) => ResultAsync<unknown, unknown>;\nexport type BranchRecord = Record<string, (ctx: never) => ResultAsync<unknown, unknown>>;\ntype BranchOk<R> = R extends (ctx: never) => ResultAsync<infer T, infer _E> ? T : never;\ntype BranchErr<R> = R extends (ctx: never) => ResultAsync<infer _T, infer E> ? E : never;\nexport type ParallelOutput<R extends BranchRecord> = {\n [K in keyof R]: BranchOk<R[K]>;\n};\nexport type ParallelError<R extends BranchRecord> = BranchErr<R[keyof R]>;\n\nconst addField = <C extends object, K extends string, T>(\n ctx: C,\n key: K,\n value: T,\n): C & Record<K, T> => ({ ...ctx, [key]: value }) as C & Record<K, T>;\n\n/**\n * Named-context workflow builder. Each step appends a typed field to the\n * accumulating context object; the workflow tracks sync/async mode so the\n * final output type ({@link RailwayOutput}) is correct.\n */\nexport class Railway<C extends object, E, M extends RailwayMode> {\n private constructor(private readonly state: RailwayState<C, E>) {}\n\n /** Start an empty sync workflow with no fields in context. */\n static empty(): Railway<Record<never, never>, never, \"sync\"> {\n return new Railway({ mode: \"sync\", result: ok({}) });\n }\n\n /** Start a sync workflow with the given context as the initial state. */\n static context<C extends object>(context: C): Railway<C, never, \"sync\"> {\n return new Railway({ mode: \"sync\", result: ok(context) });\n }\n\n /** Start a sync workflow with a throwing function. */\n static fromSync<K extends string, T, E>(\n key: K,\n fn: () => T,\n onThrow: (error: unknown) => E,\n ): Railway<Record<K, T>, E, \"sync\"> {\n return Railway.empty().fromSync(key, fn, onThrow);\n }\n\n /** Start a sync workflow with a `Result`-returning function. */\n static fromResult<K extends string, T, E>(\n key: K,\n fn: () => Result<T, E>,\n ): Railway<Record<K, T>, E, \"sync\"> {\n return Railway.empty().fromResult(key, fn);\n }\n\n /** Start an async workflow with a `PromiseLike`-returning function. */\n static fromPromise<K extends string, T, E>(\n key: K,\n fn: () => PromiseLike<T>,\n onReject: (error: unknown) => E,\n ): Railway<Record<K, T>, E, \"async\"> {\n return Railway.empty().fromPromise(key, fn, onReject);\n }\n\n /** Start an async workflow with a `ResultAsync`-returning function. */\n static fromAsync<K extends string, T, E>(\n key: K,\n fn: () => ResultAsync<T, E>,\n ): Railway<Record<K, T>, E, \"async\"> {\n return Railway.empty().fromAsync(key, fn);\n }\n\n /**\n * Rebuild the workflow in its current mode after transforming the carried\n * result. Single re-link point for the state/phantom invariant: the mode\n * tag is preserved verbatim, so `M` still describes the new state — TS\n * cannot narrow the phantom `M` from the runtime tag, hence the cast.\n */\n private step<C2 extends object, F>(\n onSync: (result: Result<C, E>) => Result<C2, E | F>,\n onAsync: (result: ResultAsync<C, E>) => ResultAsync<C2, E | F>,\n ): Railway<C2, E | F, M> {\n const next: RailwayState<C2, E | F> =\n this.state.mode === \"sync\"\n ? { mode: \"sync\", result: onSync(this.state.result) }\n : { mode: \"async\", result: onAsync(this.state.result) };\n return new Railway(next) as Railway<C2, E | F, M>;\n }\n\n /**\n * Project the carried result into the mode-aware output type. Counterpart\n * of {@link Railway.step} for terminal steps: the runtime branch matches\n * the branch `RailwayOutput` picks for `M` (state/phantom invariant), but\n * TS cannot resolve the conditional on an unresolved `M`, hence the cast.\n */\n private out<T>(\n onSync: (result: Result<C, E>) => Result<T, E>,\n onAsync: (result: ResultAsync<C, E>) => ResultAsync<T, E>,\n ): RailwayOutput<T, E, M> {\n return (\n this.state.mode === \"sync\" ? onSync(this.state.result) : onAsync(this.state.result)\n ) as RailwayOutput<T, E, M>;\n }\n\n /** Lift the carried result into `ResultAsync` for async-upgrading steps. */\n private toAsync(): ResultAsync<C, E> {\n return this.state.mode === \"sync\"\n ? ResultAsync.fromResult(this.state.result)\n : this.state.result;\n }\n\n /** Pure sync derivation. */\n derive<K extends string, T>(key: K, fn: (ctx: C) => T): Railway<C & Record<K, T>, E, M> {\n return this.fromResult(key, (ctx) => ok(fn(ctx)));\n }\n\n /** Throwing sync transform. */\n fromSync<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => T,\n onThrow: (error: unknown) => F,\n ): Railway<C & Record<K, T>, E | F, M> {\n return this.fromResult(key, (ctx) => trySync(fn, onThrow)(ctx));\n }\n\n /** Sync `Result`-returning step. */\n fromResult<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => Result<T, F>,\n ): Railway<C & Record<K, T>, E | F, M> {\n return this.step(\n (result) => flatMap(result, (ctx) => map(fn(ctx), (value) => addField(ctx, key, value))),\n (result) =>\n result.flatMap((ctx) =>\n ResultAsync.fromResult(fn(ctx)).map((value) => addField(ctx, key, value)),\n ),\n );\n }\n\n /** Promise-returning step — upgrades the workflow to async mode. */\n fromPromise<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => PromiseLike<T>,\n onReject: (error: unknown) => F,\n ): Railway<C & Record<K, T>, E | F, \"async\"> {\n return this.fromAsync(key, (ctx) => ResultAsync.fromPromise(fn(ctx), onReject));\n }\n\n /** `ResultAsync`-returning step — upgrades the workflow to async mode. */\n fromAsync<K extends string, T, F>(\n key: K,\n fn: (ctx: C) => ResultAsync<T, F>,\n ): Railway<C & Record<K, T>, E | F, \"async\"> {\n return new Railway({\n mode: \"async\",\n result: this.toAsync().flatMap((ctx) => fn(ctx).map((value) => addField(ctx, key, value))),\n });\n }\n\n /** Narrow a nullable context field into a required non-null field. */\n require<K extends string, S extends keyof C, F>(\n key: K,\n source: S,\n onMissing: (ctx: C) => F,\n ): Railway<C & Record<K, NonNullable<C[S]>>, E | F, M> {\n return this.fromResult(key, (ctx) => {\n const value = ctx[source];\n return value == null ? err(onMissing(ctx)) : ok(value);\n });\n }\n\n /** Run independent `ResultAsync` branches concurrently and merge outputs. */\n parallel<R extends Record<string, BranchFn<C>>>(\n branches: R,\n ): Railway<C & ParallelOutput<R>, E | ParallelError<R>, \"async\"> {\n const merged = this.toAsync().flatMap((ctx) =>\n ResultAsync.combineTupleParallel(\n Object.entries(branches).map(([, branch]) => branch(ctx)),\n ).map(\n (values) =>\n // Branch outputs land under exactly R's keys; Object.fromEntries\n // erases that correspondence, so reassert the merged shape.\n ({\n ...ctx,\n ...Object.fromEntries(Object.keys(branches).map((key, index) => [key, values[index]])),\n }) as C & ParallelOutput<R>,\n ),\n );\n return new Railway({\n mode: \"async\",\n // BranchFn erases per-key types to `ResultAsync<unknown, unknown>`\n // (ParallelOutput/ParallelError recover them from R), so re-assert the\n // precise value/error union the branches actually produce.\n result: merged as ResultAsync<C & ParallelOutput<R>, E | ParallelError<R>>,\n });\n }\n\n /** Project the final context into the workflow's output type. */\n select<T>(fn: (ctx: C) => T): RailwayOutput<T, E, M> {\n return this.out(\n (result) => map(result, fn),\n (result) => result.map(fn),\n );\n }\n\n /** Return the accumulated context as-is. */\n done(): RailwayOutput<C, E, M> {\n return this.out(\n (result) => result,\n (result) => result,\n );\n }\n}\n"]}
|
package/dist/railway.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as ResultAsync } from './async-
|
|
1
|
+
import { R as ResultAsync } from './async-DcXR7k9K.cjs';
|
|
2
2
|
import { R as Result } from './types-BQ9vv0nD.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -11,20 +11,10 @@ type RailwayMode = "sync" | "async";
|
|
|
11
11
|
* `Result<T, E>`, async mode → `ResultAsync<T, E>`.
|
|
12
12
|
*/
|
|
13
13
|
type RailwayOutput<T, E, M extends RailwayMode> = M extends "async" ? ResultAsync<T, E> : Result<T, E>;
|
|
14
|
-
/**
|
|
15
|
-
* Initial context shape for a `railway` functional pipeline.
|
|
16
|
-
* Wraps the raw input under the `input` key so subsequent named steps
|
|
17
|
-
* can reference it via `ctx.input`.
|
|
18
|
-
*/
|
|
19
|
-
type RailwayInput<I> = {
|
|
20
|
-
readonly input: I;
|
|
21
|
-
};
|
|
22
14
|
type BranchFn<C extends object> = (ctx: C) => ResultAsync<unknown, unknown>;
|
|
23
15
|
type BranchRecord = Record<string, (ctx: never) => ResultAsync<unknown, unknown>>;
|
|
24
16
|
type BranchOk<R> = R extends (ctx: never) => ResultAsync<infer T, infer _E> ? T : never;
|
|
25
17
|
type BranchErr<R> = R extends (ctx: never) => ResultAsync<infer _T, infer E> ? E : never;
|
|
26
|
-
type BranchInput<R> = R extends (ctx: infer C) => ResultAsync<unknown, unknown> ? C : never;
|
|
27
|
-
type ParallelInput<R extends BranchRecord> = BranchInput<R[keyof R]> & object;
|
|
28
18
|
type ParallelOutput<R extends BranchRecord> = {
|
|
29
19
|
[K in keyof R]: BranchOk<R[K]>;
|
|
30
20
|
};
|
|
@@ -33,27 +23,6 @@ type ParallelError<R extends BranchRecord> = BranchErr<R[keyof R]>;
|
|
|
33
23
|
* Named-context workflow builder. Each step appends a typed field to the
|
|
34
24
|
* accumulating context object; the workflow tracks sync/async mode so the
|
|
35
25
|
* final output type ({@link RailwayOutput}) is correct.
|
|
36
|
-
*
|
|
37
|
-
* Use `Railway` when a service workflow has 4+ named steps, mixed sync and
|
|
38
|
-
* async boundaries, or independent async branches that should run in
|
|
39
|
-
* parallel. For 1–2 step flows, prefer `flatMap` / `asyncAfter` directly.
|
|
40
|
-
*
|
|
41
|
-
* @example
|
|
42
|
-
* ```ts
|
|
43
|
-
* const summary = Railway
|
|
44
|
-
* .fromSync("id", () => IdSchema.parse(raw), toError)
|
|
45
|
-
* .fromPromise("row", ({ id }) => db.profiles.findFirst({ where: eq(profiles.id, id) }), toError)
|
|
46
|
-
* .require("profile", "row", ({ id }) => ({ kind: "not_found" as const, id }))
|
|
47
|
-
* .derive("normalized", ({ profile }) => normalizeProfile(profile))
|
|
48
|
-
* .parallel({
|
|
49
|
-
* artifacts: ({ normalized }) => loadArtifacts(normalized.id),
|
|
50
|
-
* metrics: ({ normalized }) => loadMetrics(normalized.id),
|
|
51
|
-
* })
|
|
52
|
-
* .select(({ normalized, artifacts, metrics }) =>
|
|
53
|
-
* toProfileSummary({ profile: normalized, artifacts, metrics }),
|
|
54
|
-
* );
|
|
55
|
-
* // ResultAsync<ProfileSummary, ParseError | DbError | NotFound>
|
|
56
|
-
* ```
|
|
57
26
|
*/
|
|
58
27
|
declare class Railway<C extends object, E, M extends RailwayMode> {
|
|
59
28
|
private readonly state;
|
|
@@ -62,10 +31,7 @@ declare class Railway<C extends object, E, M extends RailwayMode> {
|
|
|
62
31
|
static empty(): Railway<Record<never, never>, never, "sync">;
|
|
63
32
|
/** Start a sync workflow with the given context as the initial state. */
|
|
64
33
|
static context<C extends object>(context: C): Railway<C, never, "sync">;
|
|
65
|
-
/**
|
|
66
|
-
* Start a sync workflow with a throwing function — `onThrow` maps any
|
|
67
|
-
* exception to a typed error.
|
|
68
|
-
*/
|
|
34
|
+
/** Start a sync workflow with a throwing function. */
|
|
69
35
|
static fromSync<K extends string, T, E>(key: K, fn: () => T, onThrow: (error: unknown) => E): Railway<Record<K, T>, E, "sync">;
|
|
70
36
|
/** Start a sync workflow with a `Result`-returning function. */
|
|
71
37
|
static fromResult<K extends string, T, E>(key: K, fn: () => Result<T, E>): Railway<Record<K, T>, E, "sync">;
|
|
@@ -74,159 +40,39 @@ declare class Railway<C extends object, E, M extends RailwayMode> {
|
|
|
74
40
|
/** Start an async workflow with a `ResultAsync`-returning function. */
|
|
75
41
|
static fromAsync<K extends string, T, E>(key: K, fn: () => ResultAsync<T, E>): Railway<Record<K, T>, E, "async">;
|
|
76
42
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
43
|
+
* Rebuild the workflow in its current mode after transforming the carried
|
|
44
|
+
* result. Single re-link point for the state/phantom invariant: the mode
|
|
45
|
+
* tag is preserved verbatim, so `M` still describes the new state — TS
|
|
46
|
+
* cannot narrow the phantom `M` from the runtime tag, hence the cast.
|
|
79
47
|
*/
|
|
80
|
-
|
|
48
|
+
private step;
|
|
81
49
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
50
|
+
* Project the carried result into the mode-aware output type. Counterpart
|
|
51
|
+
* of {@link Railway.step} for terminal steps: the runtime branch matches
|
|
52
|
+
* the branch `RailwayOutput` picks for `M` (state/phantom invariant), but
|
|
53
|
+
* TS cannot resolve the conditional on an unresolved `M`, hence the cast.
|
|
84
54
|
*/
|
|
55
|
+
private out;
|
|
56
|
+
/** Lift the carried result into `ResultAsync` for async-upgrading steps. */
|
|
57
|
+
private toAsync;
|
|
58
|
+
/** Pure sync derivation. */
|
|
59
|
+
derive<K extends string, T>(key: K, fn: (ctx: C) => T): Railway<C & Record<K, T>, E, M>;
|
|
60
|
+
/** Throwing sync transform. */
|
|
85
61
|
fromSync<K extends string, T, F>(key: K, fn: (ctx: C) => T, onThrow: (error: unknown) => F): Railway<C & Record<K, T>, E | F, M>;
|
|
86
|
-
/**
|
|
87
|
-
* Sync `Result`-returning step. Adds `{ [key]: T }` to context on `Ok`;
|
|
88
|
-
* short-circuits the workflow on `Err`. Error union widens to `E | F`.
|
|
89
|
-
*/
|
|
62
|
+
/** Sync `Result`-returning step. */
|
|
90
63
|
fromResult<K extends string, T, F>(key: K, fn: (ctx: C) => Result<T, F>): Railway<C & Record<K, T>, E | F, M>;
|
|
91
|
-
/**
|
|
92
|
-
* Promise-returning step — upgrades the workflow to async mode. Reject
|
|
93
|
-
* reasons go through `onReject` to become typed `Err<F>`.
|
|
94
|
-
*/
|
|
64
|
+
/** Promise-returning step — upgrades the workflow to async mode. */
|
|
95
65
|
fromPromise<K extends string, T, F>(key: K, fn: (ctx: C) => PromiseLike<T>, onReject: (error: unknown) => F): Railway<C & Record<K, T>, E | F, "async">;
|
|
96
|
-
/**
|
|
97
|
-
* `ResultAsync`-returning step — upgrades the workflow to async mode.
|
|
98
|
-
* Already-typed error: no mapper needed.
|
|
99
|
-
*/
|
|
66
|
+
/** `ResultAsync`-returning step — upgrades the workflow to async mode. */
|
|
100
67
|
fromAsync<K extends string, T, F>(key: K, fn: (ctx: C) => ResultAsync<T, F>): Railway<C & Record<K, T>, E | F, "async">;
|
|
101
|
-
/**
|
|
102
|
-
* Narrow a nullable context field into a required non-null field. If the
|
|
103
|
-
* source field is `null` / `undefined`, the workflow short-circuits with
|
|
104
|
-
* `onMissing(ctx)`.
|
|
105
|
-
*
|
|
106
|
-
* @example
|
|
107
|
-
* ```ts
|
|
108
|
-
* .fromPromise("row", ({ id }) => db.users.findFirst({ where: eq(users.id, id) }))
|
|
109
|
-
* .require("user", "row", ({ id }) => ({ kind: "not_found" as const, id }))
|
|
110
|
-
* // user is now User (non-null), not User | null
|
|
111
|
-
* ```
|
|
112
|
-
*/
|
|
68
|
+
/** Narrow a nullable context field into a required non-null field. */
|
|
113
69
|
require<K extends string, S extends keyof C, F>(key: K, source: S, onMissing: (ctx: C) => F): Railway<C & Record<K, NonNullable<C[S]>>, E | F, M>;
|
|
114
|
-
/**
|
|
115
|
-
* Run independent `ResultAsync` branches concurrently and merge their
|
|
116
|
-
* named outputs back into context. Upgrades the workflow to async mode.
|
|
117
|
-
* On multiple failures, the first `Err` in record-iteration order wins.
|
|
118
|
-
*
|
|
119
|
-
* @example
|
|
120
|
-
* ```ts
|
|
121
|
-
* .parallel({
|
|
122
|
-
* recent: ({ userId }) => loadRecent(userId),
|
|
123
|
-
* metrics: ({ userId }) => loadMetrics(userId),
|
|
124
|
-
* })
|
|
125
|
-
* // ctx now has { ..., recent, metrics }
|
|
126
|
-
* ```
|
|
127
|
-
*/
|
|
70
|
+
/** Run independent `ResultAsync` branches concurrently and merge outputs. */
|
|
128
71
|
parallel<R extends Record<string, BranchFn<C>>>(branches: R): Railway<C & ParallelOutput<R>, E | ParallelError<R>, "async">;
|
|
129
|
-
/**
|
|
130
|
-
* Project the final context into the workflow's output type. Hides the
|
|
131
|
-
* internal context shape from callers.
|
|
132
|
-
*/
|
|
72
|
+
/** Project the final context into the workflow's output type. */
|
|
133
73
|
select<T>(fn: (ctx: C) => T): RailwayOutput<T, E, M>;
|
|
134
|
-
/**
|
|
135
|
-
* Return the accumulated context as-is. Use when downstream code needs
|
|
136
|
-
* every named field; prefer {@link select} when you can project to a DTO.
|
|
137
|
-
*/
|
|
74
|
+
/** Return the accumulated context as-is. */
|
|
138
75
|
done(): RailwayOutput<C, E, M>;
|
|
139
76
|
}
|
|
140
77
|
|
|
141
|
-
type
|
|
142
|
-
readonly parse: (input: I) => T;
|
|
143
|
-
} | ((input: I) => T);
|
|
144
|
-
type UnaryStep<I, O> = (input: I) => O;
|
|
145
|
-
/**
|
|
146
|
-
* Functional companion to {@link Railway} — point-free composition of
|
|
147
|
-
* reusable workflow steps. Starts from `Railway.context({ input })` and
|
|
148
|
-
* applies each step in order. Step factories live below: {@link parseWith},
|
|
149
|
-
* {@link fromSyncNamed}, {@link fromResultNamed}, {@link fromPromiseNamed},
|
|
150
|
-
* {@link fromAsyncNamed}, {@link deriveNamed}, {@link requireNamed},
|
|
151
|
-
* {@link parallelNamed}, {@link select}.
|
|
152
|
-
*
|
|
153
|
-
* @example
|
|
154
|
-
* ```ts
|
|
155
|
-
* const summary = railway(
|
|
156
|
-
* rawId,
|
|
157
|
-
* parseWith(IdSchema, toError).as("id"),
|
|
158
|
-
* fromPromiseNamed("row", ({ id }) => db.profiles.findFirst({ where: eq(profiles.id, id) }), toError),
|
|
159
|
-
* requireNamed("profile", "row", ({ id }) => ({ kind: "not_found" as const, id })),
|
|
160
|
-
* deriveNamed("normalized", ({ profile }) => normalizeProfile(profile)),
|
|
161
|
-
* select(({ normalized }) => toProfileSummary(normalized)),
|
|
162
|
-
* );
|
|
163
|
-
* ```
|
|
164
|
-
*/
|
|
165
|
-
declare function railway<I, A>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>): A;
|
|
166
|
-
declare function railway<I, A, B>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>): B;
|
|
167
|
-
declare function railway<I, A, B, C>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>, step3: UnaryStep<B, C>): C;
|
|
168
|
-
declare function railway<I, A, B, C, D>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>, step3: UnaryStep<B, C>, step4: UnaryStep<C, D>): D;
|
|
169
|
-
declare function railway<I, A, B, C, D, E>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>, step3: UnaryStep<B, C>, step4: UnaryStep<C, D>, step5: UnaryStep<D, E>): E;
|
|
170
|
-
declare function railway<I, A, B, C, D, E, F>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>, step3: UnaryStep<B, C>, step4: UnaryStep<C, D>, step5: UnaryStep<D, E>, step6: UnaryStep<E, F>): F;
|
|
171
|
-
declare function railway<I, A, B, C, D, E, F, G>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>, step3: UnaryStep<B, C>, step4: UnaryStep<C, D>, step5: UnaryStep<D, E>, step6: UnaryStep<E, F>, step7: UnaryStep<F, G>): G;
|
|
172
|
-
declare function railway<I, A, B, C, D, E, F, G, H>(input: I, step1: UnaryStep<Railway<RailwayInput<I>, never, "sync">, A>, step2: UnaryStep<A, B>, step3: UnaryStep<B, C>, step4: UnaryStep<C, D>, step5: UnaryStep<D, E>, step6: UnaryStep<E, F>, step7: UnaryStep<F, G>, step8: UnaryStep<G, H>): H;
|
|
173
|
-
/**
|
|
174
|
-
* Step factory: parse the workflow input with a Zod-like schema (or a
|
|
175
|
-
* unary parse function). Call `.as(key)` to name the output field.
|
|
176
|
-
*
|
|
177
|
-
* @example
|
|
178
|
-
* ```ts
|
|
179
|
-
* parseWith(IdSchema, toError).as("id");
|
|
180
|
-
* // Used as the first step in `railway(rawId, parseId, ...)`
|
|
181
|
-
* ```
|
|
182
|
-
*/
|
|
183
|
-
declare const parseWith: <I, T, E>(parser: ParserLike<I, T>, onThrow: (error: unknown) => E) => {
|
|
184
|
-
as: <K extends string>(key: K) => <F, M extends RailwayMode>(workflow: Railway<RailwayInput<I>, F, M>) => Railway<RailwayInput<I> & Record<K, T>, F | E, M>;
|
|
185
|
-
};
|
|
186
|
-
/**
|
|
187
|
-
* Name-first companion to {@link parseWith}: parse the workflow input with a
|
|
188
|
-
* Zod-like schema (or unary parse fn), naming the output field in the same
|
|
189
|
-
* `(key, ...)` shape as {@link fromSyncNamed}, {@link deriveNamed}, et al.
|
|
190
|
-
* Prefer this in `railway(...)` pipelines so every step's name aligns at the
|
|
191
|
-
* left edge.
|
|
192
|
-
*
|
|
193
|
-
* @example
|
|
194
|
-
* ```ts
|
|
195
|
-
* railway(
|
|
196
|
-
* rawId,
|
|
197
|
-
* parseNamed("id", IdSchema, toError),
|
|
198
|
-
* fromPromiseNamed("profile", ({ id }) => fetchProfile(id), toError),
|
|
199
|
-
* );
|
|
200
|
-
* ```
|
|
201
|
-
*/
|
|
202
|
-
declare const parseNamed: <K extends string, I, T, E>(key: K, parser: ParserLike<I, T>, onThrow: (error: unknown) => E) => <F, M extends RailwayMode>(workflow: Railway<RailwayInput<I>, F, M>) => Railway<RailwayInput<I> & Record<K, T>, F | E, M>;
|
|
203
|
-
/**
|
|
204
|
-
* Reusable wrapper around {@link Railway.fromSync}. Captures key + fn +
|
|
205
|
-
* onThrow once; applies to any compatible workflow.
|
|
206
|
-
*/
|
|
207
|
-
declare const fromSyncNamed: <K extends string, C extends object, T, E>(key: K, fn: (ctx: C) => T, onThrow: (error: unknown) => E) => <I extends C, F, M extends RailwayMode>(workflow: Railway<I, F, M>) => Railway<I & Record<K, T>, F | E, M>;
|
|
208
|
-
/** Reusable wrapper around {@link Railway.fromResult}. */
|
|
209
|
-
declare const fromResultNamed: <K extends string, C extends object, T, E>(key: K, fn: (ctx: C) => Result<T, E>) => <I extends C, F, M extends RailwayMode>(workflow: Railway<I, F, M>) => Railway<I & Record<K, T>, F | E, M>;
|
|
210
|
-
/**
|
|
211
|
-
* Reusable wrapper around {@link Railway.fromPromise}. Upgrades the
|
|
212
|
-
* workflow to async mode when applied.
|
|
213
|
-
*/
|
|
214
|
-
declare const fromPromiseNamed: <K extends string, C extends object, T, E>(key: K, fn: (ctx: C) => PromiseLike<T>, onReject: (error: unknown) => E) => <I extends C, F, M extends RailwayMode>(workflow: Railway<I, F, M>) => Railway<I & Record<K, T>, F | E, "async">;
|
|
215
|
-
/** Reusable wrapper around {@link Railway.fromAsync}. */
|
|
216
|
-
declare const fromAsyncNamed: <K extends string, C extends object, T, E>(key: K, fn: (ctx: C) => ResultAsync<T, E>) => <I extends C, F, M extends RailwayMode>(workflow: Railway<I, F, M>) => Railway<I & Record<K, T>, F | E, "async">;
|
|
217
|
-
/** Reusable wrapper around {@link Railway.derive} — pure sync derivation. */
|
|
218
|
-
declare const deriveNamed: <K extends string, C extends object, T>(key: K, fn: (ctx: C) => T) => <I extends C, E, M extends RailwayMode>(workflow: Railway<I, E, M>) => Railway<I & Record<K, T>, E, M>;
|
|
219
|
-
/** Reusable wrapper around {@link Railway.require} — narrows a nullable field. */
|
|
220
|
-
declare const requireNamed: <K extends string, S extends string, C extends object, E>(key: K, source: S, onMissing: (ctx: C & Record<S, unknown>) => E) => <I extends C & Record<S, unknown>, F, M extends RailwayMode>(workflow: Railway<I, F, M>) => Railway<I & Record<K, NonNullable<I[S]>>, F | E, M>;
|
|
221
|
-
/**
|
|
222
|
-
* Reusable wrapper around {@link Railway.parallel}. Branches run
|
|
223
|
-
* concurrently and merge their named outputs back into context.
|
|
224
|
-
*/
|
|
225
|
-
declare const parallelNamed: <R extends BranchRecord>(branches: R) => <I extends ParallelInput<R>, E, M extends RailwayMode>(workflow: Railway<I, E, M>) => Railway<I & ParallelOutput<R>, E | ParallelError<R>, "async">;
|
|
226
|
-
/**
|
|
227
|
-
* Reusable wrapper around {@link Railway.select} — projects the final
|
|
228
|
-
* context into the workflow's output type.
|
|
229
|
-
*/
|
|
230
|
-
declare const select: <C extends object, T>(fn: (ctx: C) => T) => <E, M extends RailwayMode>(workflow: Railway<C, E, M>) => RailwayOutput<T, E, M>;
|
|
231
|
-
|
|
232
|
-
export { Railway, type RailwayInput, type RailwayMode, type RailwayOutput, deriveNamed, fromAsyncNamed, fromPromiseNamed, fromResultNamed, fromSyncNamed, parallelNamed, parseNamed, parseWith, railway, requireNamed, select };
|
|
78
|
+
export { type BranchFn, type BranchRecord, type ParallelError, type ParallelOutput, Railway, type RailwayMode, type RailwayOutput };
|