@qlever-llc/result 0.6.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/esm/result.js ADDED
@@ -0,0 +1,1033 @@
1
+ /**
2
+ * A class-based Result<T, E> system inspired by Rust's Result type.
3
+ *
4
+ * This module provides Result and AsyncResult classes for elegant error handling
5
+ * with method chaining and the `take()` pattern for early returns.
6
+ *
7
+ * @module @qlever-llc/result
8
+ */
9
+ import { UnexpectedError } from "./error.js";
10
+ function isOkValue(value) {
11
+ return value.success;
12
+ }
13
+ function isErrValue(value) {
14
+ return !value.success;
15
+ }
16
+ /**
17
+ * A synchronous Result class that represents either success (Ok) or failure (Err).
18
+ *
19
+ * Provides method chaining for transformations and the `take()` pattern for
20
+ * unwrapping values with early returns.
21
+ *
22
+ * @template T - The type of the success value
23
+ * @template E - The type of the error (must extend BaseError)
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * function divide(a: number, b: number): Result<number, ValidationError> {
28
+ * if (b === 0) {
29
+ * return Result.err(new ValidationError("Division by zero"));
30
+ * }
31
+ * return Result.ok(a / b);
32
+ * }
33
+ *
34
+ * const result = divide(10, 2)
35
+ * .map(x => x * 2)
36
+ * .map(x => x + 1);
37
+ *
38
+ * const value = result.take();
39
+ * if (isErr(value)) return value;
40
+ * console.log(value); // 11
41
+ * ```
42
+ */
43
+ export class Result {
44
+ constructor(_value) {
45
+ Object.defineProperty(this, "_value", {
46
+ enumerable: true,
47
+ configurable: true,
48
+ writable: true,
49
+ value: _value
50
+ });
51
+ }
52
+ /**
53
+ * Creates a successful Result containing a value.
54
+ *
55
+ * @template T - The type of the success value
56
+ * @template E - The type of the error (defaults to never)
57
+ * @param value - The success value to wrap
58
+ * @returns A Result instance containing the value
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const result = Result.ok(42);
63
+ * const value = result.take();
64
+ * if (!isErr(value)) {
65
+ * console.log(value); // 42
66
+ * }
67
+ * ```
68
+ */
69
+ static ok(value) {
70
+ return new Result({ success: true, value });
71
+ }
72
+ /**
73
+ * Creates a failed Result containing an error.
74
+ *
75
+ * @template E - The type of the error (must extend BaseError)
76
+ * @template T - The type of the success value (defaults to never)
77
+ * @param error - The error to wrap
78
+ * @returns A Result instance containing the error
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const result = Result.err(new ValidationError("Invalid input"));
83
+ * const value = result.take();
84
+ * if (isErr(value)) {
85
+ * console.error(value.error.message); // "Invalid input"
86
+ * }
87
+ * ```
88
+ */
89
+ static err(error) {
90
+ return new Result({ success: false, error });
91
+ }
92
+ /**
93
+ * Wraps a function that might throw into a Result.
94
+ *
95
+ * Catches any exceptions and wraps them in UnexpectedError.
96
+ *
97
+ * @template T - The type of the return value
98
+ * @param fn - Function that might throw
99
+ * @param context - Optional context to add to the error
100
+ * @returns Ok with the return value, or Err with UnexpectedError
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * const obj = Result.try(() =>
105
+ * typeof data === "string" ? JSON.parse(data) : data
106
+ * );
107
+ *
108
+ * const value = obj.take();
109
+ * if (isErr(value)) {
110
+ * console.error("Parse failed:", value.error);
111
+ * return;
112
+ * }
113
+ * console.log(value); // parsed object
114
+ * ```
115
+ */
116
+ static try(fn, context) {
117
+ try {
118
+ return Result.ok(fn());
119
+ }
120
+ catch (cause) {
121
+ return Result.err(new UnexpectedError({ cause }).withContext(context));
122
+ }
123
+ }
124
+ /**
125
+ * Type guard to check if a value is an Ok Result.
126
+ *
127
+ * @template T - The type of the success value
128
+ * @template E - The type of the error
129
+ * @param result - The Result to check
130
+ * @returns True if the result is Ok, false otherwise
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * const result = Result.ok(42);
135
+ * if (Result.isOk(result)) {
136
+ * // TypeScript knows result is Ok<number> here
137
+ * }
138
+ * ```
139
+ */
140
+ static isOk(result) {
141
+ return result.isOk();
142
+ }
143
+ static isErr(value) {
144
+ // Check if it's a Result instance
145
+ if (value instanceof Result) {
146
+ return value.isErr();
147
+ }
148
+ // For non-Result values, return false
149
+ return false;
150
+ }
151
+ /**
152
+ * Combines multiple Results into a single Result containing an array.
153
+ *
154
+ * If all Results are Ok, returns Ok with an array of all values.
155
+ * If any Result is Err, returns the first Err encountered.
156
+ *
157
+ * @template T - The type of the Ok values
158
+ * @template E - The type of the errors
159
+ * @param results - Array of Results to combine
160
+ * @returns Ok with array of values, or the first Err
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * const results = [Result.ok(1), Result.ok(2), Result.ok(3)];
165
+ * const combined = Result.all(results);
166
+ * // Ok([1, 2, 3])
167
+ *
168
+ * const withError = [Result.ok(1), Result.err(new ValidationError("Failed")), Result.ok(3)];
169
+ * const combined2 = Result.all(withError);
170
+ * // Err(ValidationError)
171
+ * ```
172
+ */
173
+ static all(results) {
174
+ const values = [];
175
+ for (const result of results) {
176
+ if (result.isErr()) {
177
+ return result;
178
+ }
179
+ const resultValue = result._unsafeValue();
180
+ if (resultValue.success) {
181
+ values.push(resultValue.value);
182
+ }
183
+ }
184
+ return Result.ok(values);
185
+ }
186
+ /**
187
+ * Returns the first Ok result from an array of Results.
188
+ *
189
+ * If any Result is Ok, returns that Ok result.
190
+ * If all Results are Err, returns the last Err.
191
+ *
192
+ * @template T - The type of the Ok values
193
+ * @template E - The type of the errors
194
+ * @param results - Array of Results to check
195
+ * @returns The first Ok, or the last Err if all failed
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const results = [Result.err(new Error("e1")), Result.ok(2), Result.ok(3)];
200
+ * const first = Result.any(results);
201
+ * // Ok(2)
202
+ *
203
+ * const allErrors = [
204
+ * Result.err(new Error("e1")),
205
+ * Result.err(new Error("e2")),
206
+ * Result.err(new Error("e3"))
207
+ * ];
208
+ * const first2 = Result.any(allErrors);
209
+ * // Err(Error("e3")) - the last error
210
+ * ```
211
+ */
212
+ static any(results) {
213
+ for (const result of results) {
214
+ if (result.isOk()) {
215
+ return result;
216
+ }
217
+ }
218
+ return results[results.length - 1];
219
+ }
220
+ /**
221
+ * Type guard to check if this Result is Ok.
222
+ *
223
+ * @returns True if this result is Ok, false otherwise
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * const result = Result.ok(42);
228
+ * if (result.isOk()) {
229
+ * // TypeScript knows result is Ok here
230
+ * }
231
+ * ```
232
+ */
233
+ isOk() {
234
+ return this._value.success === true;
235
+ }
236
+ /**
237
+ * Type guard to check if this Result is Err.
238
+ *
239
+ * @returns True if this result is Err, false otherwise
240
+ *
241
+ * @example
242
+ * ```typescript
243
+ * const result = Result.err(new ValidationError("Failed"));
244
+ * if (result.isErr()) {
245
+ * // TypeScript knows result is Err here
246
+ * }
247
+ * ```
248
+ */
249
+ isErr() {
250
+ return this._value.success === false;
251
+ }
252
+ /**
253
+ * Transforms the Ok value using a mapper function, leaving Err untouched.
254
+ *
255
+ * @template U - The type of the transformed value
256
+ * @param fn - Function to transform the Ok value
257
+ * @returns A new Result with the transformed value, or the original Err
258
+ *
259
+ * @example
260
+ * ```typescript
261
+ * const result = Result.ok(5)
262
+ * .map(x => x * 2)
263
+ * .map(x => x.toString());
264
+ *
265
+ * const value = result.take();
266
+ * if (!isErr(value)) {
267
+ * console.log(value); // "10"
268
+ * }
269
+ * ```
270
+ */
271
+ map(fn) {
272
+ const value = this._value;
273
+ if (isOkValue(value)) {
274
+ return Result.ok(fn(value.value));
275
+ }
276
+ return Result.err(value.error);
277
+ }
278
+ /**
279
+ * Transforms the Err value using a mapper function, leaving Ok untouched.
280
+ *
281
+ * @template F - The type of the transformed error
282
+ * @param fn - Function to transform the Err value
283
+ * @returns A new Result with the transformed error, or the original Ok
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * const result = Result.err(new ValidationError("Failed"))
288
+ * .mapErr(e => new NetworkError({ cause: e }));
289
+ * ```
290
+ */
291
+ mapErr(fn) {
292
+ const value = this._value;
293
+ if (isOkValue(value)) {
294
+ return Result.ok(value.value);
295
+ }
296
+ return Result.err(fn(value.error));
297
+ }
298
+ /**
299
+ * Chains operations that return Results (also known as flatMap).
300
+ *
301
+ * If this Result is Ok, calls the function with the Ok value and returns its Result.
302
+ * If this Result is Err, returns the Err without calling the function.
303
+ *
304
+ * @template U - The type of the new Ok value
305
+ * @template F - The type of the new error
306
+ * @param fn - Function that takes the Ok value and returns a new Result
307
+ * @returns The Result from calling fn, or the original Err
308
+ *
309
+ * @example
310
+ * ```typescript
311
+ * function parseNumber(s: string): Result<number, ValidationError> {
312
+ * const n = Number(s);
313
+ * if (isNaN(n)) {
314
+ * return Result.err(new ValidationError("Not a number"));
315
+ * }
316
+ * return Result.ok(n);
317
+ * }
318
+ *
319
+ * const result = Result.ok("42")
320
+ * .andThen(parseNumber)
321
+ * .map(x => x * 2);
322
+ * ```
323
+ */
324
+ andThen(fn) {
325
+ const value = this._value;
326
+ if (isOkValue(value)) {
327
+ return fn(value.value);
328
+ }
329
+ return Result.err(value.error);
330
+ }
331
+ /**
332
+ * Extracts the value from Ok or returns the Err for early returns.
333
+ *
334
+ * This is the equivalent of Rust's `?` operator. Use it with `isErr()` for
335
+ * early returns in functions that return Results.
336
+ *
337
+ * Returns either:
338
+ * - The unwrapped value T if this result is Ok
339
+ * - An Err Result<never, E> if this result is Err (can be directly returned)
340
+ *
341
+ * @returns The unwrapped value or Err Result
342
+ *
343
+ * @example
344
+ * ```typescript
345
+ * function processData(input: string): Result<number, ValidationError> {
346
+ * const parsed = parseInput(input).take();
347
+ * if (isErr(parsed)) return parsed;
348
+ *
349
+ * const validated = validate(parsed).take();
350
+ * if (isErr(validated)) return validated;
351
+ *
352
+ * return Result.ok(validated * 2);
353
+ * }
354
+ * ```
355
+ */
356
+ take() {
357
+ const value = this._value;
358
+ if (isOkValue(value)) {
359
+ return value.value;
360
+ }
361
+ return Result.err(value.error);
362
+ }
363
+ /**
364
+ * Adds context to an Err result for early returns.
365
+ * Chainable with take() for adding context when propagating errors.
366
+ *
367
+ * @param message - Context message describing the operation that failed
368
+ * @param extra - Optional additional context data
369
+ * @returns This Result with context added to the error
370
+ *
371
+ * @example
372
+ * ```typescript
373
+ * const user = await getUser(id).take();
374
+ * if (isErr(user)) return user.context("failed to fetch user");
375
+ *
376
+ * // With extra data:
377
+ * if (isErr(user)) return user.context("failed to fetch user", { userId: id });
378
+ * ```
379
+ */
380
+ context(message, extra) {
381
+ const value = this._value;
382
+ if (isErrValue(value)) {
383
+ const contextData = extra ? { message, ...extra } : { message };
384
+ value.error.withContext(contextData);
385
+ }
386
+ return this;
387
+ }
388
+ /**
389
+ * Pattern matching for Results - handle both Ok and Err cases.
390
+ *
391
+ * @template U - The type of the return value
392
+ * @param pattern - Object with ok and err handler functions
393
+ * @returns The result of calling either the ok or err handler
394
+ *
395
+ * @example
396
+ * ```typescript
397
+ * const message = result.match({
398
+ * ok: (value) => `Success: ${value}`,
399
+ * err: (error) => `Error: ${error.message}`
400
+ * });
401
+ * ```
402
+ */
403
+ match(pattern) {
404
+ const value = this._value;
405
+ if (isOkValue(value)) {
406
+ return pattern.ok(value.value);
407
+ }
408
+ return pattern.err(value.error);
409
+ }
410
+ /**
411
+ * Returns the Ok value or a default value if Err.
412
+ *
413
+ * @template U - The type of the default value
414
+ * @param defaultValue - The value to return if this result is Err
415
+ * @returns The Ok value or the default value
416
+ *
417
+ * @example
418
+ * ```typescript
419
+ * const value = result.unwrapOr(0);
420
+ * console.log(value); // 42 or 0
421
+ * ```
422
+ */
423
+ unwrapOr(defaultValue) {
424
+ const value = this._value;
425
+ if (isOkValue(value)) {
426
+ return value.value;
427
+ }
428
+ return defaultValue;
429
+ }
430
+ /**
431
+ * Returns the Ok value or computes a default from the error.
432
+ *
433
+ * @template U - The type of the default value
434
+ * @param fn - Function to compute the default value from the error
435
+ * @returns The Ok value or the computed default value
436
+ *
437
+ * @example
438
+ * ```typescript
439
+ * const value = result.unwrapOrElse(error => {
440
+ * console.error(error);
441
+ * return 0;
442
+ * });
443
+ * ```
444
+ */
445
+ unwrapOrElse(fn) {
446
+ const value = this._value;
447
+ if (isOkValue(value)) {
448
+ return value.value;
449
+ }
450
+ return fn(value.error);
451
+ }
452
+ /**
453
+ * Returns this result if Ok, otherwise returns the fallback result.
454
+ *
455
+ * @template U - The type of the fallback Ok value
456
+ * @param other - The fallback Result to use if this is Err
457
+ * @returns This result if Ok, otherwise the fallback
458
+ *
459
+ * @example
460
+ * ```typescript
461
+ * const result = fetchFromCache()
462
+ * .or(fetchFromDatabase())
463
+ * .or(fetchFromAPI());
464
+ * ```
465
+ */
466
+ or(other) {
467
+ if (isOkValue(this._value)) {
468
+ return this;
469
+ }
470
+ return other;
471
+ }
472
+ /**
473
+ * Returns this result if Ok, otherwise computes a fallback from the error.
474
+ *
475
+ * @template R - The Result type returned by the fallback function
476
+ * @param fn - Function to compute a fallback Result from the error
477
+ * @returns This result if Ok, otherwise the computed fallback
478
+ *
479
+ * @example
480
+ * ```typescript
481
+ * const result = fetchData().orElse(error => {
482
+ * console.warn("Primary failed, trying backup");
483
+ * return fetchBackup();
484
+ * });
485
+ * ```
486
+ */
487
+ orElse(fn) {
488
+ const value = this._value;
489
+ if (isOkValue(value)) {
490
+ return Result.ok(value.value);
491
+ }
492
+ return fn(value.error);
493
+ }
494
+ /**
495
+ * Performs a side effect on the Ok value without changing the Result.
496
+ *
497
+ * @param fn - Function to call with the Ok value (if Ok)
498
+ * @returns This Result, unchanged
499
+ *
500
+ * @example
501
+ * ```typescript
502
+ * const result = fetchUser("123")
503
+ * .inspect(user => console.log("Fetched:", user))
504
+ * .map(user => user.name);
505
+ * ```
506
+ */
507
+ inspect(fn) {
508
+ const value = this._value;
509
+ if (isOkValue(value)) {
510
+ fn(value.value);
511
+ }
512
+ return this;
513
+ }
514
+ /**
515
+ * Performs a side effect on the Err value without changing the Result.
516
+ *
517
+ * @param fn - Function to call with the error value (if Err)
518
+ * @returns This Result, unchanged
519
+ *
520
+ * @example
521
+ * ```typescript
522
+ * const result = fetchUser("123")
523
+ * .inspectErr(error => console.error("Failed:", error))
524
+ * .map(user => user.name);
525
+ * ```
526
+ */
527
+ inspectErr(fn) {
528
+ const value = this._value;
529
+ if (isErrValue(value)) {
530
+ fn(value.error);
531
+ }
532
+ return this;
533
+ }
534
+ /**
535
+ * Gets the error from an Err Result.
536
+ *
537
+ * Only call this after checking `isErr()`. If called on Ok, throws an error.
538
+ *
539
+ * @returns The error value
540
+ *
541
+ * @example
542
+ * ```typescript
543
+ * const result = err(new ValidationError("Failed"));
544
+ * if (result.isErr()) {
545
+ * console.log(result.error.message); // "Failed"
546
+ * }
547
+ * ```
548
+ */
549
+ get error() {
550
+ const value = this._value;
551
+ if (isErrValue(value)) {
552
+ return value.error;
553
+ }
554
+ throw new Error("Called .error on an Ok Result");
555
+ }
556
+ /**
557
+ * Internal method to get the raw value (for testing/debugging).
558
+ * Not recommended for general use - prefer take() instead.
559
+ */
560
+ _unsafeValue() {
561
+ return this._value;
562
+ }
563
+ }
564
+ /**
565
+ * An asynchronous Result class that represents a Promise of Result<T, E>.
566
+ *
567
+ * Implements PromiseLike to be awaitable, and provides async versions of
568
+ * all Result methods that return AsyncResult for seamless chaining.
569
+ *
570
+ * @template T - The type of the success value
571
+ * @template E - The type of the error (must extend BaseError)
572
+ *
573
+ * @example
574
+ * ```typescript
575
+ * async function fetchUser(id: string): AsyncResult<User, NetworkError> {
576
+ * return AsyncResult.wrap(async () => {
577
+ * const response = await fetch(`/api/users/${id}`);
578
+ * return await response.json();
579
+ * });
580
+ * }
581
+ *
582
+ * const result = fetchUser("123")
583
+ * .map(user => user.name)
584
+ * .map(name => name.toUpperCase());
585
+ *
586
+ * const value = await result.take();
587
+ * if (isErr(value)) return value;
588
+ * console.log(value); // "ALICE"
589
+ * ```
590
+ */
591
+ export class AsyncResult {
592
+ constructor(promise) {
593
+ Object.defineProperty(this, "promise", {
594
+ enumerable: true,
595
+ configurable: true,
596
+ writable: true,
597
+ value: promise
598
+ });
599
+ }
600
+ /**
601
+ * Creates an AsyncResult from a Promise of Result.
602
+ *
603
+ * @template T - The type of the success value
604
+ * @template E - The type of the error
605
+ * @param promise - The promise that resolves to a Result
606
+ * @returns An AsyncResult wrapping the promise
607
+ *
608
+ * @example
609
+ * ```typescript
610
+ * const asyncResult = AsyncResult.from(fetchData());
611
+ * ```
612
+ */
613
+ static from(promise) {
614
+ return new AsyncResult(promise);
615
+ }
616
+ /**
617
+ * Creates a successful AsyncResult with the given value.
618
+ *
619
+ * @template T - The type of the Ok value
620
+ * @template E - The type of the error (defaults to never)
621
+ * @param value - The value to wrap in an Ok AsyncResult
622
+ * @returns AsyncResult in the Ok state
623
+ *
624
+ * @example
625
+ * ```typescript
626
+ * const result = AsyncResult.ok(42);
627
+ * const value = await result.take();
628
+ * console.log(value); // 42
629
+ * ```
630
+ */
631
+ static ok(value) {
632
+ return new AsyncResult(Promise.resolve(Result.ok(value)));
633
+ }
634
+ /**
635
+ * Creates a failed AsyncResult with the given error.
636
+ *
637
+ * @template E - The type of the error
638
+ * @template T - The type of the Ok value (defaults to never)
639
+ * @param error - The error to wrap in an Err AsyncResult
640
+ * @returns AsyncResult in the Err state
641
+ *
642
+ * @example
643
+ * ```typescript
644
+ * const result = AsyncResult.err(new ValidationError("Invalid input"));
645
+ * const value = await result.take();
646
+ * if (Result.isErr(value)) {
647
+ * console.error(value.error.message); // "Invalid input"
648
+ * }
649
+ * ```
650
+ */
651
+ static err(error) {
652
+ return new AsyncResult(Promise.resolve(Result.err(error)));
653
+ }
654
+ /**
655
+ * Creates an AsyncResult from a Result, AsyncResult, or Promise<Result>.
656
+ *
657
+ * This is the key method for working with MaybeAsync types - it normalizes
658
+ * both synchronous Results and asynchronous AsyncResults into AsyncResults.
659
+ *
660
+ * @template T - The type of the success value
661
+ * @template E - The type of the error
662
+ * @param value - A Result, AsyncResult, or Promise<Result>
663
+ * @returns An AsyncResult
664
+ *
665
+ * @example
666
+ * ```typescript
667
+ * const asyncResult = AsyncResult.lift(Result.ok(42));
668
+ * const asyncResult2 = AsyncResult.lift(Promise.resolve(Result.ok(42)));
669
+ * const asyncResult3 = AsyncResult.lift(existingAsyncResult); // Pass-through
670
+ * ```
671
+ */
672
+ static lift(value) {
673
+ if (value instanceof AsyncResult) {
674
+ return value; // Already an AsyncResult, just return it
675
+ }
676
+ if (value instanceof Promise) {
677
+ return new AsyncResult(value);
678
+ }
679
+ return new AsyncResult(Promise.resolve(value));
680
+ }
681
+ /**
682
+ * Wraps an async function that might throw into an AsyncResult.
683
+ *
684
+ * Catches any exceptions and wraps them in UnexpectedError.
685
+ *
686
+ * @template T - The type of the return value
687
+ * @param fn - Async function that might throw
688
+ * @param context - Optional context to add to the error
689
+ * @returns AsyncResult with the return value or UnexpectedError
690
+ *
691
+ * @example
692
+ * ```typescript
693
+ * const user = AsyncResult.try(async () => {
694
+ * const response = await fetch("/api/user");
695
+ * return await response.json();
696
+ * });
697
+ *
698
+ * const value = await user.take();
699
+ * if (isErr(value)) {
700
+ * console.error("Fetch failed:", value.error);
701
+ * return;
702
+ * }
703
+ * console.log(value); // user object
704
+ * ```
705
+ */
706
+ static try(fn, context) {
707
+ return new AsyncResult((async () => {
708
+ try {
709
+ const value = await fn();
710
+ return Result.ok(value);
711
+ }
712
+ catch (cause) {
713
+ return Result.err(new UnexpectedError({ cause }).withContext(context));
714
+ }
715
+ })());
716
+ }
717
+ /**
718
+ * Combines multiple AsyncResults into a single AsyncResult containing an array.
719
+ *
720
+ * If all Results are Ok, returns Ok with an array of all values.
721
+ * If any Result is Err, returns the first Err encountered.
722
+ *
723
+ * @template T - The type of the Ok values
724
+ * @template E - The type of the errors
725
+ * @param results - Array of AsyncResults or Promises to combine
726
+ * @returns AsyncResult with array of values, or the first Err
727
+ *
728
+ * @example
729
+ * ```typescript
730
+ * const users = await AsyncResult.all([
731
+ * fetchUser("1"),
732
+ * fetchUser("2"),
733
+ * fetchUser("3")
734
+ * ]).take();
735
+ *
736
+ * if (Result.isErr(users)) {
737
+ * console.error("Failed to fetch users");
738
+ * } else {
739
+ * console.log(users); // [user1, user2, user3]
740
+ * }
741
+ * ```
742
+ */
743
+ static all(results) {
744
+ return new AsyncResult((async () => {
745
+ const resolvedResults = await Promise.all(results.map(async (r) => {
746
+ if (r instanceof AsyncResult) {
747
+ const res = await r;
748
+ return res;
749
+ }
750
+ return r;
751
+ }));
752
+ const values = [];
753
+ for (const result of resolvedResults) {
754
+ if (result.isErr()) {
755
+ return result;
756
+ }
757
+ const resultValue = result._unsafeValue();
758
+ if (resultValue.success) {
759
+ values.push(resultValue.value);
760
+ }
761
+ }
762
+ return Result.ok(values);
763
+ })());
764
+ }
765
+ /**
766
+ * Returns the first Ok result from an array of AsyncResults.
767
+ *
768
+ * If any Result is Ok, returns that Ok result.
769
+ * If all Results are Err, returns the last Err.
770
+ *
771
+ * @template T - The type of the Ok values
772
+ * @template E - The type of the errors
773
+ * @param results - Array of AsyncResults or Promises to check
774
+ * @returns AsyncResult with the first Ok, or the last Err
775
+ *
776
+ * @example
777
+ * ```typescript
778
+ * const data = await AsyncResult.any([
779
+ * fetchFromPrimary(),
780
+ * fetchFromSecondary(),
781
+ * fetchFromBackup()
782
+ * ]).take();
783
+ *
784
+ * if (Result.isErr(data)) {
785
+ * console.error("All sources failed");
786
+ * } else {
787
+ * console.log(data); // First successful result
788
+ * }
789
+ * ```
790
+ */
791
+ static any(results) {
792
+ return new AsyncResult((async () => {
793
+ const resolvedResults = await Promise.all(results.map(async (r) => {
794
+ if (r instanceof AsyncResult) {
795
+ const res = await r;
796
+ return res;
797
+ }
798
+ return r;
799
+ }));
800
+ for (const result of resolvedResults) {
801
+ if (result.isOk()) {
802
+ return result;
803
+ }
804
+ }
805
+ return resolvedResults[resolvedResults.length - 1];
806
+ })());
807
+ }
808
+ /**
809
+ * Implements PromiseLike to make AsyncResult awaitable.
810
+ *
811
+ * @template TResult1 - The type when fulfilled
812
+ * @template TResult2 - The type when rejected
813
+ * @param onfulfilled - Callback for when the promise is fulfilled
814
+ * @param onrejected - Callback for when the promise is rejected
815
+ * @returns A Promise of the result
816
+ */
817
+ then(onfulfilled, onrejected) {
818
+ return this.promise.then(onfulfilled, onrejected);
819
+ }
820
+ /**
821
+ * Transforms the Ok value using a mapper function, leaving Err untouched.
822
+ *
823
+ * @template U - The type of the transformed value
824
+ * @param fn - Function to transform the Ok value
825
+ * @returns A new AsyncResult with the transformed value
826
+ *
827
+ * @example
828
+ * ```typescript
829
+ * const result = fetchUser("123")
830
+ * .map(user => user.name)
831
+ * .map(name => name.toUpperCase());
832
+ * ```
833
+ */
834
+ map(fn) {
835
+ return new AsyncResult(this.promise.then((result) => result.map(fn)));
836
+ }
837
+ /**
838
+ * Transforms the Err value using a mapper function, leaving Ok untouched.
839
+ *
840
+ * @template F - The type of the transformed error
841
+ * @param fn - Function to transform the Err value
842
+ * @returns A new AsyncResult with the transformed error
843
+ *
844
+ * @example
845
+ * ```typescript
846
+ * const result = fetchUser("123")
847
+ * .mapErr(e => new NetworkError({ cause: e }));
848
+ * ```
849
+ */
850
+ mapErr(fn) {
851
+ return new AsyncResult(this.promise.then((result) => result.mapErr(fn)));
852
+ }
853
+ /**
854
+ * Chains operations that return Results.
855
+ *
856
+ * @template R - The Result type returned by the function
857
+ * @param fn - Function that takes the Ok value and returns a Result, AsyncResult, or Promise
858
+ * @returns A new AsyncResult from the chained operation
859
+ *
860
+ * @example
861
+ * ```typescript
862
+ * const result = fetchUser("123")
863
+ * .andThen(user => fetchPermissions(user.id));
864
+ * ```
865
+ */
866
+ andThen(fn) {
867
+ return new AsyncResult(this.promise.then(async (result) => {
868
+ const resultValue = result._unsafeValue();
869
+ if (isErrValue(resultValue)) {
870
+ return Result.err(resultValue.error);
871
+ }
872
+ const nextResult = fn(resultValue.value);
873
+ if (nextResult instanceof AsyncResult) {
874
+ return await nextResult;
875
+ }
876
+ return await nextResult;
877
+ }));
878
+ }
879
+ /**
880
+ * Extracts the value from Ok or returns the Err for early returns.
881
+ *
882
+ * This is the async version of Result.take(). It returns a Promise that
883
+ * resolves to either the unwrapped value T or an Err Result.
884
+ *
885
+ * @returns Promise of the unwrapped value or Err Result
886
+ *
887
+ * @example
888
+ * ```typescript
889
+ * async function processUser(id: string): Promise<Result<string, AppError>> {
890
+ * const user = await fetchUser(id).take();
891
+ * if (isErr(user)) return user;
892
+ *
893
+ * const perms = await fetchPermissions(user.id).take();
894
+ * if (isErr(perms)) return perms;
895
+ *
896
+ * return Result.ok(perms.join(", "));
897
+ * }
898
+ * ```
899
+ */
900
+ async take() {
901
+ const result = await this.promise;
902
+ return result.take();
903
+ }
904
+ /**
905
+ * Adds context to an Err result for early returns.
906
+ * Async version - can be chained before take().
907
+ *
908
+ * @param message - Context message describing the operation that failed
909
+ * @param extra - Optional additional context data
910
+ * @returns AsyncResult with context added to any error
911
+ *
912
+ * @example
913
+ * ```typescript
914
+ * const user = await fetchUser(id).context("failed to fetch user").take();
915
+ * if (isErr(user)) return user;
916
+ * ```
917
+ */
918
+ context(message, extra) {
919
+ return new AsyncResult(this.promise.then((result) => {
920
+ result.context(message, extra);
921
+ return result;
922
+ }));
923
+ }
924
+ /**
925
+ * Pattern matching for async Results.
926
+ *
927
+ * @template U - The type of the return value
928
+ * @param pattern - Object with ok and err handler functions
929
+ * @returns Promise of the result from calling either handler
930
+ *
931
+ * @example
932
+ * ```typescript
933
+ * const message = await fetchUser("123").match({
934
+ * ok: (user) => `Welcome, ${user.name}`,
935
+ * err: (error) => `Error: ${error.message}`
936
+ * });
937
+ * ```
938
+ */
939
+ async match(pattern) {
940
+ const result = await this.promise;
941
+ return result.match(pattern);
942
+ }
943
+ /**
944
+ * Returns the Ok value or a default value if Err.
945
+ *
946
+ * @template U - The type of the default value
947
+ * @param defaultValue - The value to return if the result is Err
948
+ * @returns Promise of the Ok value or the default value
949
+ */
950
+ async unwrapOr(defaultValue) {
951
+ const result = await this.promise;
952
+ return result.unwrapOr(defaultValue);
953
+ }
954
+ /**
955
+ * Returns the Ok value or computes a default from the error.
956
+ *
957
+ * @template U - The type of the default value
958
+ * @param fn - Function to compute the default value from the error
959
+ * @returns Promise of the Ok value or the computed default value
960
+ */
961
+ async unwrapOrElse(fn) {
962
+ const result = await this.promise;
963
+ return result.unwrapOrElse(fn);
964
+ }
965
+ /**
966
+ * Returns this result if Ok, otherwise returns the fallback.
967
+ *
968
+ * @template U - The type of the fallback Ok value
969
+ * @param other - The fallback Result or AsyncResult
970
+ * @returns AsyncResult of this or the fallback
971
+ */
972
+ or(other) {
973
+ return new AsyncResult(this.promise.then(async (result) => {
974
+ if (result.isOk()) {
975
+ return result;
976
+ }
977
+ if (other instanceof AsyncResult) {
978
+ return (await other);
979
+ }
980
+ return (await other);
981
+ }));
982
+ }
983
+ /**
984
+ * Returns this result if Ok, otherwise computes a fallback from the error.
985
+ *
986
+ * @template R - The Result or AsyncResult type returned by the fallback function
987
+ * @param fn - Function to compute a fallback Result from the error
988
+ * @returns AsyncResult of this or the computed fallback
989
+ */
990
+ orElse(fn) {
991
+ return new AsyncResult(this.promise.then(async (result) => {
992
+ const resultValue = result._unsafeValue();
993
+ if (isOkValue(resultValue)) {
994
+ return Result.ok(resultValue.value);
995
+ }
996
+ const nextResult = fn(resultValue.error);
997
+ if (nextResult instanceof AsyncResult) {
998
+ return await nextResult;
999
+ }
1000
+ return await nextResult;
1001
+ }));
1002
+ }
1003
+ /**
1004
+ * Performs a side effect on the Ok value without changing the result.
1005
+ *
1006
+ * @param fn - Function to call with the Ok value (if Ok)
1007
+ * @returns This AsyncResult, unchanged
1008
+ */
1009
+ inspect(fn) {
1010
+ return new AsyncResult(this.promise.then(async (result) => {
1011
+ const resultValue = result._unsafeValue();
1012
+ if (isOkValue(resultValue)) {
1013
+ await fn(resultValue.value);
1014
+ }
1015
+ return result;
1016
+ }));
1017
+ }
1018
+ /**
1019
+ * Performs a side effect on the Err value without changing the result.
1020
+ *
1021
+ * @param fn - Function to call with the error value (if Err)
1022
+ * @returns This AsyncResult, unchanged
1023
+ */
1024
+ inspectErr(fn) {
1025
+ return new AsyncResult(this.promise.then(async (result) => {
1026
+ const resultValue = result._unsafeValue();
1027
+ if (isErrValue(resultValue)) {
1028
+ await fn(resultValue.error);
1029
+ }
1030
+ return result;
1031
+ }));
1032
+ }
1033
+ }