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