@nlozgachev/pipelined 0.63.0 → 0.64.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,4 +1,4 @@
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-GFn4RTwD.cjs';
1
+ import { h as WithKind, o as WithValue, e as WithError, a as NonEmptyArr, f as WithErrors, D as Deferred, T as Thenable } from './InternalTypes-GFn4RTwD.cjs';
2
2
  import { D as Duration } from './Duration-DeyxG6VQ.cjs';
3
3
  import { RetryPolicy } from './types.cjs';
4
4
 
@@ -891,1667 +891,858 @@ declare const Result: {
891
891
  bimap: <E1, E2, A, B>(onErr: (e: E1) => E2, onOk: (a: A) => B) => (data: Result<E1, A>) => Result<E2, B>;
892
892
  };
893
893
 
894
+ type Passed<A> = WithKind<"Passed"> & WithValue<A>;
895
+ type Failed<E> = WithKind<"Failed"> & WithErrors<E>;
896
+ declare function toResult<E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2): (val: Validation<E1, A>) => Result<E2, A>;
897
+ declare function toResult<E, A>(data: Validation<E, A>): Result<NonEmptyArr<E>, A>;
894
898
  /**
895
- * TaskMaybe represents a lazy, infallible async operation that resolves to a `Maybe<A>`.
896
- * It is a type alias for `Task<Maybe<A>>`.
899
+ * Validation represents a value that is either passed with a success value,
900
+ * or failed with accumulated errors.
901
+ * Unlike Result, Validation can accumulate multiple errors instead of short-circuiting.
897
902
  *
898
- * Use Task.Maybe for async operations that can result in a missing value (e.g. database lookups).
903
+ * Use Validation when you need to collect all errors (e.g., form validation).
904
+ * Use Result when you want to fail fast on the first error.
899
905
  *
900
906
  * @example
901
907
  * ```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
- * );
908
+ * const validateName = (name: string): Validation<string, string> =>
909
+ * name.length > 0 ? Validation.make.passed(name) : Validation.make.failed("Name is required");
910
+ *
911
+ * const validateAge = (age: number): Validation<string, number> =>
912
+ * age >= 0 ? Validation.make.passed(age) : Validation.make.failed("Age must be positive");
913
+ *
914
+ * // Accumulates all errors using ap
915
+ * pipe(
916
+ * Validation.make.passed((name: string) => (age: number) => ({ name, age })),
917
+ * Validation.ap(validateName("")),
918
+ * Validation.ap(validateAge(-1))
919
+ * );
920
+ * // Failed(["Name is required", "Age must be positive"])
906
921
  * ```
907
922
  */
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
- */
923
+ type Validation<E, A> = Passed<A> | Failed<E>;
924
+ declare const Validation: {
919
925
  make: {
920
926
  /**
921
- * Creates a Task.Maybe that resolves to Some(value).
927
+ * Wraps a value in a passed Validation.
928
+ *
929
+ * @example
930
+ * ```ts
931
+ * Validation.make.passed(42); // Passed(42)
932
+ * ```
933
+ */
934
+ passed: <E, A>(value: A) => Validation<E, A>;
935
+ /**
936
+ * Creates a failed Validation from a single error.
937
+ *
938
+ * @example
939
+ * ```ts
940
+ * Validation.make.failed("Invalid input");
941
+ * ```
942
+ */
943
+ failed: <E>(error: E) => Failed<E>;
944
+ /**
945
+ * Creates a failed Validation from multiple errors.
946
+ *
947
+ * @example
948
+ * ```ts
949
+ * Validation.make.failedAll(["Invalid input"]);
950
+ * ```
951
+ */
952
+ failedAll: <E>(errors: NonEmptyArr<E>) => Failed<E>;
953
+ };
954
+ is: {
955
+ /**
956
+ * Type guard that checks if a Validation is passed.
922
957
  *
923
958
  * @example
924
959
  * ```ts
925
- * const task = Task.Maybe.make.some(42);
926
- * const res = await task(); // Some(42)
960
+ * const v = Validation.make.passed(42);
961
+ * if (Validation.is.passed(v)) {
962
+ * console.log(v.value); // 42
963
+ * }
927
964
  * ```
928
965
  */
929
- some: <A>(value: A) => TaskMaybe<A>;
966
+ passed: <E, A>(data: Validation<E, A>) => data is Passed<A>;
930
967
  /**
931
- * Creates a Task.Maybe that resolves to None.
968
+ * Type guard that checks if a Validation is failed.
932
969
  *
933
970
  * @example
934
971
  * ```ts
935
- * const task = Task.Maybe.make.none();
936
- * const res = await task(); // None
972
+ * const v = Validation.make.failed("invalid");
973
+ * if (Validation.is.failed(v)) {
974
+ * console.log(v.errors); // ["invalid"]
975
+ * }
937
976
  * ```
938
977
  */
939
- none: <A = never>() => TaskMaybe<A>;
978
+ failed: <E, A>(data: Validation<E, A>) => data is Failed<E>;
940
979
  };
941
- some: <A>(value: A) => TaskMaybe<A>;
942
- none: <A = never>() => TaskMaybe<A>;
980
+ /**
981
+ * Creates a Validation from a synchronous thunk that may throw.
982
+ * Catches any errors and transforms them using the `onError` function into a Failed validation.
983
+ *
984
+ * @example
985
+ * ```ts
986
+ * const result = Validation.tryCatch(
987
+ * () => JSON.parse(rawString),
988
+ * { onError: (e) => `Parse error: ${e}` }
989
+ * );
990
+ * ```
991
+ */
992
+ tryCatch: <E, A>(f: () => A, options: {
993
+ onError: (e: unknown) => E;
994
+ }) => Validation<E, A>;
943
995
  from: {
944
996
  /**
945
- * Lifts a Maybe into a Task.Maybe.
997
+ * Creates a Validation from a predicate applied to a value.
998
+ * Returns Passed if the predicate passes, Failed from `onFalse` otherwise.
946
999
  *
947
1000
  * @example
948
1001
  * ```ts
949
- * Task.Maybe.from.Maybe(Maybe.make.some(42));
1002
+ * const validateName = Validation.from.Predicate(
1003
+ * (s: string) => s.length > 0,
1004
+ * () => "Name is required"
1005
+ * );
1006
+ *
1007
+ * validateName("Alice"); // Passed("Alice")
1008
+ * validateName(""); // Failed(["Name is required"])
950
1009
  * ```
951
1010
  */
952
- Maybe: <A>(option: Maybe<A>) => TaskMaybe<A>;
1011
+ Predicate: <E, A>(pred: (a: A) => boolean, onFalse: (a: A) => E) => (a: A) => Validation<E, A>;
953
1012
  /**
954
- * Creates a Task.Maybe from a nullable value.
955
- * Returns Some if the value is not null or undefined, None otherwise.
1013
+ * Creates a Validation from a nullable value.
1014
+ * If the value is null or undefined, returns Failed with the error from onNull.
1015
+ * Otherwise, returns Passed.
956
1016
  *
957
1017
  * @example
958
1018
  * ```ts
959
- * Task.Maybe.from.nullable(42); // resolves to Some(42)
960
- * Task.Maybe.from.nullable(null); // resolves to None
1019
+ * pipe(null, Validation.from.nullable(() => "is null")); // Failed(["is null"])
1020
+ * pipe(42, Validation.from.nullable(() => "is null")); // Passed(42)
961
1021
  * ```
962
1022
  */
963
- nullable: <A>(value: A | null | undefined) => TaskMaybe<A>;
1023
+ nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Validation<E, A>;
964
1024
  /**
965
- * Creates a Task.Maybe from a Result.
966
- * Ok becomes Some, Error becomes None (the error value is discarded).
1025
+ * Creates a Validation from a Maybe.
1026
+ * If the Maybe is None, returns Failed with the error from onNone.
1027
+ * Otherwise, returns Passed.
967
1028
  *
968
1029
  * @example
969
1030
  * ```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
1031
+ * pipe(Maybe.make.none(), Validation.from.Maybe(() => "is none")); // Failed(["is none"])
1032
+ * pipe(Maybe.make.some(42), Validation.from.Maybe(() => "is none")); // Passed(42)
972
1033
  * ```
973
1034
  */
974
- Result: <E, A>(result: Result<E, A>) => TaskMaybe<A>;
1035
+ Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Validation<E, A>;
975
1036
  /**
976
- * Lifts a Task into a Task.Maybe by wrapping its result in Some.
1037
+ * Converts a `Result` to a `Validation`. `Ok` becomes `Passed`; `Err(e)` becomes `Failed([e])`.
1038
+ *
1039
+ * Useful when bridging from error-short-circuiting `Result` pipelines into
1040
+ * error-accumulating `Validation` pipelines.
977
1041
  *
978
1042
  * @example
979
1043
  * ```ts
980
- * Task.Maybe.from.Task(Task.resolve(42)); // resolves to Some(42)
1044
+ * Validation.from.Result(Result.make.ok(42)); // Passed(42)
1045
+ * Validation.from.Result(Result.make.err("bad")); // Failed(["bad"])
981
1046
  * ```
982
1047
  */
983
- Task: <A>(task: Task<A>) => TaskMaybe<A>;
1048
+ Result: <E, A>(data: Result<E, A>) => Validation<E, A>;
984
1049
  };
985
1050
  /**
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.
1051
+ * Transforms the success value inside a Validation.
989
1052
  *
990
1053
  * @example
991
1054
  * ```ts
992
- * const fetchUser = Task.Maybe.tryCatch((signal) =>
993
- * fetch("/user/1", { signal }).then(r => r.json())
994
- * );
1055
+ * pipe(Validation.make.passed(5), Validation.map(n => n * 2)); // Passed(10)
1056
+ * pipe(Validation.make.failed("oops"), Validation.map(n => n * 2)); // Failed(["oops"])
995
1057
  * ```
996
1058
  */
997
- tryCatch: <A>(f: (signal?: AbortSignal) => Thenable<A>) => TaskMaybe<A>;
1059
+ map: <A, B>(f: (a: A) => B) => <E>(data: Validation<E, A>) => Validation<E, B>;
998
1060
  /**
999
- * Transforms the value inside a Task.Maybe.
1061
+ * Transforms the error list inside a Validation.
1062
+ *
1063
+ * @example
1064
+ * ```ts
1065
+ * pipe(Validation.make.failed("oops"), Validation.mapError(e => e.toUpperCase())); // Failed(["OOPS"])
1066
+ * ```
1000
1067
  */
1001
- map: <A, B>(f: (a: A) => B) => (data: TaskMaybe<A>) => TaskMaybe<B>;
1068
+ mapError: <E, F, A>(f: (e: E) => F) => (data: Validation<E, A>) => Validation<F, A>;
1002
1069
  /**
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.
1070
+ * Applies a function wrapped in a Validation to a value wrapped in a Validation.
1071
+ * Accumulates errors from both sides.
1005
1072
  *
1006
1073
  * @example
1007
1074
  * ```ts
1075
+ * const add = (a: number) => (b: number) => a + b;
1076
+ * pipe(
1077
+ * Validation.make.passed(add),
1078
+ * Validation.ap(Validation.make.passed(5)),
1079
+ * Validation.ap(Validation.make.passed(3))
1080
+ * ); // Passed(8)
1081
+ *
1008
1082
  * pipe(
1009
- * findUser("123"),
1010
- * Task.Maybe.chain(user => findOrg(user.orgId))
1011
- * )();
1083
+ * Validation.make.passed(add),
1084
+ * Validation.ap(Validation.make.failed<string>("bad a")),
1085
+ * Validation.ap(Validation.make.failed<string>("bad b"))
1086
+ * ); // Failed(["bad a", "bad b"])
1012
1087
  * ```
1013
1088
  */
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>;
1089
+ ap: <E, A>(arg: Validation<E, A>) => <B>(data: Validation<E, (a: A) => B>) => Validation<E, B>;
1020
1090
  /**
1021
- * Extracts a value from a Task.Maybe by providing handlers for both cases.
1091
+ * Applies a function wrapped in a Validation to a value wrapped in a Validation,
1092
+ * using a custom error concatenator function when both sides fail.
1093
+ *
1094
+ * @example
1095
+ * ```ts
1096
+ * const concat = (e1: NonEmptyArr<string>, e2: NonEmptyArr<string>): NonEmptyArr<string> =>
1097
+ * [...e1, ...e2];
1098
+ * pipe(fnVal, Validation.apCustom(concat)(argVal));
1099
+ * ```
1022
1100
  */
1023
- fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: TaskMaybe<A>) => Task<B>;
1101
+ 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>;
1024
1102
  /**
1025
- * Pattern matches on a Task.Maybe, returning a Task of the result.
1103
+ * Extracts the value from a Validation by providing handlers for both cases.
1026
1104
  *
1027
1105
  * @example
1028
1106
  * ```ts
1029
1107
  * pipe(
1030
- * findUser("123"),
1031
- * Task.Maybe.match({
1032
- * some: user => `Hello, ${user.name}`,
1033
- * none: () => "User not found"
1034
- * })
1035
- * )();
1108
+ * Validation.make.passed(42),
1109
+ * Validation.fold(
1110
+ * errors => `Errors: ${errors.join(", ")}`,
1111
+ * value => `Value: ${value}`
1112
+ * )
1113
+ * );
1036
1114
  * ```
1037
1115
  */
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
- };
1116
+ fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: Validation<E, A>) => B;
1070
1117
  /**
1071
- * Lifts a Task.Maybe value into an accumulator object.
1118
+ * Pattern matches on a Validation, returning the result of the matching case.
1072
1119
  *
1073
1120
  * @example
1074
1121
  * ```ts
1075
- * pipe(Task.Maybe.some(42), Task.Maybe.bindTo("value")); // Task.Maybe({ value: 42 })
1122
+ * pipe(
1123
+ * validation,
1124
+ * Validation.match({
1125
+ * passed: value => `Got ${value}`,
1126
+ * failed: errors => `Failed: ${errors.join(", ")}`
1127
+ * })
1128
+ * );
1076
1129
  * ```
1077
1130
  */
