@carbonteq/fp 0.9.1 → 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 +310 -96
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs.map +1 -1
- 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 +26 -11
- package/dist/index.d.cts +8 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.mjs +8 -3
- package/dist/match.cjs +282 -0
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +471 -5
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +471 -5
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +277 -1
- package/dist/match.mjs.map +1 -1
- 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 +556 -29
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +505 -24
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +505 -24
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +556 -30
- package/dist/option.mjs.map +1 -1
- 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 +715 -122
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +785 -94
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +785 -94
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +714 -117
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -1
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +5 -1
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +2 -0
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +2 -0
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -0
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -0
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +15 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +10 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +10 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +13 -1
- package/dist/utils.mjs.map +1 -1
- 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 +50 -18
package/dist/result.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { UnwrappedErrWithOk, UnwrappedOkWithErr } from "./errors.mjs";
|
|
2
2
|
import { UNIT } from "./unit.mjs";
|
|
3
|
-
import { isPromiseLike } from "./utils.mjs";
|
|
3
|
+
import { CapturedTrace, isCapturedTrace, isPromiseLike } from "./utils.mjs";
|
|
4
4
|
import { Option } from "./option.mjs";
|
|
5
5
|
|
|
6
6
|
//#region src/result.ts
|
|
@@ -10,6 +10,40 @@ const ERR_VAL = Symbol("Result::Err");
|
|
|
10
10
|
const NO_ERR = Symbol("Result::NoErr");
|
|
11
11
|
/** Internal symbol for accessing private factory - not exported */
|
|
12
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
|
+
*/
|
|
13
47
|
var Result = class Result {
|
|
14
48
|
/** Discriminant tag for type-level identification */
|
|
15
49
|
_tag;
|
|
@@ -35,26 +69,57 @@ var Result = class Result {
|
|
|
35
69
|
}
|
|
36
70
|
/** Singleton UNIT_RESULT for void-success operations */
|
|
37
71
|
static UNIT_RESULT = new Result(UNIT, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
38
|
-
/**
|
|
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
|
+
*/
|
|
39
80
|
static Ok(val) {
|
|
40
81
|
return new Result(val, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
41
82
|
}
|
|
42
|
-
/**
|
|
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
|
+
*/
|
|
43
91
|
static Err(err) {
|
|
44
92
|
return new Result(ERR_VAL, err, { asyncErr: NO_ERR }, "Err");
|
|
45
93
|
}
|
|
46
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Type guard for Ok state.
|
|
96
|
+
*
|
|
97
|
+
* @returns true if this Result is Ok
|
|
98
|
+
*/
|
|
47
99
|
isOk() {
|
|
48
100
|
return this._tag === "Ok" && this.#ctx.asyncErr === NO_ERR;
|
|
49
101
|
}
|
|
50
|
-
/**
|
|
102
|
+
/**
|
|
103
|
+
* Type guard for Err state.
|
|
104
|
+
*
|
|
105
|
+
* @returns true if this Result is Err
|
|
106
|
+
*/
|
|
51
107
|
isErr() {
|
|
52
108
|
return this._tag === "Err" || this.#ctx.asyncErr !== NO_ERR || this._tag === "Ok" && this.#val === ERR_VAL;
|
|
53
109
|
}
|
|
54
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
* Type guard for Ok containing UNIT.
|
|
112
|
+
*
|
|
113
|
+
* @returns true if the Ok value is UNIT
|
|
114
|
+
*/
|
|
55
115
|
isUnit() {
|
|
56
116
|
return this.#val === UNIT;
|
|
57
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Returns a string representation of the Result.
|
|
120
|
+
*
|
|
121
|
+
* @returns "Result::Ok<value>" or "Result::Err<error>"
|
|
122
|
+
*/
|
|
58
123
|
toString() {
|
|
59
124
|
if (this.isOk()) return `Result::Ok<${String(this.#val)}>`;
|
|
60
125
|
return `Result::Err<${String(this.getErr())}>`;
|
|
@@ -119,7 +184,13 @@ var Result = class Result {
|
|
|
119
184
|
});
|
|
120
185
|
return curr === ERR_VAL ? null : curr;
|
|
121
186
|
}
|
|
122
|
-
/**
|
|
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
|
+
*/
|
|
123
194
|
match(cases) {
|
|
124
195
|
if (this.isErr()) return cases.Err(this.getErr());
|
|
125
196
|
return cases.Ok(this.#val);
|
|
@@ -131,13 +202,24 @@ var Result = class Result {
|
|
|
131
202
|
if (isPromiseLike(curr)) {
|
|
132
203
|
const p = curr;
|
|
133
204
|
const newCtx = { asyncErr: NO_ERR };
|
|
134
|
-
|
|
135
|
-
return new Result(out, parentErr, newCtx, "Ok");
|
|
205
|
+
return new Result(Result.safeMap(p, fn, newCtx, this.#ctx), parentErr, newCtx, "Ok");
|
|
136
206
|
}
|
|
137
207
|
const next = fn(curr);
|
|
138
208
|
if (isPromiseLike(next)) return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
139
209
|
return new Result(next, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
140
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
|
+
*/
|
|
141
223
|
static safeMap(p, mapper, ctx, parentCtx) {
|
|
142
224
|
return p.then((v) => {
|
|
143
225
|
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) {
|
|
@@ -147,6 +229,27 @@ var Result = class Result {
|
|
|
147
229
|
return mapper(v);
|
|
148
230
|
});
|
|
149
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
|
+
*/
|
|
150
253
|
mapErr(fn) {
|
|
151
254
|
if (this._tag === "Err") {
|
|
152
255
|
const mappedErr = fn(this.getErr());
|
|
@@ -156,18 +259,15 @@ var Result = class Result {
|
|
|
156
259
|
const parentCtx = this.#ctx;
|
|
157
260
|
if (isPromiseLike(curr)) {
|
|
158
261
|
const newCtx = { asyncErr: NO_ERR };
|
|
159
|
-
|
|
262
|
+
return new Result(curr.then((v) => {
|
|
160
263
|
if (v === ERR_VAL || parentCtx.asyncErr !== NO_ERR) newCtx.asyncErr = fn(parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err);
|
|
161
264
|
return v;
|
|
162
|
-
});
|
|
163
|
-
return new Result(p, void 0, newCtx, "Ok");
|
|
265
|
+
}), void 0, newCtx, "Ok");
|
|
164
266
|
}
|
|
165
267
|
return new Result(this.#val, void 0, { asyncErr: NO_ERR }, "Ok");
|
|
166
268
|
}
|
|
167
269
|
mapBoth(fnOk, fnErr) {
|
|
168
|
-
|
|
169
|
-
if (isPromiseLike(this.#val)) return this.map(fnOk);
|
|
170
|
-
return this.map(fnOk);
|
|
270
|
+
return this.map(fnOk).mapErr(fnErr);
|
|
171
271
|
}
|
|
172
272
|
flatMap(fn) {
|
|
173
273
|
if (this.isErr()) return new Result(ERR_VAL, this.getErr(), { asyncErr: NO_ERR }, "Err");
|
|
@@ -175,31 +275,48 @@ var Result = class Result {
|
|
|
175
275
|
const parentErr = this.#err;
|
|
176
276
|
const parentCtx = this.#ctx;
|
|
177
277
|
const newCtx = { asyncErr: NO_ERR };
|
|
178
|
-
if (isPromiseLike(curr)) {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
});
|
|
189
|
-
return new Result(newP, parentErr, newCtx, "Ok");
|
|
190
|
-
}
|
|
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");
|
|
191
288
|
const mapped = fn(curr);
|
|
192
|
-
if (isPromiseLike(mapped))
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
return new Result(mapped.#val, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
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");
|
|
198
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
|
+
*/
|
|
199
306
|
static flatMapHelper(mutableCtx, mapped) {
|
|
200
307
|
if (isPromiseLike(mapped)) return mapped.then((r) => Result.flatMapInnerHelper(mutableCtx, r));
|
|
201
308
|
return Result.flatMapInnerHelper(mutableCtx, mapped);
|
|
202
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
|
+
*/
|
|
203
320
|
static flatMapInnerHelper(mutableCtx, r) {
|
|
204
321
|
if (r._tag === "Err") {
|
|
205
322
|
mutableCtx.asyncErr = r.getErr();
|
|
@@ -222,23 +339,17 @@ var Result = class Result {
|
|
|
222
339
|
const parentErr = this.#err;
|
|
223
340
|
const parentCtx = this.#ctx;
|
|
224
341
|
const newCtx = { asyncErr: NO_ERR };
|
|
225
|
-
if (isPromiseLike(curr)) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
});
|
|
235
|
-
return new Result(newP, parentErr, newCtx, "Ok");
|
|
236
|
-
}
|
|
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");
|
|
237
351
|
const u = fn(curr);
|
|
238
|
-
if (isPromiseLike(u)) {
|
|
239
|
-
const p = u.then((uu) => [curr, uu]);
|
|
240
|
-
return new Result(p, parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
241
|
-
}
|
|
352
|
+
if (isPromiseLike(u)) return new Result(u.then((uu) => [curr, uu]), parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
242
353
|
return new Result([curr, u], parentErr, { asyncErr: NO_ERR }, "Ok");
|
|
243
354
|
}
|
|
244
355
|
flatZip(fn) {
|
|
@@ -247,27 +358,48 @@ var Result = class Result {
|
|
|
247
358
|
const parentErr = this.#err;
|
|
248
359
|
const parentCtx = this.#ctx;
|
|
249
360
|
const newCtx = { asyncErr: NO_ERR };
|
|
250
|
-
if (isPromiseLike(curr)) {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
});
|
|
259
|
-
return new Result(newP, parentErr, newCtx, "Ok");
|
|
260
|
-
}
|
|
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");
|
|
261
369
|
const mapped = fn(curr);
|
|
262
370
|
const p = Result.flatZipHelper(newCtx, curr, mapped);
|
|
263
371
|
if (isPromiseLike(p)) return new Result(p, parentErr, newCtx, "Ok");
|
|
264
372
|
if (p === ERR_VAL) return new Result(ERR_VAL, newCtx.asyncErr !== NO_ERR ? newCtx.asyncErr : parentErr, newCtx, "Err");
|
|
265
373
|
return new Result(p, parentErr, newCtx, "Ok");
|
|
266
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
|
+
*/
|
|
267
387
|
static flatZipHelper(mutableCtx, originalVal, mapped) {
|
|
268
388
|
if (isPromiseLike(mapped)) return mapped.then((r) => Result.flatZipInnerHelper(mutableCtx, originalVal, r));
|
|
269
389
|
return Result.flatZipInnerHelper(mutableCtx, originalVal, mapped);
|
|
270
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
|
+
*/
|
|
271
403
|
static flatZipInnerHelper(mutableCtx, originalVal, r) {
|
|
272
404
|
if (r._tag === "Err") {
|
|
273
405
|
mutableCtx.asyncErr = r.getErr();
|
|
@@ -293,31 +425,51 @@ var Result = class Result {
|
|
|
293
425
|
const parentErr = this.#err;
|
|
294
426
|
const parentCtx = this.#ctx;
|
|
295
427
|
const newCtx = { asyncErr: NO_ERR };
|
|
296
|
-
if (isPromiseLike(curr)) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
});
|
|
305
|
-
return new Result(newP$1, parentErr, newCtx, "Ok");
|
|
306
|
-
}
|
|
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");
|
|
307
436
|
const r = fn(curr);
|
|
308
437
|
const newP = Result.zipErrHelper(curr, r, newCtx);
|
|
309
438
|
if (isPromiseLike(newP)) return new Result(newP, parentErr, newCtx, "Ok");
|
|
310
439
|
if (newCtx.asyncErr !== NO_ERR) return new Result(ERR_VAL, newCtx.asyncErr, newCtx, "Err");
|
|
311
440
|
return new Result(newP, parentErr, newCtx, "Ok");
|
|
312
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
|
+
*/
|
|
313
452
|
static zipErrHelper(v, r, newCtx) {
|
|
314
453
|
if (isPromiseLike(r)) return r.then((newResult) => {
|
|
315
|
-
|
|
454
|
+
const maybeAwaited = Result.captureZipErr(newResult, newCtx);
|
|
455
|
+
if (isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
|
|
316
456
|
return v;
|
|
317
457
|
});
|
|
318
|
-
|
|
458
|
+
const maybeAwaited = Result.captureZipErr(r, newCtx);
|
|
459
|
+
if (isPromiseLike(maybeAwaited)) return maybeAwaited.then(() => v);
|
|
319
460
|
return v;
|
|
320
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
|
+
}
|
|
321
473
|
validate(validators) {
|
|
322
474
|
if (this.isErr()) return this;
|
|
323
475
|
const currVal = this.#val;
|
|
@@ -330,8 +482,8 @@ var Result = class Result {
|
|
|
330
482
|
return ERR_VAL;
|
|
331
483
|
}
|
|
332
484
|
const awaitedVal = c;
|
|
333
|
-
const results
|
|
334
|
-
return Promise.all(results
|
|
485
|
+
const results = validators.map((v) => v(awaitedVal));
|
|
486
|
+
return Promise.all(results).then((resolved) => Result.validateHelper(resolved, mutableCtx, awaitedVal));
|
|
335
487
|
}), parentErr, mutableCtx, "Ok");
|
|
336
488
|
const baseVal = currVal;
|
|
337
489
|
const results = validators.map((v) => v(baseVal));
|
|
@@ -341,6 +493,16 @@ var Result = class Result {
|
|
|
341
493
|
const combinedRes = Result.all(...syncResults);
|
|
342
494
|
return combinedRes.isErr() ? combinedRes : this;
|
|
343
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
|
+
*/
|
|
344
506
|
static validateHelper(results, currCtx, currVal) {
|
|
345
507
|
const combinedRes = Result.all(...results);
|
|
346
508
|
if (isPromiseLike(combinedRes.#val)) return combinedRes.#val.then((v) => {
|
|
@@ -359,27 +521,89 @@ var Result = class Result {
|
|
|
359
521
|
static all(...results) {
|
|
360
522
|
const vals = results.map((r) => r.#val);
|
|
361
523
|
const newCtx = { asyncErr: NO_ERR };
|
|
362
|
-
if (vals.some(isPromiseLike)) {
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
});
|
|
372
|
-
return new Result(p, [], newCtx, "Ok");
|
|
373
|
-
}
|
|
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");
|
|
374
533
|
const errs = [];
|
|
375
534
|
for (const r of results) if (r._tag === "Err") errs.push(r.getErr());
|
|
376
535
|
if (errs.length > 0) return Result.Err(errs);
|
|
377
536
|
return Result.Ok(vals);
|
|
378
537
|
}
|
|
379
|
-
/**
|
|
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
|
+
*/
|
|
380
577
|
static any(...results) {
|
|
381
|
-
|
|
382
|
-
|
|
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");
|
|
383
607
|
}
|
|
384
608
|
tap(fn) {
|
|
385
609
|
if (this.isErr()) return this;
|
|
@@ -387,62 +611,179 @@ var Result = class Result {
|
|
|
387
611
|
const parentCtx = this.#ctx;
|
|
388
612
|
if (isPromiseLike(curr)) {
|
|
389
613
|
const newCtx = { asyncErr: NO_ERR };
|
|
390
|
-
|
|
614
|
+
return new Result(curr.then((v) => {
|
|
391
615
|
if (v !== ERR_VAL && parentCtx.asyncErr === NO_ERR) fn(v);
|
|
392
616
|
else newCtx.asyncErr = parentCtx.asyncErr !== NO_ERR ? parentCtx.asyncErr : this.#err;
|
|
393
617
|
return v;
|
|
394
|
-
});
|
|
395
|
-
return new Result(newPromise, this.#err, newCtx, "Ok");
|
|
618
|
+
}), this.#err, newCtx, "Ok");
|
|
396
619
|
}
|
|
397
620
|
fn(curr);
|
|
398
621
|
return this;
|
|
399
622
|
}
|
|
400
|
-
/**
|
|
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
|
+
*/
|
|
401
646
|
tapErr(fn) {
|
|
402
647
|
if (this.isErr()) fn(this.getErr());
|
|
403
648
|
return this;
|
|
404
649
|
}
|
|
405
|
-
/**
|
|
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
|
+
*/
|
|
406
670
|
flip() {
|
|
407
671
|
if (this.isErr()) return new Result(this.getErr(), void 0, { asyncErr: NO_ERR }, "Ok");
|
|
408
672
|
return new Result(ERR_VAL, this.#val, { asyncErr: NO_ERR }, "Err");
|
|
409
673
|
}
|
|
410
|
-
/**
|
|
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
|
+
*/
|
|
411
696
|
toOption() {
|
|
412
697
|
if (this.isErr()) return Option.None;
|
|
413
698
|
return Option.Some(this.#val);
|
|
414
699
|
}
|
|
415
|
-
/**
|
|
700
|
+
/**
|
|
701
|
+
* Resolves the inner promise while preserving Result structure.
|
|
702
|
+
*
|
|
703
|
+
* @returns Promise of Result with awaited value or Err
|
|
704
|
+
*/
|
|
416
705
|
async toPromise() {
|
|
417
706
|
const v = await this.#val;
|
|
418
|
-
if (v === ERR_VAL || this.#ctx.asyncErr !== NO_ERR) {
|
|
419
|
-
const errVal = this.#ctx.asyncErr !== NO_ERR ? this.#ctx.asyncErr : this.#err;
|
|
420
|
-
return new Result(ERR_VAL, errVal, { asyncErr: NO_ERR }, "Err");
|
|
421
|
-
}
|
|
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");
|
|
422
708
|
return new Result(v, this.#err, { asyncErr: NO_ERR }, "Ok");
|
|
423
709
|
}
|
|
424
|
-
/**
|
|
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
|
+
*/
|
|
425
726
|
innerMap(mapper) {
|
|
426
727
|
if (this.isErr()) return this;
|
|
427
728
|
if (Array.isArray(this.#val)) return new Result(this.#val.map(mapper), this.#err, this.#ctx, "Ok");
|
|
428
729
|
throw new Error("Can only be called for Result<Array<T>, E>");
|
|
429
730
|
}
|
|
430
|
-
/**
|
|
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
|
+
*/
|
|
431
741
|
orElse(fn) {
|
|
432
742
|
if (this.isOk()) return this;
|
|
433
743
|
return fn(this.getErr());
|
|
434
744
|
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
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) {
|
|
438
757
|
return val === null || val === void 0 ? Result.Err(error) : Result.Ok(val);
|
|
439
758
|
}
|
|
440
|
-
|
|
441
|
-
|
|
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) {
|
|
442
772
|
return pred(val) ? Result.Ok(val) : Result.Err(error);
|
|
443
773
|
}
|
|
444
|
-
|
|
445
|
-
|
|
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) {
|
|
446
787
|
const ctx = { asyncErr: NO_ERR };
|
|
447
788
|
const p = promise.then((innerResult) => {
|
|
448
789
|
if (innerResult.isErr()) {
|
|
@@ -455,16 +796,36 @@ var Result = class Result {
|
|
|
455
796
|
});
|
|
456
797
|
return Result[RESULT_INTERNAL].create(p, void 0, ctx, "Ok");
|
|
457
798
|
}
|
|
458
|
-
|
|
459
|
-
|
|
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) {
|
|
460
809
|
try {
|
|
461
810
|
return Result.Ok(fn());
|
|
462
811
|
} catch (e) {
|
|
463
812
|
return Result.Err(errorMapper ? errorMapper(e) : e);
|
|
464
813
|
}
|
|
465
814
|
}
|
|
466
|
-
|
|
467
|
-
|
|
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) {
|
|
468
829
|
const ctx = { asyncErr: NO_ERR };
|
|
469
830
|
const pWithErr = fn().then((v) => v).catch((e) => {
|
|
470
831
|
ctx.asyncErr = errorMapper ? errorMapper(e) : e;
|
|
@@ -472,8 +833,244 @@ var Result = class Result {
|
|
|
472
833
|
});
|
|
473
834
|
return Result[RESULT_INTERNAL].create(pWithErr, void 0, ctx, "Ok");
|
|
474
835
|
}
|
|
475
|
-
|
|
476
|
-
|
|
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
|
+
};
|
|
477
1074
|
|
|
478
1075
|
//#endregion
|
|
479
1076
|
export { Result };
|