@onrails/result 0.3.1 → 0.4.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.
Files changed (73) hide show
  1. package/DESIGN.md +4 -3
  2. package/README.md +166 -13
  3. package/RECIPES.md +6 -4
  4. package/dist/async-fns.cjs +52 -0
  5. package/dist/async-fns.cjs.map +1 -0
  6. package/dist/async-fns.d.cts +143 -0
  7. package/dist/async-fns.d.ts +143 -0
  8. package/dist/async-fns.js +42 -0
  9. package/dist/async-fns.js.map +1 -0
  10. package/dist/async-lift.d.cts +109 -0
  11. package/dist/async-lift.d.ts +109 -0
  12. package/dist/{async-Ci6WSL5-.d.ts → async.d.cts} +42 -58
  13. package/dist/{async-DcXR7k9K.d.cts → async.d.ts} +42 -58
  14. package/dist/collections.d.cts +105 -0
  15. package/dist/collections.d.ts +105 -0
  16. package/dist/compat/neverthrow.cjs +57 -45
  17. package/dist/compat/neverthrow.cjs.map +1 -1
  18. package/dist/compat/neverthrow.d.cts +21 -24
  19. package/dist/compat/neverthrow.d.ts +21 -24
  20. package/dist/compat/neverthrow.js +56 -44
  21. package/dist/compat/neverthrow.js.map +1 -1
  22. package/dist/extra.cjs +3 -1
  23. package/dist/extra.cjs.map +1 -1
  24. package/dist/extra.d.cts +11 -14
  25. package/dist/extra.d.ts +11 -14
  26. package/dist/extra.js +3 -1
  27. package/dist/extra.js.map +1 -1
  28. package/dist/fluent.cjs +15 -28
  29. package/dist/fluent.cjs.map +1 -1
  30. package/dist/fluent.d.cts +4 -34
  31. package/dist/fluent.d.ts +4 -34
  32. package/dist/fluent.js +16 -28
  33. package/dist/fluent.js.map +1 -1
  34. package/dist/index.cjs +77 -52
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +28 -490
  37. package/dist/index.d.ts +28 -490
  38. package/dist/index.js +77 -53
  39. package/dist/index.js.map +1 -1
  40. package/dist/internal/ctor.d.cts +12 -0
  41. package/dist/internal/ctor.d.ts +12 -0
  42. package/dist/internal/dual.d.cts +42 -0
  43. package/dist/internal/dual.d.ts +42 -0
  44. package/dist/internal/infer.d.cts +40 -0
  45. package/dist/internal/infer.d.ts +40 -0
  46. package/dist/internal/lock.d.cts +16 -0
  47. package/dist/internal/lock.d.ts +16 -0
  48. package/dist/internal/to-error.d.cts +2 -0
  49. package/dist/internal/to-error.d.ts +2 -0
  50. package/dist/pipe.cjs +8 -0
  51. package/dist/pipe.cjs.map +1 -1
  52. package/dist/pipe.d.cts +58 -11
  53. package/dist/pipe.d.ts +58 -11
  54. package/dist/pipe.js +8 -1
  55. package/dist/pipe.js.map +1 -1
  56. package/dist/railway.cjs +87 -63
  57. package/dist/railway.cjs.map +1 -1
  58. package/dist/railway.d.cts +49 -19
  59. package/dist/railway.d.ts +49 -19
  60. package/dist/railway.js +87 -63
  61. package/dist/railway.js.map +1 -1
  62. package/dist/result.d.cts +315 -0
  63. package/dist/result.d.ts +315 -0
  64. package/dist/try-gen.cjs +3 -3
  65. package/dist/try-gen.cjs.map +1 -1
  66. package/dist/try-gen.d.cts +4 -7
  67. package/dist/try-gen.d.ts +4 -7
  68. package/dist/try-gen.js +3 -3
  69. package/dist/try-gen.js.map +1 -1
  70. package/dist/{types-BQ9vv0nD.d.cts → types.d.cts} +6 -8
  71. package/dist/{types-BQ9vv0nD.d.ts → types.d.ts} +6 -8
  72. package/package.json +69 -24
  73. package/skills/railway-do-notation/SKILL.md +9 -9
package/dist/index.js CHANGED
@@ -1,3 +1,13 @@
1
+ // src/internal/ctor.ts
2
+ var mkOk = (value) => ({
3
+ _tag: "Ok",
4
+ value
5
+ });
6
+ var mkErr = (error) => ({
7
+ _tag: "Err",
8
+ error
9
+ });
10
+
1
11
  // src/internal/dual.ts