1078
- bindTo: <K extends string>(key: K) => <A>(data: TaskMaybe<A>) => TaskMaybe<{ [P in K]: A; }>;
1131
+ match: <E, A, B>(cases: {
1132
+ passed: (a: A) => B;
1133
+ failed: (errors: NonEmptyArr<E>) => B;
1134
+ }) => (data: Validation<E, A>) => B;
1079
1135
  /**
1080
- * Evaluates a new Task.Maybe using the current accumulator and attaches the output to a new key.
1136
+ * Returns the success value or a default value if the Validation is failed.
1137
+ * The default can be a different type, widening the result to `A | B`.
1081
1138
  *
1082
1139
  * @example
1083
1140
  * ```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 })
1141
+ * pipe(Validation.make.passed(5), Validation.getOrElse(() => 0)); // 5
1142
+ * pipe(Validation.make.failed("oops"), Validation.getOrElse(() => 0)); // 0
1143
+ * pipe(Validation.make.failed("oops"), Validation.getOrElse(() => null)); // null typed as number | null
1088
1144
  * ```
1089
1145
  */
1090
- bind: <K extends string, A, B>(key: K, f: (a: A) => TaskMaybe<B>) => (data: TaskMaybe<A>) => TaskMaybe<A & { [P in K]: B; }>;
1146
+ getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Validation<E, A>) => A | B;
1091
1147
  /**
1092
- * Recovers from a None state by providing a fallback Task.Maybe.
1148
+ * Executes a side effect on the success value without changing the Validation.
1093
1149
  *
1094
1150
  * @example
1095
1151
  * ```ts
1096
1152
  * pipe(
1097
- * Task.Maybe.none(),
1098
- * Task.Maybe.recover(() => Task.Maybe.some(42))
1099
- * ); // Task.Maybe(42)
1153
+ * Validation.make.passed(5),
1154
+ * Validation.tap(n => console.log("Value:", n)),
1155
+ * Validation.map(n => n * 2)
1156
+ * );
1100
1157
  * ```
1101
1158
  */
