@onrails/result 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/DESIGN.md +11 -18
  2. package/README.md +14 -59
  3. package/RECIPES.md +12 -25
  4. package/dist/{async-1fIhfzFu.d.ts → async-Ci6WSL5-.d.ts} +60 -18
  5. package/dist/{async-u8U5P2EH.d.cts → async-DcXR7k9K.d.cts} +60 -18
  6. package/dist/compat/neverthrow.cjs +42 -51
  7. package/dist/compat/neverthrow.cjs.map +1 -1
  8. package/dist/compat/neverthrow.d.cts +3 -3
  9. package/dist/compat/neverthrow.d.ts +3 -3
  10. package/dist/compat/neverthrow.js +42 -51
  11. package/dist/compat/neverthrow.js.map +1 -1
  12. package/dist/extra.cjs +1 -1
  13. package/dist/extra.cjs.map +1 -1
  14. package/dist/extra.d.cts +5 -11
  15. package/dist/extra.d.ts +5 -11
  16. package/dist/extra.js +1 -1
  17. package/dist/extra.js.map +1 -1
  18. package/dist/fluent.cjs +66 -28
  19. package/dist/fluent.cjs.map +1 -1
  20. package/dist/fluent.d.cts +41 -6
  21. package/dist/fluent.d.ts +41 -6
  22. package/dist/fluent.js +66 -28
  23. package/dist/fluent.js.map +1 -1
  24. package/dist/index.cjs +95 -95
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +168 -44
  27. package/dist/index.d.ts +168 -44
  28. package/dist/index.js +90 -95
  29. package/dist/index.js.map +1 -1
  30. package/dist/railway.cjs +101 -172
  31. package/dist/railway.cjs.map +1 -1
  32. package/dist/railway.d.cts +25 -179
  33. package/dist/railway.d.ts +25 -179
  34. package/dist/railway.js +102 -162
  35. package/dist/railway.js.map +1 -1
  36. package/dist/try-gen.cjs +1 -1
  37. package/dist/try-gen.cjs.map +1 -1
  38. package/dist/try-gen.js +1 -1
  39. package/dist/try-gen.js.map +1 -1
  40. package/package.json +1 -16
  41. package/skills/railway-do-notation/SKILL.md +29 -68
  42. package/skills/result-composition/SKILL.md +2 -4
  43. package/dist/$.cjs +0 -40
  44. package/dist/$.cjs.map +0 -1
  45. package/dist/$.js +0 -36
  46. package/dist/$.js.map +0 -1
  47. package/dist/_.d.cts +0 -2
  48. package/dist/_.d.ts +0 -2
  49. package/dist/interop.cjs +0 -433
  50. package/dist/interop.cjs.map +0 -1
  51. package/dist/interop.d.cts +0 -75
  52. package/dist/interop.d.ts +0 -75
  53. package/dist/interop.js +0 -429
  54. package/dist/interop.js.map +0 -1
  55. package/dist/validation.cjs +0 -53
  56. package/dist/validation.cjs.map +0 -1
  57. package/dist/validation.d.cts +0 -72
  58. package/dist/validation.d.ts +0 -72
  59. package/dist/validation.js +0 -48
  60. package/dist/validation.js.map +0 -1
package/dist/railway.cjs CHANGED
@@ -1,5 +1,12 @@
1
1
  'use strict';
2
2
 
3
+ // src/internal/dual.ts
4
+ var dual = (arity, body) => {
5
+ const run = body;
6
+ const dispatcher = (...args) => args.length >= arity ? run(...args) : (self) => run(self, ...args);
7
+ return dispatcher;
8
+ };
9
+
3
10
  // src/result.ts