2
12
  var dual = (arity, body) => {
3
13
  const run = body;
@@ -5,37 +15,38 @@ var dual = (arity, body) => {
5
15
  return dispatcher;
6
16
  };
7
17
 
18
+ // src/internal/to-error.ts
19
+ var toError = (error) => error instanceof Error ? error : new Error(String(error));
20
+
8
21
  // src/result.ts
9
- var ok = (value) => ({
10
- _tag: "Ok",
11
- value
12
- });
22
+ function ok(value) {
23
+ return mkOk(value);
24
+ }
13
25
  var of = ok;
14
- var err = (error) => ({
15
- _tag: "Err",
16
- error
17
- });
26
+ function err(error) {
27
+ return mkErr(error);
28
+ }
18
29
  var isOk = (result) => result._tag === "Ok";
19
30
  var isErr = (result) => result._tag === "Err";
20
31
  var map = dual(
21
32
  2,
22
- (result, fn) => isOk(result) ? ok(fn(result.value)) : err(result.error)
33
+ (result, fn) => isOk(result) ? mkOk(fn(result.value)) : mkErr(result.error)
23
34
  );
24
35
  var mapErr = dual(
25
36
  2,
26
- (result, fn) => isErr(result) ? err(fn(result.error)) : ok(result.value)
37
+ (result, fn) => isErr(result) ? mkErr(fn(result.error)) : mkOk(result.value)
27
38
  );
28
39
  var bimap = dual(
29
40
  3,
30
- (result, onOk, onErr) => isOk(result) ? ok(onOk(result.value)) : err(onErr(result.error))
41
+ (result, onOk, onErr) => isOk(result) ? mkOk(onOk(result.value)) : mkErr(onErr(result.error))
31
42
  );
32
43
  var flatMap = dual(
33
44
  2,
34
- (result, fn) => isOk(result) ? fn(result.value) : err(result.error)
45
+ (result, fn) => isOk(result) ? fn(result.value) : mkErr(result.error)
35
46
  );
36
47
  var recover = dual(
37
48
  2,
38
- (result, fn) => isErr(result) ? fn(result.error) : ok(result.value)
49
+ (result, fn) => isErr(result) ? fn(result.error) : mkOk(result.value)
39
50
  );
40
51
  var tap = dual(2, (result, fn) => {
41
52
  if (isOk(result)) fn(result.value);
@@ -62,21 +73,21 @@ function unwrapErr(result) {
62
73
  if (isOk(result)) throw new TypeError("unwrapErr called on Ok");
63
74
  return result.error;
64
75
  }
65
- function trySync(fn, onThrow) {
76
+ function fromThrowable(fn, onThrow) {
66
77
  return (...args) => {
67
78
  try {
68
- return ok(fn(...args));
79
+ return mkOk(fn(...args));
69
80
  } catch (error) {
70
- return err(onThrow(error));
81
+ return mkErr(onThrow(error));
71
82
  }
72
83
  };
73
84
  }
74
- function pipe(value, ...fns) {
75
- let acc = value;
76
- for (const fn of fns) {
77
- acc = fn(acc);
85
+ function trySync(fn, onThrow) {
86
+ try {
87
+ return mkOk(fn());
88
+ } catch (error) {
89
+ return mkErr(onThrow ? onThrow(error) : toError(error));
78
90
  }
79
- return acc;
80
91
  }
81
92
  var printPayload = (payload) => {
82
93
  try {
@@ -102,11 +113,11 @@ var sequenceSettled = (settled) => {
102
113
  const values = [];
103
114
  for (const result of settled) {
104
115
  if (isErr(result)) {
105
- return err(result.error);
116
+ return mkErr(result.error);
106
117
  }
107
118
  values.push(result.value);
108
119
  }
109
- return ok(values);
120
+ return mkOk(values);
110
121
  };
111
122
  var ResultAsync = class _ResultAsync {
112
123
  constructor(run) {
@@ -143,9 +154,9 @@ var ResultAsync = class _ResultAsync {
143
154
  static fromPromise(promise, onReject) {
144
155
  return new _ResultAsync(async () => {
145
156
  try {
146
- return ok(await promise);
157
+ return mkOk(await promise);
147
158
  } catch (error) {
148
- return err(onReject(error));
159
+ return mkErr(onReject(error));
149
160
  }
150
161
  });
151
162
  }
@@ -159,7 +170,7 @@ var ResultAsync = class _ResultAsync {
159
170
  * ```
160
171
  */
161
172
  static fromSafePromise(promise) {
162
- return new _ResultAsync(async () => ok(await promise));
173
+ return new _ResultAsync(async () => mkOk(await promise));
163
174
  }
164
175
  /**
165
176
  * Defers work until {@link resolve}. Unlike {@link fromPromise}, the factory
@@ -177,21 +188,13 @@ var ResultAsync = class _ResultAsync {
177
188
  return new _ResultAsync(fn);
178
189
  }
179
190
  static ok(value) {
180
- return new _ResultAsync(async () => ok(value));
191
+ return new _ResultAsync(async () => mkOk(value));
181
192
  }
182
193
  static of(value) {
183
194
  return _ResultAsync.ok(value);
184
195
  }
185
- /**
186
- * Lifts an error into an `Err` async result.
187
- *
188
- * @example
189
- * ```ts
190
- * const r = ResultAsync.err({ kind: "not_found" as const });
191
- * ```
192
- */
193
196
  static err(error) {
194
- return new _ResultAsync(async () => err(error));
197
+ return new _ResultAsync(async () => mkErr(error));
195
198
  }
196
199
  /**
197
200
  * Lifts an existing `Promise<Result<T, E>>` (e.g. from interop code) into a
@@ -209,7 +212,7 @@ var ResultAsync = class _ResultAsync {
209
212
  try {
210
213
  return await promise;
211
214
  } catch (error) {
212
- return err(mapDefect(error));
215
+ return mkErr(mapDefect(error));
213
216
  }
214
217
  });
215
218
  }
@@ -231,11 +234,11 @@ var ResultAsync = class _ResultAsync {
231
234
  for (const ra of results) {
232
235
  const result = await ra.resolve();
233
236
  if (isErr(result)) {
234
- return err(result.error);
237
+ return mkErr(result.error);
235
238
  }
236
239
  values.push(result.value);
237
240
  }
238
- return ok(values);
241
+ return mkOk(values);
239
242
  });
240
243
  }
241
244
  /**
@@ -247,7 +250,7 @@ var ResultAsync = class _ResultAsync {
247
250
  *
248
251
  * @example
249
252
  * ```ts
250
- * const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()] as const);
253
+ * const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()]);
251
254
  * // ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>
252
255
  * const r = await combined;
253
256
  * if (isOk(r)) {
@@ -255,7 +258,7 @@ var ResultAsync = class _ResultAsync {
255
258
  * }
256
259
  * ```
257
260
  */
258
- static combineTuple(results) {
261
+ static combineTuple(results, ..._guard) {
259
262
  return _ResultAsync.combine(
260
263
  results
261
264
  );
@@ -270,12 +273,14 @@ var ResultAsync = class _ResultAsync {
270
273
  * const combined = ResultAsync.combineTupleParallel([
271
274
  * loadProfile(id),
272
275
  * loadMetrics(id),
273
- * ] as const);
276
+ * ]);
274
277
  * ```
275
278
  */
276
- static combineTupleParallel(results) {
279
+ static combineTupleParallel(results, ..._guard) {
277
280
  return new _ResultAsync(
278
- async () => sequenceSettled(await Promise.all(results.map((ra) => ra.resolve())))
281
+ async () => sequenceSettled(
282
+ await Promise.all(results.map((ra) => ra.resolve()))
283
+ )
279
284
  );
280
285
  }
281
286
  /**
@@ -301,6 +306,18 @@ var ResultAsync = class _ResultAsync {
301
306
  mapErr(fn) {
302
307
  return new _ResultAsync(async () => mapErr(await this.resolve(), fn));
303
308
  }
309
+ /**
310
+ * Transforms both tracks in one step — the async mirror of the sync
311
+ * `bimap`. Exactly one of `onOk` / `onErr` runs.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * load(id).bimap(toDto, (e): AppError => ({ kind: "load", cause: e }));
316
+ * ```
317
+ */
318
+ bimap(onOk, onErr) {
319
+ return new _ResultAsync(async () => bimap(await this.resolve(), onOk, onErr));
320
+ }
304
321
  /**
305
322
  * Canonical bind — chains a step that itself returns a `ResultAsync` or sync
306
323
  * `Result`, short-circuiting on `Err`. Error types accumulate (`E | F`).
@@ -476,7 +493,6 @@ var asyncAfter = dual(
476
493
  (result, fn) => fromResult(result).flatMap(fn)
477
494
  );
478
495
  var fromAsync = (fn, onDefect) => (...args) => ResultAsync.fromResultPromise(fn(...args), onDefect);
479
- var toError = (error) => error instanceof Error ? error : new Error(String(error));
480
496
  function tryAsync(promise, onReject) {
481
497
  return onReject ? ResultAsync.fromPromise(promise, onReject) : ResultAsync.fromPromise(promise, toError);
482
498
  }
@@ -485,12 +501,12 @@ function tryAsync(promise, onReject) {
485
501
  var combine = (results) => {
486
502
  const values = [];
487
503
  for (const result of results) {
488
- if (isErr(result)) return err(result.error);
504
+ if (isErr(result)) return mkErr(result.error);
489
505
  values.push(result.value);
490
506
  }
491
- return ok(values);
507
+ return mkOk(values);
492
508
  };
493
- var combineTuple = (results) => (
509
+ var combineTuple = (results, ..._guard) => (
494
510
  // Runtime identical to combine; the cast restores per-index tuple types.
495
511
  combine(results)
496
512
  );
@@ -504,14 +520,22 @@ function validateAll(results, combineErrors) {
504
520
  values.push(result.value);
505
521
  }
506
522
  }
507
- if (errors.length === 0) return ok(values);
508
- return err(combineErrors ? errors.reduce(combineErrors) : errors);
523
+ if (errors.length === 0) return mkOk(values);
524
+ return mkErr(combineErrors ? errors.reduce(combineErrors) : errors);
509
525
  }
510
- function validateTuple(results, combineErrors) {
526
+ function validateTuple(results, ...rest) {
527
+ const combineErrors = rest[0];
511
528
  return combineErrors ? validateAll(results, combineErrors) : validateAll(results);
512
529
  }
513
530
 
514
531
  // src/pipe.ts
532
+ function pipe(value, ...fns) {
533
+ let acc = value;
534
+ for (const fn of fns) {
535
+ acc = fn(acc);
536
+ }
537
+ return acc;
538
+ }
515
539
  function flow(first, ...rest) {
516
540
  return (...args) => {
517
541
  let acc = first(...args);
@@ -542,12 +566,12 @@ var tryGen = (fn) => {
542
566
  return fn();
543
567
  } catch (error) {
544
568
  if (error instanceof ErrSignal) {
545
- return err(error.error);
569
+ return mkErr(error.error);
546
570
  }
547
571
  throw error;
548
572
  }
549
573
  };
550
574
 
551
- export { $, ResultAsync, UnexpectedError, asyncAfter, bimap, combine, combineTuple, err, errAsync, flatMap, flow, fromAsync, fromPromise, fromResult, fromSafePromise, isErr, isOk, map, mapErr, match, of, ok, okAsync, pipe, recover, show, tap, tapErr, tryAsync, tryGen, trySync, unwrap, unwrapErr, unwrapOk, unwrapOr, validateAll, validateTuple, yieldResult };
575
+ export { $, ResultAsync, UnexpectedError, asyncAfter, bimap, combine, combineTuple, err, errAsync, flatMap, flow, fromAsync, fromPromise, fromResult, fromSafePromise, fromThrowable, isErr, isOk, map, mapErr, match, of, ok, okAsync, pipe, recover, show, tap, tapErr, tryAsync, tryGen, trySync, unwrap, unwrapErr, unwrapOk, unwrapOr, validateAll, validateTuple, yieldResult };
552
576
  //# sourceMappingURL=index.js.map
553
577
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/dual.ts","../src/result.ts","../src/types.ts","../src/async.ts","../src/async-lift.ts","../src/collections.ts","../src/pipe.ts","../src/try-gen.ts"],"names":[],"mappings":";AA0CO,IAAM,IAAA,GAAO,CAAI,KAAA,EAAe,IAAA,KAA2C;AAMhF,EAAA,MAAM,GAAA,GAAM,IAAA;AACZ,EAAA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AA,CACd,UACG,IAAA,EAC8B;AACjC,EAAA,OAAO,IAAI,IAAA,KAAoB;AAC7B,IAAA,IAAI,GAAA,GAAM,KAAA,CAAM,GAAG,IAAI,CAAA;AACvB,IAAA,KAAA,MAAW,MAAM,IAAA,EAAM;AACrB,MAAA,GAAA,GAAM,GAAG,GAAG,CAAA;AAAA,IACd;AACA,IAAA,OAAO,GAAA;AAAA,EACT,CAAA;AACF;;;AC3EA,IAAM,YAAN,MAAmB;AAAA,EAEjB,YAAqB,KAAA,EAAU;AAAV,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAAW;AAAA,EAAX,KAAA;AAAA,EADZ,IAAA,GAAO,WAAA;AAElB,CAAA;AAmBO,IAAM,WAAA,GAAc,CAAO,MAAA,KAA4B;AAC5D,EAAA,IAAI,KAAA,CAAM,MAAM,CAAA,EAAG;AACjB,IAAA,MAAM,IAAI,SAAA,CAAU,MAAA,CAAO,KAAK,CAAA;AAAA,EAClC;AACA,EAAA,OAAO,MAAA,CAAO,KAAA;AAChB;AAeO,IAAM,CAAA,GAAI;AAcV,IAAM,MAAA,GAAS,CAAO,EAAA,KAAyC;AACpE,EAAA,IAAI;AACF,IAAA,OAAO,EAAA,EAAG;AAAA,EACZ,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,iBAAiB,SAAA,EAAW;AAC9B,MAAA,OAAO,GAAA,CAAI,MAAM,KAAK,CAAA;AAAA,IACxB;AACA,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"index.js","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","/**\n * @onrails/result — THE lift module. Every \"value → {@link ResultAsync}\"\n * entry point is defined exactly once, here: `okAsync`, `errAsync`,\n * `fromPromise`, `fromSafePromise`, `fromResult`, `fromAsync`, `asyncAfter`,\n * `tryAsync`.\n */\n\nimport { ResultAsync } from \"./async.js\";\nimport { dual } from \"./internal/dual.js\";\nimport type { InferErr, InferOk } from \"./internal/infer.js\";\nimport type { Result, UnexpectedError } from \"./types.js\";\n\n// The bare renames below detach statics from the class. Safe: every\n// `ResultAsync` static references the class by name (`new ResultAsync`,\n// `ResultAsync.combine`), never `this`.\n\n/**\n * Lifts a value into an `Ok` async result.\n *\n * @example\n * ```ts\n * const r = okAsync(42); // ResultAsync<number, never>\n * ```\n */\nexport const okAsync = ResultAsync.ok;\n\n/**\n * Lifts a value into an `Err` async result.\n *\n * @example\n * ```ts\n * const r = errAsync({ kind: \"not_found\" as const });\n * ```\n */\nexport const errAsync = ResultAsync.err;\n\n/**\n * Wraps a `PromiseLike<T>` into a {@link ResultAsync}. Reject reasons go\n * through `onReject` to become typed `Err`s; success becomes `Ok<T>`.\n *\n * @example\n * ```ts\n * const body = fromPromise(\n * fetch(url).then((r) => r.text()),\n * (e): NetworkError => ({ kind: \"network\", cause: String(e) }),\n * );\n * ```\n */\nexport const fromPromise = ResultAsync.fromPromise;\n\n/**\n * Wraps a `PromiseLike<T>` that **never rejects** into {@link ResultAsync}.\n * Skips the `onReject` mapper. Use only when the promise is provably safe.\n */\nexport const fromSafePromise = ResultAsync.fromSafePromise;\n\n/**\n * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}, so\n * it can be chained alongside async steps in a railway.\n *\n * @example\n * ```ts\n * const ra = fromResult(ok(1)); // ResultAsync<number, never>\n * await fromResult(err(error)).resolve(); // Err(error)\n * ```\n */\nexport const fromResult = ResultAsync.fromResult;\n\n/**\n * Bind a sync {@link Result} into an async step without widening defects.\n * Dual-form: data-first for one-shots, data-last (curried) for `pipe`/`flow`.\n *\n * @example\n * ```ts\n * asyncAfter(result, (u) => tryAsync(db.insert(u), toErr)); // data-first\n * asyncAfter((u) => tryAsync(db.insert(u), toErr)); // data-last\n * ```\n */\nexport const asyncAfter: {\n <T, U, E, F>(result: Result<T, E>, fn: (value: T) => ResultAsync<U, F>): ResultAsync<U, E | F>;\n <T, U, F>(\n fn: (value: T) => ResultAsync<U, F>,\n ): <E>(result: Result<T, E>) => ResultAsync<U, E | F>;\n} = dual(\n 2,\n <T, U, E, F>(result: Result<T, E>, fn: (value: T) => ResultAsync<U, F>): ResultAsync<U, E | F> =>\n fromResult(result).flatMap(fn),\n);\n\ntype AnyResult = Result<unknown, unknown>;\n\n/**\n * Lifts a `(...args) => Promise<Result<T, E>>` function (typical of interop or\n * boundary code) into one returning `(...args) => ResultAsync<T, E>`. Expected\n * `Err`s pass through; an unexpected promise rejection (a defect) is routed via\n * `onDefect`, defaulting to {@link UnexpectedError} and widening the error union.\n *\n * @param fn - a function returning a promise that already yields a `Result`\n * @param onDefect - maps an unexpected rejection to the `Err` channel\n *\n * @example\n * ```ts\n * const loadUser = fromAsync(\n * (id: string): Promise<Result<User, NotFound>> => api.getUser(id),\n * );\n * const ra = loadUser(\"u1\"); // ResultAsync<User, NotFound | UnexpectedError>\n * ```\n */\nexport const fromAsync =\n <A extends readonly unknown[], R extends AnyResult>(\n fn: (...args: A) => Promise<R>,\n onDefect?: (error: unknown) => InferErr<R> | UnexpectedError,\n ): ((...args: A) => ResultAsync<InferOk<R>, InferErr<R> | UnexpectedError>) =>\n (...args: A) =>\n ResultAsync.fromResultPromise(fn(...args), onDefect) as ResultAsync<\n InferOk<R>,\n InferErr<R> | UnexpectedError\n >;\n\nconst toError = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n\n/**\n * Convenience wrapper over {@link fromPromise} with default `Error`\n * normalization. Call without `onReject` to get `ResultAsync<T, Error>`,\n * or pass a custom mapper for a typed error.\n *\n * @example\n * ```ts\n * // Default: rejection → Err(Error)\n * const a = tryAsync(db.users.insert(row));\n *\n * // Custom: typed error\n * const b = tryAsync(db.users.insert(row), (e): DbError => ({\n * kind: \"db\",\n * cause: e,\n * }));\n * ```\n */\nexport function tryAsync<T>(promise: PromiseLike<T>): ResultAsync<T, Error>;\nexport function tryAsync<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n): ResultAsync<T, E>;\nexport function tryAsync<T, E>(\n promise: PromiseLike<T>,\n onReject?: (error: unknown) => E,\n): ResultAsync<T, E | Error> {\n return onReject\n ? ResultAsync.fromPromise(promise, onReject)\n : ResultAsync.fromPromise(promise, toError);\n}\n","/**\n * @onrails/result — sync aggregation, one module, two axes:\n *\n * short-circuit (first `Err` wins) — {@link combine} / {@link combineTuple}\n * accumulate expected failures — {@link validateAll} / {@link validateTuple}\n *\n * The accumulate pair collects every failure into a readonly array by\n * default, or folds them with an explicit `combineErrors` when given one.\n */\n\nimport type { InferErr, InferOk } from \"./internal/infer.js\";\nimport { err, isErr, ok } from \"./result.js\";\nimport type { Result } from \"./types.js\";\n\n/**\n * Combines a homogeneous array of results into a single result holding an\n * array of the `Ok` values, in input order. Short-circuits on the first `Err`\n * (first failure wins). For heterogeneous tuples that preserve per-index\n * types, use {@link combineTuple}.\n *\n * @example\n * ```ts\n * combine([ok(1), ok(2)]); // Ok([1, 2])\n * combine([ok(1), err(\"e\")]); // Err(\"e\")\n * ```\n */\nexport const combine = <T, E>(results: readonly Result<T, E>[]): Result<T[], E> => {\n const values: T[] = [];\n for (const result of results) {\n if (isErr(result)) return err(result.error);\n values.push(result.value);\n }\n return ok(values);\n};\n\ntype CombineTuple<R extends readonly Result<unknown, unknown>[]> = Result<\n { [K in keyof R]: InferOk<R[K]> },\n { [K in keyof R]: InferErr<R[K]> }[number]\n>;\n\n/**\n * Heterogeneous tuple combine — like {@link combine} but preserves each\n * branch's `Ok` type by position, so the result destructures type-safely.\n * Short-circuits on the first `Err` in input order (neverthrow-style).\n *\n * @example\n * ```ts\n * const r = combineTuple([ok(1), ok(\"x\")] as const);\n * // Result<readonly [number, string], never>\n * if (isOk(r)) {\n * const [n, s] = r.value; // typed per position\n * }\n * ```\n */\nexport const combineTuple = <const R extends readonly Result<unknown, unknown>[]>(\n results: R,\n): CombineTuple<R> =>\n // Runtime identical to combine; the cast restores per-index tuple types.\n combine(results as readonly Result<unknown, unknown>[]) as CombineTuple<R>;\n\n/**\n * Accumulate independent validation failures. Returns `Ok<T[]>` only when\n * every input is `Ok`. Without a combiner, failures are collected into a\n * readonly array; with `combineErrors` they are folded into a single `E`.\n *\n * Unlike {@link combine}, this does **not** short-circuit on first failure —\n * use for independent checks where you want to report all problems at once.\n *\n * @example\n * ```ts\n * const checks: Result<string, string[]>[] = [ok(\"Ada\"), err([\"age required\"])];\n *\n * validateAll(checks);\n * // Result<string[], readonly string[][]>\n *\n * validateAll(checks, (left, right) => [...left, ...right]);\n * // Result<string[], string[]>\n * ```\n */\nexport function validateAll<T, E>(results: readonly Result<T, E>[]): Result<T[], readonly E[]>;\nexport function validateAll<T, E>(\n results: readonly Result<T, E>[],\n combineErrors: (left: E, right: E) => E,\n): Result<T[], E>;\nexport function validateAll<T, E>(\n results: readonly Result<T, E>[],\n combineErrors?: (left: E, right: E) => E,\n): Result<T[], E | readonly E[]> {\n const values: T[] = [];\n const errors: E[] = [];\n\n for (const result of results) {\n if (isErr(result)) {\n errors.push(result.error);\n } else {\n values.push(result.value);\n }\n }\n\n if (errors.length === 0) return ok(values);\n return err(combineErrors ? errors.reduce(combineErrors) : errors);\n}\n\n/**\n * Tuple-preserving variant of {@link validateAll}. Heterogeneous input tuple\n * → preserved `Ok` tuple shape. Without a combiner, the error union is\n * collected into a readonly array; with `combineErrors`, all inputs must\n * share the error type `E` and failures fold into a single `E`.\n *\n * @example\n * ```ts\n * const name: Result<string, string[]> = ok(\"Ada\");\n * const age: Result<number, string[]> = ok(36);\n *\n * validateTuple([name, age] as const);\n * // Result<readonly [string, number], readonly string[][]>\n *\n * validateTuple([name, age] as const, (l, r) => [...l, ...r]);\n * // Result<readonly [string, number], string[]>\n * ```\n */\nexport function validateTuple<const R extends readonly Result<unknown, unknown>[]>(\n results: R,\n): Result<{ [K in keyof R]: InferOk<R[K]> }, readonly InferErr<R[number]>[]>;\nexport function validateTuple<\n const R extends readonly Result<unknown, unknown>[],\n E = InferErr<R[number]>,\n>(\n results: R & readonly Result<unknown, E>[],\n combineErrors: (left: E, right: E) => E,\n): Result<{ [K in keyof R]: InferOk<R[K]> }, E>;\nexport function validateTuple(\n results: readonly Result<unknown, unknown>[],\n combineErrors?: (left: unknown, right: unknown) => unknown,\n): Result<readonly unknown[], unknown> {\n // Runtime identical to validateAll; the overloads restore per-index tuple types.\n return combineErrors ? validateAll(results, combineErrors) : validateAll(results);\n}\n","/**\n * Variadic point-free composition — chains up to nine unary fns left-to-right\n * into one reusable function. The first fn may take multiple arguments; the\n * rest are unary. Use {@link pipe} from `@onrails/result` when you already\n * have a starting value; use {@link flow} to define a reusable composed\n * function with no value yet.\n *\n * @example\n * ```ts\n * const parseUserName = flow(\n * (raw: string) => parseConfig(raw),\n * map((cfg) => cfg.user),\n * flatMap((u) => (u.name ? ok(u.name) : err({ kind: \"missing\" as const }))),\n * );\n *\n * parseUserName(raw); // Result<string, ParseError | { kind: \"missing\" }>\n * ```\n */\nexport function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;\nexport function flow<A extends readonly unknown[], B, C>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends readonly unknown[], B, C, D>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends readonly unknown[], B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends readonly unknown[], B, C, D, E, F>(\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): (...a: A) => F;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G>(\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): (...a: A) => G;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(\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): (...a: A) => H;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(\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): (...a: A) => I;\nexport function flow(\n first: (...args: unknown[]) => unknown,\n ...rest: ReadonlyArray<(x: unknown) => unknown>\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n let acc = first(...args);\n for (const fn of rest) {\n acc = fn(acc);\n }\n return acc;\n };\n}\n","import { err, isErr } from \"./result.js\";\nimport type { Result } from \"./types.js\";\n\n/** Internal control-flow signal — not part of public error types */\nclass ErrSignal<E> {\n readonly _tag = \"ErrSignal\" as const;\n constructor(readonly error: E) {}\n}\n\n/**\n * Unwraps a {@link Result} inside a {@link tryGen} block — the sync analogue of\n * Rust's `?` operator. On `Ok` it returns the value; on `Err` it short-circuits\n * the enclosing `tryGen`, which returns that `Err`. Only valid inside `tryGen`;\n * prefer {@link flatMap} / `pipe` for long pipelines.\n *\n * @returns the unwrapped `Ok` value\n *\n * @example\n * ```ts\n * const out = tryGen(() => {\n * const a = yieldResult(parseA()); // unwrap or short-circuit\n * const b = yieldResult(parseB());\n * return ok(a + b);\n * });\n * ```\n */\nexport const yieldResult = <T, E>(result: Result<T, E>): T => {\n if (isErr(result)) {\n throw new ErrSignal(result.error);\n }\n return result.value;\n};\n\n/**\n * Terse alias of {@link yieldResult} (mirrors Rust's `?`), for compact\n * {@link tryGen} blocks.\n *\n * @example\n * ```ts\n * const out = tryGen(() => {\n * const a = $(parseA());\n * const b = $(parseB());\n * return ok(a + b);\n * });\n * ```\n */\nexport const $ = yieldResult;\n\n/**\n * Run a block that uses {@link yieldResult}; returns the final `Result` or the first Err.\n *\n * @example\n * ```ts\n * const out = tryGen(() => {\n * const a = $(parseA());\n * const b = $(parseB());\n * return ok(a + b);\n * });\n * ```\n */\nexport const tryGen = <T, E>(fn: () => Result<T, E>): Result<T, E> => {\n try {\n return fn();\n } catch (error) {\n if (error instanceof ErrSignal) {\n return err(error.error);\n }\n throw error;\n }\n};\n"]}
1
+ {"version":3,"sources":["../src/internal/ctor.ts","../src/internal/dual.ts","../src/internal/to-error.ts","../src/result.ts","../src/types.ts","../src/async.ts","../src/async-lift.ts","../src/collections.ts","../src/pipe.ts","../src/try-gen.ts"],"names":[],"mappings":";AAUO,IAAM,IAAA,GAAO,CAAe,KAAA,MAA4B;AAAA,EAC7D,IAAA,EAAM,IAAA;AAAA,EACN;AACF,CAAA,CAAA;AAGO,IAAM,KAAA,GAAQ,CAAyB,KAAA,MAA4B;AAA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AI,SAAA,CAAU,MAAA,CAAO,KAAK,CAAA;AAAA,EAClC;AACA,EAAA,OAAO,MAAA,CAAO,KAAA;AAChB;AAeO,IAAM,CAAA,GAAI;AAcV,IAAM,MAAA,GAAS,CAAO,EAAA,KAAyC;AACpE,EAAA,IAAI;AACF,IAAA,OAAO,EAAA,EAAG;AAAA,EACZ,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,iBAAiB,SAAA,EAAW;AAC9B,MAAA,OAAO,KAAA,CAAM,MAAM,KAAK,CAAA;AAAA,IAC1B;AACA,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"index.js","sourcesContent":["import type { Result } from \"../types.js\";\n\n/**\n * Unlocked `Ok` constructor for library internals.\n *\n * The public {@link ok} takes a `const` type parameter so caller literals stay\n * narrow. That is wrong inside a generic transform, where the payload type is\n * an unresolved type parameter and the resulting `Locked<T>` would never reduce\n * back to `T`. Internals build results through this constructor instead.\n */\nexport const mkOk = <T, E = never>(value: T): Result<T, E> => ({\n _tag: \"Ok\",\n value,\n});\n\n/** Unlocked `Err` constructor for library internals. Mirror of {@link mkOk}. */\nexport const mkErr = <T = never, E = unknown>(error: E): Result<T, E> => ({\n _tag: \"Err\",\n error,\n});\n","/**\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","/** Normalizes an unknown thrown/rejected value into an `Error`. */\nexport const toError = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n","import { mkErr, mkOk } from \"./internal/ctor.js\";\nimport { dual } from \"./internal/dual.js\";\nimport type { Locked } from \"./internal/lock.js\";\nimport { toError } from \"./internal/to-error.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<42, never> — literal locked\n * const typed: Result<number, \"parse\"> = ok(1);\n * const lift = <T, E>(v: T): Result<T, E> => ok<T, E>(v); // explicit args opt out\n * ```\n *\n * @remarks\n * An inline literal keeps its narrow type instead of widening (`ok(\"a\")` is\n * `Result<\"a\", never>`, not `Result<string, never>`). Pass both type arguments\n * to opt out — generic code that must produce `Result<T, E>` for an unresolved\n * `T` needs that form.\n */\nexport function ok<const T>(value: T): Result<Locked<T>, never>;\nexport function ok<T, E>(value: T): Result<T, E>;\nexport function ok<T>(value: T): Result<T, never> {\n // Safe: `Locked<T>` only unwraps the readonly tuple that `const` inference\n // adds; the runtime payload is the value the caller passed, unchanged.\n return mkOk(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<42, 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, { readonly kind: \"parse\"; readonly message: string }>\n *\n * type AppError = { kind: \"parse\" } | { kind: \"io\" };\n * err<AppError>({ kind: \"io\" }); // Result<never, AppError> — one arg names the error\n * err<number, AppError>({ kind: \"io\" }); // Result<number, AppError> — neverthrow's T, E order\n * ```\n *\n * @remarks\n * One explicit type argument names the **error** channel, which is what the\n * call site almost always means. Both channels still take neverthrow's `T, E`\n * order, and that two-argument form is also the escape hatch for generic code:\n * inference-driven calls lock literals, so a generic `E` must be passed\n * explicitly to keep the error type from being rewritten.\n */\nexport function err<const E>(error: E): Result<never, Locked<E>>;\nexport function err<T, E>(error: E): Result<T, E>;\nexport function err<E>(error: E): Result<never, E> {\n // Safe: see the note on `ok` — `Locked` is a type-level unwrap only.\n return mkErr(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) ? mkOk(fn(result.value)) : mkErr(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) ? mkErr(fn(result.error)) : mkOk(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) ? mkOk(onOk(result.value)) : mkErr(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) : mkErr(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) : mkOk(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`. The\n * fallback may be a different type from `T` — the return widens to `T | U`,\n * matching `ResultAsync.unwrapOr` and the compat shim.\n *\n * @example\n * ```ts\n * unwrapOr(parsedSetting, \"default-value\"); // string\n * unwrapOr(parsedPort, null); // number | null\n * ```\n */\nexport const unwrapOr: {\n <T, E, U>(result: Result<T, E>, defaultValue: U): T | U;\n <U>(defaultValue: U): <T, E>(result: Result<T, E>) => T | U;\n} = dual(2, <T, E, U>(result: Result<T, E>, defaultValue: U): T | U =>\n 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`. Same name and shape as\n * neverthrow's `Result.fromThrowable`.\n *\n * Reach for {@link trySync} instead when you want to run the call right now\n * rather than build a reusable wrapper.\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 = fromThrowable(\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 fromThrowable<A extends readonly unknown[], T, E>(\n fn: (...args: A) => T,\n onThrow: (error: unknown) => E,\n): (...args: A) => Result<T, E>;\nexport function fromThrowable<F extends (...args: never) => unknown, E>(\n fn: F,\n onThrow: (error: unknown) => E,\n): (...args: Parameters<F>) => Result<ReturnType<F>, E>;\nexport function fromThrowable(\n fn: (...args: never) => unknown,\n onThrow: (error: unknown) => unknown,\n): (...args: never) => Result<unknown, unknown> {\n return (...args: never) => {\n try {\n return mkOk(fn(...args));\n } catch (error) {\n return mkErr(onThrow(error));\n }\n };\n}\n\n/**\n * Runs `fn` **now**, catching a throw into the `Err` track — the sync mirror\n * of `tryAsync`. Without `onThrow` the thrown value is normalized to an\n * `Error`; pass a mapper for a typed error.\n *\n * To lift a throwing function once and call it many times, use\n * {@link fromThrowable}.\n *\n * @param fn - the throwing thunk to run\n * @param onThrow - maps a thrown value to the `Err` channel\n *\n * @example\n * ```ts\n * trySync(() => JSON.parse(raw)); // Result<unknown, Error>\n * trySync(() => Schema.parse(input), (e): SchemaError => ({\n * kind: \"schema\",\n * cause: e,\n * }));\n * ```\n */\nexport function trySync<T>(fn: () => T): Result<T, Error>;\nexport function trySync<T, E>(fn: () => T, onThrow: (error: unknown) => E): Result<T, E>;\nexport function trySync<T, E>(fn: () => T, onThrow?: (error: unknown) => E): Result<T, E | Error> {\n try {\n return mkOk(fn());\n } catch (error) {\n return mkErr(onThrow ? onThrow(error) : toError(error));\n }\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 { mkErr, mkOk } from \"./internal/ctor.js\";\nimport type { InferErr, InferOk } from \"./internal/infer.js\";\nimport type { Locked } from \"./internal/lock.js\";\nimport { bimap, isErr, map, mapErr } from \"./result.js\";\nimport type { Result } from \"./types.js\";\nimport { UnexpectedError } from \"./types.js\";\n\ntype PromiseFactory<T, E> = () => Promise<Result<T, E>>;\ntype AnyResultAsync = ResultAsync<unknown, unknown>;\n\n/**\n * Mirrors the sync `CombineTuple` in `./collections.ts`: the element check\n * lives in the RETURN type, never in the parameter constraint. A\n * `ResultAsync<unknown, unknown>` constraint contextually types the arguments\n * and widens `okAsync(1)`'s defaulted `E = never` to `unknown`, so call sites\n * would need hoisted intermediates to keep their error union.\n */\ntype CombineTupleAsync<R extends readonly unknown[]> = R[number] extends AnyResultAsync\n ? ResultAsync<{ [K in keyof R]: InferOk<R[K]> }, InferErr<R[number]>>\n : never;\n\n/** Mirrors `TupleGuard` in `./collections.ts` — see the note there. */\ntype AsyncTupleGuard<R extends readonly unknown[]> = R[number] extends AnyResultAsync\n ? []\n : [error: \"expected an array of ResultAsync values\"];\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 mkErr(result.error);\n }\n values.push(result.value);\n }\n return mkOk(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`, `mapErr`,\n * `bimap`, `flatMap`, `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 mkOk(await promise);\n } catch (error) {\n return mkErr(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 () => mkOk(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<const T>(value: T): ResultAsync<Locked<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 () => mkOk(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<const T>(value: T): ResultAsync<Locked<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<T, E>(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<const E>(error: E): ResultAsync<never, Locked<E>>;\n static err<T, E>(error: E): ResultAsync<T, E>;\n static err<T = never, E = unknown>(error: E): ResultAsync<T, E> {\n return new ResultAsync(async () => mkErr(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 mkErr(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 mkErr(result.error);\n }\n values.push(result.value);\n }\n return mkOk(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()]);\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 unknown[]>(\n results: R,\n ..._guard: AsyncTupleGuard<R>\n ): CombineTupleAsync<R> {\n // Runtime identical to combine; the cast restores per-index tuple types.\n return ResultAsync.combine(\n results as readonly AnyResultAsync[],\n ) as unknown 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 * ]);\n * ```\n */\n static combineTupleParallel<const R extends readonly unknown[]>(\n results: R,\n ..._guard: AsyncTupleGuard<R>\n ): CombineTupleAsync<R> {\n // Cast restores per-index tuple types over the untyped sequence core.\n return new ResultAsync(async () =>\n sequenceSettled(\n await Promise.all((results as readonly AnyResultAsync[]).map((ra) => ra.resolve())),\n ),\n ) as unknown 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 * Transforms both tracks in one step — the async mirror of the sync\n * `bimap`. Exactly one of `onOk` / `onErr` runs.\n *\n * @example\n * ```ts\n * load(id).bimap(toDto, (e): AppError => ({ kind: \"load\", cause: e }));\n * ```\n */\n bimap<U, F>(onOk: (value: T) => U, onErr: (error: E) => F): ResultAsync<U, F> {\n return new ResultAsync(async () => bimap(await this.resolve(), onOk, onErr));\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","/**\n * @onrails/result — THE lift module. Every \"value → {@link ResultAsync}\"\n * entry point is defined exactly once, here: `okAsync`, `errAsync`,\n * `fromPromise`, `fromSafePromise`, `fromResult`, `fromAsync`, `asyncAfter`,\n * `tryAsync`.\n */\n\nimport { ResultAsync } from \"./async.js\";\nimport { dual } from \"./internal/dual.js\";\nimport type { InferErr, InferOk } from \"./internal/infer.js\";\nimport { toError } from \"./internal/to-error.js\";\nimport type { Result, UnexpectedError } from \"./types.js\";\n\n// The bare renames below detach statics from the class. Safe: every\n// `ResultAsync` static references the class by name (`new ResultAsync`,\n// `ResultAsync.combine`), never `this`.\n\n/**\n * Lifts a value into an `Ok` async result.\n *\n * @example\n * ```ts\n * const r = okAsync(42); // ResultAsync<42, never> — literal locked\n * ```\n */\nexport const okAsync = ResultAsync.ok;\n\n/**\n * Lifts a value into an `Err` async result.\n *\n * @example\n * ```ts\n * const r = errAsync({ kind: \"not_found\" as const });\n * ```\n */\nexport const errAsync = ResultAsync.err;\n\n/**\n * Wraps a `PromiseLike<T>` into a {@link ResultAsync}. Reject reasons go\n * through `onReject` to become typed `Err`s; success becomes `Ok<T>`.\n *\n * @example\n * ```ts\n * const body = fromPromise(\n * fetch(url).then((r) => r.text()),\n * (e): NetworkError => ({ kind: \"network\", cause: String(e) }),\n * );\n * ```\n */\nexport const fromPromise = ResultAsync.fromPromise;\n\n/**\n * Wraps a `PromiseLike<T>` that **never rejects** into {@link ResultAsync}.\n * Skips the `onReject` mapper. Use only when the promise is provably safe.\n */\nexport const fromSafePromise = ResultAsync.fromSafePromise;\n\n/**\n * Lifts an already-settled sync {@link Result} into a {@link ResultAsync}, so\n * it can be chained alongside async steps in a railway.\n *\n * @example\n * ```ts\n * const ra = fromResult(ok(1)); // ResultAsync<number, never>\n * await fromResult(err(error)).resolve(); // Err(error)\n * ```\n */\nexport const fromResult = ResultAsync.fromResult;\n\n/**\n * Bind a sync {@link Result} into an async step without widening defects.\n * Dual-form: data-first for one-shots, data-last (curried) for `pipe`/`flow`.\n *\n * @example\n * ```ts\n * asyncAfter(result, (u) => tryAsync(db.insert(u), toErr)); // data-first\n * asyncAfter((u) => tryAsync(db.insert(u), toErr)); // data-last\n * ```\n */\nexport const asyncAfter: {\n <T, U, E, F>(result: Result<T, E>, fn: (value: T) => ResultAsync<U, F>): ResultAsync<U, E | F>;\n <T, U, F>(\n fn: (value: T) => ResultAsync<U, F>,\n ): <E>(result: Result<T, E>) => ResultAsync<U, E | F>;\n} = dual(\n 2,\n <T, U, E, F>(result: Result<T, E>, fn: (value: T) => ResultAsync<U, F>): ResultAsync<U, E | F> =>\n fromResult(result).flatMap(fn),\n);\n\ntype AnyResult = Result<unknown, unknown>;\n\n/**\n * Lifts a `(...args) => Promise<Result<T, E>>` function (typical of interop or\n * boundary code) into one returning `(...args) => ResultAsync<T, E>`. Expected\n * `Err`s pass through; an unexpected promise rejection (a defect) is routed via\n * `onDefect`, defaulting to {@link UnexpectedError} and widening the error union.\n *\n * @param fn - a function returning a promise that already yields a `Result`\n * @param onDefect - maps an unexpected rejection to the `Err` channel\n *\n * @example\n * ```ts\n * const loadUser = fromAsync(\n * (id: string): Promise<Result<User, NotFound>> => api.getUser(id),\n * );\n * const ra = loadUser(\"u1\"); // ResultAsync<User, NotFound | UnexpectedError>\n * ```\n */\nexport const fromAsync =\n <A extends readonly unknown[], R extends AnyResult>(\n fn: (...args: A) => Promise<R>,\n onDefect?: (error: unknown) => InferErr<R> | UnexpectedError,\n ): ((...args: A) => ResultAsync<InferOk<R>, InferErr<R> | UnexpectedError>) =>\n (...args: A) =>\n ResultAsync.fromResultPromise(fn(...args), onDefect) as ResultAsync<\n InferOk<R>,\n InferErr<R> | UnexpectedError\n >;\n\n/**\n * Convenience wrapper over {@link fromPromise} with default `Error`\n * normalization. Call without `onReject` to get `ResultAsync<T, Error>`,\n * or pass a custom mapper for a typed error.\n *\n * @example\n * ```ts\n * // Default: rejection → Err(Error)\n * const a = tryAsync(db.users.insert(row));\n *\n * // Custom: typed error\n * const b = tryAsync(db.users.insert(row), (e): DbError => ({\n * kind: \"db\",\n * cause: e,\n * }));\n * ```\n */\nexport function tryAsync<T>(promise: PromiseLike<T>): ResultAsync<T, Error>;\nexport function tryAsync<T, E>(\n promise: PromiseLike<T>,\n onReject: (error: unknown) => E,\n): ResultAsync<T, E>;\nexport function tryAsync<T, E>(\n promise: PromiseLike<T>,\n onReject?: (error: unknown) => E,\n): ResultAsync<T, E | Error> {\n return onReject\n ? ResultAsync.fromPromise(promise, onReject)\n : ResultAsync.fromPromise(promise, toError);\n}\n","/**\n * @onrails/result — sync aggregation, one module, two axes:\n *\n * short-circuit (first `Err` wins) — {@link combine} / {@link combineTuple}\n * accumulate expected failures — {@link validateAll} / {@link validateTuple}\n *\n * The accumulate pair collects every failure into a readonly array by\n * default, or folds them with an explicit `combineErrors` when given one.\n */\n\nimport { mkErr, mkOk } from \"./internal/ctor.js\";\nimport type { InferErr, InferOk } from \"./internal/infer.js\";\nimport { isErr } from \"./result.js\";\nimport type { Result } from \"./types.js\";\n\n/**\n * Combines a homogeneous array of results into a single result holding an\n * array of the `Ok` values, in input order. Short-circuits on the first `Err`\n * (first failure wins). For heterogeneous tuples that preserve per-index\n * types, use {@link combineTuple}.\n *\n * @example\n * ```ts\n * combine([ok(1), ok(2)]); // Ok([1, 2])\n * combine([ok(1), err(\"e\")]); // Err(\"e\")\n * ```\n */\nexport const combine = <T, E>(results: readonly Result<T, E>[]): Result<T[], E> => {\n const values: T[] = [];\n for (const result of results) {\n if (isErr(result)) return mkErr(result.error);\n values.push(result.value);\n }\n return mkOk(values);\n};\n\ntype AnyResult = Result<unknown, unknown>;\n\n/** Positionally preserved `Ok` payloads for a tuple of results. */\ntype OkTuple<R extends readonly unknown[]> = { [K in keyof R]: InferOk<R[K]> };\n\n/**\n * The element check lives in the RETURN type, never in the parameter\n * constraint. A `readonly Result<unknown, unknown>[]` constraint contextually\n * types the arguments, which widens `ok(1)`'s defaulted `E = never` — and\n * `err(e)`'s `T = never` — all the way to `unknown`. Holding the parameter at\n * a bare `R` keeps both channels precise for inline literals, so call sites\n * need neither `as const` nor hoisted intermediates.\n */\ntype CombineTuple<R extends readonly unknown[]> = R[number] extends AnyResult\n ? Result<OkTuple<R>, InferErr<R[number]>>\n : never;\n\n/**\n * Restores the \"every element is a Result\" check the parameter constraint used\n * to provide. Resolves to `[]` for a well-formed tuple and to a one-element\n * tuple otherwise, so a bad call fails at the call site (with the message\n * visible in signature help) instead of silently yielding `never`.\n */\ntype TupleGuard<R extends readonly unknown[]> = R[number] extends AnyResult\n ? []\n : [error: \"expected an array of Result values\"];\n\n/**\n * Heterogeneous tuple combine — like {@link combine} but preserves each\n * branch's `Ok` type by position, so the result destructures type-safely.\n * Short-circuits on the first `Err` in input order (neverthrow-style).\n *\n * @example\n * ```ts\n * const r = combineTuple([ok(1), ok(\"x\")]);\n * // Result<readonly [number, string], never> — no `as const` needed\n * if (isOk(r)) {\n * const [n, s] = r.value; // typed per position\n * }\n * ```\n */\nexport const combineTuple = <const R extends readonly unknown[]>(\n results: R,\n ..._guard: TupleGuard<R>\n): CombineTuple<R> =>\n // Runtime identical to combine; the cast restores per-index tuple types.\n combine(results as readonly AnyResult[]) as CombineTuple<R>;\n\n/**\n * Accumulate independent validation failures. Returns `Ok<T[]>` only when\n * every input is `Ok`. Without a combiner, failures are collected into a\n * readonly array; with `combineErrors` they are folded into a single `E`.\n *\n * Unlike {@link combine}, this does **not** short-circuit on first failure —\n * use for independent checks where you want to report all problems at once.\n *\n * @example\n * ```ts\n * const checks: Result<string, string[]>[] = [ok(\"Ada\"), err([\"age required\"])];\n *\n * validateAll(checks);\n * // Result<string[], readonly string[][]>\n *\n * validateAll(checks, (left, right) => [...left, ...right]);\n * // Result<string[], string[]>\n * ```\n */\nexport function validateAll<T, E>(results: readonly Result<T, E>[]): Result<T[], readonly E[]>;\nexport function validateAll<T, E>(\n results: readonly Result<T, E>[],\n combineErrors: (left: E, right: E) => E,\n): Result<T[], E>;\nexport function validateAll<T, E>(\n results: readonly Result<T, E>[],\n combineErrors?: (left: E, right: E) => E,\n): Result<T[], E | readonly E[]> {\n const values: T[] = [];\n const errors: E[] = [];\n\n for (const result of results) {\n if (isErr(result)) {\n errors.push(result.error);\n } else {\n values.push(result.value);\n }\n }\n\n if (errors.length === 0) return mkOk(values);\n return mkErr(combineErrors ? errors.reduce(combineErrors) : errors);\n}\n\n/**\n * Tuple-preserving variant of {@link validateAll}. Heterogeneous input tuple\n * → preserved `Ok` tuple shape. Without a combiner, the error union is\n * collected into a readonly array; with `combineErrors`, all inputs must\n * share the error type `E` and failures fold into a single `E`.\n *\n * Like {@link combineTuple}, the element check lives in the return type, so\n * inline literals keep their precise error types without `as const`.\n *\n * @example\n * ```ts\n * const name: Result<string, string[]> = ok(\"Ada\");\n * const age: Result<number, string[]> = ok(36);\n *\n * validateTuple([name, age]);\n * // Result<readonly [string, number], readonly string[][]>\n *\n * validateTuple([name, age], (l, r) => [...l, ...r]);\n * // Result<readonly [string, number], string[]>\n * ```\n */\nexport function validateTuple<const R extends readonly unknown[]>(\n results: R,\n ..._guard: TupleGuard<R>\n): R[number] extends AnyResult ? Result<OkTuple<R>, readonly InferErr<R[number]>[]> : never;\nexport function validateTuple<const R extends readonly unknown[], E = InferErr<R[number]>>(\n results: R,\n combineErrors: (left: E, right: E) => E,\n ..._guard: TupleGuard<R>\n): R[number] extends AnyResult ? Result<OkTuple<R>, E> : never;\nexport function validateTuple(\n results: readonly AnyResult[],\n // Rest-typed so both overloads (whose trailing `TupleGuard` arity differs)\n // stay assignable to this implementation signature.\n ...rest: readonly unknown[]\n): Result<readonly unknown[], unknown> {\n const combineErrors = rest[0] as ((left: unknown, right: unknown) => unknown) | undefined;\n // Runtime identical to validateAll; the overloads restore per-index tuple types.\n return combineErrors ? validateAll(results, combineErrors) : validateAll(results);\n}\n","/**\n * `@onrails/result/pipe` — the two composition entry points.\n *\n * {@link pipe} threads a starting value left-to-right through unary steps.\n * {@link flow} composes the steps into a reusable function with no value yet;\n * its first step may take multiple arguments.\n *\n * Both are hand-written overload towers rather than one recursive variadic\n * signature. That is deliberate: a variadic `...fns: F` cannot give each step a\n * contextual type from the previous step's output, so lambda parameters degrade\n * to `unknown` (`map((cfg) => cfg.user)` stops inferring). The tower costs lines\n * and caps the chain length; the alternative costs inference everywhere.\n *\n * The cap is {@link MAX_STEPS} steps. Longer chains nest — `pipe(pipe(v, ...), ...)`\n * — or factor a segment into a named `flow`.\n */\n\n/** Documented step cap for {@link pipe} and {@link flow}. */\nexport type MAX_STEPS = 12;\n\n/**\n * Variadic value-first pipe — threads `value` through up to twelve unary fns,\n * left-to-right. Use {@link pipe} when you already have a starting value; use\n * {@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.user),\n * flatMap((u) => (u.name ? ok(u.name) : err({ kind: \"missing\" as const }))),\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<A, B, C, D, E, F, G, H, I, J>(\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 ij: (i: I) => J,\n): J;\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K>(\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 ij: (i: I) => J,\n jk: (j: J) => K,\n): K;\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(\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 ij: (i: I) => J,\n jk: (j: J) => K,\n kl: (k: K) => L,\n): L;\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(\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 ij: (i: I) => J,\n jk: (j: J) => K,\n kl: (k: K) => L,\n lm: (l: L) => M,\n): M;\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/**\n * Variadic point-free composition — chains up to twelve unary fns left-to-right\n * into one reusable function. The first fn may take multiple arguments; the\n * rest are unary. Use {@link pipe} from `@onrails/result` when you already\n * have a starting value; use {@link flow} to define a reusable composed\n * function with no value yet.\n *\n * @example\n * ```ts\n * const parseUserName = flow(\n * (raw: string) => parseConfig(raw),\n * map((cfg) => cfg.user),\n * flatMap((u) => (u.name ? ok(u.name) : err({ kind: \"missing\" as const }))),\n * );\n *\n * parseUserName(raw); // Result<string, ParseError | { kind: \"missing\" }>\n * ```\n */\nexport function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B;\nexport function flow<A extends readonly unknown[], B, C>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n): (...a: A) => C;\nexport function flow<A extends readonly unknown[], B, C, D>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n): (...a: A) => D;\nexport function flow<A extends readonly unknown[], B, C, D, E>(\n ab: (...a: A) => B,\n bc: (b: B) => C,\n cd: (c: C) => D,\n de: (d: D) => E,\n): (...a: A) => E;\nexport function flow<A extends readonly unknown[], B, C, D, E, F>(\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): (...a: A) => F;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G>(\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): (...a: A) => G;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(\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): (...a: A) => H;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(\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): (...a: A) => I;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J>(\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 ij: (i: I) => J,\n): (...a: A) => J;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J, K>(\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 ij: (i: I) => J,\n jk: (j: J) => K,\n): (...a: A) => K;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J, K, L>(\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 ij: (i: I) => J,\n jk: (j: J) => K,\n kl: (k: K) => L,\n): (...a: A) => L;\nexport function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J, K, L, M>(\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 ij: (i: I) => J,\n jk: (j: J) => K,\n kl: (k: K) => L,\n lm: (l: L) => M,\n): (...a: A) => M;\nexport function flow(\n first: (...args: unknown[]) => unknown,\n ...rest: ReadonlyArray<(x: unknown) => unknown>\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n let acc = first(...args);\n for (const fn of rest) {\n acc = fn(acc);\n }\n return acc;\n };\n}\n","import { mkErr } from \"./internal/ctor.js\";\nimport { isErr } from \"./result.js\";\nimport type { Result } from \"./types.js\";\n\n/** Internal control-flow signal — not part of public error types */\nclass ErrSignal<E> {\n readonly _tag = \"ErrSignal\" as const;\n constructor(readonly error: E) {}\n}\n\n/**\n * Unwraps a {@link Result} inside a {@link tryGen} block — the sync analogue of\n * Rust's `?` operator. On `Ok` it returns the value; on `Err` it short-circuits\n * the enclosing `tryGen`, which returns that `Err`. Only valid inside `tryGen`;\n * prefer {@link flatMap} / `pipe` for long pipelines.\n *\n * @returns the unwrapped `Ok` value\n *\n * @example\n * ```ts\n * const out = tryGen(() => {\n * const a = yieldResult(parseA()); // unwrap or short-circuit\n * const b = yieldResult(parseB());\n * return ok(a + b);\n * });\n * ```\n */\nexport const yieldResult = <T, E>(result: Result<T, E>): T => {\n if (isErr(result)) {\n throw new ErrSignal(result.error);\n }\n return result.value;\n};\n\n/**\n * Terse alias of {@link yieldResult} (mirrors Rust's `?`), for compact\n * {@link tryGen} blocks.\n *\n * @example\n * ```ts\n * const out = tryGen(() => {\n * const a = $(parseA());\n * const b = $(parseB());\n * return ok(a + b);\n * });\n * ```\n */\nexport const $ = yieldResult;\n\n/**\n * Run a block that uses {@link yieldResult}; returns the final `Result` or the first Err.\n *\n * @example\n * ```ts\n * const out = tryGen(() => {\n * const a = $(parseA());\n * const b = $(parseB());\n * return ok(a + b);\n * });\n * ```\n */\nexport const tryGen = <T, E>(fn: () => Result<T, E>): Result<T, E> => {\n try {\n return fn();\n } catch (error) {\n if (error instanceof ErrSignal) {\n return mkErr(error.error);\n }\n throw error;\n }\n};\n"]}
@@ -0,0 +1,12 @@
1
+ import type { Result } from "../types.js";
2
+ /**
3
+ * Unlocked `Ok` constructor for library internals.
4
+ *
5
+ * The public {@link ok} takes a `const` type parameter so caller literals stay
6
+ * narrow. That is wrong inside a generic transform, where the payload type is
7
+ * an unresolved type parameter and the resulting `Locked<T>` would never reduce
8
+ * back to `T`. Internals build results through this constructor instead.
9
+ */
10
+ export declare const mkOk: <T, E = never>(value: T) => Result<T, E>;
11
+ /** Unlocked `Err` constructor for library internals. Mirror of {@link mkOk}. */
12
+ export declare const mkErr: <T = never, E = unknown>(error: E) => Result<T, E>;