1102
- recover: <B>(fallback: () => TaskMaybe<B>) => <A>(data: TaskMaybe<A>) => TaskMaybe<A | B>;
1159
+ tap: <E, A>(f: (a: A) => void) => (data: Validation<E, A>) => Validation<E, A>;
1103
1160
  /**
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.
1161
+ * Executes a side effect on the accumulated errors without changing the Validation.
1162
+ * Useful for logging or reporting validation failures.
1106
1163
  *
1107
1164
  * @example
1108
1165
  * ```ts
1109
- * Task.Maybe.struct({
1110
- * name: Task.Maybe.some("Alice"),
1111
- * age: Task.Maybe.some(30)
1112
- * }); // Task.Maybe({ name: "Alice", age: 30 })
1166
+ * pipe(
1167
+ * Validation.make.failed("Name required"),
1168
+ * Validation.tapError(errors => console.error("validation failed:", errors)),
1169
+ * Validation.map(toUser)
1170
+ * );
1113
1171
  * ```
1114
1172
  */
1115
- struct: <R extends Record<string, any>>(fields: { [K in keyof R]: TaskMaybe<R[K]>; }) => TaskMaybe<R>;
1173
+ tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: Validation<E, A>) => Validation<E, A>;
1174
+ /**
1175
+ * Recovers from a Failed state by providing a fallback Validation.
1176
+ * The fallback receives the accumulated error list so callers can inspect which errors occurred.
1177
+ * The fallback can produce a different success type, widening the result to `Validation<E, A | B>`.
1178
+ */
1179
+ recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => Validation<E, B>) => <A>(data: Validation<E, A>) => Validation<E, A | B>;
1116
1180
  /**
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.
1181
+ * Recovers from a Failed state unless `isBlocked` returns true for any of the accumulated errors.
1182
+ * The fallback can produce a different success type, widening the result to `Validation<E, A | B>`.
1119
1183
  *
1120
1184
  * @example
1121
1185
  * ```ts
1122
- * const loadUser = Task.Maybe.memoize(fetchUserMaybeTask);
1186
+ * pipe(
1187
+ * Validation.make.failed("field-error"),
1188
+ * Validation.recoverUnless(e => e === "fatal", () => Validation.make.passed(0))
1189
+ * ); // Passed(0)
1123
1190
  * ```
1124
1191
  */
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: {
1192
+ recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: () => Validation<E, B>) => <A>(data: Validation<E, A>) => Validation<E, A | B>;
1193
+ to: {
1144
1194
  /**
1145
- * Wraps a value in a successful Task.Result.
1195
+ * Converts a Validation to a Result.
1196
+ * Passed becomes Ok.
1197
+ * Direct call converts Failed to Err with accumulated error list `NonEmptyArr<E>`.
1198
+ * Curried call converts Failed to Err with combined error `E2` via `combineErrors`.
1146
1199
  *
1147
1200
  * @example
1148
1201
  * ```ts
1149
- * const task = Task.Result.make.ok(42);
1150
- * const res = await task(); // Ok(42)
1202
+ * Validation.to.Result(Validation.make.passed(42)); // Ok(42)
1203
+ * Validation.to.Result(Validation.make.failed("oops")); // Err(["oops"])
1204
+ * pipe(Validation.make.failed("oops"), Validation.to.Result(errors => errors.join(", "))); // Err("oops")
1151
1205
  * ```
1152
1206
  */
1153
- ok: <E = never, A = unknown>(value: A) => TaskResult<E, A>;
1207
+ Result: typeof toResult;
1154
1208
  /**
1155
- * Creates a failed Task.Result with the given error.
1209
+ * Converts a Validation to a Maybe. `Passed` becomes `Some`; `Failed` becomes `None`
1210
+ * (errors are discarded).
1156
1211
  *
1157
1212
  * @example
1158
1213
  * ```ts
1159
- * const task = Task.Result.make.err("failed");
1160
- * const res = await task(); // Err("failed")
1214
+ * Validation.to.Maybe(Validation.make.passed(42)); // Some(42)
1215
+ * Validation.to.Maybe(Validation.make.failed("bad")); // None
1161
1216
  * ```
1162
1217
  */
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>;
1218
+ Maybe: <E, A>(data: Validation<E, A>) => Maybe<A>;
1211
1219
  };