4
11
  var ok = (value) => ({
5
12
  _tag: "Ok",
@@ -11,18 +18,18 @@ var err = (error) => ({
11
18
  });
12
19
  var isOk = (result) => result._tag === "Ok";
13
20
  var isErr = (result) => result._tag === "Err";
14
- var mapImpl = (result, fn) => isOk(result) ? ok(fn(result.value)) : err(result.error);
15
- function map(...args) {
16
- if (args.length === 2) return mapImpl(args[0], args[1]);
17
- const fn = args[0];
18
- return (result) => mapImpl(result, fn);
19
- }
20
- var mapErrImpl = (result, fn) => isErr(result) ? err(fn(result.error)) : ok(result.value);
21
- function mapErr(...args) {
22
- if (args.length === 2) return mapErrImpl(args[0], args[1]);
23
- const fn = args[0];
24
- return (result) => mapErrImpl(result, fn);
25
- }
21
+ var map = dual(
22
+ 2,
23
+ (result, fn) => isOk(result) ? ok(fn(result.value)) : err(result.error)
24
+ );
25
+ var mapErr = dual(
26
+ 2,
27
+ (result, fn) => isErr(result) ? err(fn(result.error)) : ok(result.value)
28
+ );
29
+ var flatMap = dual(
30
+ 2,
31
+ (result, fn) => isOk(result) ? fn(result.value) : err(result.error)
32
+ );
26
33
  function trySync(fn, onThrow) {
27
34
  return (...args) => {
28
35
  try {
@@ -44,17 +51,6 @@ var UnexpectedError = class extends Error {
44
51
  };
45
52
 
46
53
  // src/async.ts
47
- var liftPromiseResult = async (promise, onDefect) => {
48
- try {
49
- const result = await promise;
50
- if (isErr(result)) {
51
- return result;
52
- }
53
- return isResultLike(result.value) ? result.value : result;
54
- } catch (error) {
55
- return err(onDefect(error));
56
- }
57
- };
58
54
  var sequenceSettled = (settled) => {
59
55
  const values = [];
60
56
  for (const result of settled) {
@@ -136,6 +132,9 @@ var ResultAsync = class _ResultAsync {
136
132
  static ok(value) {
137
133
  return new _ResultAsync(async () => ok(value));
138
134
  }
135
+ static of(value) {
136
+ return _ResultAsync.ok(value);
137
+ }
139
138
  /**
140
139
  * Lifts an error into an `Err` async result.
141
140
  *
@@ -149,16 +148,23 @@ var ResultAsync = class _ResultAsync {
149
148
  }
150
149
  /**
151
150
  * Lifts an existing `Promise<Result<T, E>>` (e.g. from interop code) into a
152
- * {@link ResultAsync}, auto-flattening one level of double-wrapping. A thrown
153
- * defect is routed through `onDefect`, defaulting to {@link UnexpectedError}.
151
+ * {@link ResultAsync}. A thrown defect is routed through `onDefect`,
152
+ * defaulting to {@link UnexpectedError}. The `Ok` value passes through
153
+ * verbatim — even when it happens to be Result-shaped.
154
154
  *
155
155
  * @param promise - a promise that already yields a `Result`
156
156
  * @param onDefect - maps an unexpected throw to the `Err` channel
157
- * @see {@link fromAsync} from `@onrails/result/interop`
157
+ * @see {@link fromAsync} from `@onrails/result`
158
158
  */
159
159
  static fromResultPromise(promise, onDefect) {
160
160
  const mapDefect = onDefect ?? ((error) => new UnexpectedError("Unexpected async defect", error));
161
- return new _ResultAsync(() => liftPromiseResult(promise, mapDefect));
161
+ return new _ResultAsync(async () => {
162
+ try {
163
+ return await promise;
164
+ } catch (error) {
165
+ return err(mapDefect(error));
166
+ }
167
+ });
162
168
  }
163
169
  /**
164
170
  * Combines a homogeneous array of async results into one. Resolves
@@ -242,7 +248,7 @@ var ResultAsync = class _ResultAsync {
242
248
  *
243
249
  * @example
244
250
  * ```ts
245
- * load(id).mapErr((e): AppError => ({ kind: "load", cause: e }));
251
+ * load(id).mapErr((e): AppError => ({ kind: "load", cause: e })); // ResultAsync<T, AppError>
246
252
  * ```
247
253
  */
248
254
  mapErr(fn) {
@@ -266,18 +272,12 @@ var ResultAsync = class _ResultAsync {
266
272
  return first;
267
273
  }
268
274
  const next = fn(first.value);
269
- if (next instanceof _ResultAsync) {
270
- return next.resolve();
271
- }
272
- if (isResultLike(next)) {
273
- return next;
274
- }
275
- return isCompatLike(next) ? next.inner : next;
275
+ return next instanceof _ResultAsync ? next.resolve() : next;
276
276
  });
277
277
  }
278
278
  /**
279
279
  * neverthrow-compat alias of {@link flatMap}. Kept as the documented compat
280
- * tier; prefer `flatMap` in new code.
280
+ * tier; prefer {@link flatMap} in new code.
281
281
  *
282
282
  * @example
283
283
  * ```ts
@@ -294,7 +294,7 @@ var ResultAsync = class _ResultAsync {
294
294
  *
295
295
  * @example
296
296
  * ```ts
297
- * loadFromCache(id).recover(() => loadFromOrigin(id));
297
+ * loadFromCache(id).recover(() => loadFromOrigin(id)); // ResultAsync<T, F>
298
298
  * ```
299
299
  */
300
300
  recover(fn) {
@@ -309,7 +309,7 @@ var ResultAsync = class _ResultAsync {
309
309
  }
310
310
  /**
311
311
  * neverthrow-compat alias of {@link recover}. Kept as the documented compat
312
- * tier; prefer `recover` in new code.
312
+ * tier; prefer {@link recover} in new code.
313
313
  *
314
314
  * @example
315
315
  * ```ts
@@ -417,16 +417,9 @@ var ResultAsync = class _ResultAsync {
417
417
  );
418
418
  }
419
419
  };
420
- function isResultLike(v) {
421
- return typeof v === "object" && v !== null && "_tag" in v && (v._tag === "Ok" || v._tag === "Err");
422
- }
423
- function isCompatLike(v) {
424
- return typeof v === "object" && v !== null && "inner" in v && isResultLike(v.inner);
425
- }
426
420
 
427
- // src/railway-core.ts
421
+ // src/railway.ts
428
422
  var addField = (ctx, key, value) => ({ ...ctx, [key]: value });
429
- var liftResult = (result) => ResultAsync.fromResult(result);
430
423
  var Railway = class _Railway {
431
424
  constructor(state) {
432
425
  this.state = state;
@@ -440,10 +433,7 @@ var Railway = class _Railway {
440
433
  static context(context) {
441
434
  return new _Railway({ mode: "sync", result: ok(context) });
442
435
  }
443
- /**
444
- * Start a sync workflow with a throwing function — `onThrow` maps any
445
- * exception to a typed error.
446
- */
436
+ /** Start a sync workflow with a throwing function. */
447
437
  static fromSync(key, fn, onThrow) {
448
438
  return _Railway.empty().fromSync(key, fn, onThrow);
449
439
  }
@@ -460,164 +450,103 @@ var Railway = class _Railway {
460
450
  return _Railway.empty().fromAsync(key, fn);
461
451
  }
462
452
  /**
463
- * Pure sync derivation — `fn` must not throw. Use {@link fromSync} for
464
- * throwing transforms.
453
+ * Rebuild the workflow in its current mode after transforming the carried
454
+ * result. Single re-link point for the state/phantom invariant: the mode
455
+ * tag is preserved verbatim, so `M` still describes the new state — TS
456
+ * cannot narrow the phantom `M` from the runtime tag, hence the cast.
465
457
  */
466
- derive(key, fn) {
467
- return this.fromResult(key, (ctx) => ok(fn(ctx)));
458
+ step(onSync, onAsync) {
459
+ const next = this.state.mode === "sync" ? { mode: "sync", result: onSync(this.state.result) } : { mode: "async", result: onAsync(this.state.result) };
460
+ return new _Railway(next);
468
461
  }
469
462
  /**
470
- * Throwing sync transform. Adds `{ [key]: T }` to context; converts any
471
- * exception to `Err<F>` via `onThrow`.
463
+ * Project the carried result into the mode-aware output type. Counterpart
464
+ * of {@link Railway.step} for terminal steps: the runtime branch matches
465
+ * the branch `RailwayOutput` picks for `M` (state/phantom invariant), but
466
+ * TS cannot resolve the conditional on an unresolved `M`, hence the cast.
472
467
  */
468
+ out(onSync, onAsync) {
469
+ return this.state.mode === "sync" ? onSync(this.state.result) : onAsync(this.state.result);
470
+ }
471
+ /** Lift the carried result into `ResultAsync` for async-upgrading steps. */
472
+ toAsync() {
473
+ return this.state.mode === "sync" ? ResultAsync.fromResult(this.state.result) : this.state.result;
474
+ }
475
+ /** Pure sync derivation. */
476
+ derive(key, fn) {
477
+ return this.fromResult(key, (ctx) => ok(fn(ctx)));
478
+ }
479
+ /** Throwing sync transform. */
473
480
  fromSync(key, fn, onThrow) {
474
481
  return this.fromResult(key, (ctx) => trySync(fn, onThrow)(ctx));
475
482
  }
476
- /**
477
- * Sync `Result`-returning step. Adds `{ [key]: T }` to context on `Ok`;
478
- * short-circuits the workflow on `Err`. Error union widens to `E | F`.
479
- */
483
+ /** Sync `Result`-returning step. */
480
484
  fromResult(key, fn) {
481
- if (this.state.mode === "sync") {
482
- const current = this.state.result;
483
- if (isErr(current)) {
484
- return new _Railway({ mode: "sync", result: err(current.error) });
485
- }
486
- const next = fn(current.value);
487
- return isErr(next) ? new _Railway({ mode: "sync", result: err(next.error) }) : new _Railway({
488
- mode: "sync",
489
- result: ok(addField(current.value, key, next.value))
490
- });
491
- }
492
- return new _Railway({
493
- mode: "async",
494
- result: this.state.result.flatMap(
485
+ return this.step(
486
+ (result) => flatMap(result, (ctx) => map(fn(ctx), (value) => addField(ctx, key, value))),
487
+ (result) => result.flatMap(
495
488
  (ctx) => ResultAsync.fromResult(fn(ctx)).map((value) => addField(ctx, key, value))
496
489
  )
497
- });
490
+ );
498
491
  }
499
- /**
500
- * Promise-returning step — upgrades the workflow to async mode. Reject
501
- * reasons go through `onReject` to become typed `Err<F>`.
502
- */
492
+ /** Promise-returning step — upgrades the workflow to async mode. */
503
493
  fromPromise(key, fn, onReject) {
504
494
  return this.fromAsync(key, (ctx) => ResultAsync.fromPromise(fn(ctx), onReject));
505
495
  }
506
- /**
507
- * `ResultAsync`-returning step — upgrades the workflow to async mode.
508
- * Already-typed error: no mapper needed.
509
- */
496
+ /** `ResultAsync`-returning step — upgrades the workflow to async mode. */
510
497
  fromAsync(key, fn) {
511
- const current = this.state.mode === "sync" ? liftResult(this.state.result) : this.state.result;
512
498
  return new _Railway({
513
499
  mode: "async",
514
- result: current.flatMap((ctx) => fn(ctx).map((value) => addField(ctx, key, value)))
500
+ result: this.toAsync().flatMap((ctx) => fn(ctx).map((value) => addField(ctx, key, value)))
515
501
  });
516
502
  }
517
- /**
518
- * Narrow a nullable context field into a required non-null field. If the
519
- * source field is `null` / `undefined`, the workflow short-circuits with
520
- * `onMissing(ctx)`.
521
- *
522
- * @example
523
- * ```ts
524
- * .fromPromise("row", ({ id }) => db.users.findFirst({ where: eq(users.id, id) }))
525
- * .require("user", "row", ({ id }) => ({ kind: "not_found" as const, id }))
526
- * // user is now User (non-null), not User | null
527
- * ```
528
- */
503
+ /** Narrow a nullable context field into a required non-null field. */
529
504
  require(key, source, onMissing) {
530
505
  return this.fromResult(key, (ctx) => {
531
506
  const value = ctx[source];
532
507
  return value == null ? err(onMissing(ctx)) : ok(value);
533
508
  });
534
509
  }
535
- /**
536
- * Run independent `ResultAsync` branches concurrently and merge their
537
- * named outputs back into context. Upgrades the workflow to async mode.
538
- * On multiple failures, the first `Err` in record-iteration order wins.
539
- *
540
- * @example
541
- * ```ts
542
- * .parallel({
543
- * recent: ({ userId }) => loadRecent(userId),
544
- * metrics: ({ userId }) => loadMetrics(userId),
545
- * })
546
- * // ctx now has { ..., recent, metrics }
547
- * ```
548
- */
510
+ /** Run independent `ResultAsync` branches concurrently and merge outputs. */
549
511
  parallel(branches) {
550
- const current = this.state.mode === "sync" ? liftResult(this.state.result) : this.state.result;
512
+ const merged = this.toAsync().flatMap(
513
+ (ctx) => ResultAsync.combineTupleParallel(
514
+ Object.entries(branches).map(([, branch]) => branch(ctx))
515
+ ).map(
516
+ (values) => (
517
+ // Branch outputs land under exactly R's keys; Object.fromEntries
518
+ // erases that correspondence, so reassert the merged shape.
519
+ {
520
+ ...ctx,
521
+ ...Object.fromEntries(Object.keys(branches).map((key, index) => [key, values[index]]))
522
+ }
523
+ )
524
+ )
525
+ );
551
526
  return new _Railway({
552
527
  mode: "async",
553
- result: current.flatMap(
554
- (ctx) => ResultAsync.combineTupleParallel(
555
- Object.entries(branches).map(([, branch]) => branch(ctx))
556
- ).map((values) => {
557
- const next = { ...ctx };
558
- Object.keys(branches).forEach((key, index) => {
559
- next[key] = values[index];
560
- });
561
- return next;
562
- })
563
- )
528
+ // BranchFn erases per-key types to `ResultAsync<unknown, unknown>`
529
+ // (ParallelOutput/ParallelError recover them from R), so re-assert the
530
+ // precise value/error union the branches actually produce.
531
+ result: merged
564
532
  });
565
533
  }
566
- /**
567
- * Project the final context into the workflow's output type. Hides the
568
- * internal context shape from callers.
569
- */
534
+ /** Project the final context into the workflow's output type. */
570
535
  select(fn) {
571
- if (this.state.mode === "sync") {
572
- const current = this.state.result;
573
- return isErr(current) ? err(current.error) : ok(fn(current.value));
574
- }
575
- return this.state.result.map(fn);
536
+ return this.out(
537
+ (result) => map(result, fn),
538
+ (result) => result.map(fn)
539
+ );
576
540
  }
577
- /**
578
- * Return the accumulated context as-is. Use when downstream code needs
579
- * every named field; prefer {@link select} when you can project to a DTO.
580
- */
541
+ /** Return the accumulated context as-is. */
581
542
  done() {
582
- return this.state.result;
543
+ return this.out(
544
+ (result) => result,
545
+ (result) => result
546
+ );
583
547
  }
584
548
  };
585
549
 
586
- // src/railway-steps.ts
587
- var parseWithParser = (parser, input) => typeof parser === "function" ? parser(input) : parser.parse(input);
588
- function railway(input, ...steps) {
589
- return steps.reduce(
590
- (current, step) => step(current),
591
- Railway.context({ input })
592
- );
593
- }
594
- var parseWith = (parser, onThrow) => ({
595
- as: (key) => (workflow) => workflow.fromSync(key, ({ input }) => parseWithParser(parser, input), onThrow)
596
- });
597
- var parseNamed = (key, parser, onThrow) => (workflow) => workflow.fromSync(key, ({ input }) => parseWithParser(parser, input), onThrow);
598
- var fromSyncNamed = (key, fn, onThrow) => (workflow) => workflow.fromSync(key, fn, onThrow);
599
- var fromResultNamed = (key, fn) => (workflow) => workflow.fromResult(key, fn);
600
- var fromPromiseNamed = (key, fn, onReject) => (workflow) => workflow.fromPromise(key, fn, onReject);
601
- var fromAsyncNamed = (key, fn) => (workflow) => workflow.fromAsync(key, fn);
602
- var deriveNamed = (key, fn) => (workflow) => workflow.derive(key, fn);
603
- var requireNamed = (key, source, onMissing) => (workflow) => workflow.require(key, source, onMissing);
604
- var parallelNamed = (branches) => (workflow) => {
605
- const typedBranches = branches;
606
- return workflow.parallel(typedBranches);
607
- };
608
- var select = (fn) => (workflow) => workflow.select(fn);
609
-
610
550
  exports.Railway = Railway;
611
- exports.deriveNamed = deriveNamed;
612
- exports.fromAsyncNamed = fromAsyncNamed;
613
- exports.fromPromiseNamed = fromPromiseNamed;
614
- exports.fromResultNamed = fromResultNamed;
615
- exports.fromSyncNamed = fromSyncNamed;
616
- exports.parallelNamed = parallelNamed;
617
- exports.parseNamed = parseNamed;
618
- exports.parseWith = parseWith;
619
- exports.railway = railway;
620
- exports.requireNamed = requireNamed;
621
- exports.select = select;
622
551
  //# sourceMappingURL=railway.cjs.map
623
552
  //# sourceMappingURL=railway.cjs.map