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