1212
1220
  /**
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.
1221
+ * Combines two independent Validation instances into a tuple.
1222
+ * If both are Passed, returns Passed with both values as a tuple.
1223
+ * If either is Failed, accumulates errors from both sides.
1216
1224
  *
1217
1225
  * @example
1218
1226
  * ```ts
1219
- * const loadUser = Task.Result.tryCatch(
1220
- * (signal) => userStore.get("u_123", { signal }),
1221
- * { onError: (e) => new DbError(e) }
1222
- * );
1227
+ * Validation.product(
1228
+ * Validation.make.passed("alice"),
1229
+ * Validation.make.passed(30)
1230
+ * ); // Passed(["alice", 30])
1231
+ *
1232
+ * Validation.product(
1233
+ * Validation.make.failed("Name required"),
1234
+ * Validation.make.failed("Age must be >= 0")
1235
+ * ); // Failed(["Name required", "Age must be >= 0"])
1223
1236
  * ```
1224
1237
  */
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>;
1238
+ product: <E, A, B>(first: Validation<E, A>, second: Validation<E, B>) => Validation<E, readonly [A, B]>;
1241
1239
  /**
1242
- * Extracts the value from a Task.Result by providing handlers for both cases.
1240
+ * Combines a non-empty list of Validation instances, accumulating all errors.
1241
+ * If all are Passed, returns Passed with all values collected into an array.
1242
+ * If any are Failed, returns Failed with all accumulated errors.
1243
+ *
1244
+ * @example
1245
+ * ```ts
1246
+ * Validation.productAll([
1247
+ * validateName(name),
1248
+ * validateEmail(email),
1249
+ * validateAge(age)
1250
+ * ]);
1251
+ * // Passed([name, email, age]) or Failed([...all errors])
1252
+ * ```
1243
1253
  */
1244
- fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: TaskResult<E, A>) => Task<B>;
1254
+ productAll: <E, A>(data: NonEmptyArr<Validation<E, A>>) => Validation<E, readonly A[]>;
1245
1255
  /**
1246
- * Pattern matches on a Task.Result, returning a Task of the result.
1256
+ * Combines a record of Validations into a single Validation of a record.
1257
+ * Accumulates all failed branches' errors.
1258
+ *
1259
+ * @example
1260
+ * ```ts
1261
+ * Validation.struct({
1262
+ * name: Validation.make.passed("Alice"),
1263
+ * age: Validation.make.passed(30)
1264
+ * }); // Passed({ name: "Alice", age: 30 })
1265
+ *
1266
+ * Validation.struct({
1267
+ * name: Validation.make.failed("Name required"),
1268
+ * age: Validation.make.failed("Age must be >= 0")
1269
+ * }); // Failed(["Name required", "Age must be >= 0"])
1270
+ * ```
1247
1271
  */
