@nlozgachev/pipelined 0.63.0 → 0.65.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.
@@ -1,2557 +0,0 @@
1
- import { h as WithKind, o as WithValue, e as WithError, a as NonEmptyArr, T as Thenable, D as Deferred, f as WithErrors } from './InternalTypes-CCXa8Kvr.js';
2
- import { D as Duration } from './Duration-DeyxG6VQ.js';
3
- import { RetryPolicy } from './types.js';
4
-
5
- /**
6
- * A function that checks whether two values of type `A` are equal.
7
- * Use built-in instances (`Equality.string`, `Equality.number`, etc.) as starting points,
8
- * then adapt them with `Equality.by` and combine them with `Equality.and`.
9
- *
10
- * @example
11
- * ```ts
12
- * type User = { id: string; name: string };
13
- * const byId = pipe(Equality.string, Equality.by((u: User) => u.id));
14
- *
15
- * pipe(users, Arr.uniqWith(byId));
16
- * ```
17
- */
18
- type Equality<A> = (a: A, b: A) => boolean;
19
- declare const Equality: {
20
- /**
21
- * Equality for strings. Case-sensitive.
22
- *
23
- * @example
24
- * ```ts
25
- * Equality.string("hello", "hello"); // true
26
- * Equality.string("hello", "Hello"); // false
27
- * ```
28
- */
29
- string: Equality<string>;
30
- /**
31
- * Equality for numbers. Uses strict equality.
32
- *
33
- * @example
34
- * ```ts
35
- * Equality.number(42, 42); // true
36
- * ```
37
- */
38
- number: Equality<number>;
39
- /**
40
- * Equality for booleans.
41
- *
42
- * @example
43
- * ```ts
44
- * Equality.boolean(true, true); // true
45
- * ```
46
- */
47
- boolean: Equality<boolean>;
48
- /**
49
- * Equality for `Date` values. Compares by numeric time value.
50
- *
51
- * @example
52
- * ```ts
53
- * Equality.date(new Date("2024-01-01"), new Date("2024-01-01")); // true
54
- * ```
55
- */
56
- date: Equality<Date>;
57
- /**
58
- * Lifts an element equality into an array equality. Two arrays are equal if they have the
59
- * same length and every element pair is equal under `eq`.
60
- *
61
- * @example
62
- * ```ts
63
- * Equality.array(Equality.number)([1, 2, 3], [1, 2, 3]); // true
64
- * ```
65
- */
66
- array: <A>(eq: Equality<A>) => Equality<readonly A[]>;
67
- /**
68
- * Adapts an equality for type `A` into an equality for type `B` by extracting a field.
69
- * Read as "equality by this field": `pipe(Equality.string, Equality.by(u => u.name))`.
70
- *
71
- * @example
72
- * ```ts
73
- * type Product = { id: string; price: number };
74
- * const byId = pipe(Equality.string, Equality.by((p: Product) => p.id));
75
- * byId({ id: "p1", price: 9 }, { id: "p1", price: 12 }); // true
76
- * ```
77
- */
78
- by: <A, B>(f: (b: B) => A) => (eq: Equality<A>) => Equality<B>;
79
- /**
80
- * Combines two equalities with logical AND. Both must pass for two values to be considered equal.
81
- * Data-last: the first equality is the data being piped.
82
- *
83
- * @example
84
- * ```ts
85
- * const exact = pipe(byName, Equality.and(byRole));
86
- * exact(userA, userB); // true only if name AND role match
87
- * ```
88
- */
89
- and: <A>(eq2: Equality<A>) => (eq1: Equality<A>) => Equality<A>;
90
- /**
91
- * Derives deep equality for a record from field-level `Equality` checkers.
92
- *
93
- * @example
94
- * ```ts
95
- * const userEq = Equality.struct({
96
- * id: Equality.string,
97
- * age: Equality.number,
98
- * });
99
- * ```
100
- */
101
- struct: <R extends Record<string, unknown>>(fields: { [K in keyof R]: Equality<R[K]>; }) => Equality<R>;
102
- /**
103
- * Derives element-wise equality for a tuple from positional `Equality` checkers.
104
- *
105
- * @example
106
- * ```ts
107
- * const pairEq = Equality.tuple(Equality.string, Equality.number);
108
- * pairEq(["a", 1], ["a", 1]); // true
109
- * ```
110
- */
111
- tuple: <T extends readonly unknown[]>(...equalities: { [K in keyof T]: Equality<T[K]>; }) => Equality<T>;
112
- };
113
-
114
- type Some<A> = WithKind<"Some"> & WithValue<A>;
115
- type None = WithKind<"None">;
116
- /**
117
- * Maybe represents an optional value: every Maybe is either Some (contains a value) or None (empty).
118
- * Use Maybe instead of null/undefined to make optionality explicit and composable.
119
- *
120
- * @example
121
- * ```ts
122
- * const user = { name: "Alice", email: Maybe.make.some("alice@example.com") };
123
- *
124
- * pipe(
125
- * user.email,
126
- * Maybe.map(email => email.toUpperCase()),
127
- * Maybe.getOrElse(() => "NO EMAIL")
128
- * ); // "ALICE@EXAMPLE.COM"
129
- * ```
130
- */
131
- type Maybe<T> = Some<T> | None;
132
- declare const Maybe: {
133
- make: {
134
- /**
135
- * Creates a Some containing the given value.
136
- *
137
- * @example
138
- * ```ts
139
- * Maybe.make.some(42); // Some(42)
140
- * ```
141
- */
142
- some: <A>(value: A) => Some<A>;
143
- /**
144
- * Creates a None (empty Maybe).
145
- *
146
- * @example
147
- * ```ts
148
- * Maybe.make.none(); // None
149
- * ```
150
- */
151
- none: () => None;
152
- };
153
- is: {
154
- /**
155
- * Type guard that checks if a Maybe is Some.
156
- *
157
- * @example
158
- * ```ts
159
- * const value = Maybe.make.some(42);
160
- * if (Maybe.is.some(value)) {
161
- * console.log(value.value); // 42
162
- * }
163
- * ```
164
- */
165
- some: <A>(data: Maybe<A>) => data is Some<A>;
166
- /**
167
- * Type guard that checks if a Maybe is None.
168
- *
169
- * @example
170
- * ```ts
171
- * const value = Maybe.make.none();
172
- * if (Maybe.is.none(value)) {
173
- * console.log("No value present");
174
- * }
175
- * ```
176
- */
177
- none: <A>(data: Maybe<A>) => data is None;
178
- };
179
- to: {
180
- /**
181
- * Extracts the value from a Maybe, returning null if None.
182
- *
183
- * @example
184
- * ```ts
185
- * Maybe.to.nullable(Maybe.make.some(42)); // 42
186
- * Maybe.to.nullable(Maybe.make.none()); // null
187
- * ```
188
- */
189
- nullable: <A>(data: Maybe<A>) => A | null;
190
- /**
191
- * Extracts the value from a Maybe, returning undefined if None.
192
- *
193
- * @example
194
- * ```ts
195
- * Maybe.to.undefined(Maybe.make.some(42)); // 42
196
- * Maybe.to.undefined(Maybe.make.none()); // undefined
197
- * ```
198
- */
199
- undefined: <A>(data: Maybe<A>) => A | undefined;
200
- /**
201
- * Converts a Maybe to a Result.
202
- * Some becomes Ok, None becomes Err with the provided error.
203
- *
204
- * @example
205
- * ```ts
206
- * pipe(
207
- * Maybe.make.some(42),
208
- * Maybe.to.Result(() => "Value was missing")
209
- * ); // Ok(42)
210
- *
211
- * pipe(
212
- * Maybe.make.none(),
213
- * Maybe.to.Result(() => "Value was missing")
214
- * ); // Err("Value was missing")
215
- * ```
216
- */
217
- Result: <E>(onNone: () => E) => <A>(data: Maybe<A>) => Result<E, A>;
218
- };
219
- from: {
220
- /**
221
- * Creates a Maybe from a nullable value.
222
- * Returns None if the value is null or undefined, Some otherwise.
223
- *
224
- * @example
225
- * ```ts
226
- * Maybe.from.nullable(null); // None
227
- * Maybe.from.nullable(42); // Some(42)
228
- * ```
229
- */
230
- nullable: <A>(value: A | null | undefined) => Maybe<A>;
231
- /**
232
- * Creates a Maybe from a predicate applied to a value.
233
- * Returns Some if the predicate passes, None otherwise.
234
- *
235
- * @example
236
- * ```ts
237
- * Maybe.from.Predicate((n: number) => n >= 18)(21); // Some(21)
238
- * Maybe.from.Predicate((n: number) => n >= 18)(15); // None
239
- *
240
- * pipe("hello", Maybe.from.Predicate((s: string) => s.length > 0)); // Some("hello")
241
- * pipe("", Maybe.from.Predicate((s: string) => s.length > 0)); // None
242
- * ```
243
- */
244
- Predicate: <A>(pred: (a: A) => boolean) => (a: A) => Maybe<A>;
245
- /**
246
- * Creates a Maybe from a Result.
247
- * Ok becomes Some, Err becomes None (the error is discarded).
248
- *
249
- * @example
250
- * ```ts
251
- * Maybe.from.Result(Result.make.ok(42)); // Some(42)
252
- * Maybe.from.Result(Result.make.err("oops")); // None
253
- * ```
254
- */
255
- Result: <E, A>(data: Result<E, A>) => Maybe<A>;
256
- };
257
- /**
258
- * Transforms the value inside a Maybe if it exists.
259
- *
260
- * @example
261
- * ```ts
262
- * pipe(Maybe.make.some(5), Maybe.map(n => n * 2)); // Some(10)
263
- * pipe(Maybe.make.none(), Maybe.map(n => n * 2)); // None
264
- * ```
265
- */
266
- map: <A, B>(f: (a: A) => B) => (data: Maybe<A>) => Maybe<B>;
267
- /**
268
- * Chains Maybe computations. If the first is Some, passes the value to f.
269
- * If the first is None, propagates None.
270
- *
271
- * @example
272
- * ```ts
273
- * const parseNumber = (s: string): Maybe<number> => {
274
- * const n = parseInt(s, 10);
275
- * return isNaN(n) ? Maybe.make.none() : Maybe.make.some(n);
276
- * };
277
- *
278
- * pipe(Maybe.make.some("42"), Maybe.chain(parseNumber)); // Some(42)
279
- * pipe(Maybe.make.some("abc"), Maybe.chain(parseNumber)); // None
280
- * ```
281
- */
282
- chain: <A, B>(f: (a: A) => Maybe<B>) => (data: Maybe<A>) => Maybe<B>;
283
- /**
284
- * Extracts the value from a Maybe by providing handlers for both cases.
285
- *
286
- * @example
287
- * ```ts
288
- * pipe(
289
- * Maybe.make.some(5),
290
- * Maybe.fold(
291
- * () => "No value",
292
- * n => `Value: ${n}`
293
- * )
294
- * ); // "Value: 5"
295
- * ```
296
- */
297
- fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: Maybe<A>) => B;
298
- /**
299
- * Pattern matches on a Maybe, returning the result of the matching case.
300
- *
301
- * @example
302
- * ```ts
303
- * pipe(
304
- * optionUser,
305
- * Maybe.match({
306
- * some: user => `Hello, ${user.name}`,
307
- * none: () => "Hello, stranger"
308
- * })
309
- * );
310
- * ```
311
- */
312
- match: <A, B>(cases: {
313
- none: () => B;
314
- some: (a: A) => B;
315
- }) => (data: Maybe<A>) => B;
316
- /**
317
- * Returns the value inside a Maybe, or a default value if None.
318
- * The default is a thunk `() => B` — evaluated only when the Maybe is None.
319
- * The default can be a different type, widening the result to `A | B`.
320
- *
321
- * @example
322
- * ```ts
323
- * pipe(Maybe.make.some(5), Maybe.getOrElse(() => 0)); // 5
324
- * pipe(Maybe.make.none(), Maybe.getOrElse(() => 0)); // 0
325
- * pipe(Maybe.make.none<string>(), Maybe.getOrElse(() => null)); // null — typed as string | null
326
- * ```
327
- */
328
- getOrElse: <B>(defaultValue: () => B) => <A>(data: Maybe<A>) => A | B;
329
- /**
330
- * Executes a side effect on the value without changing the Maybe.
331
- * Useful for logging or debugging.
332
- *
333
- * @example
334
- * ```ts
335
- * pipe(
336
- * Maybe.make.some(5),
337
- * Maybe.tap(n => console.log("Value:", n)),
338
- * Maybe.map(n => n * 2)
339
- * );
340
- * ```
341
- */
342
- tap: <A>(f: (a: A) => void) => (data: Maybe<A>) => Maybe<A>;
343
- /**
344
- * Filters a Maybe based on a predicate.
345
- * Returns None if the predicate returns false or if the Maybe is already None.
346
- *
347
- * @example
348
- * ```ts
349
- * pipe(Maybe.make.some(5), Maybe.filter(n => n > 3)); // Some(5)
350
- * pipe(Maybe.make.some(2), Maybe.filter(n => n > 3)); // None
351
- * ```
352
- */
353
- filter: <A>(predicate: (a: A) => boolean) => (data: Maybe<A>) => Maybe<A>;
354
- /**
355
- * Recovers from a None by providing a fallback Maybe.
356
- * The fallback can produce a different type, widening the result to `Maybe<A | B>`.
357
- *
358
- * @example
359
- * ```ts
360
- * pipe(Maybe.make.none(), Maybe.recover(() => Maybe.make.some(42))); // Some(42)
361
- * pipe(Maybe.make.some(10), Maybe.recover(() => Maybe.make.some(42))); // Some(10)
362
- * ```
363
- */
364
- recover: <B>(fallback: () => Maybe<B>) => <A>(data: Maybe<A>) => Maybe<A | B>;
365
- /**
366
- * Applies a function wrapped in a Maybe to a value wrapped in a Maybe.
367
- *
368
- * @example
369
- * ```ts
370
- * const add = (a: number) => (b: number) => a + b;
371
- * pipe(
372
- * Maybe.make.some(add),
373
- * Maybe.ap(Maybe.make.some(5)),
374
- * Maybe.ap(Maybe.make.some(3))
375
- * ); // Some(8)
376
- * ```
377
- */
378
- ap: <A>(arg: Maybe<A>) => <B>(data: Maybe<(a: A) => B>) => Maybe<B>;
379
- /**
380
- * Converts a Maybe value into an object containing a single property.
381
- * Initiates the pipeline accumulator record.
382
- *
383
- * @example
384
- * ```ts
385
- * pipe(Maybe.make.some(42), Maybe.bindTo("value")); // Some({ value: 42 })
386
- * ```
387
- */
388
- bindTo: <K extends string>(key: K) => <A>(data: Maybe<A>) => Maybe<{ [P in K]: A; }>;
389
- /**
390
- * Evaluates a new Maybe using the current accumulator and attaches the output to a new key.
391
- *
392
- * @example
393
- * ```ts
394
- * pipe(
395
- * Maybe.make.some({ a: 1 }),
396
- * Maybe.bind("b", ({ a }) => Maybe.make.some(a + 1))
397
- * ); // Some({ a: 1, b: 2 })
398
- * ```
399
- */
400
- bind: <K extends string, A, B>(key: K, f: (a: A) => Maybe<B>) => (data: Maybe<A>) => Maybe<A & { [P in K]: B; }>;
401
- /**
402
- * Combines a record of Maybes into a single Maybe of a record.
403
- * Evaluates fields in key order and short-circuits on the first None.
404
- *
405
- * @example
406
- * ```ts
407
- * Maybe.struct({
408
- * name: Maybe.make.some("Alice"),
409
- * age: Maybe.make.some(30)
410
- * }); // Some({ name: "Alice", age: 30 })
411
- * ```
412
- */
413
- struct: <R extends Record<string, any>>(fields: { [K in keyof R]: Maybe<R[K]>; }) => Maybe<R>;
414
- /**
415
- * Swaps the outer `Maybe` and inner `Result` context.
416
- * `Some(Ok(a))` becomes `Ok(Some(a))`, `Some(Err(e))` becomes `Err(e)`, and `None` becomes `Ok(None)`.
417
- *
418
- * @example
419
- * ```ts
420
- * Maybe.transposeResult(Maybe.make.some(Result.make.ok(42))); // Ok(Some(42))
421
- * Maybe.transposeResult(Maybe.make.some(Result.make.err("e"))); // Err("e")
422
- * Maybe.transposeResult(Maybe.make.none()); // Ok(None)
423
- * ```
424
- */
425
- transposeResult: <E, A>(data: Maybe<Result<E, A>>) => Result<E, Maybe<A>>;
426
- };
427
-
428
- /**
429
- * A function that orders two values of type `A`. Returns a negative number when `a` comes before
430
- * `b`, a positive number when `a` comes after `b`, and `0` when they are equal.
431
- *
432
- * Compatible with `Array.prototype.sort` and `Arr.sortWith`.
433
- *
434
- * @example
435
- * ```ts
436
- * type Employee = { name: string; salary: number };
437
- *
438
- * const byName = pipe(Ordering.string, Ordering.by((e: Employee) => e.name));
439
- * const bySalary = pipe(Ordering.number, Ordering.by((e: Employee) => e.salary));
440
- *
441
- * pipe(employees, Arr.sortWith(pipe(byName, Ordering.thenBy(bySalary))));
442
- * ```
443
- */
444
- type Ordering<A> = (a: A, b: A) => number;
445
- declare const Ordering: {
446
- /**
447
- * Alphabetical ordering for strings.
448
- *
449
- * @example
450
- * ```ts
451
- * Ordering.string("apple", "banana"); // negative
452
- * ```
453
- */
454
- string: Ordering<string>;
455
- /**
456
- * Numeric ordering. Equivalent to `(a, b) => a - b`.
457
- *
458
- * @example
459
- * ```ts
460
- * pipe([3, 1, 2], Arr.sortWith(Ordering.number)); // [1, 2, 3]
461
- * ```
462
- */
463
- number: Ordering<number>;
464
- /**
465
- * Ordering for `Date` values by numeric time value.
466
- *
467
- * @example
468
- * ```ts
469
- * pipe(dates, Arr.sortWith(Ordering.date)); // earliest first
470
- * ```
471
- */
472
- date: Ordering<Date>;
473
- /**
474
- * Flips the direction of an ordering.
475
- *
476
- * @example
477
- * ```ts
478
- * pipe([3, 1, 2], Arr.sortWith(Ordering.reverse(Ordering.number))); // [3, 2, 1]
479
- * ```
480
- */
481
- reverse: <A>(ord: Ordering<A>) => Ordering<A>;
482
- /**
483
- * Chains two orderings: the second is used only when the first returns `0`.
484
- * Data-last: the first ordering is the data being piped.
485
- *
486
- * @example
487
- * ```ts
488
- * const byDeptThenSalary = pipe(byDept, Ordering.thenBy(bySalary));
489
- * ```
490
- */
491
- thenBy: <A>(ord2: Ordering<A>) => (ord1: Ordering<A>) => Ordering<A>;
492
- /**
493
- * Adapts an ordering for type `A` into an ordering for type `B` by extracting a field.
494
- * Read as "ordering by this field": `pipe(Ordering.number, Ordering.by(p => p.price))`.
495
- *
496
- * @example
497
- * ```ts
498
- * type Product = { name: string; price: number };
499
- * const byPrice = pipe(Ordering.number, Ordering.by((p: Product) => p.price));
500
- * pipe(products, Arr.sortWith(byPrice));
501
- * ```
502
- */
503
- by: <A, B>(f: (b: B) => A) => (ord: Ordering<A>) => Ordering<B>;
504
- /**
505
- * Combines a list of orderings into a single composite comparator.
506
- * Evaluates each ordering in sequence until a non-zero comparison result is found.
507
- *
508
- * @example
509
- * ```ts
510
- * const byName = pipe(Ordering.string, Ordering.by((u: User) => u.name));
511
- * const byAge = pipe(Ordering.number, Ordering.by((u: User) => u.age));
512
- * const sortUsers = Ordering.byFields([byName, byAge]);
513
- * ```
514
- */
515
- byFields: <A>(orderings: ReadonlyArray<Ordering<A>>) => Ordering<A>;
516
- /**
517
- * Derives a lexicographical tuple ordering from positional `Ordering` comparators.
518
- *
519
- * @example
520
- * ```ts
521
- * const pairOrd = Ordering.tuple(Ordering.string, Ordering.number);
522
- * pairOrd(["a", 1], ["a", 2]); // negative
523
- * ```
524
- */
525
- tuple: <T extends readonly unknown[]>(...orderings: { [K in keyof T]: Ordering<T[K]>; }) => Ordering<T>;
526
- };
527
-
528
- type Ok<A> = WithKind<"Ok"> & WithValue<A>;
529
- type Err<E> = WithKind<"Err"> & WithError<E>;
530
- /**
531
- * Result represents a value that can be one of two types: a success (Ok) or a failure (Err).
532
- * Use Result when an operation can fail with a meaningful error value.
533
- *
534
- * @example
535
- * ```ts
536
- * const divide = (a: number, b: number): Result<string, number> =>
537
- * b === 0 ? Result.make.err("Division by zero") : Result.make.ok(a / b);
538
- *
539
- * pipe(
540
- * divide(10, 2),
541
- * Result.map(n => n * 2),
542
- * Result.getOrElse(() => 0)
543
- * ); // 10
544
- * ```
545
- */
546
- type Result<E, A> = Ok<A> | Err<E>;
547
- declare const Result: {
548
- make: {
549
- /**
550
- * Creates a successful Result with the given value.
551
- *
552
- * @example
553
- * ```ts
554
- * Result.make.ok(42); // Ok(42)
555
- * ```
556
- */
557
- ok: <A>(value: A) => Ok<A>;
558
- /**
559
- * Creates a failed Result with the given error.
560
- *
561
- * @example
562
- * ```ts
563
- * Result.make.err("Error message"); // Err("Error message")
564
- * ```
565
- */
566
- err: <E>(e: E) => Err<E>;
567
- };
568
- is: {
569
- /**
570
- * Type guard that checks if a Result is Ok.
571
- *
572
- * @example
573
- * ```ts
574
- * const res = Result.make.ok(42);
575
- * if (Result.is.ok(res)) {
576
- * console.log(res.value); // 42
577
- * }
578
- * ```
579
- */
580
- ok: <E, A>(data: Result<E, A>) => data is Ok<A>;
581
- /**
582
- * Type guard that checks if a Result is Err.
583
- *
584
- * @example
585
- * ```ts
586
- * const res = Result.make.err("failed");
587
- * if (Result.is.err(res)) {
588
- * console.log(res.error); // "failed"
589
- * }
590
- * ```
591
- */
592
- err: <E, A>(data: Result<E, A>) => data is Err<E>;
593
- };
594
- /**
595
- * Creates a Result from a synchronous thunk that may throw.
596
- * Catches any errors and transforms them using the `onError` function.
597
- *
598
- * @example
599
- * ```ts
600
- * const result = Result.tryCatch(
601
- * () => JSON.parse(rawString),
602
- * { onError: (e) => `Parse error: ${e}` }
603
- * );
604
- * ```
605
- */
606
- tryCatch: <E, A>(f: () => A, options: {
607
- onError: (e: unknown) => E;
608
- }) => Result<E, A>;
609
- /**
610
- * Transforms the success value inside a Result.
611
- *
612
- * @example
613
- * ```ts
614
- * pipe(Result.make.ok(5), Result.map(n => n * 2)); // Ok(10)
615
- * pipe(Result.make.err("error"), Result.map(n => n * 2)); // Err("error")
616
- * ```
617
- */
618
- map: <E, A, B>(f: (a: A) => B) => (data: Result<E, A>) => Result<E, B>;
619
- /**
620
- * Transforms the error value inside a Result.
621
- *
622
- * @example
623
- * ```ts
624
- * pipe(Result.make.err("oops"), Result.mapError(e => e.toUpperCase())); // Err("OOPS")
625
- * ```
626
- */
627
- mapError: <E, F, A>(f: (e: E) => F) => (data: Result<E, A>) => Result<F, A>;
628
- /**
629
- * Chains Result computations. If the first is Ok, passes the value to f.
630
- * If the first is Err, propagates the error.
631
- *
632
- * @example
633
- * ```ts
634
- * const validatePositive = (n: number): Result<string, number> =>
635
- * n > 0 ? Result.make.ok(n) : Result.make.err("Must be positive");
636
- *
637
- * pipe(Result.make.ok(5), Result.chain(validatePositive)); // Ok(5)
638
- * pipe(Result.make.ok(-1), Result.chain(validatePositive)); // Err("Must be positive")
639
- * ```
640
- */
641
- chain: <E2, A, B>(f: (a: A) => Result<E2, B>) => <E1 = never>(data: Result<E1, A>) => Result<E1 | E2, B>;
642
- /**
643
- * Extracts the value from a Result by providing handlers for both cases.
644
- *
645
- * @example
646
- * ```ts
647
- * pipe(
648
- * Result.make.ok(5),
649
- * Result.fold(
650
- * e => `Error: ${e}`,
651
- * n => `Value: ${n}`
652
- * )
653
- * ); // "Value: 5"
654
- * ```
655
- */
656
- fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: Result<E, A>) => B;
657
- /**
658
- * Pattern matches on a Result, returning the result of the matching case.
659
- *
660
- * @example
661
- * ```ts
662
- * pipe(
663
- * result,
664
- * Result.match({
665
- * ok: value => `Got ${value}`,
666
- * err: error => `Failed: ${error}`
667
- * })
668
- * );
669
- * ```
670
- */
671
- match: <E, A, B>(cases: {
672
- ok: (a: A) => B;
673
- err: (e: E) => B;
674
- }) => (data: Result<E, A>) => B;
675
- /**
676
- * Returns the success value or a default value if the Result is an error.
677
- * The default is a thunk `() => B` — evaluated only when the Result is Err.
678
- * The default can be a different type, widening the result to `A | B`.
679
- *
680
- * @example
681
- * ```ts
682
- * pipe(Result.make.ok(5), Result.getOrElse(() => 0)); // 5
683
- * pipe(Result.make.err("error"), Result.getOrElse(() => 0)); // 0
684
- * pipe(Result.make.err("error"), Result.getOrElse(() => null)); // null — typed as number | null
685
- * ```
686
- */
687
- getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Result<E, A>) => A | B;
688
- /**
689
- * Executes a side effect on the success value without changing the Result.
690
- * Useful for logging or debugging.
691
- *
692
- * @example
693
- * ```ts
694
- * pipe(
695
- * Result.make.ok(5),
696
- * Result.tap(n => console.log("Value:", n)),
697
- * Result.map(n => n * 2)
698
- * );
699
- * ```
700
- */
701
- tap: <E, A>(f: (a: A) => void) => (data: Result<E, A>) => Result<E, A>;
702
- /**
703
- * Executes a side effect on the error value without changing the Result.
704
- * Useful for logging or reporting errors.
705
- *
706
- * @example
707
- * ```ts
708
- * pipe(
709
- * Result.make.err("not found"),
710
- * Result.tapError(e => console.error("validation failed:", e)),
711
- * Result.chain(save),
712
- * )
713
- * ```
714
- */
715
- tapError: <E, A>(f: (e: E) => void) => (data: Result<E, A>) => Result<E, A>;
716
- from: {
717
- /**
718
- * Creates a Result from a predicate applied to a value.
719
- * Returns Ok if the predicate passes, Err from onFalse otherwise.
720
- *
721
- * @example
722
- * ```ts
723
- * pipe(5, Result.from.Predicate(n => n > 0, n => `${n} is not positive`)); // Ok(5)
724
- * pipe(-1, Result.from.Predicate(n => n > 0, n => `${n} is not positive`)); // Err("-1 is not positive")
725
- * pipe("", Result.from.Predicate(s => s.length > 0, () => "empty string")); // Err("empty string")
726
- * ```
727
- */
728
- Predicate: <E, A>(pred: (a: A) => boolean, onFalse: (a: A) => E) => (a: A) => Result<E, A>;
729
- /**
730
- * Creates a Result from a nullable value.
731
- * Returns Ok if the value is not null or undefined, error from onNull otherwise.
732
- *
733
- * @example
734
- * ```ts
735
- * pipe(null, Result.from.nullable(() => "is null")); // Err("is null")
736
- * pipe(42, Result.from.nullable(() => "is null")); // Ok(42)
737
- * ```
738
- */
739
- nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Result<E, A>;
740
- /**
741
- * Creates a Result from a Maybe.
742
- * Some becomes Ok, None becomes error from onNone.
743
- *
744
- * @example
745
- * ```ts
746
- * pipe(Maybe.make.none(), Result.from.Maybe(() => "is none")); // Err("is none")
747
- * pipe(Maybe.make.some(42), Result.from.Maybe(() => "is none")); // Ok(42)
748
- * ```
749
- */
750
- Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Result<E, A>;
751
- /**
752
- * Converts a `Validation` to a `Result`, combining accumulated errors using `combineErrors`.
753
- * `Passed(a)` becomes `Ok(a)`; `Failed(errors)` becomes `Err(combineErrors(errors))`.
754
- *
755
- * @example
756
- * ```ts
757
- * Result.from.Validation((errors) => errors.join(", "))(Validation.make.failed("error1")); // Err("error1")
758
- * ```
759
- */
760
- Validation: <E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2) => (val: Validation<E1, A>) => Result<E2, A>;
761
- };
762
- /**
763
- * Recovers from an error by providing a fallback Result.
764
- * The fallback can produce a different success type, widening the result to `Result<E, A | B>`.
765
- */
766
- recover: <E, B>(fallback: (e: E) => Result<E, B>) => <A>(data: Result<E, A>) => Result<E, A | B>;
767
- /**
768
- * Recovers from an error unless the predicate `isBlocked` returns true for that error.
769
- * The fallback can produce a different success type, widening the result to `Result<E, A | B>`.
770
- *
771
- * @example
772
- * ```ts
773
- * pipe(
774
- * Result.make.err(new Error("not found")),
775
- * Result.recoverUnless(e => e.message === "fatal", () => Result.make.ok(0))
776
- * ); // Ok(0)
777
- * ```
778
- */
779
- recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: () => Result<E, B>) => <A>(data: Result<E, A>) => Result<E, A | B>;
780
- to: {
781
- /**
782
- * Converts a Result to a Maybe.
783
- * Ok becomes Some, Err becomes None (the error is discarded).
784
- *
785
- * @example
786
- * ```ts
787
- * Result.to.Maybe(Result.make.ok(42)); // Some(42)
788
- * Result.to.Maybe(Result.make.err("oops")); // None
789
- * ```
790
- */
791
- Maybe: <E, A>(data: Result<E, A>) => Maybe<A>;
792
- /**
793
- * Converts a `Result` to a `Validation`. `Ok(a)` becomes `Passed(a)`; `Err(e)` becomes `Failed([e])`.
794
- *
795
- * @example
796
- * ```ts
797
- * Result.to.Validation(Result.make.ok(42)); // Passed(42)
798
- * Result.to.Validation(Result.make.err("bad")); // Failed(["bad"])
799
- * ```
800
- */
801
- Validation: <E, A>(data: Result<E, A>) => Validation<E, A>;
802
- };
803
- /**
804
- * Swaps the outer `Result` and inner `Maybe` context.
805
- * `Ok(Some(a))` becomes `Some(Ok(a))`, `Ok(None)` becomes `None`, and `Err(e)` becomes `Some(Err(e))`.
806
- *
807
- * @example
808
- * ```ts
809
- * Result.transposeMaybe(Result.make.ok(Maybe.make.some(42))); // Some(Ok(42))
810
- * Result.transposeMaybe(Result.make.ok(Maybe.make.none())); // None
811
- * Result.transposeMaybe(Result.make.err("error")); // Some(Err("error"))
812
- * ```
813
- */
814
- transposeMaybe: <E, A>(data: Result<E, Maybe<A>>) => Maybe<Result<E, A>>;
815
- /**
816
- * Applies a function wrapped in a Result to a value wrapped in a Result.
817
- *
818
- * @example
819
- * ```ts
820
- * const add = (a: number) => (b: number) => a + b;
821
- * pipe(
822
- * Result.make.ok(add),
823
- * Result.ap(Result.make.ok(5)),
824
- * Result.ap(Result.make.ok(3))
825
- * ); // Ok(8)
826
- * ```
827
- */
828
- ap: <E, A>(arg: Result<E, A>) => <B>(data: Result<E, (a: A) => B>) => Result<E, B>;
829
- /**
830
- * Converts a Result value into an object containing a single property.
831
- * Initiates the pipeline accumulator record.
832
- *
833
- * @example
834
- * ```ts
835
- * pipe(Result.make.ok(42), Result.bindTo("value")); // Ok({ value: 42 })
836
- * ```
837
- */
838
- bindTo: <K extends string>(key: K) => <E, A>(data: Result<E, A>) => Result<E, { [P in K]: A; }>;
839
- /**
840
- * Evaluates a new Result using the current accumulator and attaches the output to a new key.
841
- *
842
- * @example
843
- * ```ts
844
- * pipe(
845
- * Result.make.ok({ a: 1 }),
846
- * Result.bind("b", ({ a }) => Result.make.ok(a + 1))
847
- * ); // Ok({ a: 1, b: 2 })
848
- * ```
849
- */
850
- bind: <K extends string, E, A, B>(key: K, f: (a: A) => Result<E, B>) => (data: Result<E, A>) => Result<E, A & { [P in K]: B; }>;
851
- /**
852
- * Combines a record of Results into a single Result of a record.
853
- * Evaluates fields in key order and short-circuits on the first failure.
854
- *
855
- * @example
856
- * ```ts
857
- * Result.struct({
858
- * name: Result.make.ok("Alice"),
859
- * age: Result.make.ok(30)
860
- * }); // Ok({ name: "Alice", age: 30 })
861
- * ```
862
- */
863
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Result<E, R[K]>; }) => Result<E, R>;
864
- /**
865
- * Narrows an `Ok` value with a predicate, converting to `Err(onFail(a))` if the predicate returns false.
866
- *
867
- * @example
868
- * ```ts
869
- * pipe(
870
- * Result.make.ok(15),
871
- * Result.ensure((n) => n >= 18, (n) => `Age ${n} is below 18`)
872
- * ); // Err("Age 15 is below 18")
873
- * ```
874
- */
875
- ensure: <A, E2>(predicate: (a: A) => boolean, onFail: (a: A) => E2) => <E1 = never>(data: Result<E1, A>) => Result<E1 | E2, A>;
876
- /**
877
- * Transforms both branches of a Result simultaneously.
878
- * Applies `onErr` to `Err` values and `onOk` to `Ok` values.
879
- *
880
- * @example
881
- * ```ts
882
- * pipe(
883
- * Result.make.ok(5),
884
- * Result.bimap(
885
- * (e) => `Error: ${e}`,
886
- * (n) => n * 2
887
- * )
888
- * ); // Ok(10)
889
- * ```
890
- */
891
- bimap: <E1, E2, A, B>(onErr: (e: E1) => E2, onOk: (a: A) => B) => (data: Result<E1, A>) => Result<E2, B>;
892
- };
893
-
894
- /**
895
- * TaskMaybe represents a lazy, infallible async operation that resolves to a `Maybe<A>`.
896
- * It is a type alias for `Task<Maybe<A>>`.
897
- *
898
- * Use Task.Maybe for async operations that can result in a missing value (e.g. database lookups).
899
- *
900
- * @example
901
- * ```ts
902
- * const findUser = (id: string): Task.Maybe<User> =>
903
- * Task.Maybe.tryCatch((signal) =>
904
- * fetch(`/users/${id}`, { signal }).then(r => r.ok ? r.json() : null)
905
- * );
906
- * ```
907
- */
908
- type TaskMaybe<A> = Task<Maybe<A>>;
909
- declare const TaskMaybe: {
910
- /**
911
- * Wraps a value in a Some inside a Task.
912
- *
913
- * @example
914
- * ```ts
915
- * const task = Task.Maybe.some(42);
916
- * const res = await task(); // Some(42)
917
- * ```
918
- */
919
- make: {
920
- /**
921
- * Creates a Task.Maybe that resolves to Some(value).
922
- *
923
- * @example
924
- * ```ts
925
- * const task = Task.Maybe.make.some(42);
926
- * const res = await task(); // Some(42)
927
- * ```
928
- */
929
- some: <A>(value: A) => TaskMaybe<A>;
930
- /**
931
- * Creates a Task.Maybe that resolves to None.
932
- *
933
- * @example
934
- * ```ts
935
- * const task = Task.Maybe.make.none();
936
- * const res = await task(); // None
937
- * ```
938
- */
939
- none: <A = never>() => TaskMaybe<A>;
940
- };
941
- some: <A>(value: A) => TaskMaybe<A>;
942
- none: <A = never>() => TaskMaybe<A>;
943
- from: {
944
- /**
945
- * Lifts a Maybe into a Task.Maybe.
946
- *
947
- * @example
948
- * ```ts
949
- * Task.Maybe.from.Maybe(Maybe.make.some(42));
950
- * ```
951
- */
952
- Maybe: <A>(option: Maybe<A>) => TaskMaybe<A>;
953
- /**
954
- * Creates a Task.Maybe from a nullable value.
955
- * Returns Some if the value is not null or undefined, None otherwise.
956
- *
957
- * @example
958
- * ```ts
959
- * Task.Maybe.from.nullable(42); // resolves to Some(42)
960
- * Task.Maybe.from.nullable(null); // resolves to None
961
- * ```
962
- */
963
- nullable: <A>(value: A | null | undefined) => TaskMaybe<A>;
964
- /**
965
- * Creates a Task.Maybe from a Result.
966
- * Ok becomes Some, Error becomes None (the error value is discarded).
967
- *
968
- * @example
969
- * ```ts
970
- * Task.Maybe.from.Result(Result.make.ok(42)); // resolves to Some(42)
971
- * Task.Maybe.from.Result(Result.make.err("e")); // resolves to None
972
- * ```
973
- */
974
- Result: <E, A>(result: Result<E, A>) => TaskMaybe<A>;
975
- /**
976
- * Lifts a Task into a Task.Maybe by wrapping its result in Some.
977
- *
978
- * @example
979
- * ```ts
980
- * Task.Maybe.from.Task(Task.resolve(42)); // resolves to Some(42)
981
- * ```
982
- */
983
- Task: <A>(task: Task<A>) => TaskMaybe<A>;
984
- };
985
- /**
986
- * Creates a Task.Maybe from a Promise-returning function.
987
- * Returns Some if the promise resolves, None if it rejects.
988
- * The factory optionally receives an `AbortSignal` forwarded from the call site.
989
- *
990
- * @example
991
- * ```ts
992
- * const fetchUser = Task.Maybe.tryCatch((signal) =>
993
- * fetch("/user/1", { signal }).then(r => r.json())
994
- * );
995
- * ```
996
- */
997
- tryCatch: <A>(f: (signal?: AbortSignal) => Thenable<A>) => TaskMaybe<A>;
998
- /**
999
- * Transforms the value inside a Task.Maybe.
1000
- */
1001
- map: <A, B>(f: (a: A) => B) => (data: TaskMaybe<A>) => TaskMaybe<B>;
1002
- /**
1003
- * Chains Task.Maybe computations. If the first resolves to Some, passes the
1004
- * value to f. If the first resolves to None, propagates None.
1005
- *
1006
- * @example
1007
- * ```ts
1008
- * pipe(
1009
- * findUser("123"),
1010
- * Task.Maybe.chain(user => findOrg(user.orgId))
1011
- * )();
1012
- * ```
1013
- */
1014
- chain: <A, B>(f: (a: A) => TaskMaybe<B>) => (data: TaskMaybe<A>) => TaskMaybe<B>;
1015
- /**
1016
- * Applies a function wrapped in a Task.Maybe to a value wrapped in a Task.Maybe.
1017
- * Both Tasks run in parallel.
1018
- */
1019
- ap: <A>(arg: TaskMaybe<A>) => <B>(data: TaskMaybe<(a: A) => B>) => TaskMaybe<B>;
1020
- /**
1021
- * Extracts a value from a Task.Maybe by providing handlers for both cases.
1022
- */
1023
- fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: TaskMaybe<A>) => Task<B>;
1024
- /**
1025
- * Pattern matches on a Task.Maybe, returning a Task of the result.
1026
- *
1027
- * @example
1028
- * ```ts
1029
- * pipe(
1030
- * findUser("123"),
1031
- * Task.Maybe.match({
1032
- * some: user => `Hello, ${user.name}`,
1033
- * none: () => "User not found"
1034
- * })
1035
- * )();
1036
- * ```
1037
- */
1038
- match: <A, B>(cases: {
1039
- none: () => B;
1040
- some: (a: A) => B;
1041
- }) => (data: TaskMaybe<A>) => Task<B>;
1042
- /**
1043
- * Returns the value or a default if the Task.Maybe resolves to None.
1044
- * The default can be a different type, widening the result to `Task<A | B>`.
1045
- */
1046
- getOrElse: <B>(defaultValue: () => B) => <A>(data: TaskMaybe<A>) => Task<A | B>;
1047
- /**
1048
- * Executes a side effect on the value without changing the Task.Maybe.
1049
- * Useful for logging or debugging.
1050
- */
1051
- tap: <A>(f: (a: A) => void) => (data: TaskMaybe<A>) => TaskMaybe<A>;
1052
- /**
1053
- * Filters the value inside a Task.Maybe. Returns None if the predicate fails.
1054
- */
1055
- filter: <A>(predicate: (a: A) => boolean) => (data: TaskMaybe<A>) => TaskMaybe<A>;
1056
- to: {
1057
- /**
1058
- * Converts a Task.Maybe to a Task.Result, using onNone to produce the error value.
1059
- *
1060
- * @example
1061
- * ```ts
1062
- * pipe(
1063
- * findUser("123"),
1064
- * Task.Maybe.to.Result(() => "User not found")
1065
- * );
1066
- * ```
1067
- */
1068
- Result: <E>(onNone: () => E) => <A>(data: TaskMaybe<A>) => Task.Result<E, A>;
1069
- };
1070
- /**
1071
- * Lifts a Task.Maybe value into an accumulator object.
1072
- *
1073
- * @example
1074
- * ```ts
1075
- * pipe(Task.Maybe.some(42), Task.Maybe.bindTo("value")); // Task.Maybe({ value: 42 })
1076
- * ```
1077
- */
1078
- bindTo: <K extends string>(key: K) => <A>(data: TaskMaybe<A>) => TaskMaybe<{ [P in K]: A; }>;
1079
- /**
1080
- * Evaluates a new Task.Maybe using the current accumulator and attaches the output to a new key.
1081
- *
1082
- * @example
1083
- * ```ts
1084
- * pipe(
1085
- * Task.Maybe.some({ a: 1 }),
1086
- * Task.Maybe.bind("b", ({ a }) => Task.Maybe.some(a + 1))
1087
- * ); // Task.Maybe({ a: 1, b: 2 })
1088
- * ```
1089
- */
1090
- bind: <K extends string, A, B>(key: K, f: (a: A) => TaskMaybe<B>) => (data: TaskMaybe<A>) => TaskMaybe<A & { [P in K]: B; }>;
1091
- /**
1092
- * Recovers from a None state by providing a fallback Task.Maybe.
1093
- *
1094
- * @example
1095
- * ```ts
1096
- * pipe(
1097
- * Task.Maybe.none(),
1098
- * Task.Maybe.recover(() => Task.Maybe.some(42))
1099
- * ); // Task.Maybe(42)
1100
- * ```
1101
- */
1102
- recover: <B>(fallback: () => TaskMaybe<B>) => <A>(data: TaskMaybe<A>) => TaskMaybe<A | B>;
1103
- /**
1104
- * Combines a record of Task.Maybes into a single Task.Maybe of a record.
1105
- * Evaluates fields in parallel and returns None if any task resolves to None.
1106
- *
1107
- * @example
1108
- * ```ts
1109
- * Task.Maybe.struct({
1110
- * name: Task.Maybe.some("Alice"),
1111
- * age: Task.Maybe.some(30)
1112
- * }); // Task.Maybe({ name: "Alice", age: 30 })
1113
- * ```
1114
- */
1115
- struct: <R extends Record<string, any>>(fields: { [K in keyof R]: TaskMaybe<R[K]>; }) => TaskMaybe<R>;
1116
- /**
1117
- * Creates a memoized version of a Task.Maybe. The task is executed at most once on first call,
1118
- * and its resolved Maybe is cached for all subsequent calls.
1119
- *
1120
- * @example
1121
- * ```ts
1122
- * const loadUser = Task.Maybe.memoize(fetchUserMaybeTask);
1123
- * ```
1124
- */
1125
- memoize: <A>(task: TaskMaybe<A>) => TaskMaybe<A>;
1126
- };
1127
-
1128
- /**
1129
- * A Task that can fail with an error of type E or succeed with a value of type A.
1130
- * Combines async operations with typed error handling.
1131
- *
1132
- * @example
1133
- * ```ts
1134
- * const fetchUser = (id: string): Task.Result<Error, User> =>
1135
- * Task.Result.tryCatch(
1136
- * (signal) => fetch(`/users/${id}`, { signal }).then(r => r.json()),
1137
- * { onError: (e) => new Error(`Failed to fetch user: ${e}`) }
1138
- * );
1139
- * ```
1140
- */
1141
- type TaskResult<E, A> = Task<Result<E, A>>;
1142
- declare const TaskResult: {
1143
- make: {
1144
- /**
1145
- * Wraps a value in a successful Task.Result.
1146
- *
1147
- * @example
1148
- * ```ts
1149
- * const task = Task.Result.make.ok(42);
1150
- * const res = await task(); // Ok(42)
1151
- * ```
1152
- */
1153
- ok: <E = never, A = unknown>(value: A) => TaskResult<E, A>;
1154
- /**
1155
- * Creates a failed Task.Result with the given error.
1156
- *
1157
- * @example
1158
- * ```ts
1159
- * const task = Task.Result.make.err("failed");
1160
- * const res = await task(); // Err("failed")
1161
- * ```
1162
- */
1163
- err: <E, A = never>(error: E) => TaskResult<E, A>;
1164
- };
1165
- ok: <E = never, A = unknown>(value: A) => TaskResult<E, A>;
1166
- err: <E, A = never>(error: E) => TaskResult<E, A>;
1167
- from: {
1168
- /**
1169
- * Creates a Task.Result from a nullable value.
1170
- * Returns Ok if the value is not null or undefined, err from onNull otherwise.
1171
- *
1172
- * @example
1173
- * ```ts
1174
- * Task.Result.from.nullable(() => "missing")(42); // resolves to Ok(42)
1175
- * Task.Result.from.nullable(() => "missing")(null); // resolves to Err("missing")
1176
- * ```
1177
- */
1178
- nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => TaskResult<E, A>;
1179
- /**
1180
- * Creates a Task.Result from a Maybe.
1181
- * Some becomes Ok, None becomes err from onNone.
1182
- *
1183
- * @example
1184
- * ```ts
1185
- * Task.Result.from.Maybe(() => "empty")(Maybe.make.some(42)); // resolves to Ok(42)
1186
- * Task.Result.from.Maybe(() => "empty")(Maybe.make.none()); // resolves to Err("empty")
1187
- * ```
1188
- */
1189
- Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => TaskResult<E, A>;
1190
- /**
1191
- * Lifts a Result into a Task.Result.
1192
- *
1193
- * @example
1194
- * ```ts
1195
- * Task.Result.from.Result(Result.make.ok(42)); // resolves to Ok(42)
1196
- * ```
1197
- */
1198
- Result: <E, A>(result: Result<E, A>) => TaskResult<E, A>;
1199
- };
1200
- to: {
1201
- /**
1202
- * Converts a Task.Result to a Task.Maybe, dropping the error value on Err.
1203
- *
1204
- * @example
1205
- * ```ts
1206
- * const taskResult = Task.Result.ok(42);
1207
- * const taskMaybe = pipe(taskResult, Task.Result.to.Maybe);
1208
- * ```
1209
- */
1210
- Maybe: <E, A>(data: TaskResult<E, A>) => TaskMaybe<A>;
1211
- };
1212
- /**
1213
- * Creates a Task.Result from a Promise-returning thunk that may throw or reject.
1214
- * Catches any errors and transforms them using the `onError` function into an `Err`.
1215
- * The thunk optionally receives an `AbortSignal` forwarded from the call site.
1216
- *
1217
- * @example
1218
- * ```ts
1219
- * const loadUser = Task.Result.tryCatch(
1220
- * (signal) => userStore.get("u_123", { signal }),
1221
- * { onError: (e) => new DbError(e) }
1222
- * );
1223
- * ```
1224
- */
1225
- tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
1226
- onError: (error: unknown) => E;
1227
- }) => TaskResult<E, A>;
1228
- /**
1229
- * Transforms the success value inside a Task.Result.
1230
- */
1231
- map: <E, A, B>(f: (a: A) => B) => (data: TaskResult<E, A>) => TaskResult<E, B>;
1232
- /**
1233
- * Transforms the error value inside a Task.Result.
1234
- */
1235
- mapError: <E, F, A>(f: (e: E) => F) => (data: TaskResult<E, A>) => TaskResult<F, A>;
1236
- /**
1237
- * Chains Task.Result computations. If the first succeeds, passes the value to f.
1238
- * If the first fails, propagates the error.
1239
- */
1240
- chain: <E2, A, B>(f: (a: A) => TaskResult<E2, B>) => <E1 = never>(data: TaskResult<E1, A>) => TaskResult<E1 | E2, B>;
1241
- /**
1242
- * Extracts the value from a Task.Result by providing handlers for both cases.
1243
- */
1244
- fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: TaskResult<E, A>) => Task<B>;
1245
- /**
1246
- * Pattern matches on a Task.Result, returning a Task of the result.
1247
- */
1248
- match: <E, A, B>(cases: {
1249
- err: (e: E) => B;
1250
- ok: (a: A) => B;
1251
- }) => (data: TaskResult<E, A>) => Task<B>;
1252
- /**
1253
- * Recovers from an error by providing a fallback Task.Result.
1254
- * The fallback can produce a different success type, widening the result to `Task.Result<E, A | B>`.
1255
- */
1256
- recover: <E, B>(fallback: (e: E) => TaskResult<E, B>) => <A>(data: TaskResult<E, A>) => TaskResult<E, A | B>;
1257
- /**
1258
- * Recovers from an error unless the predicate `isBlocked` returns true for that error.
1259
- * The fallback can produce a different success type, widening the result to `Task.Result<E, A | B>`.
1260
- *
1261
- * @example
1262
- * ```ts
1263
- * pipe(
1264
- * fetchTask,
1265
- * Task.Result.recoverUnless(
1266
- * (e) => e === "fatal",
1267
- * () => Task.Result.ok("fallback")
1268
- * )
1269
- * );
1270
- * ```
1271
- */
1272
- recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: (e: E) => TaskResult<E, B>) => <A>(data: TaskResult<E, A>) => TaskResult<E, A | B>;
1273
- /**
1274
- * Returns the success value or a default value if the Task.Result is an error.
1275
- * The default can be a different type, widening the result to `Task<A | B>`.
1276
- */
1277
- getOrElse: <B>(defaultValue: () => B) => <E, A>(data: TaskResult<E, A>) => Task<A | B>;
1278
- /**
1279
- * Executes a side effect on the success value without changing the Task.Result.
1280
- * Useful for logging or debugging.
1281
- */
1282
- tap: <E, A>(f: (a: A) => void) => (data: TaskResult<E, A>) => TaskResult<E, A>;
1283
- /**
1284
- * Executes a side effect on the error value without changing the Task.Result.
1285
- * Useful for logging or reporting async errors.
1286
- *
1287
- * @example
1288
- * ```ts
1289
- * pipe(
1290
- * fetchUser(id),
1291
- * Task.Result.tapError(e => console.error("fetch failed:", e)),
1292
- * Task.Result.chain(saveToCache),
1293
- * )
1294
- * ```
1295
- */
1296
- tapError: <E, A>(f: (e: E) => void) => (data: TaskResult<E, A>) => TaskResult<E, A>;
1297
- /**
1298
- * Applies a function wrapped in a Task.Result to a value wrapped in a Task.Result.
1299
- * Both Tasks run in parallel.
1300
- */
1301
- ap: <E, A>(arg: TaskResult<E, A>) => <B>(data: TaskResult<E, (a: A) => B>) => TaskResult<E, B>;
1302
- /**
1303
- * Executes a `Task.Result` with an optional signal, returning `Promise<Result<E, A>>`.
1304
- * Use as a terminal step in a `pipe` chain.
1305
- *
1306
- * @example
1307
- * ```ts
1308
- * const controller = new AbortController();
1309
- * const result = await pipe(
1310
- * fetchUser("42"),
1311
- * Task.Result.chain(user => fetchPosts(user.id)),
1312
- * Task.Result.run(controller.signal),
1313
- * );
1314
- * if (Result.is.ok(result)) render(result.value);
1315
- * ```
1316
- */
1317
- run: (signal?: AbortSignal) => <E, A>(task: TaskResult<E, A>) => Deferred<Result<E, A>>;
1318
- /**
1319
- * Converts a Task.Result value into an object containing a single property.
1320
- * Initiates the pipeline accumulator record.
1321
- *
1322
- * @example
1323
- * ```ts
1324
- * pipe(Task.Result.ok(42), Task.Result.bindTo("value")); // Task.Result({ value: 42 })
1325
- * ```
1326
- */
1327
- bindTo: <K extends string>(key: K) => <E, A>(data: TaskResult<E, A>) => TaskResult<E, { [P in K]: A; }>;
1328
- /**
1329
- * Evaluates a new Task.Result using the current accumulator and attaches the output to a new key.
1330
- *
1331
- * @example
1332
- * ```ts
1333
- * pipe(
1334
- * Task.Result.ok({ a: 1 }),
1335
- * Task.Result.bind("b", ({ a }) => Task.Result.ok(a + 1))
1336
- * ); // Task.Result({ a: 1, b: 2 })
1337
- * ```
1338
- */
1339
- bind: <K extends string, E, A, B>(key: K, f: (a: A) => TaskResult<E, B>) => (data: TaskResult<E, A>) => TaskResult<E, A & { [P in K]: B; }>;
1340
- /**
1341
- * Combines a record of Task.Results into a single Task.Result of a record.
1342
- * Evaluates all tasks in parallel, forwarding the AbortSignal down to each sub-task.
1343
- * Returns the first Err encountered in key order.
1344
- *
1345
- * @example
1346
- * ```ts
1347
- * Task.Result.struct({
1348
- * name: Task.Result.ok("Alice"),
1349
- * age: Task.Result.ok(30)
1350
- * }); // Task.Result({ name: "Alice", age: 30 })
1351
- * ```
1352
- */
1353
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: TaskResult<E, R[K]>; }) => TaskResult<E, R>;
1354
- /**
1355
- * Retries a fallible Task.Result according to a RetryPolicy.
1356
- * If the task succeeds, returns Ok immediately.
1357
- * If the task fails, retries up to policy.attempts times with delays generated by policy.
1358
- *
1359
- * @example
1360
- * ```ts
1361
- * const policy = RetryPolicy.exponential({ attempts: 3, initial: Duration.milliseconds(100) });
1362
- * const retryableFetch = pipe(fetchData, Task.Result.retry(policy));
1363
- * ```
1364
- */
1365
- retry: (policy: RetryPolicy) => <E, A>(task: TaskResult<E, A>) => TaskResult<E, A>;
1366
- /**
1367
- * Creates a memoized version of a Task.Result. The task is executed at most once on first call,
1368
- * and its resolved Result is cached for all subsequent calls.
1369
- *
1370
- * @example
1371
- * ```ts
1372
- * const loadConfig = Task.Result.memoize(fetchConfigTask);
1373
- * ```
1374
- */
1375
- memoize: <E, A>(task: TaskResult<E, A>) => TaskResult<E, A>;
1376
- /**
1377
- * Times out a fallible task, resolving to `Err(onTimeout())` if the duration elapses
1378
- * before the task completes.
1379
- *
1380
- * @example
1381
- * ```ts
1382
- * const fetchWithTimeout = pipe(
1383
- * fetchTask,
1384
- * Task.Result.timeout({ duration: Duration.seconds(5), onTimeout: () => "Request timed out" })
1385
- * );
1386
- * ```
1387
- */
1388
- timeout: <E2>(options: {
1389
- duration: Duration;
1390
- onTimeout: () => E2;
1391
- }) => <E1 = never, A = unknown>(task: TaskResult<E1, A>) => TaskResult<E1 | E2, A>;
1392
- /**
1393
- * Runs a list of fallible tasks in parallel and collects all outcomes (`Ok` and `Err`)
1394
- * without short-circuiting on failure.
1395
- *
1396
- * @example
1397
- * ```ts
1398
- * const results = await Task.Result.allSettled([task1, task2, task3])();
1399
- * // [Ok(val1), Err(err2), Ok(val3)]
1400
- * ```
1401
- */
1402
- allSettled: <E, A>(tasks: ReadonlyArray<TaskResult<E, A>>) => Task<ReadonlyArray<Result<E, A>>>;
1403
- };
1404
-
1405
- /**
1406
- * A Task that resolves to a Validation — combining async operations with
1407
- * error accumulation. Unlike Task.Result, multiple failures are collected
1408
- * rather than short-circuiting on the first error.
1409
- *
1410
- * @example
1411
- * ```ts
1412
- * const validateName = (name: string): Task.Validation<string, string> =>
1413
- * name.length > 0
1414
- * ? Task.Validation.passed(name)
1415
- * : Task.Validation.failed("Name is required");
1416
- *
1417
- * // Accumulate errors from multiple async validations using ap
1418
- * pipe(
1419
- * Task.Validation.passed((name: string) => (age: number) => ({ name, age })),
1420
- * Task.Validation.ap(validateName("")),
1421
- * Task.Validation.ap(validateAge(-1))
1422
- * )();
1423
- * // Failed(["Name is required", "Age must be positive"])
1424
- * ```
1425
- */
1426
- type TaskValidation<E, A> = Task<Validation<E, A>>;
1427
- declare const TaskValidation: {
1428
- make: {
1429
- /**
1430
- * Wraps a value in a passed Task.Validation.
1431
- *
1432
- * @example
1433
- * ```ts
1434
- * const task = Task.Validation.make.passed(42);
1435
- * const res = await task(); // Passed(42)
1436
- * ```
1437
- */
1438
- passed: <E = never, A = unknown>(value: A) => TaskValidation<E, A>;
1439
- /**
1440
- * Creates a failed Task.Validation with a single error.
1441
- *
1442
- * @example
1443
- * ```ts
1444
- * const task = Task.Validation.make.failed("invalid");
1445
- * const res = await task(); // Failed(["invalid"])
1446
- * ```
1447
- */
1448
- failed: <E, A = never>(error: E) => TaskValidation<E, A>;
1449
- /**
1450
- * Creates a failed Task.Validation from multiple errors.
1451
- *
1452
- * @example
1453
- * ```ts
1454
- * const task = Task.Validation.make.failedAll(["err1", "err2"]);
1455
- * const res = await task(); // Failed(["err1", "err2"])
1456
- * ```
1457
- */
1458
- failedAll: <E, A = never>(errors: NonEmptyArr<E>) => TaskValidation<E, A>;
1459
- };
1460
- passed: <E = never, A = unknown>(value: A) => TaskValidation<E, A>;
1461
- failed: <E, A = never>(error: E) => TaskValidation<E, A>;
1462
- failedAll: <E, A = never>(errors: NonEmptyArr<E>) => TaskValidation<E, A>;
1463
- from: {
1464
- /**
1465
- * Lifts a Validation into a Task.Validation.
1466
- *
1467
- * @example
1468
- * ```ts
1469
- * Task.Validation.from.Validation(Validation.make.passed(42));
1470
- * ```
1471
- */
1472
- Validation: <E, A>(validation: Validation<E, A>) => TaskValidation<E, A>;
1473
- /**
1474
- * Creates a Task.Validation from a nullable value.
1475
- * If the value is null or undefined, returns Failed with the error from onNull.
1476
- * Otherwise, returns Passed.
1477
- *
1478
- * @example
1479
- * ```ts
1480
- * Task.Validation.from.nullable(() => "missing")(42); // resolves to Passed(42)
1481
- * Task.Validation.from.nullable(() => "missing")(null); // resolves to Failed(["missing"])
1482
- * ```
1483
- */
1484
- nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => TaskValidation<E, A>;
1485
- /**
1486
- * Creates a Task.Validation from a Maybe.
1487
- * Some becomes Passed, None becomes Failed with the error from onNone.
1488
- *
1489
- * @example
1490
- * ```ts
1491
- * Task.Validation.from.Maybe(() => "empty")(Maybe.make.some(42)); // resolves to Passed(42)
1492
- * Task.Validation.from.Maybe(() => "empty")(Maybe.make.none()); // resolves to Failed(["empty"])
1493
- * ```
1494
- */
1495
- Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => TaskValidation<E, A>;
1496
- /**
1497
- * Creates a Task.Validation from a Result.
1498
- * Ok becomes Passed, Err(e) becomes Failed([e]).
1499
- *
1500
- * @example
1501
- * ```ts
1502
- * Task.Validation.from.Result(Result.make.ok(42)); // resolves to Passed(42)
1503
- * Task.Validation.from.Result(Result.make.err("bad")); // resolves to Failed(["bad"])
1504
- * ```
1505
- */
1506
- Result: <E, A>(result: Result<E, A>) => TaskValidation<E, A>;
1507
- };
1508
- to: {
1509
- /**
1510
- * Converts a `Task.Validation` to a `Task.Result`, combining accumulated errors using `combineErrors`.
1511
- * `Passed(a)` becomes `Ok(a)`; `Failed(errors)` becomes `Err(combineErrors(errors))`.
1512
- *
1513
- * @example
1514
- * ```ts
1515
- * Task.Validation.to.Result((errors) => errors.join(", "))(validationTask);
1516
- * ```
1517
- */
1518
- Result: <E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2) => (data: TaskValidation<E1, A>) => TaskResult<E2, A>;
1519
- /**
1520
- * Converts a `Task.Validation` to a `Task.Maybe`.
1521
- * `Passed(a)` becomes `Some(a)`; `Failed(errors)` becomes `None` (errors are discarded).
1522
- *
1523
- * @example
1524
- * ```ts
1525
- * Task.Validation.to.Maybe(validationTask);
1526
- * ```
1527
- */
1528
- Maybe: <E, A>(data: TaskValidation<E, A>) => TaskMaybe<A>;
1529
- };
1530
- /**
1531
- * Creates a Task.Validation from a Promise-returning thunk that may throw or reject.
1532
- * Catches any errors and transforms them using the `onError` function into a Failed validation.
1533
- * The thunk optionally receives an `AbortSignal` forwarded from the call site.
1534
- *
1535
- * @example
1536
- * ```ts
1537
- * const loadConfig = Task.Validation.tryCatch(
1538
- * (signal) => configStore.get("default", { signal }),
1539
- * { onError: (e) => `Failed to load config: ${e}` }
1540
- * );
1541
- * ```
1542
- */
1543
- tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
1544
- onError: (error: unknown) => E;
1545
- }) => TaskValidation<E, A>;
1546
- /**
1547
- * Transforms the success value inside a Task.Validation.
1548
- */
1549
- map: <E, A, B>(f: (a: A) => B) => (data: TaskValidation<E, A>) => TaskValidation<E, B>;
1550
- /**
1551
- * Applies a function wrapped in a Task.Validation to a value wrapped in a
1552
- * Task.Validation. Both Tasks run in parallel and errors from both sides
1553
- * are accumulated.
1554
- *
1555
- * @example
1556
- * ```ts
1557
- * pipe(
1558
- * Task.Validation.passed((name: string) => (age: number) => ({ name, age })),
1559
- * Task.Validation.ap(validateName(name)),
1560
- * Task.Validation.ap(validateAge(age))
1561
- * )();
1562
- * ```
1563
- */
1564
- ap: <E, A>(arg: TaskValidation<E, A>) => <B>(data: TaskValidation<E, (a: A) => B>) => TaskValidation<E, B>;
1565
- /**
1566
- * Extracts a value from a Task.Validation by providing handlers for both cases.
1567
- */
1568
- fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: TaskValidation<E, A>) => Task<B>;
1569
- /**
1570
- * Pattern matches on a Task.Validation, returning a Task of the result.
1571
- *
1572
- * @example
1573
- * ```ts
1574
- * pipe(
1575
- * validateForm(input),
1576
- * Task.Validation.match({
1577
- * passed: data => save(data),
1578
- * failed: errors => showErrors(errors)
1579
- * })
1580
- * )();
1581
- * ```
1582
- */
1583
- match: <E, A, B>(cases: {
1584
- passed: (a: A) => B;
1585
- failed: (errors: NonEmptyArr<E>) => B;
1586
- }) => (data: TaskValidation<E, A>) => Task<B>;
1587
- /**
1588
- * Returns the success value or a default value if the Task.Validation is failed.
1589
- * The default can be a different type, widening the result to `Task<A | B>`.
1590
- */
1591
- getOrElse: <B>(defaultValue: () => B) => <E, A>(data: TaskValidation<E, A>) => Task<A | B>;
1592
- /**
1593
- * Executes a side effect on the success value without changing the Task.Validation.
1594
- * Useful for logging or debugging.
1595
- */
1596
- tap: <E, A>(f: (a: A) => void) => (data: TaskValidation<E, A>) => TaskValidation<E, A>;
1597
- /**
1598
- * Recovers from a Failed state by providing a fallback Task.Validation.
1599
- * The fallback receives the accumulated error list so callers can inspect which errors occurred.
1600
- * The fallback can produce a different success type, widening the result to `Task.Validation<E, A | B>`.
1601
- */
1602
- recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => TaskValidation<E, B>) => <A>(data: TaskValidation<E, A>) => TaskValidation<E, A | B>;
1603
- /**
1604
- * Recovers from a Failed state unless the predicate `isBlocked` returns true for the accumulated errors.
1605
- * The fallback receives the accumulated errors and can produce a different success type, widening the result to `Task.Validation<E, A | B>`.
1606
- *
1607
- * @example
1608
- * ```ts
1609
- * pipe(
1610
- * validationTask,
1611
- * Task.Validation.recoverUnless(
1612
- * (errors) => errors.includes("fatal"),
1613
- * (errors) => Task.Validation.passed("fallback")
1614
- * )
1615
- * );
1616
- * ```
1617
- */
1618
- recoverUnless: <E, B>(isBlocked: (errors: NonEmptyArr<E>) => boolean, fallback: (errors: NonEmptyArr<E>) => TaskValidation<E, B>) => <A>(data: TaskValidation<E, A>) => TaskValidation<E, A | B>;
1619
- /**
1620
- * Runs two Task.Validations concurrently and combines their results into a tuple.
1621
- * If both are Passed, returns Passed with both values. If either fails, accumulates
1622
- * errors from both sides.
1623
- *
1624
- * @example
1625
- * ```ts
1626
- * await Task.Validation.product(
1627
- * validateName(form.name),
1628
- * validateAge(form.age),
1629
- * )(); // Passed(["Alice", 30]) or Failed([...errors])
1630
- * ```
1631
- */
1632
- product: <E, A, B>(first: TaskValidation<E, A>, second: TaskValidation<E, B>) => TaskValidation<E, readonly [A, B]>;
1633
- /**
1634
- * Runs all Task.Validations concurrently and collects results.
1635
- * If all are Passed, returns Passed with all values as an array.
1636
- * If any fail, returns Failed with all accumulated errors.
1637
- *
1638
- * @example
1639
- * ```ts
1640
- * await Task.Validation.productAll([
1641
- * validateName(form.name),
1642
- * validateEmail(form.email),
1643
- * validateAge(form.age),
1644
- * ])(); // Passed([name, email, age]) or Failed([...all errors])
1645
- * ```
1646
- */
1647
- productAll: <E, A>(data: NonEmptyArr<TaskValidation<E, A>>) => TaskValidation<E, readonly A[]>;
1648
- /**
1649
- * Transforms all accumulated errors inside a Task.Validation.
1650
- *
1651
- * @example
1652
- * ```ts
1653
- * pipe(
1654
- * Task.Validation.failed("oops"),
1655
- * Task.Validation.mapError(e => e.toUpperCase())
1656
- * ); // Task.Validation(Failed(["OOPS"]))
1657
- * ```
1658
- */
1659
- mapError: <E, F, A>(f: (e: E) => F) => (data: TaskValidation<E, A>) => TaskValidation<F, A>;
1660
- /**
1661
- * Executes a side effect on the accumulated errors without changing the Task.Validation.
1662
- *
1663
- * @example
1664
- * ```ts
1665
- * pipe(
1666
- * Task.Validation.failed("invalid name"),
1667
- * Task.Validation.tapError(errs => logger.error(errs))
1668
- * );
1669
- * ```
1670
- */
1671
- tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: TaskValidation<E, A>) => TaskValidation<E, A>;
1672
- /**
1673
- * Combines a record of Task.Validations into a single Task.Validation of a record.
1674
- * Evaluates fields in parallel and accumulates all validation errors.
1675
- *
1676
- * @example
1677
- * ```ts
1678
- * Task.Validation.struct({
1679
- * name: Task.Validation.passed("Alice"),
1680
- * age: Task.Validation.passed(30)
1681
- * }); // Task.Validation({ name: "Alice", age: 30 })
1682
- * ```
1683
- */
1684
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: TaskValidation<E, R[K]>; }) => TaskValidation<E, R>;
1685
- /**
1686
- * Creates a memoized version of a Task.Validation. The task is executed at most once on first call,
1687
- * and its resolved Validation is cached for all subsequent calls.
1688
- *
1689
- * @example
1690
- * ```ts
1691
- * const validate = Task.Validation.memoize(validateFormTask);
1692
- * ```
1693
- */
1694
- memoize: <E, A>(task: TaskValidation<E, A>) => TaskValidation<E, A>;
1695
- };
1696
-
1697
- /**
1698
- * A lazy async computation that always resolves.
1699
- *
1700
- * Two guarantees:
1701
- * - **Lazy** — nothing starts until you call it.
1702
- * - **Infallible** — it never rejects. If failure is possible, encode it in the
1703
- * return type using `Task.Result<E, A>` instead.
1704
- *
1705
- * An optional `AbortSignal` can be passed at the call site. Combinators like
1706
- * `retry`, `pollUntil`, and `timeout` thread it automatically to every inner
1707
- * operation. Existing tasks that ignore the signal continue to work unchanged.
1708
- *
1709
- * Calling a Task returns a `Deferred<A>` — a one-shot async value that supports
1710
- * `await` but has no `.catch()`, `.finally()`, or chainable `.then()`.
1711
- *
1712
- * **Consuming a Task:**
1713
- *
1714
- * Use `await task()` to run it and get the value directly:
1715
- * ```ts
1716
- * const value: number = await task();
1717
- * ```
1718
- *
1719
- * When you need an explicit `Promise<A>` (e.g. for a third-party API), convert
1720
- * the `Deferred` with `Deferred.to.Promise`:
1721
- * ```ts
1722
- * const p: Promise<number> = Deferred.to.Promise(task());
1723
- * ```
1724
- *
1725
- * @example
1726
- * ```ts
1727
- * const getTimestamp: Task<number> = Task.resolve(Date.now());
1728
- *
1729
- * // Nothing runs yet — getTimestamp is just a description
1730
- * const formatted = pipe(
1731
- * getTimestamp,
1732
- * Task.map(ts => new Date(ts).toISOString())
1733
- * );
1734
- *
1735
- * // Execute when ready
1736
- * const result = await formatted();
1737
- * ```
1738
- */
1739
- type Task<A> = (signal?: AbortSignal) => Deferred<A>;
1740
- declare const Task: {
1741
- /**
1742
- * Creates a Task that immediately resolves to the given value.
1743
- *
1744
- * @example
1745
- * ```ts
1746
- * const task = Task.resolve(42);
1747
- * const value = await task(); // 42
1748
- * ```
1749
- */
1750
- resolve: <A>(value: A) => Task<A>;
1751
- from: {
1752
- /**
1753
- * Creates a Task from a lazy synchronous thunk.
1754
- * Unlike `Task.resolve(f())`, `from.sync` does not evaluate `f` until the Task is called.
1755
- *
1756
- * @example
1757
- * ```ts
1758
- * const t = Task.from.sync(() => Date.now()); // Date.now() not called yet
1759
- * const ts = await t(); // called here, every time
1760
- * ```
1761
- */
1762
- sync: <A>(f: () => A) => Task<A>;
1763
- };
1764
- /**
1765
- * Wraps a Promise-returning thunk that may throw or reject,
1766
- * trapping errors with a fallback function and returning a guaranteed `Task<A>`.
1767
- *
1768
- * @example
1769
- * ```ts
1770
- * const loadConfig = Task.tryCatch(
1771
- * () => configStore.get("default"),
1772
- * { onError: () => DEFAULT_CONFIG }
1773
- * );
1774
- * ```
1775
- */
1776
- tryCatch: <A>(f: (signal?: AbortSignal) => globalThis.Promise<A>, options: {
1777
- onError: (error: unknown) => A;
1778
- }) => Task<A>;
1779
- /**
1780
- * Transforms the value inside a Task.
1781
- *
1782
- * @example
1783
- * ```ts
1784
- * pipe(
1785
- * Task.resolve(5),
1786
- * Task.map(n => n * 2)
1787
- * )(); // Deferred<10>
1788
- * ```
1789
- */
1790
- map: <A, B>(f: (a: A) => B) => (data: Task<A>) => Task<B>;
1791
- /**
1792
- * Chains Task computations. Passes the resolved value of the first Task to f.
1793
- *
1794
- * @example
1795
- * ```ts
1796
- * const readUserId: Task<string> = Task.resolve(session.userId);
1797
- * const loadPrefs = (id: string): Task<Preferences> =>
1798
- * Task.resolve(prefsCache.get(id));
1799
- *
1800
- * pipe(
1801
- * readUserId,
1802
- * Task.chain(loadPrefs)
1803
- * )(); // Deferred<Preferences>
1804
- * ```
1805
- */
1806
- chain: <A, B>(f: (a: A) => Task<B>) => (data: Task<A>) => Task<B>;
1807
- /**
1808
- * Applies a function wrapped in a Task to a value wrapped in a Task.
1809
- * Both Tasks run in parallel.
1810
- *
1811
- * @example
1812
- * ```ts
1813
- * const add = (a: number) => (b: number) => a + b;
1814
- * pipe(
1815
- * Task.resolve(add),
1816
- * Task.ap(Task.resolve(5)),
1817
- * Task.ap(Task.resolve(3))
1818
- * )(); // Deferred<8>
1819
- * ```
1820
- */
1821
- ap: <A>(arg: Task<A>) => <B>(data: Task<(a: A) => B>) => Task<B>;
1822
- /**
1823
- * Executes a side effect on the value without changing the Task.
1824
- * Useful for logging or debugging.
1825
- *
1826
- * @example
1827
- * ```ts
1828
- * pipe(
1829
- * loadConfig,
1830
- * Task.tap(cfg => console.log("Config:", cfg)),
1831
- * Task.map(buildReport)
1832
- * );
1833
- * ```
1834
- */
1835
- tap: <A>(f: (a: A) => void) => (data: Task<A>) => Task<A>;
1836
- /**
1837
- * Runs multiple Tasks in parallel and collects their results.
1838
- *
1839
- * @example
1840
- * ```ts
1841
- * Task.all([loadConfig, detectLocale, loadTheme])();
1842
- * // Deferred<[Config, string, Theme]>
1843
- * ```
1844
- */
1845
- all: <T extends readonly Task<unknown>[]>(tasks: T) => Task<{ [K in keyof T]: T[K] extends Task<infer A> ? A : never; }>;
1846
- /**
1847
- * Delays the execution of a Task by the specified duration.
1848
- * Useful for debouncing or rate limiting.
1849
- *
1850
- * @example
1851
- * ```ts
1852
- * pipe(
1853
- * Task.resolve(42),
1854
- * Task.delay(Duration.seconds(1))
1855
- * )(); // Resolves after 1 second
1856
- * ```
1857
- */
1858
- delay: (duration: Duration) => <A>(data: Task<A>) => Task<A>;
1859
- /**
1860
- * Runs a Task a fixed number of times sequentially, collecting all results into an array.
1861
- * An optional delay duration can be inserted between runs.
1862
- *
1863
- * @example
1864
- * ```ts
1865
- * pipe(
1866
- * pollSensor,
1867
- * Task.repeat({ times: 5, delay: Duration.seconds(1) })
1868
- * )(); // Task<Reading[]> — 5 readings, one per second
1869
- * ```
1870
- */
1871
- repeat: (options: {
1872
- times: number;
1873
- delay?: Duration;
1874
- }) => <A>(task: Task<A>) => Task<readonly A[]>;
1875
- /**
1876
- * Runs a Task repeatedly until the result satisfies a predicate, returning that result.
1877
- * An optional delay duration can be inserted between runs.
1878
- * An optional `maxAttempts` cap stops the loop after N calls — the last value is returned
1879
- * regardless of whether the predicate was satisfied.
1880
- *
1881
- * @example
1882
- * ```ts
1883
- * pipe(
1884
- * checkStatus,
1885
- * Task.repeatUntil({ when: (s) => s === "ready", delay: Duration.milliseconds(500) })
1886
- * )(); // polls every 500ms until status is "ready"
1887
- * ```
1888
- */
1889
- repeatUntil: <A>(options: {
1890
- when: (a: A) => boolean;
1891
- delay?: Duration;
1892
- maxAttempts?: number;
1893
- }) => (task: Task<A>) => Task<A>;
1894
- /**
1895
- * Resolves with the value of the first Task to complete. All Tasks start
1896
- * immediately. When one resolves, the other tasks are cancelled (aborted)
1897
- * downstream.
1898
- *
1899
- * @example
1900
- * ```ts
1901
- * const fast = Task.resolve("fast");
1902
- * const slow = Task.delay(Duration.milliseconds(200))(Task.resolve("slow"));
1903
- *
1904
- * await Task.race([fast, slow])(); // "fast"
1905
- * ```
1906
- */
1907
- race: <A>(tasks: ReadonlyArray<Task<A>>) => Task<A>;
1908
- /**
1909
- * Runs an array of Tasks concurrently and collects their results in an array.
1910
- * Forward-propagates the call site's AbortSignal to all subtasks concurrently.
1911
- *
1912
- * @example
1913
- * ```ts
1914
- * Task.sequence([loadConfig, detectLocale, loadTheme])();
1915
- * // Deferred<[Config, string, Theme]>
1916
- * ```
1917
- */
1918
- sequence: <A>(tasks: ReadonlyArray<Task<A>>) => Task<ReadonlyArray<A>>;
1919
- /**
1920
- * Runs an array of Tasks one at a time in order, collecting all results.
1921
- * Each Task starts only after the previous one resolves.
1922
- *
1923
- * @example
1924
- * ```ts
1925
- * let log: number[] = [];
1926
- * const makeTask = (n: number) => Task.resolve(n);
1927
- *
1928
- * await Task.sequential([makeTask(1), makeTask(2), makeTask(3)])();
1929
- * // log = [1, 2, 3] — tasks ran in order
1930
- * ```
1931
- */
1932
- sequential: <A>(tasks: ReadonlyArray<Task<A>>) => Task<ReadonlyArray<A>>;
1933
- /**
1934
- * Converts a `Task<A>` into a `Task<Result<E, A>>`, resolving to `Err` if the
1935
- * Task does not complete within the given duration. The inner Task receives an
1936
- * `AbortSignal` that fires when the deadline passes, so asynchronous operations
1937
- * that accept a signal are cancelled rather than left dangling.
1938
- *
1939
- * @example
1940
- * ```ts
1941
- * pipe(
1942
- * heavyComputation,
1943
- * Task.timeout({ duration: Duration.seconds(5), onTimeout: () => "timed out" }),
1944
- * Task.Result.chain(processResult)
1945
- * );
1946
- * ```
1947
- */
1948
- timeout: <E>(options: {
1949
- duration: Duration;
1950
- onTimeout: () => E;
1951
- }) => <A>(task: Task<A>) => Task<Result<E, A>>;
1952
- /**
1953
- * Creates a Task paired with an `abort` handle. Calling `abort()` cancels the
1954
- * current in-flight call immediately. Unlike a one-shot abort, calling `task()`
1955
- * again after `abort()` starts a fresh call with a new signal.
1956
- *
1957
- * Each invocation of `task()` automatically cancels the previous in-flight call,
1958
- * making it safe to call repeatedly (e.g. on user input) without leaking promises.
1959
- *
1960
- * If an outer signal is also present (passed at the call site), aborting it
1961
- * propagates into the internal controller.
1962
- *
1963
- * @example
1964
- * ```ts
1965
- * const { task: poll, abort } = Task.abortable(
1966
- * (signal) => waitForEvent(bus, "ready", { signal }),
1967
- * );
1968
- *
1969
- * onUnmount(abort);
1970
- * await poll();
1971
- * ```
1972
- */
1973
- abortable: <A>(factory: (signal: AbortSignal) => Thenable<A>) => {
1974
- task: Task<A>;
1975
- abort: () => void;
1976
- };
1977
- /**
1978
- * Executes a task with an optional signal. Use as a terminal step in a `pipe` chain.
1979
- *
1980
- * @example
1981
- * ```ts
1982
- * const name = await pipe(
1983
- * loadConfig,
1984
- * Task.map(config => config.name),
1985
- * Task.run(),
1986
- * );
1987
- * ```
1988
- */
1989
- run: (signal?: AbortSignal) => <A>(task: Task<A>) => Deferred<A>;
1990
- /**
1991
- * Converts a Task value into an object containing a single property.
1992
- * Initiates the pipeline accumulator record.
1993
- *
1994
- * @example
1995
- * ```ts
1996
- * pipe(Task.resolve(42), Task.bindTo("value")); // Task({ value: 42 })
1997
- * ```
1998
- */
1999
- bindTo: <K extends string>(key: K) => <A>(data: Task<A>) => Task<{ [P in K]: A; }>;
2000
- /**
2001
- * Evaluates a new Task using the current accumulator and attaches the output to a new key.
2002
- *
2003
- * @example
2004
- * ```ts
2005
- * pipe(
2006
- * Task.resolve({ a: 1 }),
2007
- * Task.bind("b", ({ a }) => Task.resolve(a + 1))
2008
- * ); // Task({ a: 1, b: 2 })
2009
- * ```
2010
- */
2011
- bind: <K extends string, A, B>(key: K, f: (a: A) => Task<B>) => (data: Task<A>) => Task<A & { [P in K]: B; }>;
2012
- /**
2013
- * Creates a memoized version of a Task. The task is executed at most once on first call,
2014
- * and its resolved value is cached for all subsequent calls.
2015
- *
2016
- * @example
2017
- * ```ts
2018
- * const loadToken = Task.memoize(loadAuthToken);
2019
- * const token1 = await loadToken(); // loads token
2020
- * const token2 = await loadToken(); // returns cached token immediately
2021
- * ```
2022
- */
2023
- memoize: <A>(task: Task<A>) => Task<A>;
2024
- /**
2025
- * Monitors progress of a Task by calling `onProgress(0)` before execution and `onProgress(1)` upon completion.
2026
- *
2027
- * @example
2028
- * ```ts
2029
- * const taskWithProgress = pipe(
2030
- * readTask,
2031
- * Task.withProgress((ratio) => console.log(`Progress: ${ratio * 100}%`))
2032
- * );
2033
- * ```
2034
- */
2035
- withProgress: <A>(onProgress: (ratio: number) => void) => (task: Task<A>) => Task<A>;
2036
- /**
2037
- * Attaches a read-only `.label` property to a Task, preserving the literal string generic type for IDE tooltips.
2038
- *
2039
- * @example
2040
- * ```ts
2041
- * const labeledTask = pipe(readTask, Task.withLabel("readUser"));
2042
- * console.log(labeledTask.label); // "readUser"
2043
- * ```
2044
- */
2045
- withLabel: <L extends string>(label: L) => <A>(task: Task<A>) => Task.LabeledTask<L, A>;
2046
- Maybe: {
2047
- make: {
2048
- some: <A>(value: A) => TaskMaybe<A>;
2049
- none: <A = never>() => TaskMaybe<A>;
2050
- };
2051
- some: <A>(value: A) => TaskMaybe<A>;
2052
- none: <A = never>() => TaskMaybe<A>;
2053
- from: {
2054
- Maybe: <A>(option: Maybe<A>) => TaskMaybe<A>;
2055
- nullable: <A>(value: A | null | undefined) => TaskMaybe<A>;
2056
- Result: <E, A>(result: Result<E, A>) => TaskMaybe<A>;
2057
- Task: <A>(task: Task<A>) => TaskMaybe<A>;
2058
- };
2059
- tryCatch: <A>(f: (signal?: AbortSignal) => Thenable<A>) => TaskMaybe<A>;
2060
- map: <A, B>(f: (a: A) => B) => (data: TaskMaybe<A>) => TaskMaybe<B>;
2061
- chain: <A, B>(f: (a: A) => TaskMaybe<B>) => (data: TaskMaybe<A>) => TaskMaybe<B>;
2062
- ap: <A>(arg: TaskMaybe<A>) => <// Deferred<10>
2063
- B>(data: TaskMaybe<(a: A) => B>) => TaskMaybe<B>;
2064
- fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: TaskMaybe<A>) => Task<B>;
2065
- match: <A, B>(cases: {
2066
- none: () => B;
2067
- some: (a: A) => B;
2068
- }) => (data: TaskMaybe<A>) => Task<B>;
2069
- getOrElse: <B>(defaultValue: () => B) => <A>(data: TaskMaybe<A>) => Task<A | B>;
2070
- tap: <A>(f: (a: A) => void) => (data: TaskMaybe<A>) => TaskMaybe<A>;
2071
- filter: <A>(predicate: (a: A) => boolean) => (data: TaskMaybe<A>) => TaskMaybe<A>;
2072
- to: {
2073
- Result: <E>(onNone: () => E) => <A>(data: TaskMaybe<A>) => Task.Result<E, A>;
2074
- };
2075
- bindTo: <K extends string>(key: K) => <A>(data: TaskMaybe<A>) => TaskMaybe<{ [P in K]: A; }>;
2076
- bind: <K extends string, A, B>(key: K, f: (a: A) => TaskMaybe<B>) => (data: TaskMaybe<A>) => TaskMaybe<A & { [P in K]: B; }>;
2077
- recover: <B>(fallback: () => TaskMaybe<B>) => <A>(data: TaskMaybe<A>) => TaskMaybe<A | B>;
2078
- struct: <R extends Record<string, any>>(fields: { [K in keyof R]: TaskMaybe<R[K]>; }) => TaskMaybe<R>;
2079
- memoize: <A>(task: TaskMaybe<A>) => TaskMaybe<A>;
2080
- };
2081
- Result: {
2082
- make: {
2083
- ok: <E = never, A = unknown>(value: A) => TaskResult<E, A>;
2084
- err: <E, A = never>(error: E) => TaskResult<E, A>;
2085
- };
2086
- ok: <E = never, A = unknown>(value: A) => TaskResult<E, A>;
2087
- err: <E, A = never>(error: E) => TaskResult<E, A>;
2088
- from: {
2089
- nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => TaskResult<E, A>;
2090
- Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => TaskResult<E, A>;
2091
- Result: <E, A>(result: Result<E, A>) => TaskResult<E, A>;
2092
- };
2093
- to: {
2094
- Maybe: <E, A>(data: TaskResult<E, A>) => TaskMaybe<A>;
2095
- };
2096
- tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
2097
- onError: (error: unknown) => E;
2098
- }) => TaskResult<E, A>;
2099
- map: <E, A, B>(f: (a: A) => B) => (data: TaskResult<E, A>) => TaskResult<E, B>;
2100
- mapError: <E, F, A>(f: (e: E) => F) => (data: TaskResult<E, A>) => TaskResult<F, A>;
2101
- chain: <E2, A, B>(f: (a: A) => TaskResult<E2, B>) => <E1 = never>(data: TaskResult<E1, A>) => TaskResult<E1 | E2, B>;
2102
- fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: TaskResult<E, A>) => Task<B>;
2103
- match: <E, A, B>(cases: {
2104
- err: (e: E) => B;
2105
- ok: (a: A) => B;
2106
- }) => (data: TaskResult<E, A>) => Task<B>;
2107
- recover: <E, B>(fallback: (e: E) => TaskResult<E, B>) => <A>(data: TaskResult<E, A>) => TaskResult<E, A | B>;
2108
- recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: (e: E) => TaskResult<E, B>) => <A>(data: TaskResult<E, A>) => TaskResult<E, A | B>;
2109
- getOrElse: <B>(defaultValue: () => B) => <E, A>(// oxlint-disable-next-line prefer-const
2110
- data: TaskResult<E, A>) => Task<A | B>;
2111
- tap: <E, A>(f: (a: A) => void) => (data: TaskResult<E, A>) => TaskResult<E, A>;
2112
- tapError: <E, A>(f: (e: E) => void) => (data: TaskResult<E, A>) => TaskResult<E, A>;
2113
- ap: <E, A>(arg: TaskResult<E, A>) => <B>(data: TaskResult<E, (a: A) => B>) => TaskResult<E, B>;
2114
- run: (signal?: AbortSignal) => <E, A>(task: TaskResult<E, A>) => Deferred<Result<E, A>>;
2115
- bindTo: <K extends string>(key: K) => <E, A>(data: TaskResult<E, A>) => TaskResult<E, { [P in K]: A; }>;
2116
- bind: <K extends string, E, A, B>(key: K, f: (a: A) => TaskResult<E, B>) => (data: TaskResult<E, A>) => TaskResult<E, A & { [P in K]: B; }>;
2117
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: TaskResult<E, R[K]>; }) => TaskResult<E, R>;
2118
- retry: (policy: RetryPolicy) => <E, A>(task: TaskResult<E, A>) => TaskResult<E, A>;
2119
- memoize: <E, A>(task: TaskResult<E, A>) => TaskResult<E, A>;
2120
- timeout: <E2>(options: {
2121
- duration: Duration;
2122
- onTimeout: () => E2;
2123
- }) => <E1 = never, A = unknown>(task: TaskResult<E1, A>) => TaskResult<E1 | E2, A>;
2124
- allSettled: <E, A>(tasks: ReadonlyArray<TaskResult<E, A>>) => Task<ReadonlyArray<Result<E, A>>>;
2125
- };
2126
- Validation: {
2127
- make: {
2128
- passed: <E = never, A = unknown>(value: A) => TaskValidation<E, A>;
2129
- failed: <E, A = never>(error: E) => TaskValidation<E, A>;
2130
- failedAll: <E, A = never>(errors: NonEmptyArr<E>) => TaskValidation<E, A>;
2131
- };
2132
- passed: <E = never, A = unknown>(value: A) => TaskValidation<E, A>;
2133
- failed: <E, A = never>(error: E) => TaskValidation<E, A>;
2134
- failedAll: <E, A = never>(errors: NonEmptyArr<E>) => TaskValidation<E, A>;
2135
- from: {
2136
- Validation: <E, A>(validation: Validation<E, A>) => TaskValidation<E, A>;
2137
- nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => TaskValidation<E, A>;
2138
- Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => TaskValidation<E, A>;
2139
- Result: <E, A>(result: Result<E, A>) => TaskValidation<E, A>;
2140
- };
2141
- to: {
2142
- Result: <E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2) => (data: TaskValidation<E1, A>) => TaskResult<E2, A>;
2143
- Maybe: <E, A>(data: TaskValidation<E, A>) => TaskMaybe<A>;
2144
- };
2145
- tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
2146
- onError: (error: unknown) => E;
2147
- }) => TaskValidation<E, A>;
2148
- map: <E, A, B>(f: (a: A) => B) => (data: TaskValidation<E, A>) => TaskValidation<E, B>;
2149
- ap: <E, A>(arg: TaskValidation<E, A>) => <B>(data: TaskValidation<E, (a: A) => B>) => TaskValidation<E, B>;
2150
- fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: TaskValidation<E, A>) => Task<B>;
2151
- match: <E, A, B>(cases: {
2152
- passed: (a: A) => B;
2153
- failed: (errors: NonEmptyArr<E>) => B;
2154
- }) => (data: TaskValidation<E, A>) => Task<B>;
2155
- getOrElse: <B>(defaultValue: () => B) => <E, A>(data: TaskValidation<E, A>) => Task<A | B>;
2156
- tap: <E, A>(f: (a: A) => void) => (data: TaskValidation<E, A>) => TaskValidation<E, A>;
2157
- recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => TaskValidation<E, B>) => <A>(data: TaskValidation<E, A>) => TaskValidation<E, A | B>;
2158
- recoverUnless: <E, B>(isBlocked: (errors: NonEmptyArr<E>) => boolean, fallback: (errors: NonEmptyArr<E>) => TaskValidation<E, B>) => <A>(data: TaskValidation<E, A>) => TaskValidation<E, A | B>;
2159
- product: <E, A, B>(first: TaskValidation<E, A>, second: TaskValidation<E, B>) => TaskValidation<E, readonly [A, B]>;
2160
- productAll: <E, A>(data: NonEmptyArr<TaskValidation<E, A>>) => TaskValidation<E, readonly A[]>;
2161
- mapError: <E, F, A>(f: (e: E) => F) => (data: TaskValidation<E, A>) => TaskValidation<F, A>;
2162
- tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: TaskValidation<E, A>) => TaskValidation<E, A>;
2163
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: TaskValidation<E, R[K]>; }) => TaskValidation<E, R>;
2164
- memoize: <E, A>(task: TaskValidation<E, A>) => TaskValidation<E, A>;
2165
- };
2166
- };
2167
- declare namespace Task {
2168
- type LabeledTask<L extends string, A> = Task<A> & {
2169
- readonly label: L;
2170
- };
2171
- type Maybe<A> = TaskMaybe<A>;
2172
- type Result<E, A> = TaskResult<E, A>;
2173
- type Validation<E, A> = TaskValidation<E, A>;
2174
- }
2175
-
2176
- type Passed<A> = WithKind<"Passed"> & WithValue<A>;
2177
- type Failed<E> = WithKind<"Failed"> & WithErrors<E>;
2178
- declare function toResult<E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2): (val: Validation<E1, A>) => Result<E2, A>;
2179
- declare function toResult<E, A>(data: Validation<E, A>): Result<NonEmptyArr<E>, A>;
2180
- /**
2181
- * Validation represents a value that is either passed with a success value,
2182
- * or failed with accumulated errors.
2183
- * Unlike Result, Validation can accumulate multiple errors instead of short-circuiting.
2184
- *
2185
- * Use Validation when you need to collect all errors (e.g., form validation).
2186
- * Use Result when you want to fail fast on the first error.
2187
- *
2188
- * @example
2189
- * ```ts
2190
- * const validateName = (name: string): Validation<string, string> =>
2191
- * name.length > 0 ? Validation.make.passed(name) : Validation.make.failed("Name is required");
2192
- *
2193
- * const validateAge = (age: number): Validation<string, number> =>
2194
- * age >= 0 ? Validation.make.passed(age) : Validation.make.failed("Age must be positive");
2195
- *
2196
- * // Accumulates all errors using ap
2197
- * pipe(
2198
- * Validation.make.passed((name: string) => (age: number) => ({ name, age })),
2199
- * Validation.ap(validateName("")),
2200
- * Validation.ap(validateAge(-1))
2201
- * );
2202
- * // Failed(["Name is required", "Age must be positive"])
2203
- * ```
2204
- */
2205
- type Validation<E, A> = Passed<A> | Failed<E>;
2206
- declare const Validation: {
2207
- make: {
2208
- /**
2209
- * Wraps a value in a passed Validation.
2210
- *
2211
- * @example
2212
- * ```ts
2213
- * Validation.make.passed(42); // Passed(42)
2214
- * ```
2215
- */
2216
- passed: <E, A>(value: A) => Validation<E, A>;
2217
- /**
2218
- * Creates a failed Validation from a single error.
2219
- *
2220
- * @example
2221
- * ```ts
2222
- * Validation.make.failed("Invalid input");
2223
- * ```
2224
- */
2225
- failed: <E>(error: E) => Failed<E>;
2226
- /**
2227
- * Creates a failed Validation from multiple errors.
2228
- *
2229
- * @example
2230
- * ```ts
2231
- * Validation.make.failedAll(["Invalid input"]);
2232
- * ```
2233
- */
2234
- failedAll: <E>(errors: NonEmptyArr<E>) => Failed<E>;
2235
- };
2236
- is: {
2237
- /**
2238
- * Type guard that checks if a Validation is passed.
2239
- *
2240
- * @example
2241
- * ```ts
2242
- * const v = Validation.make.passed(42);
2243
- * if (Validation.is.passed(v)) {
2244
- * console.log(v.value); // 42
2245
- * }
2246
- * ```
2247
- */
2248
- passed: <E, A>(data: Validation<E, A>) => data is Passed<A>;
2249
- /**
2250
- * Type guard that checks if a Validation is failed.
2251
- *
2252
- * @example
2253
- * ```ts
2254
- * const v = Validation.make.failed("invalid");
2255
- * if (Validation.is.failed(v)) {
2256
- * console.log(v.errors); // ["invalid"]
2257
- * }
2258
- * ```
2259
- */
2260
- failed: <E, A>(data: Validation<E, A>) => data is Failed<E>;
2261
- };
2262
- /**
2263
- * Creates a Validation from a synchronous thunk that may throw.
2264
- * Catches any errors and transforms them using the `onError` function into a Failed validation.
2265
- *
2266
- * @example
2267
- * ```ts
2268
- * const result = Validation.tryCatch(
2269
- * () => JSON.parse(rawString),
2270
- * { onError: (e) => `Parse error: ${e}` }
2271
- * );
2272
- * ```
2273
- */
2274
- tryCatch: <E, A>(f: () => A, options: {
2275
- onError: (e: unknown) => E;
2276
- }) => Validation<E, A>;
2277
- from: {
2278
- /**
2279
- * Creates a Validation from a predicate applied to a value.
2280
- * Returns Passed if the predicate passes, Failed from `onFalse` otherwise.
2281
- *
2282
- * @example
2283
- * ```ts
2284
- * const validateName = Validation.from.Predicate(
2285
- * (s: string) => s.length > 0,
2286
- * () => "Name is required"
2287
- * );
2288
- *
2289
- * validateName("Alice"); // Passed("Alice")
2290
- * validateName(""); // Failed(["Name is required"])
2291
- * ```
2292
- */
2293
- Predicate: <E, A>(pred: (a: A) => boolean, onFalse: (a: A) => E) => (a: A) => Validation<E, A>;
2294
- /**
2295
- * Creates a Validation from a nullable value.
2296
- * If the value is null or undefined, returns Failed with the error from onNull.
2297
- * Otherwise, returns Passed.
2298
- *
2299
- * @example
2300
- * ```ts
2301
- * pipe(null, Validation.from.nullable(() => "is null")); // Failed(["is null"])
2302
- * pipe(42, Validation.from.nullable(() => "is null")); // Passed(42)
2303
- * ```
2304
- */
2305
- nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Validation<E, A>;
2306
- /**
2307
- * Creates a Validation from a Maybe.
2308
- * If the Maybe is None, returns Failed with the error from onNone.
2309
- * Otherwise, returns Passed.
2310
- *
2311
- * @example
2312
- * ```ts
2313
- * pipe(Maybe.make.none(), Validation.from.Maybe(() => "is none")); // Failed(["is none"])
2314
- * pipe(Maybe.make.some(42), Validation.from.Maybe(() => "is none")); // Passed(42)
2315
- * ```
2316
- */
2317
- Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Validation<E, A>;
2318
- /**
2319
- * Converts a `Result` to a `Validation`. `Ok` becomes `Passed`; `Err(e)` becomes `Failed([e])`.
2320
- *
2321
- * Useful when bridging from error-short-circuiting `Result` pipelines into
2322
- * error-accumulating `Validation` pipelines.
2323
- *
2324
- * @example
2325
- * ```ts
2326
- * Validation.from.Result(Result.make.ok(42)); // Passed(42)
2327
- * Validation.from.Result(Result.make.err("bad")); // Failed(["bad"])
2328
- * ```
2329
- */
2330
- Result: <E, A>(data: Result<E, A>) => Validation<E, A>;
2331
- };
2332
- /**
2333
- * Transforms the success value inside a Validation.
2334
- *
2335
- * @example
2336
- * ```ts
2337
- * pipe(Validation.make.passed(5), Validation.map(n => n * 2)); // Passed(10)
2338
- * pipe(Validation.make.failed("oops"), Validation.map(n => n * 2)); // Failed(["oops"])
2339
- * ```
2340
- */
2341
- map: <A, B>(f: (a: A) => B) => <E>(data: Validation<E, A>) => Validation<E, B>;
2342
- /**
2343
- * Transforms the error list inside a Validation.
2344
- *
2345
- * @example
2346
- * ```ts
2347
- * pipe(Validation.make.failed("oops"), Validation.mapError(e => e.toUpperCase())); // Failed(["OOPS"])
2348
- * ```
2349
- */
2350
- mapError: <E, F, A>(f: (e: E) => F) => (data: Validation<E, A>) => Validation<F, A>;
2351
- /**
2352
- * Applies a function wrapped in a Validation to a value wrapped in a Validation.
2353
- * Accumulates errors from both sides.
2354
- *
2355
- * @example
2356
- * ```ts
2357
- * const add = (a: number) => (b: number) => a + b;
2358
- * pipe(
2359
- * Validation.make.passed(add),
2360
- * Validation.ap(Validation.make.passed(5)),
2361
- * Validation.ap(Validation.make.passed(3))
2362
- * ); // Passed(8)
2363
- *
2364
- * pipe(
2365
- * Validation.make.passed(add),
2366
- * Validation.ap(Validation.make.failed<string>("bad a")),
2367
- * Validation.ap(Validation.make.failed<string>("bad b"))
2368
- * ); // Failed(["bad a", "bad b"])
2369
- * ```
2370
- */
2371
- ap: <E, A>(arg: Validation<E, A>) => <B>(data: Validation<E, (a: A) => B>) => Validation<E, B>;
2372
- /**
2373
- * Applies a function wrapped in a Validation to a value wrapped in a Validation,
2374
- * using a custom error concatenator function when both sides fail.
2375
- *
2376
- * @example
2377
- * ```ts
2378
- * const concat = (e1: NonEmptyArr<string>, e2: NonEmptyArr<string>): NonEmptyArr<string> =>
2379
- * [...e1, ...e2];
2380
- * pipe(fnVal, Validation.apCustom(concat)(argVal));
2381
- * ```
2382
- */
2383
- apCustom: <E1, E2, E3>(concat: (e1: NonEmptyArr<E1>, e2: NonEmptyArr<E2>) => NonEmptyArr<E3>) => <A>(arg: Validation<E2, A>) => <B>(data: Validation<E1, (a: A) => B>) => Validation<E3, B>;
2384
- /**
2385
- * Extracts the value from a Validation by providing handlers for both cases.
2386
- *
2387
- * @example
2388
- * ```ts
2389
- * pipe(
2390
- * Validation.make.passed(42),
2391
- * Validation.fold(
2392
- * errors => `Errors: ${errors.join(", ")}`,
2393
- * value => `Value: ${value}`
2394
- * )
2395
- * );
2396
- * ```
2397
- */
2398
- fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: Validation<E, A>) => B;
2399
- /**
2400
- * Pattern matches on a Validation, returning the result of the matching case.
2401
- *
2402
- * @example
2403
- * ```ts
2404
- * pipe(
2405
- * validation,
2406
- * Validation.match({
2407
- * passed: value => `Got ${value}`,
2408
- * failed: errors => `Failed: ${errors.join(", ")}`
2409
- * })
2410
- * );
2411
- * ```
2412
- */
2413
- match: <E, A, B>(cases: {
2414
- passed: (a: A) => B;
2415
- failed: (errors: NonEmptyArr<E>) => B;
2416
- }) => (data: Validation<E, A>) => B;
2417
- /**
2418
- * Returns the success value or a default value if the Validation is failed.
2419
- * The default can be a different type, widening the result to `A | B`.
2420
- *
2421
- * @example
2422
- * ```ts
2423
- * pipe(Validation.make.passed(5), Validation.getOrElse(() => 0)); // 5
2424
- * pipe(Validation.make.failed("oops"), Validation.getOrElse(() => 0)); // 0
2425
- * pipe(Validation.make.failed("oops"), Validation.getOrElse(() => null)); // null — typed as number | null
2426
- * ```
2427
- */
2428
- getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Validation<E, A>) => A | B;
2429
- /**
2430
- * Executes a side effect on the success value without changing the Validation.
2431
- *
2432
- * @example
2433
- * ```ts
2434
- * pipe(
2435
- * Validation.make.passed(5),
2436
- * Validation.tap(n => console.log("Value:", n)),
2437
- * Validation.map(n => n * 2)
2438
- * );
2439
- * ```
2440
- */
2441
- tap: <E, A>(f: (a: A) => void) => (data: Validation<E, A>) => Validation<E, A>;
2442
- /**
2443
- * Executes a side effect on the accumulated errors without changing the Validation.
2444
- * Useful for logging or reporting validation failures.
2445
- *
2446
- * @example
2447
- * ```ts
2448
- * pipe(
2449
- * Validation.make.failed("Name required"),
2450
- * Validation.tapError(errors => console.error("validation failed:", errors)),
2451
- * Validation.map(toUser)
2452
- * );
2453
- * ```
2454
- */
2455
- tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: Validation<E, A>) => Validation<E, A>;
2456
- /**
2457
- * Recovers from a Failed state by providing a fallback Validation.
2458
- * The fallback receives the accumulated error list so callers can inspect which errors occurred.
2459
- * The fallback can produce a different success type, widening the result to `Validation<E, A | B>`.
2460
- */
2461
- recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => Validation<E, B>) => <A>(data: Validation<E, A>) => Validation<E, A | B>;
2462
- /**
2463
- * Recovers from a Failed state unless `isBlocked` returns true for any of the accumulated errors.
2464
- * The fallback can produce a different success type, widening the result to `Validation<E, A | B>`.
2465
- *
2466
- * @example
2467
- * ```ts
2468
- * pipe(
2469
- * Validation.make.failed("field-error"),
2470
- * Validation.recoverUnless(e => e === "fatal", () => Validation.make.passed(0))
2471
- * ); // Passed(0)
2472
- * ```
2473
- */
2474
- recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: () => Validation<E, B>) => <A>(data: Validation<E, A>) => Validation<E, A | B>;
2475
- to: {
2476
- /**
2477
- * Converts a Validation to a Result.
2478
- * Passed becomes Ok.
2479
- * Direct call converts Failed to Err with accumulated error list `NonEmptyArr<E>`.
2480
- * Curried call converts Failed to Err with combined error `E2` via `combineErrors`.
2481
- *
2482
- * @example
2483
- * ```ts
2484
- * Validation.to.Result(Validation.make.passed(42)); // Ok(42)
2485
- * Validation.to.Result(Validation.make.failed("oops")); // Err(["oops"])
2486
- * pipe(Validation.make.failed("oops"), Validation.to.Result(errors => errors.join(", "))); // Err("oops")
2487
- * ```
2488
- */
2489
- Result: typeof toResult;
2490
- /**
2491
- * Converts a Validation to a Maybe. `Passed` becomes `Some`; `Failed` becomes `None`
2492
- * (errors are discarded).
2493
- *
2494
- * @example
2495
- * ```ts
2496
- * Validation.to.Maybe(Validation.make.passed(42)); // Some(42)
2497
- * Validation.to.Maybe(Validation.make.failed("bad")); // None
2498
- * ```
2499
- */
2500
- Maybe: <E, A>(data: Validation<E, A>) => Maybe<A>;
2501
- };
2502
- /**
2503
- * Combines two independent Validation instances into a tuple.
2504
- * If both are Passed, returns Passed with both values as a tuple.
2505
- * If either is Failed, accumulates errors from both sides.
2506
- *
2507
- * @example
2508
- * ```ts
2509
- * Validation.product(
2510
- * Validation.make.passed("alice"),
2511
- * Validation.make.passed(30)
2512
- * ); // Passed(["alice", 30])
2513
- *
2514
- * Validation.product(
2515
- * Validation.make.failed("Name required"),
2516
- * Validation.make.failed("Age must be >= 0")
2517
- * ); // Failed(["Name required", "Age must be >= 0"])
2518
- * ```
2519
- */
2520
- product: <E, A, B>(first: Validation<E, A>, second: Validation<E, B>) => Validation<E, readonly [A, B]>;
2521
- /**
2522
- * Combines a non-empty list of Validation instances, accumulating all errors.
2523
- * If all are Passed, returns Passed with all values collected into an array.
2524
- * If any are Failed, returns Failed with all accumulated errors.
2525
- *
2526
- * @example
2527
- * ```ts
2528
- * Validation.productAll([
2529
- * validateName(name),
2530
- * validateEmail(email),
2531
- * validateAge(age)
2532
- * ]);
2533
- * // Passed([name, email, age]) or Failed([...all errors])
2534
- * ```
2535
- */
2536
- productAll: <E, A>(data: NonEmptyArr<Validation<E, A>>) => Validation<E, readonly A[]>;
2537
- /**
2538
- * Combines a record of Validations into a single Validation of a record.
2539
- * Accumulates all failed branches' errors.
2540
- *
2541
- * @example
2542
- * ```ts
2543
- * Validation.struct({
2544
- * name: Validation.make.passed("Alice"),
2545
- * age: Validation.make.passed(30)
2546
- * }); // Passed({ name: "Alice", age: 30 })
2547
- *
2548
- * Validation.struct({
2549
- * name: Validation.make.failed("Name required"),
2550
- * age: Validation.make.failed("Age must be >= 0")
2551
- * }); // Failed(["Name required", "Age must be >= 0"])
2552
- * ```
2553
- */
2554
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Validation<E, R[K]>; }) => Validation<E, R>;
2555
- };
2556
-
2557
- export { Equality as E, type Failed as F, Maybe as M, type None as N, type Ok as O, type Passed as P, Result as R, type Some as S, Task as T, Validation as V, type Err as a, Ordering as b };