@carbonteq/fp 0.8.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +718 -95
- package/dist/errors.cjs +20 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +10 -0
- package/dist/errors.d.cts.map +1 -0
- package/dist/errors.d.mts +10 -0
- package/dist/errors.d.mts.map +1 -0
- package/dist/errors.mjs +17 -0
- package/dist/errors.mjs.map +1 -0
- package/dist/flow-experimental.cjs +286 -0
- package/dist/flow-experimental.cjs.map +1 -0
- package/dist/flow-experimental.d.cts +69 -0
- package/dist/flow-experimental.d.cts.map +1 -0
- package/dist/flow-experimental.d.mts +69 -0
- package/dist/flow-experimental.d.mts.map +1 -0
- package/dist/flow-experimental.mjs +284 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +296 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +79 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +79 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +294 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +28 -7
- package/dist/index.d.cts +11 -5
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +12 -0
- package/dist/match.cjs +294 -3
- package/dist/match.cjs.map +1 -0
- package/dist/match.d.cts +481 -5
- package/dist/match.d.cts.map +1 -0
- package/dist/match.d.mts +481 -0
- package/dist/match.d.mts.map +1 -0
- package/dist/match.mjs +287 -0
- package/dist/match.mjs.map +1 -0
- package/dist/option-experimental.cjs +1503 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1383 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1383 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1501 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +806 -4
- package/dist/option.cjs.map +1 -0
- package/dist/option.d.cts +580 -3
- package/dist/option.d.cts.map +1 -0
- package/dist/option.d.mts +580 -0
- package/dist/option.d.mts.map +1 -0
- package/dist/option.mjs +805 -0
- package/dist/option.mjs.map +1 -0
- package/dist/result-experimental.cjs +1266 -0
- package/dist/result-experimental.cjs.map +1 -0
- package/dist/result-experimental.d.cts +1127 -0
- package/dist/result-experimental.d.cts.map +1 -0
- package/dist/result-experimental.d.mts +1127 -0
- package/dist/result-experimental.d.mts.map +1 -0
- package/dist/result-experimental.mjs +1265 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +1077 -5
- package/dist/result.cjs.map +1 -0
- package/dist/result.d.cts +833 -3
- package/dist/result.d.cts.map +1 -0
- package/dist/result.d.mts +833 -0
- package/dist/result.d.mts.map +1 -0
- package/dist/result.mjs +1077 -0
- package/dist/result.mjs.map +1 -0
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -2
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +15 -0
- package/dist/tuple.d.mts.map +1 -0
- package/dist/{tuple.js → tuple.mjs} +3 -1
- package/dist/tuple.mjs.map +1 -0
- package/dist/unit.cjs +8 -2
- package/dist/unit.cjs.map +1 -0
- package/dist/unit.d.cts +8 -2
- package/dist/unit.d.cts.map +1 -0
- package/dist/unit.d.mts +8 -0
- package/dist/unit.d.mts.map +1 -0
- package/dist/unit.mjs +7 -0
- package/dist/unit.mjs.map +1 -0
- package/dist/utils.cjs +24 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +14 -0
- package/dist/utils.d.cts.map +1 -0
- package/dist/utils.d.mts +14 -0
- package/dist/utils.d.mts.map +1 -0
- package/dist/utils.mjs +20 -0
- package/dist/utils.mjs.map +1 -0
- package/examples/README.md +46 -0
- package/examples/flow/01-basics.ts +74 -0
- package/examples/flow/02-async.ts +73 -0
- package/examples/flow/03-recovery.ts +60 -0
- package/examples/flow/04-complex-backend.ts +237 -0
- package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
- package/examples/flow/index.ts +13 -0
- package/examples/flow-experimental/01-basics.ts +78 -0
- package/examples/flow-experimental/02-async.ts +77 -0
- package/examples/flow-experimental/03-recovery.ts +93 -0
- package/examples/flow-experimental/04-complex-backend.ts +241 -0
- package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
- package/examples/flow-experimental/index.ts +14 -0
- package/examples/match/01-stable-match.ts +147 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +150 -0
- package/examples/match-experimental/index.ts +18 -0
- package/examples/option/01-basics.ts +16 -0
- package/examples/option/02-map-flatMap.ts +36 -0
- package/examples/option/03-zip-flatZip.ts +23 -0
- package/examples/option/04-constructors.ts +21 -0
- package/examples/option/05-transform.ts +15 -0
- package/examples/option/06-aggregation.ts +14 -0
- package/examples/option/index.ts +49 -0
- package/examples/option-experimental/01-map.ts +109 -0
- package/examples/option-experimental/02-flatMap.ts +234 -0
- package/examples/option-experimental/03-zip.ts +197 -0
- package/examples/option-experimental/04-flatZip.ts +251 -0
- package/examples/option-experimental/05-gen.ts +360 -0
- package/examples/option-experimental/06-genAdapter.ts +463 -0
- package/examples/option-experimental/07-asyncGen.ts +353 -0
- package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
- package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
- package/examples/option-experimental/10-workflow-async.ts +378 -0
- package/examples/option-experimental/index.ts +341 -0
- package/examples/option-experimental/shared-domain.ts +325 -0
- package/examples/result/01-basics.ts +16 -0
- package/examples/result/02-map-flatMap.ts +34 -0
- package/examples/result/03-zip-flatZip.ts +23 -0
- package/examples/result/04-validation.ts +44 -0
- package/examples/result/05-constructors.ts +30 -0
- package/examples/result/06-utilities.ts +36 -0
- package/examples/result/index.ts +53 -0
- package/examples/result-experimental/01-map.ts +60 -0
- package/examples/result-experimental/02-flatMap.ts +169 -0
- package/examples/result-experimental/03-zip.ts +145 -0
- package/examples/result-experimental/04-flatZip.ts +252 -0
- package/examples/result-experimental/05-gen.ts +293 -0
- package/examples/result-experimental/06-genAdapter.ts +396 -0
- package/examples/result-experimental/07-asyncGen.ts +379 -0
- package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
- package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
- package/examples/result-experimental/10-workflow-async.ts +356 -0
- package/examples/result-experimental/index.ts +312 -0
- package/examples/result-experimental/shared-domain.ts +263 -0
- package/package.json +120 -48
- package/dist/chunk-CUT6urMc.cjs +0 -30
- package/dist/index.d.ts +0 -5
- package/dist/index.js +0 -6
- package/dist/match-BQP0RNSk.js +0 -13
- package/dist/match-BQP0RNSk.js.map +0 -1
- package/dist/match-COIWq-e8.d.cts +0 -18
- package/dist/match-COIWq-e8.d.cts.map +0 -1
- package/dist/match-DXKW7ym5.d.ts +0 -18
- package/dist/match-DXKW7ym5.d.ts.map +0 -1
- package/dist/match-DyAuOeqx.cjs +0 -25
- package/dist/match-DyAuOeqx.cjs.map +0 -1
- package/dist/match.d.ts +0 -5
- package/dist/match.js +0 -3
- package/dist/option-8_eiz02z.d.cts +0 -45
- package/dist/option-8_eiz02z.d.cts.map +0 -1
- package/dist/option-Be_DXVE6.js +0 -181
- package/dist/option-Be_DXVE6.js.map +0 -1
- package/dist/option-CoelyMEg.d.ts +0 -45
- package/dist/option-CoelyMEg.d.ts.map +0 -1
- package/dist/option-DHCdfOco.cjs +0 -193
- package/dist/option-DHCdfOco.cjs.map +0 -1
- package/dist/option.d.ts +0 -3
- package/dist/option.js +0 -4
- package/dist/result-CdGWA5IL.js +0 -318
- package/dist/result-CdGWA5IL.js.map +0 -1
- package/dist/result-DsVjSFnO.d.ts +0 -132
- package/dist/result-DsVjSFnO.d.ts.map +0 -1
- package/dist/result-Dy_C5dC6.d.cts +0 -132
- package/dist/result-Dy_C5dC6.d.cts.map +0 -1
- package/dist/result-nuhyCRyu.cjs +0 -336
- package/dist/result-nuhyCRyu.cjs.map +0 -1
- package/dist/result.d.ts +0 -3
- package/dist/result.js +0 -4
- package/dist/tuple.d.ts +0 -12
- package/dist/tuple.d.ts.map +0 -1
- package/dist/tuple.js.map +0 -1
- package/dist/unit-CnjFzJN1.cjs +0 -12
- package/dist/unit-CnjFzJN1.cjs.map +0 -1
- package/dist/unit-CoBLIJFc.d.ts +0 -9
- package/dist/unit-CoBLIJFc.d.ts.map +0 -1
- package/dist/unit-D0y_qAUW.d.cts +0 -9
- package/dist/unit-D0y_qAUW.d.cts.map +0 -1
- package/dist/unit-udy5j53P.js +0 -6
- package/dist/unit-udy5j53P.js.map +0 -1
- package/dist/unit.d.ts +0 -2
- package/dist/unit.js +0 -3
package/dist/result.mjs
ADDED
|
@@ -0,0 +1,1077 @@
|
|
|
1
|
+
import { UnwrappedErrWithOk, UnwrappedOkWithErr } from "./errors.mjs";
|
|
2
|
+
import { UNIT } from "./unit.mjs";
|
|
3
|
+
import { CapturedTrace, isCapturedTrace, isPromiseLike } from "./utils.mjs";
|
|
4
|
+
import { Option } from "./option.mjs";
|
|
5
|
+
|
|
6
|
+
//#region src/result.ts
|
|
7
|
+
/** Sentinel value stored in #val when Result is Err */
|
|
8
|
+
const ERR_VAL = Symbol("Result::Err");
|
|
9
|
+
/** NO_ERR sentinel indicates no async error has occurred */
|
|
10
|
+
const NO_ERR = Symbol("Result::NoErr");
|
|
11
|
+
/** Internal symbol for accessing private factory - not exported */
|
|
12
|
+
const RESULT_INTERNAL = Symbol("Result::Internal");
|
|
13
|
+
/**
|
|
14
|
+
* Wrapper that makes Result yieldable with proper type tracking.
|
|
15
|
+
* The Generator signature ensures TypeScript tracks the inner type T.
|
|
16
|
+
*
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
var ResultYieldWrap = class {
|
|
20
|
+
constructor(result) {
|
|
21
|
+
this.result = result;
|
|
22
|
+
}
|
|
23
|
+
*[Symbol.iterator]() {
|
|
24
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
25
|
+
return yield new CapturedTrace(this, trace);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Wrapper that makes Result yieldable in async generators with proper type tracking.
|
|
30
|
+
* Supports Promise<Result<T, E>> for async result chaining.
|
|
31
|
+
*
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
var AsyncResultYieldWrap = class {
|
|
35
|
+
constructor(result) {
|
|
36
|
+
this.result = result;
|
|
37
|
+
}
|
|
38
|
+
async *[Symbol.asyncIterator]() {
|
|
39
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
40
|
+
return yield new CapturedTrace(this, trace);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Represents a computation that can succeed (`Ok<T>`) or fail (`Err<E>`).
|
|
45
|
+
* Provides composable transformations with explicit error propagation.
|
|
46
|
+
*/
|
|
47
|
+
var Result = class Result {
|
|
48
|
+
/** Discriminant tag for type-level identification */
|
|
49
|
+
_tag;
|
|
50
|
+
/** Value when Ok; ERR_VAL sentinel when Err */
|
|
51
|
+
#val;
|
|
52
|
+
/** Error when Err (sync); undefined when Ok */
|
|
53
|
+
#err;
|
|
54
|
+
/** Context for async error tracking - stores actual error value when async chain fails */
|
|
55
|
+
#ctx;
|
|
56
|
+
constructor(val, err, ctx, tag) {
|
|
57
|
+
this.#val = val;
|
|
58
|
+
this.#err = err;
|
|
59
|
+
this.#ctx = ctx;
|
|
60
|
+
this._tag = tag;
|
|
61
|
+
}
|
|
62
|
+
/** Internal factory for namespace functions - not part of public API */
|
|
63
|
+
static [RESULT_INTERNAL] = { create(val, err, ctx, tag) {
|
|
64
|
+
return new Result(val, err, ctx, tag);
|
|
65
|
+
} };
|
|
66
|
+
/** Get the actual error value (from async context or sync field) */
|
|
67
|
+
getErr() {
|
|
68
|
+
return this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err;
|
|
69
|
+
}
|
|
70
|
+
/** Singleton UNIT_RESULT for void-success operations */
|
|
71
|
+
static UNIT_RESULT = new Result(UNIT, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
72
|
+
/**
|
|
73
|
+
* Creates an Ok containing the given value.
|
|
74
|
+
*
|
|
75
|
+
* @template T - Success value type
|
|
76
|
+
* @template E - Error type (defaults to never)
|
|
77
|
+
* @param val - Success value
|
|
78
|
+
* @returns Result in the Ok state
|
|
79
|
+
*/
|
|
80
|
+
static Ok(val) {
|
|
81
|
+
return new Result(val, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Creates an Err containing the given error.
|
|
85
|
+
*
|
|
86
|
+
* @template E - Error type
|
|
87
|
+
* @template T - Success value type (defaults to never)
|
|
88
|
+
* @param err - Error value
|
|
89
|
+
* @returns Result in the Err state
|
|
90
|
+
*/
|
|
91
|
+
static Err(err) {
|
|
92
|
+
return new Result(ERR_VAL, err, { asyncErr: NO_ERR }, "Err");
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Type guard for Ok state.
|
|
96
|
+
*
|
|
97
|
+
* @returns true if this Result is Ok
|
|
98
|
+
*/
|
|
99
|
+
isOk() {
|
|
100
|
+
return this._tag === "Ok" && this.#ctx.asyncErr === NO_ERR;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Type guard for Err state.
|
|
104
|
+
*
|
|
105
|
+
* @returns true if this Result is Err
|
|
106
|
+
*/
|
|
107
|
+
isErr() {
|
|
108
|
+
return this._tag === "Err" || this.#ctx.asyncErr !== NO_ERR || this._tag === "Ok" && this.#val === ERR_VAL;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Type guard for Ok containing UNIT.
|
|
112
|
+
*
|
|
113
|
+
* @returns true if the Ok value is UNIT
|
|
114
|
+
*/
|
|
115
|
+
isUnit() {
|
|
116
|
+
return this.#val === UNIT;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Returns a string representation of the Result.
|
|
120
|
+
*
|
|
121
|
+
* @returns "Result::Ok<value>" or "Result::Err<error>"
|
|
122
|
+
*/
|
|
123
|
+
toString() {
|
|
124
|
+
if (this.isOk()) return `Result::Ok<${String(this.#val)}>`;
|
|
125
|
+
return `Result::Err<${String(this.getErr())}>`;
|
|
126
|
+
}
|
|
127
|
+
unwrap() {
|
|
128
|
+
if (this.isErr()) {
|
|
129
|
+
const err = this.getErr();
|
|
130
|
+
if (err instanceof Error) throw err;
|
|
131
|
+
throw new UnwrappedOkWithErr(this.toString());
|
|
132
|
+
}
|
|
133
|
+
const curr = this.#val;
|
|
134
|
+
if (isPromiseLike(curr)) {
|
|
135
|
+
const ctx = this.#ctx;
|
|
136
|
+
return new Promise((resolve, reject) => {
|
|
137
|
+
curr.then((v) => {
|
|
138
|
+
if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) reject(ctx.asyncErr !== NO_ERR && ctx.asyncErr instanceof Error ? ctx.asyncErr : new UnwrappedOkWithErr(this.toString()));
|
|
139
|
+
else resolve(v);
|
|
140
|
+
}, reject);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return curr;
|
|
144
|
+
}
|
|
145
|
+
unwrapErr() {
|
|
146
|
+
if (this._tag === "Err") return this.getErr();
|
|
147
|
+
const curr = this.#val;
|
|
148
|
+
const ctx = this.#ctx;
|
|
149
|
+
if (isPromiseLike(curr)) return new Promise((resolve, reject) => {
|
|
150
|
+
curr.then((v) => {
|
|
151
|
+
if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) resolve(ctx.asyncErr !== NO_ERR ? ctx.asyncErr : this.#err);
|
|
152
|
+
else reject(new UnwrappedErrWithOk(this.toString()));
|
|
153
|
+
}, reject);
|
|
154
|
+
});
|
|
155
|
+
throw new UnwrappedErrWithOk(this.toString());
|
|
156
|
+
}
|
|
157
|
+
unwrapOr(defaultValue) {
|
|
158
|
+
if (this.isErr()) return defaultValue;
|
|
159
|
+
const curr = this.#val;
|
|
160
|
+
const ctx = this.#ctx;
|
|
161
|
+
if (isPromiseLike(curr)) return curr.then((v) => {
|
|
162
|
+
if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) return defaultValue;
|
|
163
|
+
return v;
|
|
164
|
+
});
|
|
165
|
+
return curr;
|
|
166
|
+
}
|
|
167
|
+
unwrapOrElse(fn) {
|
|
168
|
+
if (this.isErr()) return fn(this.getErr());
|
|
169
|
+
const curr = this.#val;
|
|
170
|
+
const ctx = this.#ctx;
|
|
171
|
+
if (isPromiseLike(curr)) return curr.then((v) => {
|
|
172
|
+
if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) return fn(ctx.asyncErr !== NO_ERR ? ctx.asyncErr : this.#err);
|
|
173
|
+
return v;
|
|
174
|
+
});
|
|
175
|
+
return curr;
|
|
176
|
+
}
|
|
177
|
+
safeUnwrap() {
|
|
178
|
+
if (this.isErr()) return null;
|
|
179
|
+
const curr = this.#val;
|
|
180
|
+
const ctx = this.#ctx;
|
|
181
|
+
if (isPromiseLike(curr)) return curr.then((v) => {
|
|
182
|
+
if (v === ERR_VAL || ctx.asyncErr !== NO_ERR) return null;
|
|
183
|
+
return v;
|
|
184
|
+
});
|
|
185
|
+
return curr === ERR_VAL ? null : curr;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Exhaustive pattern match on Result state.
|
|
189
|
+
*
|
|
190
|
+
* @template U - Result type of the handlers
|
|
191
|
+
* @param cases - Handlers for Ok and Err
|
|
192
|
+
* @returns Result of the matching handler
|
|
193
|
+
*/
|
|
194
|
+
match(cases) {
|
|
195
|
+
if (this.isErr()) return cases.Err(this.getErr());
|
|
196
|
+
return cases.Ok(this.#val);
|
|
197
|
+
}
|
|
198
|
+
map(fn) {
|
|
199
|
+
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
200
|
+
const curr = this.#val;
|
|
201
|
+
const parentErr = this.#err;
|
|
202
|
+
if (isPromiseLike(curr)) {
|
|
203
|
+
const p = curr;
|
|
204
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
205
|
+
return new Result(Result.safeMap(p, fn, newCtx, this.#ctx), parentErr, newCtx, "Ok");
|
|
206
|
+
}
|
|
207
|
+
const next = fn(curr);
|
|
208
|
+
if (isPromiseLike(next)) return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
209
|
+
return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Safely maps a promised Ok value while propagating async errors.
|
|
213
|
+
*
|
|
214
|
+
* @template In - Input value type
|
|
215
|
+
* @template U - Output value type
|
|
216
|
+
* @template E - Error type
|
|
217
|
+
* @param p - Promise of Ok value or ERR sentinel
|
|
218
|
+
* @param mapper - Transform function
|
|
219
|
+
* @param ctx - New async context to populate on error
|
|
220
|
+
* @param parentCtx - Parent async context to read error from
|
|
221
|
+
* @returns Promise of transformed value or ERR sentinel
|
|
222
|
+
*/
|
|
223
|
+
static safeMap(p, mapper, ctx, parentCtx) {
|
|
224
|
+
return p.then((v) => {
|
|
225
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
226
|
+
ctx.asyncErr = parentCtx.asyncErr;
|
|
227
|
+
return ERR_VAL;
|
|
228
|
+
}
|
|
229
|
+
return mapper(v);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Transforms the error value while preserving the success value.
|
|
234
|
+
*
|
|
235
|
+
* If the Result is Err, applies the function to the error. If Ok, returns
|
|
236
|
+
* the Ok unchanged without calling the function.
|
|
237
|
+
*
|
|
238
|
+
* @param fn - Function to transform the error
|
|
239
|
+
* @returns Result<T, E2> with transformed error or original Ok
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* ```ts
|
|
243
|
+
* Result.Err("network error").mapErr((e) => `Network: ${e}`); // Err("Network: network error")
|
|
244
|
+
* Result.Ok(42).mapErr((e) => `Error: ${e}`); // Ok(42)
|
|
245
|
+
*
|
|
246
|
+
* // Add context to errors
|
|
247
|
+
* fetchData()
|
|
248
|
+
* .mapErr((e) => new ContextualError("Failed to fetch data", e));
|
|
249
|
+
* ```
|
|
250
|
+
*
|
|
251
|
+
* @see mapBoth
|
|
252
|
+
*/
|
|
253
|
+
mapErr(fn) {
|
|
254
|
+
if (this._tag === "Err") {
|
|
255
|
+
const mappedErr = fn(this.getErr());
|
|
256
|
+
return Result.Err(mappedErr);
|
|
257
|
+
}
|
|
258
|
+
const curr = this.#val;
|
|
259
|
+
const parentCtx = this.#ctx;
|
|
260
|
+
if (isPromiseLike(curr)) {
|
|
261
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
262
|
+
return new Result(curr.then((v) => {
|
|
263
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) newCtx.asyncErr = fn(parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err);
|
|
264
|
+
return v;
|
|
265
|
+
}), void 0, newCtx, "Ok");
|
|
266
|
+
}
|
|
267
|
+
return new Result(this.#val, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
268
|
+
}
|
|
269
|
+
mapBoth(fnOk, fnErr) {
|
|
270
|
+
return this.map(fnOk).mapErr(fnErr);
|
|
271
|
+
}
|
|
272
|
+
flatMap(fn) {
|
|
273
|
+
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
274
|
+
const curr = this.#val;
|
|
275
|
+
const parentErr = this.#err;
|
|
276
|
+
const parentCtx = this.#ctx;
|
|
277
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
278
|
+
if (isPromiseLike(curr)) return new Result(new Promise((resolve, reject) => {
|
|
279
|
+
curr.then((v) => {
|
|
280
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
281
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
282
|
+
return resolve(ERR_VAL);
|
|
283
|
+
}
|
|
284
|
+
const mapped = fn(v);
|
|
285
|
+
resolve(Result.flatMapHelper(newCtx, mapped));
|
|
286
|
+
}, reject);
|
|
287
|
+
}), parentErr, newCtx, "Ok");
|
|
288
|
+
const mapped = fn(curr);
|
|
289
|
+
if (isPromiseLike(mapped)) return new Result(mapped.then((r) => Result.flatMapInnerHelper(newCtx, r)), parentErr, newCtx, "Ok");
|
|
290
|
+
const normalized = Result.flatMapInnerHelper(newCtx, mapped);
|
|
291
|
+
if (isPromiseLike(normalized)) return new Result(normalized, parentErr, newCtx, "Ok");
|
|
292
|
+
if (normalized === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
|
|
293
|
+
return new Result(normalized, parentErr, newCtx, "Ok");
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Normalizes sync/async flatMap outputs to a value or Promise.
|
|
297
|
+
*
|
|
298
|
+
* @template U - Success value type
|
|
299
|
+
* @template E - Original error type
|
|
300
|
+
* @template E2 - Mapped error type
|
|
301
|
+
* @template T - Input value type
|
|
302
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
303
|
+
* @param mapped - FlatMap output (sync or async Result)
|
|
304
|
+
* @returns Value, Promise, or ERR sentinel
|
|
305
|
+
*/
|
|
306
|
+
static flatMapHelper(mutableCtx, mapped) {
|
|
307
|
+
if (isPromiseLike(mapped)) return mapped.then((r) => Result.flatMapInnerHelper(mutableCtx, r));
|
|
308
|
+
return Result.flatMapInnerHelper(mutableCtx, mapped);
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Extracts the inner value from a Result, updating error context on failure.
|
|
312
|
+
*
|
|
313
|
+
* @template U - Success value type
|
|
314
|
+
* @template E - Original error type
|
|
315
|
+
* @template E2 - Mapped error type
|
|
316
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
317
|
+
* @param r - Inner Result to unwrap
|
|
318
|
+
* @returns Value, Promise, or ERR sentinel
|
|
319
|
+
*/
|
|
320
|
+
static flatMapInnerHelper(mutableCtx, r) {
|
|
321
|
+
if (r._tag === "Err") {
|
|
322
|
+
mutableCtx.asyncErr = r.getErr();
|
|
323
|
+
return ERR_VAL;
|
|
324
|
+
}
|
|
325
|
+
const innerVal = r.#val;
|
|
326
|
+
if (isPromiseLike(innerVal)) return innerVal.then((v) => {
|
|
327
|
+
if (v === ERR_VAL || r.#ctx.asyncErr !== NO_ERR) mutableCtx.asyncErr = r.#ctx.asyncErr !== NO_ERR ? r.#ctx.asyncErr : r.#err;
|
|
328
|
+
return v;
|
|
329
|
+
});
|
|
330
|
+
if (innerVal === ERR_VAL) {
|
|
331
|
+
mutableCtx.asyncErr = r.getErr();
|
|
332
|
+
return ERR_VAL;
|
|
333
|
+
}
|
|
334
|
+
return innerVal;
|
|
335
|
+
}
|
|
336
|
+
zip(fn) {
|
|
337
|
+
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
338
|
+
const curr = this.#val;
|
|
339
|
+
const parentErr = this.#err;
|
|
340
|
+
const parentCtx = this.#ctx;
|
|
341
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
342
|
+
if (isPromiseLike(curr)) return new Result(curr.then((v) => {
|
|
343
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
344
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
345
|
+
return ERR_VAL;
|
|
346
|
+
}
|
|
347
|
+
const u = fn(v);
|
|
348
|
+
if (isPromiseLike(u)) return u.then((uu) => [v, uu]);
|
|
349
|
+
return [v, u];
|
|
350
|
+
}), parentErr, newCtx, "Ok");
|
|
351
|
+
const u = fn(curr);
|
|
352
|
+
if (isPromiseLike(u)) return new Result(u.then((uu) => [curr, uu]), parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
353
|
+
return new Result([curr, u], parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
354
|
+
}
|
|
355
|
+
flatZip(fn) {
|
|
356
|
+
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
357
|
+
const curr = this.#val;
|
|
358
|
+
const parentErr = this.#err;
|
|
359
|
+
const parentCtx = this.#ctx;
|
|
360
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
361
|
+
if (isPromiseLike(curr)) return new Result(curr.then((v) => {
|
|
362
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
363
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
364
|
+
return ERR_VAL;
|
|
365
|
+
}
|
|
366
|
+
const mapped = fn(v);
|
|
367
|
+
return Result.flatZipHelper(newCtx, v, mapped);
|
|
368
|
+
}), parentErr, newCtx, "Ok");
|
|
369
|
+
const mapped = fn(curr);
|
|
370
|
+
const p = Result.flatZipHelper(newCtx, curr, mapped);
|
|
371
|
+
if (isPromiseLike(p)) return new Result(p, parentErr, newCtx, "Ok");
|
|
372
|
+
if (p === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
|
|
373
|
+
return new Result(p, parentErr, newCtx, "Ok");
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Normalizes sync/async flatZip outputs to a tuple or ERR sentinel.
|
|
377
|
+
*
|
|
378
|
+
* @template U - Derived value type
|
|
379
|
+
* @template E - Original error type
|
|
380
|
+
* @template E2 - Mapped error type
|
|
381
|
+
* @template In - Original value type
|
|
382
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
383
|
+
* @param originalVal - Original value to preserve
|
|
384
|
+
* @param mapped - FlatZip output (sync or async Result)
|
|
385
|
+
* @returns Tuple, Promise of tuple, or ERR sentinel
|
|
386
|
+
*/
|
|
387
|
+
static flatZipHelper(mutableCtx, originalVal, mapped) {
|
|
388
|
+
if (isPromiseLike(mapped)) return mapped.then((r) => Result.flatZipInnerHelper(mutableCtx, originalVal, r));
|
|
389
|
+
return Result.flatZipInnerHelper(mutableCtx, originalVal, mapped);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Extracts the inner value for flatZip, updating error context on failure.
|
|
393
|
+
*
|
|
394
|
+
* @template U - Derived value type
|
|
395
|
+
* @template E - Original error type
|
|
396
|
+
* @template E2 - Mapped error type
|
|
397
|
+
* @template In - Original value type
|
|
398
|
+
* @param mutableCtx - Mutable context for async error propagation
|
|
399
|
+
* @param originalVal - Original value to preserve
|
|
400
|
+
* @param r - Inner Result to unwrap
|
|
401
|
+
* @returns Tuple, Promise of tuple, or ERR sentinel
|
|
402
|
+
*/
|
|
403
|
+
static flatZipInnerHelper(mutableCtx, originalVal, r) {
|
|
404
|
+
if (r._tag === "Err") {
|
|
405
|
+
mutableCtx.asyncErr = r.getErr();
|
|
406
|
+
return ERR_VAL;
|
|
407
|
+
}
|
|
408
|
+
const innerVal = r.#val;
|
|
409
|
+
if (isPromiseLike(innerVal)) return innerVal.then((v) => {
|
|
410
|
+
if (v === ERR_VAL || r.#ctx.asyncErr !== NO_ERR) {
|
|
411
|
+
mutableCtx.asyncErr = r.#ctx.asyncErr !== NO_ERR ? r.#ctx.asyncErr : r.#err;
|
|
412
|
+
return ERR_VAL;
|
|
413
|
+
}
|
|
414
|
+
return [originalVal, v];
|
|
415
|
+
});
|
|
416
|
+
if (innerVal === ERR_VAL) {
|
|
417
|
+
mutableCtx.asyncErr = r.getErr();
|
|
418
|
+
return ERR_VAL;
|
|
419
|
+
}
|
|
420
|
+
return [originalVal, innerVal];
|
|
421
|
+
}
|
|
422
|
+
zipErr(fn) {
|
|
423
|
+
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
424
|
+
const curr = this.#val;
|
|
425
|
+
const parentErr = this.#err;
|
|
426
|
+
const parentCtx = this.#ctx;
|
|
427
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
428
|
+
if (isPromiseLike(curr)) return new Result(curr.then((v) => {
|
|
429
|
+
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
430
|
+
newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
431
|
+
return ERR_VAL;
|
|
432
|
+
}
|
|
433
|
+
const r = fn(v);
|
|
434
|
+
return Result.zipErrHelper(v, r, newCtx);
|
|
435
|
+
}), parentErr, newCtx, "Ok");
|
|
436
|
+
const r = fn(curr);
|
|
437
|
+
const newP = Result.zipErrHelper(curr, r, newCtx);
|
|
438
|
+
if (isPromiseLike(newP)) return new Result(newP, parentErr, newCtx, "Ok");
|
|
439
|
+
if (newCtx.asyncErr !== NO_ERR) return new Result(ERR_VAL, newCtx.asyncErr, newCtx, "Err");
|
|
440
|
+
return new Result(newP, parentErr, newCtx, "Ok");
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Tracks errors from a Result while preserving the original value.
|
|
444
|
+
*
|
|
445
|
+
* @template In - Original value type
|
|
446
|
+
* @template E - Error type
|
|
447
|
+
* @param v - Original value to preserve
|
|
448
|
+
* @param r - Result to inspect for errors
|
|
449
|
+
* @param newCtx - Context to populate on error
|
|
450
|
+
* @returns Original value or Promise of value
|
|
451
|
+
*/
|
|
452
|
+
static zipErrHelper(v, r, newCtx) {
|
|
453
|
+
if (isPromiseLike(r)) return r.then((newResult) => {
|
|
454
|
+
const maybeAwaited = Result.captureZipErr(newResult, newCtx);
|
|
455
|
+
if (isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
|
|
456
|
+
return v;
|
|
457
|
+
});
|
|
458
|
+
const maybeAwaited = Result.captureZipErr(r, newCtx);
|
|
459
|
+
if (isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
|
|
460
|
+
return v;
|
|
461
|
+
}
|
|
462
|
+
static captureZipErr(result, newCtx) {
|
|
463
|
+
if (result._tag === "Err") {
|
|
464
|
+
newCtx.asyncErr = result.getErr();
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const innerVal = result.#val;
|
|
468
|
+
if (isPromiseLike(innerVal)) return innerVal.then((resolved) => {
|
|
469
|
+
if (resolved === ERR_VAL || result.#ctx.asyncErr !== NO_ERR) newCtx.asyncErr = result.#ctx.asyncErr !== NO_ERR ? result.#ctx.asyncErr : result.#err;
|
|
470
|
+
});
|
|
471
|
+
if (innerVal === ERR_VAL || result.#ctx.asyncErr !== NO_ERR) newCtx.asyncErr = result.#ctx.asyncErr !== NO_ERR ? result.#ctx.asyncErr : result.#err;
|
|
472
|
+
}
|
|
473
|
+
validate(validators) {
|
|
474
|
+
if (this.isErr()) return this;
|
|
475
|
+
const currVal = this.#val;
|
|
476
|
+
const parentErr = this.#err;
|
|
477
|
+
const parentCtx = this.#ctx;
|
|
478
|
+
const mutableCtx = { asyncErr: NO_ERR };
|
|
479
|
+
if (isPromiseLike(currVal)) return new Result(currVal.then(async (c) => {
|
|
480
|
+
if (c === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
481
|
+
mutableCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : parentErr;
|
|
482
|
+
return ERR_VAL;
|
|
483
|
+
}
|
|
484
|
+
const awaitedVal = c;
|
|
485
|
+
const results = validators.map((v) => v(awaitedVal));
|
|
486
|
+
return Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, awaitedVal));
|
|
487
|
+
}), parentErr, mutableCtx, "Ok");
|
|
488
|
+
const baseVal = currVal;
|
|
489
|
+
const results = validators.map((v) => v(baseVal));
|
|
490
|
+
if (results.some(isPromiseLike)) return new Result(Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, baseVal)), parentErr, mutableCtx, "Ok");
|
|
491
|
+
const syncResults = results;
|
|
492
|
+
if (syncResults.some((r) => isPromiseLike(r.#val))) return new Result(Result.validateHelper(syncResults, mutableCtx, baseVal), parentErr, mutableCtx, "Ok");
|
|
493
|
+
const combinedRes = Result.all(...syncResults);
|
|
494
|
+
return combinedRes.isErr() ? combinedRes : this;
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Collapses validator Results into a single value or ERR sentinel.
|
|
498
|
+
*
|
|
499
|
+
* @template Val - Success value type
|
|
500
|
+
* @template Err - Error type
|
|
501
|
+
* @param results - Validator Results to combine
|
|
502
|
+
* @param currCtx - Context to populate on error
|
|
503
|
+
* @param currVal - Original value to return on success
|
|
504
|
+
* @returns Original value, Promise of value, or ERR sentinel
|
|
505
|
+
*/
|
|
506
|
+
static validateHelper(results, currCtx, currVal) {
|
|
507
|
+
const combinedRes = Result.all(...results);
|
|
508
|
+
if (isPromiseLike(combinedRes.#val)) return combinedRes.#val.then((v) => {
|
|
509
|
+
if (v === ERR_VAL || combinedRes.#ctx.asyncErr !== NO_ERR) {
|
|
510
|
+
currCtx.asyncErr = combinedRes.getErr();
|
|
511
|
+
return ERR_VAL;
|
|
512
|
+
}
|
|
513
|
+
return currVal;
|
|
514
|
+
});
|
|
515
|
+
if (combinedRes.isErr()) {
|
|
516
|
+
currCtx.asyncErr = combinedRes.getErr();
|
|
517
|
+
return ERR_VAL;
|
|
518
|
+
}
|
|
519
|
+
return currVal;
|
|
520
|
+
}
|
|
521
|
+
static all(...results) {
|
|
522
|
+
const vals = results.map((r) => r.#val);
|
|
523
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
524
|
+
if (vals.some(isPromiseLike)) return new Result(Promise.all(vals).then((resolvedVals) => {
|
|
525
|
+
const errs = [];
|
|
526
|
+
for (let i = 0; i < results.length; i++) if (results[i]._tag === "Err" || results[i].#ctx.asyncErr !== NO_ERR || resolvedVals[i] === ERR_VAL) errs.push(results[i].getErr());
|
|
527
|
+
if (errs.length > 0) {
|
|
528
|
+
newCtx.asyncErr = errs;
|
|
529
|
+
return ERR_VAL;
|
|
530
|
+
}
|
|
531
|
+
return resolvedVals;
|
|
532
|
+
}), [], newCtx, "Ok");
|
|
533
|
+
const errs = [];
|
|
534
|
+
for (const r of results) if (r._tag === "Err") errs.push(r.getErr());
|
|
535
|
+
if (errs.length > 0) return Result.Err(errs);
|
|
536
|
+
return Result.Ok(vals);
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Returns the first Ok, or collects all errors if all are Err.
|
|
540
|
+
*
|
|
541
|
+
* Useful for fallback chains where you want the first success, but want
|
|
542
|
+
* to collect all errors if everything fails.
|
|
543
|
+
*
|
|
544
|
+
* - First Ok → Returns that Ok immediately
|
|
545
|
+
* - All Err → `Err([...all errors])`
|
|
546
|
+
*
|
|
547
|
+
* For async Ok values, this waits for settlement and selects the first
|
|
548
|
+
* successful candidate in input order (not fastest-to-resolve order).
|
|
549
|
+
*
|
|
550
|
+
* @param results - Variable number of Results to check
|
|
551
|
+
* @returns First Ok found, or Err with array of all errors
|
|
552
|
+
*
|
|
553
|
+
* @example
|
|
554
|
+
* ```ts
|
|
555
|
+
* Result.any(
|
|
556
|
+
* Result.Err("Error 1"),
|
|
557
|
+
* Result.Ok("First success"),
|
|
558
|
+
* Result.Ok("Second success"),
|
|
559
|
+
* ); // Ok("First success")
|
|
560
|
+
*
|
|
561
|
+
* Result.any(
|
|
562
|
+
* Result.Err("Error 1"),
|
|
563
|
+
* Result.Err("Error 2"),
|
|
564
|
+
* Result.Err("Error 3"),
|
|
565
|
+
* ); // Err(["Error 1", "Error 2", "Error 3"])
|
|
566
|
+
*
|
|
567
|
+
* // Fallback chain
|
|
568
|
+
* Result.any(
|
|
569
|
+
* fetchFromCache(key),
|
|
570
|
+
* fetchFromDb(key),
|
|
571
|
+
* fetchFromRemote(key),
|
|
572
|
+
* );
|
|
573
|
+
* ```
|
|
574
|
+
*
|
|
575
|
+
* @see all
|
|
576
|
+
*/
|
|
577
|
+
static any(...results) {
|
|
578
|
+
const errs = [];
|
|
579
|
+
const pending = [];
|
|
580
|
+
for (const r of results) {
|
|
581
|
+
if (r.isOk()) {
|
|
582
|
+
if (isPromiseLike(r.#val)) {
|
|
583
|
+
pending.push(r);
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
return r;
|
|
587
|
+
}
|
|
588
|
+
errs.push(r.getErr());
|
|
589
|
+
}
|
|
590
|
+
if (pending.length === 0) return Result.Err(errs);
|
|
591
|
+
const ctx = { asyncErr: NO_ERR };
|
|
592
|
+
return new Result(Promise.all(pending.map(async (r) => {
|
|
593
|
+
const val = await r.#val;
|
|
594
|
+
return {
|
|
595
|
+
failed: r.#ctx.asyncErr !== NO_ERR || val === ERR_VAL,
|
|
596
|
+
val,
|
|
597
|
+
err: r.getErr()
|
|
598
|
+
};
|
|
599
|
+
})).then((settled) => {
|
|
600
|
+
for (const item of settled) {
|
|
601
|
+
if (!item.failed) return item.val;
|
|
602
|
+
errs.push(item.err);
|
|
603
|
+
}
|
|
604
|
+
ctx.asyncErr = errs;
|
|
605
|
+
return ERR_VAL;
|
|
606
|
+
}), void 0, ctx, "Ok");
|
|
607
|
+
}
|
|
608
|
+
tap(fn) {
|
|
609
|
+
if (this.isErr()) return this;
|
|
610
|
+
const curr = this.#val;
|
|
611
|
+
const parentCtx = this.#ctx;
|
|
612
|
+
if (isPromiseLike(curr)) {
|
|
613
|
+
const newCtx = { asyncErr: NO_ERR };
|
|
614
|
+
return new Result(curr.then((v) => {
|
|
615
|
+
if (v !== ERR_VAL && parentCtx.asyncErr === NO_ERR) fn(v);
|
|
616
|
+
else newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err;
|
|
617
|
+
return v;
|
|
618
|
+
}), this.#err, newCtx, "Ok");
|
|
619
|
+
}
|
|
620
|
+
fn(curr);
|
|
621
|
+
return this;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Executes a side effect function for Err values, then returns self.
|
|
625
|
+
*
|
|
626
|
+
* Useful for logging errors or executing cleanup without breaking the chain.
|
|
627
|
+
* The function is only called if the Result is Err.
|
|
628
|
+
*
|
|
629
|
+
* @param fn - Function to execute with the error (sync or async)
|
|
630
|
+
* @returns The same Result (chainable)
|
|
631
|
+
*
|
|
632
|
+
* @example
|
|
633
|
+
* ```ts
|
|
634
|
+
* Result.Err("Connection failed")
|
|
635
|
+
* .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
|
|
636
|
+
* .orElse((e) => Result.Ok(defaultValue));
|
|
637
|
+
* // Logs error timestamp
|
|
638
|
+
* // Returns: Ok(defaultValue)
|
|
639
|
+
*
|
|
640
|
+
* // Ok - tapErr does nothing
|
|
641
|
+
* Result.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
|
|
642
|
+
* ```
|
|
643
|
+
*
|
|
644
|
+
* @see tap
|
|
645
|
+
*/
|
|
646
|
+
tapErr(fn) {
|
|
647
|
+
if (this.isErr()) fn(this.getErr());
|
|
648
|
+
return this;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Swaps the Ok and Err states, turning success into failure and vice versa.
|
|
652
|
+
*
|
|
653
|
+
* Useful for inverting the meaning of a Result, such as converting
|
|
654
|
+
* validation errors to successes and valid values to errors.
|
|
655
|
+
*
|
|
656
|
+
* @returns Result<E, T> with swapped states
|
|
657
|
+
*
|
|
658
|
+
* @example
|
|
659
|
+
* ```ts
|
|
660
|
+
* Result.Ok("Success value").flip(); // Err("Success value")
|
|
661
|
+
* Result.Err("Error value").flip(); // Ok("Error value")
|
|
662
|
+
*
|
|
663
|
+
* // Invert validation (fail if value is in blacklist)
|
|
664
|
+
* const blacklist = ["admin", "root"];
|
|
665
|
+
* const isBlacklisted = (name: string) =>
|
|
666
|
+
* Result.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
|
|
667
|
+
* .flip(); // Ok if blacklisted, Err if not
|
|
668
|
+
* ```
|
|
669
|
+
*/
|
|
670
|
+
flip() {
|
|
671
|
+
if (this.isErr()) return new Result(this.getErr(), void 0, { asyncErr: NO_ERR }, "Ok");
|
|
672
|
+
return new Result(ERR_VAL, this.#val, { asyncErr: NO_ERR }, "Err");
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Converts Result to Option, discarding error information.
|
|
676
|
+
*
|
|
677
|
+
* - Ok(value) → Some(value)
|
|
678
|
+
* - Err(error) → None
|
|
679
|
+
*
|
|
680
|
+
* Use when you only care about presence/absence of a value, not the error.
|
|
681
|
+
*
|
|
682
|
+
* @returns Option<T> - Some if Ok, None if Err
|
|
683
|
+
*
|
|
684
|
+
* @example
|
|
685
|
+
* ```ts
|
|
686
|
+
* Result.Ok(42).toOption(); // Some(42)
|
|
687
|
+
* Result.Err("fail").toOption(); // None
|
|
688
|
+
*
|
|
689
|
+
* // Safe user lookup
|
|
690
|
+
* const userOpt = fetchUser(id).toOption();
|
|
691
|
+
* // User or None, regardless of why fetch failed
|
|
692
|
+
* ```
|
|
693
|
+
*
|
|
694
|
+
* @see Option.toResult
|
|
695
|
+
*/
|
|
696
|
+
toOption() {
|
|
697
|
+
if (this.isErr()) return Option.None;
|
|
698
|
+
return Option.Some(this.#val);
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Resolves the inner promise while preserving Result structure.
|
|
702
|
+
*
|
|
703
|
+
* @returns Promise of Result with awaited value or Err
|
|
704
|
+
*/
|
|
705
|
+
async toPromise() {
|
|
706
|
+
const v = await this.#val;
|
|
707
|
+
if (v === ERR_VAL || this.#ctx.asyncErr !== NO_ERR) return new Result(ERR_VAL, this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err, { asyncErr: NO_ERR }, "Err");
|
|
708
|
+
return new Result(v, this.#err, { asyncErr: NO_ERR }, "Ok");
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Maps over array elements inside a Result<Array<T>, E>.
|
|
712
|
+
*
|
|
713
|
+
* Applies the mapper function to each element if the Result is Ok and
|
|
714
|
+
* contains an array. Propagates Err unchanged.
|
|
715
|
+
*
|
|
716
|
+
* @param mapper - Function to map over each array element
|
|
717
|
+
* @returns Result<Array<Out>, E> with mapped array or propagated error
|
|
718
|
+
* @throws Error if the Result is Ok but value is not an array
|
|
719
|
+
*
|
|
720
|
+
* @example
|
|
721
|
+
* ```ts
|
|
722
|
+
* Result.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
|
|
723
|
+
* Result.Err("fail").innerMap((x) => x * 2); // Err("fail")
|
|
724
|
+
* ```
|
|
725
|
+
*/
|
|
726
|
+
innerMap(mapper) {
|
|
727
|
+
if (this.isErr()) return this;
|
|
728
|
+
if (Array.isArray(this.#val)) return new Result(this.#val.map(mapper), this.#err, this.#ctx, "Ok");
|
|
729
|
+
throw new Error("Can only be called for Result<Array<T>, E>");
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Recovers from Err by providing a fallback Result.
|
|
733
|
+
*
|
|
734
|
+
* If Ok, returns self unchanged.
|
|
735
|
+
*
|
|
736
|
+
* @template T2 - Fallback success type
|
|
737
|
+
* @template E2 - Fallback error type
|
|
738
|
+
* @param fn - Function to produce a fallback Result from the error
|
|
739
|
+
* @returns Original Ok or fallback Result
|
|
740
|
+
*/
|
|
741
|
+
orElse(fn) {
|
|
742
|
+
if (this.isOk()) return this;
|
|
743
|
+
return fn(this.getErr());
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Creates a Result from a nullable value.
|
|
747
|
+
*
|
|
748
|
+
* Returns Err when the value is null or undefined, otherwise Ok.
|
|
749
|
+
*
|
|
750
|
+
* @template T - Input value type
|
|
751
|
+
* @template E - Error type
|
|
752
|
+
* @param val - Value to wrap
|
|
753
|
+
* @param error - Error value for null/undefined
|
|
754
|
+
* @returns Ok with value or Err with error
|
|
755
|
+
*/
|
|
756
|
+
static fromNullable(val, error) {
|
|
757
|
+
return val === null || val === void 0 ? Result.Err(error) : Result.Ok(val);
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Creates a Result based on a predicate.
|
|
761
|
+
*
|
|
762
|
+
* Returns Ok when predicate passes, otherwise Err.
|
|
763
|
+
*
|
|
764
|
+
* @template T - Input value type
|
|
765
|
+
* @template E - Error type
|
|
766
|
+
* @param val - Value to test
|
|
767
|
+
* @param pred - Predicate to decide Ok vs Err
|
|
768
|
+
* @param error - Error value for predicate failure
|
|
769
|
+
* @returns Ok with value or Err with error
|
|
770
|
+
*/
|
|
771
|
+
static fromPredicate(val, pred, error) {
|
|
772
|
+
return pred(val) ? Result.Ok(val) : Result.Err(error);
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Wraps a Promise<Result<T, E>> as Result<Promise<T>, E>.
|
|
776
|
+
*
|
|
777
|
+
* Returns an optimistic `Ok(Promise<T>)`. If the inner promise fails later,
|
|
778
|
+
* the failure is tracked internally and surfaces when you settle/unwrap
|
|
779
|
+
* (`toPromise`, `unwrap`, `unwrapErr`, etc.).
|
|
780
|
+
*
|
|
781
|
+
* @template U - Success value type
|
|
782
|
+
* @template F - Error type
|
|
783
|
+
* @param promise - Promise resolving to a Result
|
|
784
|
+
* @returns Result containing a Promise of the success value
|
|
785
|
+
*/
|
|
786
|
+
static fromPromise(promise) {
|
|
787
|
+
const ctx = { asyncErr: NO_ERR };
|
|
788
|
+
const p = promise.then((innerResult) => {
|
|
789
|
+
if (innerResult.isErr()) {
|
|
790
|
+
try {
|
|
791
|
+
ctx.asyncErr = innerResult.unwrapErr();
|
|
792
|
+
} catch {}
|
|
793
|
+
return ERR_VAL;
|
|
794
|
+
}
|
|
795
|
+
return innerResult.unwrap();
|
|
796
|
+
});
|
|
797
|
+
return Result[RESULT_INTERNAL].create(p, void 0, ctx, "Ok");
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Catches synchronous exceptions and converts them to Err.
|
|
801
|
+
*
|
|
802
|
+
* @template T - Success value type
|
|
803
|
+
* @template E - Error type
|
|
804
|
+
* @param fn - Function that may throw
|
|
805
|
+
* @param errorMapper - Optional mapper for thrown errors
|
|
806
|
+
* @returns Ok with return value or Err with mapped error
|
|
807
|
+
*/
|
|
808
|
+
static tryCatch(fn, errorMapper) {
|
|
809
|
+
try {
|
|
810
|
+
return Result.Ok(fn());
|
|
811
|
+
} catch (e) {
|
|
812
|
+
return Result.Err(errorMapper ? errorMapper(e) : e);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Catches async exceptions and converts them to Err.
|
|
817
|
+
*
|
|
818
|
+
* Returns an optimistic `Ok(Promise<T>)`. If the async work fails later,
|
|
819
|
+
* the failure is tracked internally and surfaces when you settle/unwrap
|
|
820
|
+
* (`toPromise`, `unwrap`, `unwrapErr`, etc.).
|
|
821
|
+
*
|
|
822
|
+
* @template T - Success value type
|
|
823
|
+
* @template E - Error type
|
|
824
|
+
* @param fn - Async function that may throw
|
|
825
|
+
* @param errorMapper - Optional mapper for thrown errors
|
|
826
|
+
* @returns Result containing a Promise of the success value
|
|
827
|
+
*/
|
|
828
|
+
static tryAsyncCatch(fn, errorMapper) {
|
|
829
|
+
const ctx = { asyncErr: NO_ERR };
|
|
830
|
+
const pWithErr = fn().then((v) => v).catch((e) => {
|
|
831
|
+
ctx.asyncErr = errorMapper ? errorMapper(e) : e;
|
|
832
|
+
return ERR_VAL;
|
|
833
|
+
});
|
|
834
|
+
return Result[RESULT_INTERNAL].create(pWithErr, void 0, ctx, "Ok");
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Makes Result iterable for use with generator-based syntax.
|
|
838
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
839
|
+
*
|
|
840
|
+
* @example
|
|
841
|
+
* ```ts
|
|
842
|
+
* const result = Result.gen(function* () {
|
|
843
|
+
* const value = yield* Result.Ok(42);
|
|
844
|
+
* return value * 2;
|
|
845
|
+
* });
|
|
846
|
+
* ```
|
|
847
|
+
*/
|
|
848
|
+
*[Symbol.iterator]() {
|
|
849
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
850
|
+
return yield new CapturedTrace(this, trace);
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Makes Result iterable for use with async generator-based syntax.
|
|
854
|
+
* Yields self and returns the unwrapped value when resumed.
|
|
855
|
+
*
|
|
856
|
+
* @example
|
|
857
|
+
* ```ts
|
|
858
|
+
* const result = await Result.asyncGen(async function* () {
|
|
859
|
+
* const value = yield* $(Result.Ok(42));
|
|
860
|
+
* return value * 2;
|
|
861
|
+
* });
|
|
862
|
+
* ```
|
|
863
|
+
*/
|
|
864
|
+
async *[Symbol.asyncIterator]() {
|
|
865
|
+
const trace = (/* @__PURE__ */ new Error()).stack;
|
|
866
|
+
return yield new CapturedTrace(this, trace);
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Generator-based syntax for chaining Result operations (simplified, no adapter).
|
|
870
|
+
* Provides imperative-style code while maintaining functional error handling.
|
|
871
|
+
*
|
|
872
|
+
* Short-circuits on first Err, returning that error. Uses iteration instead of
|
|
873
|
+
* recursion to avoid stack overflow on deep chains.
|
|
874
|
+
*
|
|
875
|
+
* @example
|
|
876
|
+
* ```ts
|
|
877
|
+
* const result = Result.gen(function* () {
|
|
878
|
+
* const a = yield* Result.Ok(1);
|
|
879
|
+
* const b = yield* Result.Ok(2);
|
|
880
|
+
* return a + b;
|
|
881
|
+
* });
|
|
882
|
+
* // Result<number, never>
|
|
883
|
+
* ```
|
|
884
|
+
*/
|
|
885
|
+
static gen(genFn) {
|
|
886
|
+
const iterator = genFn();
|
|
887
|
+
let nextArg;
|
|
888
|
+
let currentResult;
|
|
889
|
+
while (true) {
|
|
890
|
+
const next = iterator.next(nextArg);
|
|
891
|
+
if (next.done) {
|
|
892
|
+
currentResult = Result.Ok(next.value);
|
|
893
|
+
break;
|
|
894
|
+
}
|
|
895
|
+
let yielded = next.value;
|
|
896
|
+
let stack;
|
|
897
|
+
if (isCapturedTrace(yielded)) {
|
|
898
|
+
stack = yielded.stack;
|
|
899
|
+
yielded = yielded.value;
|
|
900
|
+
}
|
|
901
|
+
if (yielded.isErr()) {
|
|
902
|
+
const err = yielded.unwrapErr();
|
|
903
|
+
if (stack && err instanceof Error) {
|
|
904
|
+
const stackLines = stack.split("\n");
|
|
905
|
+
if (stackLines.length > 2) {
|
|
906
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
907
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
currentResult = yielded;
|
|
911
|
+
break;
|
|
912
|
+
}
|
|
913
|
+
nextArg = yielded.unwrap();
|
|
914
|
+
}
|
|
915
|
+
return currentResult;
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Generator-based syntax for chaining Result operations (with adapter).
|
|
919
|
+
* Uses an adapter function ($) for improved type inference.
|
|
920
|
+
*
|
|
921
|
+
* Short-circuits on first Err, returning that error. Uses iteration instead of
|
|
922
|
+
* recursion to avoid stack overflow on deep chains.
|
|
923
|
+
*
|
|
924
|
+
* @example
|
|
925
|
+
* ```ts
|
|
926
|
+
* const result = Result.genAdapter(function* ($) {
|
|
927
|
+
* const a = yield* $(Result.Ok(1));
|
|
928
|
+
* const b = yield* $(Result.Ok(2));
|
|
929
|
+
* return a + b;
|
|
930
|
+
* });
|
|
931
|
+
* // Result<number, never>
|
|
932
|
+
* ```
|
|
933
|
+
*/
|
|
934
|
+
static genAdapter(genFn) {
|
|
935
|
+
const adapter = (result) => new ResultYieldWrap(result);
|
|
936
|
+
const iterator = genFn(adapter);
|
|
937
|
+
let nextArg;
|
|
938
|
+
let currentResult;
|
|
939
|
+
while (true) {
|
|
940
|
+
const next = iterator.next(nextArg);
|
|
941
|
+
if (next.done) {
|
|
942
|
+
currentResult = Result.Ok(next.value);
|
|
943
|
+
break;
|
|
944
|
+
}
|
|
945
|
+
const wrapped = next.value;
|
|
946
|
+
let result = wrapped.result;
|
|
947
|
+
let stack;
|
|
948
|
+
if (isCapturedTrace(wrapped)) {
|
|
949
|
+
stack = wrapped.stack;
|
|
950
|
+
result = wrapped.value.result;
|
|
951
|
+
}
|
|
952
|
+
if (result.isErr()) {
|
|
953
|
+
const err = result.unwrapErr();
|
|
954
|
+
if (stack && err instanceof Error) {
|
|
955
|
+
const stackLines = stack.split("\n");
|
|
956
|
+
if (stackLines.length > 2) {
|
|
957
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
958
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
currentResult = result;
|
|
962
|
+
break;
|
|
963
|
+
}
|
|
964
|
+
nextArg = result.unwrap();
|
|
965
|
+
}
|
|
966
|
+
return currentResult;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Async generator-based syntax for chaining Result operations (simplified, no adapter).
|
|
970
|
+
* Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
|
|
971
|
+
*
|
|
972
|
+
* Short-circuits on first Err, returning that error. Uses async iteration instead of
|
|
973
|
+
* recursion to avoid stack overflow on deep chains.
|
|
974
|
+
*
|
|
975
|
+
* @example
|
|
976
|
+
* ```ts
|
|
977
|
+
* const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
|
|
978
|
+
* Promise.resolve(Result.Ok({ id }));
|
|
979
|
+
* const result = await Result.asyncGen(async function* () {
|
|
980
|
+
* const a = yield* Result.Ok(1);
|
|
981
|
+
* const dataResult = yield* await fetchData(a);
|
|
982
|
+
* return a + dataResult.id;
|
|
983
|
+
* });
|
|
984
|
+
* // Result<number, never>
|
|
985
|
+
* ```
|
|
986
|
+
*/
|
|
987
|
+
static async asyncGen(genFn) {
|
|
988
|
+
const iterator = genFn();
|
|
989
|
+
let nextArg;
|
|
990
|
+
let currentResult;
|
|
991
|
+
while (true) {
|
|
992
|
+
const next = await iterator.next(nextArg);
|
|
993
|
+
if (next.done) {
|
|
994
|
+
currentResult = Result.Ok(next.value);
|
|
995
|
+
break;
|
|
996
|
+
}
|
|
997
|
+
let result = next.value;
|
|
998
|
+
let stack;
|
|
999
|
+
if (isCapturedTrace(result)) {
|
|
1000
|
+
stack = result.stack;
|
|
1001
|
+
result = result.value;
|
|
1002
|
+
}
|
|
1003
|
+
if (result.isErr()) {
|
|
1004
|
+
const err = result.unwrapErr();
|
|
1005
|
+
if (stack && err instanceof Error) {
|
|
1006
|
+
const stackLines = stack.split("\n");
|
|
1007
|
+
if (stackLines.length > 2) {
|
|
1008
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
1009
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
currentResult = result;
|
|
1013
|
+
break;
|
|
1014
|
+
}
|
|
1015
|
+
nextArg = result.unwrap();
|
|
1016
|
+
}
|
|
1017
|
+
return currentResult;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Async generator-based syntax for chaining Result operations (with adapter).
|
|
1021
|
+
* Uses an adapter function ($) for improved type inference.
|
|
1022
|
+
* Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
|
|
1023
|
+
*
|
|
1024
|
+
* Short-circuits on first Err, returning that error. Uses async iteration instead of
|
|
1025
|
+
* recursion to avoid stack overflow on deep chains.
|
|
1026
|
+
*
|
|
1027
|
+
* @example
|
|
1028
|
+
* ```ts
|
|
1029
|
+
* const fetchData = (id: number): Promise<Result<{ id: number }, string>> =>
|
|
1030
|
+
* Promise.resolve(Result.Ok({ id }));
|
|
1031
|
+
* const result = await Result.asyncGenAdapter(async function* ($) {
|
|
1032
|
+
* const a = yield* $(Result.Ok(1));
|
|
1033
|
+
* const data = yield* $(fetchData(a));
|
|
1034
|
+
* return a + data.id;
|
|
1035
|
+
* });
|
|
1036
|
+
* // Result<number, never>
|
|
1037
|
+
* ```
|
|
1038
|
+
*/
|
|
1039
|
+
static async asyncGenAdapter(genFn) {
|
|
1040
|
+
const adapter = (result) => new AsyncResultYieldWrap(Promise.resolve(result));
|
|
1041
|
+
const iterator = genFn(adapter);
|
|
1042
|
+
let nextArg;
|
|
1043
|
+
let currentResult;
|
|
1044
|
+
while (true) {
|
|
1045
|
+
const next = await iterator.next(nextArg);
|
|
1046
|
+
if (next.done) {
|
|
1047
|
+
currentResult = Result.Ok(next.value);
|
|
1048
|
+
break;
|
|
1049
|
+
}
|
|
1050
|
+
const wrapped = next.value;
|
|
1051
|
+
let result;
|
|
1052
|
+
let stack;
|
|
1053
|
+
if (isCapturedTrace(wrapped)) {
|
|
1054
|
+
stack = wrapped.stack;
|
|
1055
|
+
result = await wrapped.value.result;
|
|
1056
|
+
} else result = await wrapped.result;
|
|
1057
|
+
if (result.isErr()) {
|
|
1058
|
+
const err = result.unwrapErr();
|
|
1059
|
+
if (stack && err instanceof Error) {
|
|
1060
|
+
const stackLines = stack.split("\n");
|
|
1061
|
+
if (stackLines.length > 2) {
|
|
1062
|
+
const userStack = stackLines.slice(2).join("\n");
|
|
1063
|
+
err.stack = `${err.name}: ${err.message}\n${userStack}`;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
currentResult = result;
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
nextArg = result.unwrap();
|
|
1070
|
+
}
|
|
1071
|
+
return currentResult;
|
|
1072
|
+
}
|
|
1073
|
+
};
|
|
1074
|
+
|
|
1075
|
+
//#endregion
|
|
1076
|
+
export { Result };
|
|
1077
|
+
//# sourceMappingURL=result.mjs.map
|