1248
- match: <E, A, B>(cases: {
1249
- err: (e: E) => B;
1250
- ok: (a: A) => B;
1251
- }) => (data: TaskResult<E, A>) => Task<B>;
1272
+ struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Validation<E, R[K]>; }) => Validation<E, R>;
1273
+ };
1274
+
1275
+ type _CoreMaybe<A> = Maybe<A>;
1276
+ type _CoreResult<E, A> = Result<E, A>;
1277
+ type _CoreValidation<E, A> = Validation<E, A>;
1278
+ /**
1279
+ * A lazy async computation that always resolves.
1280
+ *
1281
+ * Two guarantees:
1282
+ * - **Lazy** — nothing starts until you call it.
1283
+ * - **Infallible** — it never rejects. If failure is possible, encode it in the
1284
+ * return type using `Task.Result<E, A>` instead.
1285
+ *
1286
+ * An optional `AbortSignal` can be passed at the call site. Combinators like
1287
+ * `retry`, `pollUntil`, and `timeout` thread it automatically to every inner
1288
+ * operation. Existing tasks that ignore the signal continue to work unchanged.
1289
+ *
1290
+ * Calling a Task returns a `Deferred<A>` — a one-shot async value that supports
1291
+ * `await` but has no `.catch()`, `.finally()`, or chainable `.then()`.
1292
+ *
1293
+ * **Consuming a Task:**
1294
+ *
1295
+ * Use `await task()` to run it and get the value directly:
1296
+ * ```ts
1297
+ * const value: number = await task();
1298
+ * ```
1299
+ *
1300
+ * When you need an explicit `Promise<A>` (e.g. for a third-party API), convert
1301
+ * the `Deferred` with `Deferred.to.Promise`:
1302
+ * ```ts
1303
+ * const p: Promise<number> = Deferred.to.Promise(task());
1304
+ * ```
1305
+ *
1306
+ * @example
1307
+ * ```ts
1308
+ * const getTimestamp: Task<number> = Task.resolve(Date.now());
1309
+ *
1310
+ * // Nothing runs yet — getTimestamp is just a description
1311
+ * const formatted = pipe(
1312
+ * getTimestamp,
1313
+ * Task.map(ts => new Date(ts).toISOString())
1314
+ * );
1315
+ *
1316
+ * // Execute when ready
1317
+ * const result = await formatted();
1318
+ * ```
1319
+ */
1320
+ type Task<A> = (signal?: AbortSignal) => Deferred<A>;
1321
+ declare const Task: {
1252
1322
  /**
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>`.
1323
+ * Creates a Task that immediately resolves to the given value.
1324
+ *
1325
+ * @example
1326
+ * ```ts
1327
+ * const task = Task.resolve(42);
1328
+ * const value = await task(); // 42
1329
+ * ```
1255
1330
  */
1256
- recover: <E, B>(fallback: (e: E) => TaskResult<E, B>) => <A>(data: TaskResult<E, A>) => TaskResult<E, A | B>;
1331
+ resolve: <A>(value: A) => Task<A>;
1332
+ from: {
1333
+ /**
1334
+ * Creates a Task from a lazy synchronous thunk.
1335
+ * Unlike `Task.resolve(f())`, `from.sync` does not evaluate `f` until the Task is called.
1336
+ *
1337
+ * @example
1338
+ * ```ts
1339
+ * const t = Task.from.sync(() => Date.now()); // Date.now() not called yet
1340
+ * const ts = await t(); // called here, every time
1341
+ * ```
1342
+ */
1343
+ sync: <A>(f: () => A) => Task<A>;
1344
+ };
1257
1345
  /**
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>`.
1346
+ * Wraps a Promise-returning thunk that may throw or reject,
1347
+ * trapping errors with a fallback function and returning a guaranteed `Task<A>`.
1260
1348
  *
1261
1349
  * @example
1262
1350
  * ```ts
1263
- * pipe(
1264
- * fetchTask,
1265
- * Task.Result.recoverUnless(
1266
- * (e) => e === "fatal",
1267
- * () => Task.Result.ok("fallback")
1268
- * )
1351
+ * const loadConfig = Task.tryCatch(
1352
+ * () => configStore.get("default"),
1353
+ * { onError: () => DEFAULT_CONFIG }
1269
1354
  * );
1270
1355
  * ```
1271
1356
  */
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>;
1357
+ tryCatch: <A>(f: (signal?: AbortSignal) => globalThis.Promise<A>, options: {
1358
+ onError: (error: unknown) => A;
1359
+ }) => Task<A>;
1278
1360
  /**
1279
- * Executes a side effect on the success value without changing the Task.Result.
1280
- * Useful for logging or debugging.
1361
+ * Transforms the value inside a Task.
1362
+ *
1363
+ * @example
1364
+ * ```ts
1365
+ * pipe(
1366
+ * Task.resolve(5),
1367
+ * Task.map(n => n * 2)
1368
+ * )(); // Deferred<10>
1369
+ * ```
1281
1370
  */
1282
- tap: <E, A>(f: (a: A) => void) => (data: TaskResult<E, A>) => TaskResult<E, A>;
1371
+ map: <A, B>(f: (a: A) => B) => (data: Task<A>) => Task<B>;
1283
1372
  /**
1284
- * Executes a side effect on the error value without changing the Task.Result.
1285
- * Useful for logging or reporting async errors.
1373
+ * Chains Task computations. Passes the resolved value of the first Task to f.
1286
1374
  *
1287
1375
  * @example
1288
1376
  * ```ts
1377
+ * const readUserId: Task<string> = Task.resolve(session.userId);
1378
+ * const loadPrefs = (id: string): Task<Preferences> =>
1379
+ * Task.resolve(prefsCache.get(id));
1380
+ *
1289
1381
  * pipe(
1290
- * fetchUser(id),
1291
- * Task.Result.tapError(e => console.error("fetch failed:", e)),
1292
- * Task.Result.chain(saveToCache),
1293
- * )
1382
+ * readUserId,
1383
+ * Task.chain(loadPrefs)
1384
+ * )(); // Deferred<Preferences>
1294
1385
  * ```
1295
1386
  */
1296
- tapError: <E, A>(f: (e: E) => void) => (data: TaskResult<E, A>) => TaskResult<E, A>;
1387
+ chain: <A, B>(f: (a: A) => Task<B>) => (data: Task<A>) => Task<B>;
1297
1388
  /**
1298
- * Applies a function wrapped in a Task.Result to a value wrapped in a Task.Result.
1389
+ * Applies a function wrapped in a Task to a value wrapped in a Task.
1299
1390
  * Both Tasks run in parallel.
1391
+ *
1392
+ * @example
1393
+ * ```ts
1394
+ * const add = (a: number) => (b: number) => a + b;
1395
+ * pipe(
1396
+ * Task.resolve(add),
1397
+ * Task.ap(Task.resolve(5)),
1398
+ * Task.ap(Task.resolve(3))
1399
+ * )(); // Deferred<8>
1400
+ * ```
1300
1401
  */
1301
- ap: <E, A>(arg: TaskResult<E, A>) => <B>(data: TaskResult<E, (a: A) => B>) => TaskResult<E, B>;
1402
+ ap: <A>(arg: Task<A>) => <B>(data: Task<(a: A) => B>) => Task<B>;
1302
1403
  /**
1303
- * Executes a `Task.Result` with an optional signal, returning `Promise<Result<E, A>>`.
1304
- * Use as a terminal step in a `pipe` chain.
1404
+ * Executes a side effect on the value without changing the Task.
1405
+ * Useful for logging or debugging.
1305
1406
  *
1306
1407
  * @example
1307
1408
  * ```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),
1409
+ * pipe(
1410
+ * loadConfig,
1411
+ * Task.tap(cfg => console.log("Config:", cfg)),
1412
+ * Task.map(buildReport)
1313
1413
  * );
1314
- * if (Result.is.ok(result)) render(result.value);
1315
1414
  * ```
1316
1415
  */
1317
- run: (signal?: AbortSignal) => <E, A>(task: TaskResult<E, A>) => Deferred<Result<E, A>>;
1416
+ tap: <A>(f: (a: A) => void) => (data: Task<A>) => Task<A>;
1318
1417
  /**
1319
- * Converts a Task.Result value into an object containing a single property.
1320
- * Initiates the pipeline accumulator record.
1418
+ * Runs multiple Tasks in parallel and collects their results.
1321
1419
  *
1322
1420
  * @example
1323
1421
  * ```ts
1324
- * pipe(Task.Result.ok(42), Task.Result.bindTo("value")); // Task.Result({ value: 42 })
1422
+ * Task.all([loadConfig, detectLocale, loadTheme])();
1423
+ * // Deferred<[Config, string, Theme]>
1325
1424
  * ```
1326
1425
  */
1327
- bindTo: <K extends string>(key: K) => <E, A>(data: TaskResult<E, A>) => TaskResult<E, { [P in K]: A; }>;
1426
+ all: <T extends readonly Task<unknown>[]>(tasks: T) => Task<{ [K in keyof T]: T[K] extends Task<infer A> ? A : never; }>;
1328
1427
  /**
1329
- * Evaluates a new Task.Result using the current accumulator and attaches the output to a new key.
1428
+ * Delays the execution of a Task by the specified duration.
1429
+ * Useful for debouncing or rate limiting.
1330
1430
  *
1331
1431
  * @example
1332
1432
  * ```ts
1333
1433
  * 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 })
1434
+ * Task.resolve(42),
1435
+ * Task.delay(Duration.seconds(1))
1436
+ * )(); // Resolves after 1 second
1337
1437
  * ```
1338
1438
  */
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; }>;
1439
+ delay: (duration: Duration) => <A>(data: Task<A>) => Task<A>;
1340
1440
  /**
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.
1441
+ * Runs a Task a fixed number of times sequentially, collecting all results into an array.
1442
+ * An optional delay duration can be inserted between runs.
1344
1443
  *
1345
1444
  * @example
1346
1445
  * ```ts
1347
- * Task.Result.struct({
1348
- * name: Task.Result.ok("Alice"),
1349
- * age: Task.Result.ok(30)
1350
- * }); // Task.Result({ name: "Alice", age: 30 })
1446
+ * pipe(
1447
+ * pollSensor,
1448
+ * Task.repeat({ times: 5, delay: Duration.seconds(1) })
1449
+ * )(); // Task<Reading[]> 5 readings, one per second
1351
1450
  * ```
1352
1451
  */
1353
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: TaskResult<E, R[K]>; }) => TaskResult<E, R>;
1452
+ repeat: (options: {
1453
+ times: number;
1454
+ delay?: Duration;
1455
+ }) => <A>(task: Task<A>) => Task<readonly A[]>;
1354
1456
  /**
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.
1457
+ * Runs a Task repeatedly until the result satisfies a predicate, returning that result.
1458
+ * An optional delay duration can be inserted between runs.
1459
+ * An optional `maxAttempts` cap stops the loop after N calls the last value is returned
1460
+ * regardless of whether the predicate was satisfied.
1358
1461
  *
1359
1462
  * @example
1360
1463
  * ```ts
1361
- * const policy = RetryPolicy.exponential({ attempts: 3, initial: Duration.milliseconds(100) });
1362
- * const retryableFetch = pipe(fetchData, Task.Result.retry(policy));
1464
+ * pipe(
1465
+ * checkStatus,
1466
+ * Task.repeatUntil({ when: (s) => s === "ready", delay: Duration.milliseconds(500) })
1467
+ * )(); // polls every 500ms until status is "ready"
1363
1468
  * ```
1364
1469
  */
1365
- retry: (policy: RetryPolicy) => <E, A>(task: TaskResult<E, A>) => TaskResult<E, A>;
1470
+ repeatUntil: <A>(options: {
1471
+ when: (a: A) => boolean;
1472
+ delay?: Duration;
1473
+ maxAttempts?: number;
1474
+ }) => (task: Task<A>) => Task<A>;
1366
1475
  /**
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.
1476
+ * Resolves with the value of the first Task to complete. All Tasks start
1477
+ * immediately. When one resolves, the other tasks are cancelled (aborted)
1478
+ * downstream.
1369
1479
  *
1370
1480
  * @example
1371
1481
  * ```ts
1372
- * const loadConfig = Task.Result.memoize(fetchConfigTask);
1482
+ * const fast = Task.resolve("fast");
1483
+ * const slow = Task.delay(Duration.milliseconds(200))(Task.resolve("slow"));
1484
+ *
1485
+ * await Task.race([fast, slow])(); // "fast"
1373
1486
  * ```
1374
1487
  */
1375
- memoize: <E, A>(task: TaskResult<E, A>) => TaskResult<E, A>;
1488
+ race: <A>(tasks: ReadonlyArray<Task<A>>) => Task<A>;
1376
1489
  /**
1377
- * Times out a fallible task, resolving to `Err(onTimeout())` if the duration elapses
1378
- * before the task completes.
1490
+ * Runs an array of Tasks concurrently and collects their results in an array.
1491
+ * Forward-propagates the call site's AbortSignal to all subtasks concurrently.
1379
1492
  *
1380
1493
  * @example
1381
1494
  * ```ts
1382
- * const fetchWithTimeout = pipe(
1383
- * fetchTask,
1384
- * Task.Result.timeout({ duration: Duration.seconds(5), onTimeout: () => "Request timed out" })
1385
- * );
1495
+ * Task.sequence([loadConfig, detectLocale, loadTheme])();
1496
+ * // Deferred<[Config, string, Theme]>
1386
1497
  * ```
1387
1498
  */
1388
- timeout: <E2>(options: {
1389
- duration: Duration;
1390
- onTimeout: () => E2;
1391
- }) => <E1 = never, A = unknown>(task: TaskResult<E1, A>) => TaskResult<E1 | E2, A>;
1499
+ sequence: <A>(tasks: ReadonlyArray<Task<A>>) => Task<ReadonlyArray<A>>;
1392
1500
  /**
1393
- * Runs a list of fallible tasks in parallel and collects all outcomes (`Ok` and `Err`)
1394
- * without short-circuiting on failure.
1501
+ * Runs an array of Tasks one at a time in order, collecting all results.
1502
+ * Each Task starts only after the previous one resolves.
1395
1503
  *
1396
1504
  * @example
1397
1505
  * ```ts
1398
- * const results = await Task.Result.allSettled([task1, task2, task3])();
1399
- * // [Ok(val1), Err(err2), Ok(val3)]
1506
+ * let log: number[] = [];
1507
+ * const makeTask = (n: number) => Task.resolve(n);
1508
+ *
1509
+ * await Task.sequential([makeTask(1), makeTask(2), makeTask(3)])();
1510
+ * // log = [1, 2, 3] — tasks ran in order
1400
1511
  * ```
1401
1512
  */
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>;
1513
+ sequential: <A>(tasks: ReadonlyArray<Task<A>>) => Task<ReadonlyArray<A>>;
2351
1514
  /**
2352
- * Applies a function wrapped in a Validation to a value wrapped in a Validation.
2353
- * Accumulates errors from both sides.
1515
+ * Converts a `Task<A>` into a `Task<Result<E, A>>`, resolving to `Err` if the
1516
+ * Task does not complete within the given duration. The inner Task receives an
1517
+ * `AbortSignal` that fires when the deadline passes, so asynchronous operations
1518
+ * that accept a signal are cancelled rather than left dangling.
2354
1519
  *
2355
1520
  * @example
2356
1521
  * ```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
1522
  * 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"])
1523
+ * heavyComputation,
1524
+ * Task.timeout({ duration: Duration.seconds(5), onTimeout: () => "timed out" }),
1525
+ * Task.Result.chain(processResult)
1526
+ * );
2369
1527
  * ```
2370
1528
  */
2371
- ap: <E, A>(arg: Validation<E, A>) => <B>(data: Validation<E, (a: A) => B>) => Validation<E, B>;
1529
+ timeout: <E>(options: {
1530
+ duration: Duration;
1531
+ onTimeout: () => E;
1532
+ }) => <A>(task: Task<A>) => Task<Result<E, A>>;
2372
1533
  /**
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.
1534
+ * Creates a Task paired with an `abort` handle. Calling `abort()` cancels the
1535
+ * current in-flight call immediately. Unlike a one-shot abort, calling `task()`
1536
+ * again after `abort()` starts a fresh call with a new signal.
2375
1537
  *
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.
1538
+ * Each invocation of `task()` automatically cancels the previous in-flight call,
1539
+ * making it safe to call repeatedly (e.g. on user input) without leaking promises.
2386
1540
  *
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.
1541
+ * If an outer signal is also present (passed at the call site), aborting it
1542
+ * propagates into the internal controller.
2401
1543
  *
2402
1544
  * @example
2403
1545
  * ```ts
2404
- * pipe(
2405
- * validation,
2406
- * Validation.match({
2407
- * passed: value => `Got ${value}`,
2408
- * failed: errors => `Failed: ${errors.join(", ")}`
2409
- * })
1546
+ * const { task: poll, abort } = Task.abortable(
1547
+ * (signal) => waitForEvent(bus, "ready", { signal }),
2410
1548
  * );
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
1549
  *
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
1550
+ * onUnmount(abort);
1551
+ * await poll();
2426
1552
  * ```
2427
1553
  */
2428
- getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Validation<E, A>) => A | B;
1554
+ abortable: <A>(factory: (signal: AbortSignal) => Thenable<A>) => {
1555
+ task: Task<A>;
1556
+ abort: () => void;
1557
+ };
2429
1558
  /**
2430
- * Executes a side effect on the success value without changing the Validation.
1559
+ * Executes a task with an optional signal. Use as a terminal step in a `pipe` chain.
2431
1560
  *
2432
1561
  * @example
2433
1562
  * ```ts
2434
- * pipe(
2435
- * Validation.make.passed(5),
2436
- * Validation.tap(n => console.log("Value:", n)),
2437
- * Validation.map(n => n * 2)
1563
+ * const name = await pipe(
1564
+ * loadConfig,
1565
+ * Task.map(config => config.name),
1566
+ * Task.run(),
2438
1567
  * );
2439
1568
  * ```
2440
1569
  */
2441
- tap: <E, A>(f: (a: A) => void) => (data: Validation<E, A>) => Validation<E, A>;
1570
+ run: (signal?: AbortSignal) => <A>(task: Task<A>) => Deferred<A>;
2442
1571
  /**
2443
- * Executes a side effect on the accumulated errors without changing the Validation.
2444
- * Useful for logging or reporting validation failures.
1572
+ * Converts a Task value into an object containing a single property.
1573
+ * Initiates the pipeline accumulator record.
2445
1574
  *
2446
1575
  * @example
2447
1576
  * ```ts
2448
- * pipe(
2449
- * Validation.make.failed("Name required"),
2450
- * Validation.tapError(errors => console.error("validation failed:", errors)),
2451
- * Validation.map(toUser)
2452
- * );
1577
+ * pipe(Task.resolve(42), Task.bindTo("value")); // Task({ value: 42 })
2453
1578
  * ```
2454
1579
  */
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>;
1580
+ bindTo: <K extends string>(key: K) => <A>(data: Task<A>) => Task<{ [P in K]: A; }>;
2462
1581
  /**
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>`.
1582
+ * Evaluates a new Task using the current accumulator and attaches the output to a new key.
2465
1583
  *
2466
1584
  * @example
2467
1585
  * ```ts
2468
1586
  * pipe(
2469
- * Validation.make.failed("field-error"),
2470
- * Validation.recoverUnless(e => e === "fatal", () => Validation.make.passed(0))
2471
- * ); // Passed(0)
1587
+ * Task.resolve({ a: 1 }),
1588
+ * Task.bind("b", ({ a }) => Task.resolve(a + 1))
1589
+ * ); // Task({ a: 1, b: 2 })
2472
1590
  * ```
2473
1591
  */
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
- };
1592
+ bind: <K extends string, A, B>(key: K, f: (a: A) => Task<B>) => (data: Task<A>) => Task<A & { [P in K]: B; }>;
2502
1593
  /**
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.
1594
+ * Creates a memoized version of a Task. The task is executed at most once on first call,
1595
+ * and its resolved value is cached for all subsequent calls.
2506
1596
  *
2507
1597
  * @example
2508
1598
  * ```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"])
1599
+ * const loadToken = Task.memoize(loadAuthToken);
1600
+ * const token1 = await loadToken(); // loads token
1601
+ * const token2 = await loadToken(); // returns cached token immediately
2518
1602
  * ```
2519
1603
  */
2520
- product: <E, A, B>(first: Validation<E, A>, second: Validation<E, B>) => Validation<E, readonly [A, B]>;
1604
+ memoize: <A>(task: Task<A>) => Task<A>;
2521
1605
  /**
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.
1606
+ * Monitors progress of a Task by calling `onProgress(0)` before execution and `onProgress(1)` upon completion.
2525
1607
  *
2526
1608
  * @example
2527
1609
  * ```ts
2528
- * Validation.productAll([
2529
- * validateName(name),
2530
- * validateEmail(email),
2531
- * validateAge(age)
2532
- * ]);
2533
- * // Passed([name, email, age]) or Failed([...all errors])
1610
+ * const taskWithProgress = pipe(
1611
+ * readTask,
1612
+ * Task.withProgress((ratio) => console.log(`Progress: ${ratio * 100}%`))
1613
+ * );
2534
1614
  * ```
2535
1615
  */
2536
- productAll: <E, A>(data: NonEmptyArr<Validation<E, A>>) => Validation<E, readonly A[]>;
1616
+ withProgress: <A>(onProgress: (ratio: number) => void) => (task: Task<A>) => Task<A>;
2537
1617
  /**
2538
- * Combines a record of Validations into a single Validation of a record.
2539
- * Accumulates all failed branches' errors.
1618
+ * Attaches a read-only `.label` property to a Task, preserving the literal string generic type for IDE tooltips.
2540
1619
  *
2541
1620
  * @example
2542
1621
  * ```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"])
1622
+ * const labeledTask = pipe(readTask, Task.withLabel("readUser"));
1623
+ * console.log(labeledTask.label); // "readUser"
2552
1624
  * ```
2553
1625
  */
2554
- struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Validation<E, R[K]>; }) => Validation<E, R>;
1626
+ withLabel: <L extends string>(label: L) => <A>(task: Task<A>) => Task.LabeledTask<L, A>;
1627
+ Maybe: {
1628
+ make: {
1629
+ some: <A>(value: A) => Task.Maybe<A>;
1630
+ none: <A = never>() => Task.Maybe<A>;
1631
+ };
1632
+ from: {
1633
+ Maybe: <A>(option: Maybe<A>) => Task.Maybe<A>;
1634
+ nullable: <A>(value: A | null | undefined) => Task.Maybe<A>;
1635
+ Result: <E, A>(result: Result<E, A>) => Task.Maybe<A>;
1636
+ Task: <A>(task: Task<A>) => Task.Maybe<A>;
1637
+ };
1638
+ tryCatch: <A>(f: (signal?: AbortSignal) => Thenable<A>) => Task.Maybe<A>;
1639
+ map: <A, B>(f: (a: A) => B) => (data: Task.Maybe<A>) => Task.Maybe<B>;
1640
+ chain: <A, B>(f: (a: A) => Task.Maybe<B>) => (data: Task.Maybe<A>) => Task.Maybe<B>;
1641
+ ap: <A>(arg: Task.Maybe<A>) => <B>(data: Task.Maybe<(a: A) => B>) => Task.Maybe<B>;
1642
+ fold: <A, B>(onNone: () => B, onSome: (a: A) => B) => (data: Task.Maybe<A>) => Task<B>;
1643
+ match: <A, B>(cases: {
1644
+ none: () => B;
1645
+ some: (a: A) => B;
1646
+ }) => (data: Task.Maybe<A>) => Task<B>;
1647
+ getOrElse: <B>(defaultValue: () => B) => <A>(data: Task.Maybe<A>) => Task<A | B>;
1648
+ tap: <A>(f: (a: A) => void) => (data: Task.Maybe<A>) => Task.Maybe<A>;
1649
+ filter: <A>(predicate: (a: A) => boolean) => (data: Task.Maybe<A>) => Task.Maybe<A>;
1650
+ to: {
1651
+ Result: <E>(onNone: () => E) => <A>(data: Task.Maybe<A>) => Task.Result<E, A>;
1652
+ };
1653
+ bindTo: <K extends string>(key: K) => <A>(data: Task.Maybe<A>) => Task.Maybe<{ [P in K]: A; }>;
1654
+ bind: <K extends string, A, B>(key: K, f: (a: A) => Task.Maybe<B>) => (data: Task.Maybe<A>) => Task.Maybe<A & { [P in K]: B; }>;
1655
+ recover: <B>(fallback: () => Task.Maybe<B>) => <A>(data: Task.Maybe<A>) => Task.Maybe<A | B>;
1656
+ struct: <R extends Record<string, any>>(fields: { [K in keyof R]: Task.Maybe<R[K]>; }) => Task.Maybe<R>;
1657
+ memoize: <A>(task: Task.Maybe<A>) => Task.Maybe<A>;
1658
+ };
1659
+ Result: {
1660
+ make: {
1661
+ ok: <E = never, A = unknown>(value: A) => Task.Result<E, A>;
1662
+ err: <E, A = never>(error: E) => Task.Result<E, A>;
1663
+ };
1664
+ from: {
1665
+ nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Task.Result<E, A>;
1666
+ Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Task.Result<E, A>;
1667
+ Result: <E, A>(result: Result<E, A>) => Task.Result<E, A>;
1668
+ };
1669
+ to: {
1670
+ Maybe: <E, A>(data: Task.Result<E, A>) => Task.Maybe<A>;
1671
+ };
1672
+ tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
1673
+ onError: (error: unknown) => E;
1674
+ }) => Task.Result<E, A>;
1675
+ map: <E, A, B>(f: (a: A) => B) => (data: Task.Result<E, A>) => Task.Result<E, B>;
1676
+ mapError: <E, F, A>(f: (e: E) => F) => (data: Task.Result<E, A>) => Task.Result<F, A>;
1677
+ chain: <E2, A, B>(f: (a: A) => Task.Result<E2, B>) => <E1 = never>(data: Task.Result<E1, A>) => Task.Result<E1 | E2, B>;
1678
+ fold: <E, A, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (data: Task.Result<E, A>) => Task<B>;
1679
+ match: <E, A, B>(cases: {
1680
+ err: (e: E) => B;
1681
+ ok: (a: A) => B;
1682
+ }) => (data: Task.Result<E, A>) => Task<B>;
1683
+ recover: <E, B>(fallback: (e: E) => Task.Result<E, B>) => <A>(data: Task.Result<E, A>) => Task.Result<E, A | B>;
1684
+ recoverUnless: <E, B>(isBlocked: (e: E) => boolean, fallback: (e: E) => Task.Result<E, B>) => <A>(data: Task.Result<E, A>) => Task.Result<E, A | B>;
1685
+ getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Task.Result<E, A>) => Task<A | B>;
1686
+ tap: <E, A>(f: (a: A) => void) => (data: Task.Result<E, A>) => Task.Result<E, A>;
1687
+ tapError: <E, A>(f: (e: E) => void) => (data: Task.Result<E, A>) => Task.Result<E, A>;
1688
+ ap: <E, A>(arg: Task.Result<E, A>) => <B>(data: Task.Result<E, (a: A) => B>) => Task.Result<E, B>;
1689
+ run: (signal?: AbortSignal) => <E, A>(task: Task.Result<E, A>) => Deferred<Result<E, A>>;
1690
+ bindTo: <K extends string>(key: K) => <E, A>(data: Task.Result<E, A>) => Task.Result<E, { [P in K]: A; }>;
1691
+ bind: <K extends string, E, A, B>(key: K, f: (a: A) => Task.Result<E, B>) => (data: Task.Result<E, A>) => Task.Result<E, A & { [P in K]: B; }>;
1692
+ struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Task.Result<E, R[K]>; }) => Task.Result<E, R>;
1693
+ retry: (policy: RetryPolicy) => <E, A>(task: Task.Result<E, A>) => Task.Result<E, A>;
1694
+ memoize: <E, A>(task: Task.Result<E, A>) => Task.Result<E, A>;
1695
+ timeout: <E2>(options: {
1696
+ duration: Duration;
1697
+ onTimeout: () => E2;
1698
+ }) => <E1 = never, A = unknown>(task: Task.Result<E1, A>) => Task.Result<E1 | E2, A>;
1699
+ allSettled: <E, A>(tasks: ReadonlyArray<Task.Result<E, A>>) => Task<ReadonlyArray<Result<E, A>>>;
1700
+ };
1701
+ Validation: {
1702
+ make: {
1703
+ passed: <E = never, A = unknown>(value: A) => Task.Validation<E, A>;
1704
+ failed: <E, A = never>(error: E) => Task.Validation<E, A>;
1705
+ failedAll: <E, A = never>(errors: NonEmptyArr<E>) => Task.Validation<E, A>;
1706
+ };
1707
+ from: {
1708
+ Validation: <E, A>(validation: Validation<E, A>) => Task.Validation<E, A>;
1709
+ nullable: <E>(onNull: () => E) => <A>(value: A | null | undefined) => Task.Validation<E, A>;
1710
+ Maybe: <E>(onNone: () => E) => <A>(maybe: Maybe<A>) => Task.Validation<E, A>;
1711
+ Result: <E, A>(result: Result<E, A>) => Task.Validation<E, A>;
1712
+ };
1713
+ to: {
1714
+ Result: <E1, E2, A>(combineErrors: (errors: NonEmptyArr<E1>) => E2) => (data: Task.Validation<E1, A>) => Task.Result<E2, A>;
1715
+ Maybe: <E, A>(data: Task.Validation<E, A>) => Task.Maybe<A>;
1716
+ };
1717
+ tryCatch: <E, A>(f: (signal?: AbortSignal) => Thenable<A>, options: {
1718
+ onError: (error: unknown) => E;
1719
+ }) => Task.Validation<E, A>;
1720
+ map: <E, A, B>(f: (a: A) => B) => (data: Task.Validation<E, A>) => Task.Validation<E, B>;
1721
+ ap: <E, A>(arg: Task.Validation<E, A>) => <B>(data: Task.Validation<E, (a: A) => B>) => Task.Validation<E, B>;
1722
+ fold: <E, A, B>(onFailed: (errors: NonEmptyArr<E>) => B, onPassed: (a: A) => B) => (data: Task.Validation<E, A>) => Task<B>;
1723
+ match: <E, A, B>(cases: {
1724
+ passed: (a: A) => B;
1725
+ failed: (errors: NonEmptyArr<E>) => B;
1726
+ }) => (data: Task.Validation<E, A>) => Task<B>;
1727
+ getOrElse: <B>(defaultValue: () => B) => <E, A>(data: Task.Validation<E, A>) => Task<A | B>;
1728
+ tap: <E, A>(f: (a: A) => void) => (data: Task.Validation<E, A>) => Task.Validation<E, A>;
1729
+ recover: <E, B>(fallback: (errors: NonEmptyArr<E>) => Task.Validation<E, B>) => <A>(data: Task.Validation<E, A>) => Task.Validation<E, A | B>;
1730
+ recoverUnless: <E, B>(isBlocked: (errors: NonEmptyArr<E>) => boolean, fallback: (errors: NonEmptyArr<E>) => Task.Validation<E, B>) => <A>(data: Task.Validation<E, A>) => Task.Validation<E, A | B>;
1731
+ product: <E, A, B>(first: Task.Validation<E, A>, second: Task.Validation<E, B>) => Task.Validation<E, readonly [A, B]>;
1732
+ productAll: <E, A>(data: NonEmptyArr<Task.Validation<E, A>>) => Task.Validation<E, readonly A[]>;
1733
+ mapError: <E, F, A>(f: (e: E) => F) => (data: Task.Validation<E, A>) => Task.Validation<F, A>;
1734
+ tapError: <E, A>(f: (errors: NonEmptyArr<E>) => void) => (data: Task.Validation<E, A>) => Task.Validation<E, A>;
1735
+ struct: <E, R extends Record<string, any>>(fields: { [K in keyof R]: Task.Validation<E, R[K]>; }) => Task.Validation<E, R>;
1736
+ memoize: <E, A>(task: Task.Validation<E, A>) => Task.Validation<E, A>;
1737
+ };
2555
1738
  };
1739
+ declare namespace Task {
1740
+ type LabeledTask<L extends string, A> = Task<A> & {
1741
+ readonly label: L;
1742
+ };
1743
+ type Maybe<A> = Task<_CoreMaybe<A>>;
1744
+ type Result<E, A> = Task<_CoreResult<E, A>>;
1745
+ type Validation<E, A> = Task<_CoreValidation<E, A>>;
1746
+ }
2556
1747
 
2557
1748
  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 };