resultar 3.3.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -6,6 +6,12 @@ interface ErrorConfig {
6
6
  //#region src/pipe.d.ts
7
7
  type PipeFn<Input, Output> = (input: Input) => Output;
8
8
  declare abstract class Pipeable {
9
+ /**
10
+ * Passes this value through one or more transformation functions.
11
+ *
12
+ * Use `pipe` to package reusable Result or ResultAsync combinators without hiding the underlying
13
+ * type.
14
+ */
9
15
  pipe<A>(ab: PipeFn<this, A>): A;
10
16
  pipe<A, B>(ab: PipeFn<this, A>, bc: PipeFn<A, B>): B;
11
17
  pipe<A, B, C>(ab: PipeFn<this, A>, bc: PipeFn<A, B>, cd: PipeFn<B, C>): C;
@@ -155,19 +161,19 @@ interface Resultable<T, E> {
155
161
  *
156
162
  * @returns `true` if the result is an `OK` variant of Result
157
163
  */
158
- isOk(): boolean;
164
+ isOk: () => boolean;
159
165
  /**
160
166
  * Used to check if a `Result` is an `Err`
161
167
  *
162
168
  * @returns `true` if the result is an `Err` variant of Result
163
169
  */
164
- isErr(): boolean;
170
+ isErr: () => boolean;
165
171
  /**
166
172
  * Unwrap the `Ok` value, or return the default if there is an `Err`
167
173
  *
168
174
  * @param v the default value to return if there is an `Err`
169
175
  */
170
- unwrapOr<A>(defaultValue: A): T | A;
176
+ unwrapOr: <A>(defaultValue: A) => T | A;
171
177
  /**
172
178
  * **This method is unsafe, and should only be used in a test environments**
173
179
  *
@@ -175,7 +181,7 @@ interface Resultable<T, E> {
175
181
  *
176
182
  * @param config
177
183
  */
178
- _unsafeUnwrap(config?: ErrorConfig): T;
184
+ _unsafeUnwrap: (config?: ErrorConfig) => T;
179
185
  /**
180
186
  * **This method is unsafe, and should only be used in a test environments**
181
187
  *
@@ -184,108 +190,339 @@ interface Resultable<T, E> {
184
190
  *
185
191
  * @param config
186
192
  */
187
- _unsafeUnwrapErr(config?: ErrorConfig): E;
193
+ _unsafeUnwrapErr: (config?: ErrorConfig) => E;
188
194
  }
189
195
  interface ResultOperations<T, E> {
190
- isOk(): this is OkResult<T, E>;
191
- isErr(): this is ErrResult<T, E>;
192
- unwrapOr<A>(defaultValue: A): T | A;
193
- _unsafeUnwrap(config?: ErrorConfig): T;
194
- _unsafeUnwrapErr(config?: ErrorConfig): E;
195
- map<X>(f: (t: T) => X): Result<X, E>;
196
- as<X>(value: X): Result<X, E>;
197
- filterOrElse<U extends T, F>(predicate: (value: T) => value is U, onFalse: (value: T) => F): Result<U, E | F>;
198
- filterOrElse<F>(predicate: (value: T) => boolean, onFalse: (value: T) => F): Result<T, E | F>;
199
- mapErr<X>(fn: (t: E) => X): Result<T, X>;
200
- andThen<X, Y>(f: (t: T) => Result<X, Y>): Result<X, E | Y>;
201
- if(fCondition: (t: T) => boolean): {
196
+ /**
197
+ * Narrows this result to the Ok variant.
198
+ */
199
+ isOk: () => this is OkResult<T, E>;
200
+ /**
201
+ * Narrows this result to the Err variant.
202
+ */
203
+ isErr: () => this is ErrResult<T, E>;
204
+ /**
205
+ * Returns the Ok value, or `defaultValue` when this result is Err.
206
+ */
207
+ unwrapOr: <A>(defaultValue: A) => T | A;
208
+ /**
209
+ * Returns the Ok value or throws a Resultar diagnostic error when this result is Err.
210
+ *
211
+ * Prefer `match`, `unwrapOr`, or explicit error handling in application code. This helper is
212
+ * intended for tests and trusted final boundaries.
213
+ */
214
+ _unsafeUnwrap: (config?: ErrorConfig) => T;
215
+ /**
216
+ * Returns the Err value or throws a Resultar diagnostic error when this result is Ok.
217
+ *
218
+ * Prefer `match`, `isErr`, or explicit error handling in application code. This helper is intended
219
+ * for tests.
220
+ */
221
+ _unsafeUnwrapErr: (config?: ErrorConfig) => E;
222
+ /**
223
+ * Maps the Ok value while preserving the error channel.
224
+ */
225
+ map: <X>(f: (t: T) => X) => Result<X, E>;
226
+ /**
227
+ * Replaces the Ok value with a constant while preserving the error channel.
228
+ */
229
+ as: <X>(value: X) => Result<X, E>;
230
+ /**
231
+ * Keeps the Ok value only when the predicate passes; otherwise returns an Err from `onFalse`.
232
+ */
233
+ filterOrElse: {
234
+ <U extends T, F>(predicate: (value: T) => value is U, onFalse: (value: T) => F): Result<U, E | F>;
235
+ <F>(predicate: (value: T) => boolean, onFalse: (value: T) => F): Result<T, E | F>;
236
+ };
237
+ /**
238
+ * Maps the Err value while preserving the Ok value.
239
+ */
240
+ mapErr: <X>(fn: (t: E) => X) => Result<T, X>;
241
+ /**
242
+ * Chains another fallible operation from the Ok value.
243
+ *
244
+ * Use this instead of `map` when the callback returns another `Result`.
245
+ */
246
+ andThen: <X, Y>(f: (t: T) => Result<X, Y>) => Result<X, E | Y>;
247
+ /**
248
+ * Branches from the Ok value into one of two fallible Result branches.
249
+ */
250
+ if: (fCondition: (t: T) => boolean) => {
202
251
  true: <X1, Y1>(fTrue: (t: T) => Result<X1, Y1>) => {
203
252
  false: <X2, Y2>(fFalse: (t: T) => Result<X2, Y2>) => Result<X1 | X2, Y1 | Y2 | E>;
204
253
  };
205
254
  };
206
- orElse<R extends Result<unknown, unknown>>(f: (e: E) => R): Result<InferOkTypes<R> | T, InferErrTypes<R>>;
207
- catchTag<const Tag extends TagsOf<E>, R extends Result<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => R): Result<T | InferOkTypes<R>, ExcludeTag<E, Tag> | InferErrTypes<R>>;
208
- catchTags<const Handlers extends object>(handlers: Handlers & ResultCatchTagHandlers<E, Handlers>): Result<T | InferOkTypes<CatchTagHandlerResult<Handlers>>, ExcludeTag<E, keyof Handlers & string> | InferErrTypes<CatchTagHandlerResult<Handlers>>>;
209
- catchReason<const ErrorTag extends TagsWithReasonOf<E>, const ReasonTag extends ReasonTagsOf<E, ErrorTag>, R extends Result<unknown, unknown>>(errorTag: ErrorTag, reasonTag: ReasonTag, f: (reason: ReasonForTag<E, ErrorTag, ReasonTag>, error: ErrorForTag$1<E, ErrorTag>) => R): Result<T | InferOkTypes<R>, ExcludeReasonTag<E, ErrorTag, ReasonTag> | InferErrTypes<R>>;
210
- catchReasons<const ErrorTag extends TagsWithReasonOf<E>, const Handlers extends object>(errorTag: ErrorTag, handlers: Handlers & ResultCatchReasonHandlers<E, ErrorTag, Handlers>): Result<T | InferOkTypes<CatchReasonHandlerResult<Handlers>>, ExcludeReasonTag<E, ErrorTag, keyof Handlers & string> | InferErrTypes<CatchReasonHandlerResult<Handlers>>>;
211
- unwrapReason<const ErrorTag extends TagsWithReasonOf<E>>(errorTag: ErrorTag): Result<T, ExcludeTag<E, ErrorTag> | ReasonsOf<E, ErrorTag>>;
212
- asyncAndThen<X, Y>(f: (t: T) => ResultAsync<X, Y>): ResultAsync<X, E | Y>;
213
- asyncMap<X>(f: (t: T) => Promise<X>): ResultAsync<X, E>;
214
- match<A, B = A>(handlers: MatchHandlers$1<T, E, A, B>): A | B;
215
- match<A, B = A>(fnOk: MatchOkHandler<T, A>, fnErr: MatchErrorHandler<E, B>): A | B;
216
- matchTags<A, const Handlers extends object>(fnOk: (t: T) => A, handlers: Handlers & MatchTagHandlers<E, Handlers>): A | MatchTagHandlerResult<Handlers>;
217
- matchTagsPartial<A, B, const Handlers extends object>(fnOk: (t: T) => A, handlers: Handlers & PartialMatchTagHandlers<E, Handlers>, fallback: (error: E) => B): A | MatchTagHandlerResult<Handlers> | B;
218
- pipe<A>(ab: PipeFn<Result<T, E>, A>): A;
219
- pipe<A, B>(ab: PipeFn<Result<T, E>, A>, bc: PipeFn<A, B>): B;
220
- pipe<A, B, C>(ab: PipeFn<Result<T, E>, A>, bc: PipeFn<A, B>, cd: PipeFn<B, C>): C;
221
- log(fn: (t?: T, e?: E) => void): this;
222
- tap(fn: (t: T) => void): this;
223
- tapError(fn: (e: E) => void): this;
224
- toDisposable(f: ResultFinalizer<T, E>): DisposableResult<T, E>;
225
- unwrapOrThrow(): T;
226
- [Symbol.iterator](): Generator<Result<never, E>, T>;
227
- safeUnwrap(): Generator<Result<never, E>, T>;
255
+ /**
256
+ * Recovers from Err with another Result.
257
+ */
258
+ orElse: <R extends Result<unknown, unknown>>(f: (e: E) => R) => Result<InferOkTypes<R> | T, InferErrTypes<R>>;
259
+ /**
260
+ * Recovers from a specific tagged error by `_tag`.
261
+ */
262
+ catchTag: <const Tag extends TagsOf<E>, R extends Result<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => R) => Result<T | InferOkTypes<R>, ExcludeTag<E, Tag> | InferErrTypes<R>>;
263
+ /**
264
+ * Recovers from multiple tagged errors by `_tag`.
265
+ */
266
+ catchTags: <const Handlers extends object>(handlers: Handlers & ResultCatchTagHandlers<E, Handlers>) => Result<T | InferOkTypes<CatchTagHandlerResult<Handlers>>, ExcludeTag<E, keyof Handlers & string> | InferErrTypes<CatchTagHandlerResult<Handlers>>>;
267
+ /**
268
+ * Recovers from a nested tagged `reason` on a specific tagged error.
269
+ */
270
+ catchReason: <const ErrorTag extends TagsWithReasonOf<E>, const ReasonTag extends ReasonTagsOf<E, ErrorTag>, R extends Result<unknown, unknown>>(errorTag: ErrorTag, reasonTag: ReasonTag, f: (reason: ReasonForTag<E, ErrorTag, ReasonTag>, error: ErrorForTag$1<E, ErrorTag>) => R) => Result<T | InferOkTypes<R>, ExcludeReasonTag<E, ErrorTag, ReasonTag> | InferErrTypes<R>>;
271
+ /**
272
+ * Recovers from multiple nested tagged `reason` variants on a specific tagged error.
273
+ */
274
+ catchReasons: <const ErrorTag extends TagsWithReasonOf<E>, const Handlers extends object>(errorTag: ErrorTag, handlers: Handlers & ResultCatchReasonHandlers<E, ErrorTag, Handlers>) => Result<T | InferOkTypes<CatchReasonHandlerResult<Handlers>>, ExcludeReasonTag<E, ErrorTag, keyof Handlers & string> | InferErrTypes<CatchReasonHandlerResult<Handlers>>>;
275
+ /**
276
+ * Moves the nested `reason` of a tagged error into the Result error channel.
277
+ */
278
+ unwrapReason: <const ErrorTag extends TagsWithReasonOf<E>>(errorTag: ErrorTag) => Result<T, ExcludeTag<E, ErrorTag> | ReasonsOf<E, ErrorTag>>;
279
+ /**
280
+ * Chains an async fallible operation from the Ok value.
281
+ */
282
+ asyncAndThen: <X, Y>(f: (t: T) => ResultAsync<X, Y>) => ResultAsync<X, E | Y>;
283
+ /**
284
+ * Maps the Ok value with an async function and returns a `ResultAsync`.
285
+ */
286
+ asyncMap: <X>(f: (t: T) => Promise<X>) => ResultAsync<X, E>;
287
+ /**
288
+ * Converts this Result into a plain value by handling both Ok and Err.
289
+ */
290
+ match: {
291
+ <A, B = A>(handlers: MatchHandlers$1<T, E, A, B>): A | B;
292
+ <A, B = A>(fnOk: MatchOkHandler<T, A>, fnErr: MatchErrorHandler<E, B>): A | B;
293
+ };
294
+ /**
295
+ * Converts this Result into a plain value with exhaustive tagged-error handlers.
296
+ */
297
+ matchTags: <A, const Handlers extends object>(fnOk: (t: T) => A, handlers: Handlers & MatchTagHandlers<E, Handlers>) => A | MatchTagHandlerResult<Handlers>;
298
+ /**
299
+ * Converts this Result into a plain value with partial tagged-error handlers and a fallback.
300
+ */
301
+ matchTagsPartial: <A, B, const Handlers extends object>(fnOk: (t: T) => A, handlers: Handlers & PartialMatchTagHandlers<E, Handlers>, fallback: (error: E) => B) => A | MatchTagHandlerResult<Handlers> | B;
302
+ /**
303
+ * Pipes this Result through reusable transformation functions.
304
+ */
305
+ pipe: {
306
+ <A>(ab: PipeFn<Result<T, E>, A>): A;
307
+ <A, B>(ab: PipeFn<Result<T, E>, A>, bc: PipeFn<A, B>): B;
308
+ <A, B, C>(ab: PipeFn<Result<T, E>, A>, bc: PipeFn<A, B>, cd: PipeFn<B, C>): C;
309
+ };
310
+ /**
311
+ * Runs a side effect with the Ok or Err value and returns this same Result.
312
+ *
313
+ * Exceptions thrown by the side effect are swallowed.
314
+ */
315
+ log: (fn: (t?: T, e?: E) => void) => this;
316
+ /**
317
+ * Runs a side effect only when this result is Ok and returns this same Result.
318
+ *
319
+ * Exceptions thrown by the side effect are swallowed.
320
+ */
321
+ tap: (fn: (t: T) => void) => this;
322
+ /**
323
+ * Runs a side effect only when this result is Err and returns this same Result.
324
+ *
325
+ * Exceptions thrown by the side effect are swallowed.
326
+ */
327
+ tapError: (fn: (e: E) => void) => this;
328
+ /**
329
+ * Attaches a synchronous disposal finalizer to this Result.
330
+ */
331
+ toDisposable: (f: ResultFinalizer<T, E>) => DisposableResult<T, E>;
332
+ /**
333
+ * Returns the Ok value or throws the Err value.
334
+ *
335
+ * Use this at final application boundaries after the error channel has been modeled.
336
+ */
337
+ unwrapOrThrow: () => T;
338
+ /**
339
+ * Enables `yield* result` inside `safeTry` generators.
340
+ */
341
+ [Symbol.iterator]: () => Generator<Result<never, E>, T>;
342
+ /**
343
+ * Compatibility generator for `safeTry`. Prefer `yield* result` in new code.
344
+ */
345
+ safeUnwrap: () => Generator<Result<never, E>, T>;
228
346
  }
229
347
  interface OkResult<T, E> extends ResultOperations<T, E> {
348
+ /**
349
+ * Ok value carried by this result.
350
+ */
230
351
  readonly value: T;
231
352
  }
232
353
  interface ErrResult<T, E> extends ResultOperations<T, E> {
354
+ /**
355
+ * Err value carried by this result.
356
+ */
233
357
  readonly error: E;
234
358
  }
235
359
  type Result<T, E> = OkResult<T, E> | ErrResult<T, E>;
236
360
  type StrictResult<T, E extends Error = Error> = Result<T, E>;
361
+ /**
362
+ * Object form accepted by `tryResult`.
363
+ *
364
+ * Use this form when named `try` and `catch` fields make a synchronous boundary easier to read.
365
+ */
237
366
  interface TryResultOptions<T, E = unknown> {
367
+ /**
368
+ * Runs the synchronous work whose thrown value should become `Err<E>`.
369
+ */
238
370
  readonly try: () => Exclude<T, Promise<unknown>>;
371
+ /**
372
+ * Converts a thrown `unknown` cause into the typed Resultar error channel.
373
+ *
374
+ * If omitted, the error channel is `unknown`.
375
+ */
239
376
  readonly catch?: (e: unknown) => E;
240
377
  }
241
378
  interface SafeTryOptions<YieldErr extends Result<never, unknown>, GeneratorReturnResult extends Result<unknown, unknown>, CatchErr = never> {
379
+ /**
380
+ * Generator body evaluated by `safeTry`.
381
+ *
382
+ * Use `yield* result` to unwrap Resultar values and short-circuit on Err.
383
+ */
242
384
  readonly try: () => Generator<YieldErr, GeneratorReturnResult>;
385
+ /**
386
+ * Converts synchronous throws from the generator setup into the Result error channel.
387
+ */
243
388
  readonly catch?: (e: unknown) => CatchErr;
244
389
  }
245
390
  interface SafeTryAsyncOptions<YieldErr extends Result<never, unknown>, GeneratorReturnResult extends Result<unknown, unknown>, CatchErr = never> {
391
+ /**
392
+ * Async generator body evaluated by `safeTry`.
393
+ *
394
+ * Use `yield* result` or `yield* resultAsync` to unwrap Resultar values and short-circuit on Err.
395
+ */
246
396
  readonly try: () => AsyncGenerator<YieldErr, GeneratorReturnResult>;
397
+ /**
398
+ * Converts synchronous throws or async rejections from the generator setup into the ResultAsync
399
+ * error channel.
400
+ */
247
401
  readonly catch?: (e: unknown) => CatchErr;
248
402
  }
249
403
  interface ResultStatic {
250
- [Symbol.hasInstance](value: unknown): boolean;
251
404
  /**
405
+ * Runtime `instanceof Result` support for Ok and Err values.
406
+ */
407
+ [Symbol.hasInstance]: (value: unknown) => boolean;
408
+ /**
409
+ * Runs synchronous work and captures thrown values into a Result.
410
+ *
252
411
  * Compatibility alias. Prefer the top-level `tryResult` helper in new code.
253
412
  */
254
- tryCatch<T, E>(this: void, fn: () => Exclude<T, Promise<unknown>>, errorFn?: (e: unknown) => E): Result<T, E>;
255
- fromThrowable<Fn extends (...args: readonly any[]) => unknown, E>(this: void, fn: Fn, errorFn?: (e: any) => E): (...args: Parameters<Fn>) => Result<ReturnType<Fn>, E>;
256
- ok<T, E = never>(this: void, value: T): OkResult<T, E>;
257
- ok<E = never>(this: void, value: void): OkResult<void, E>;
258
- unit<E = never>(this: void): Result<undefined, E>;
259
- err<T = never, E extends string = string>(this: void, err: E): ErrResult<T, E>;
260
- err<T = never, E = unknown>(this: void, err: E): ErrResult<T, E>;
261
- err<T = never>(this: void, err: void): ErrResult<T, void>;
262
- combine<T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(this: void, resultList: T): CombineResults<T>;
263
- combine<T extends readonly Result<unknown, unknown>[]>(this: void, resultList: T): CombineResults<T>;
264
- combine<T extends ResultRecord>(this: void, resultRecord: T): CombineResultsRecord<T>;
265
- combine<R extends Result<unknown, unknown>>(this: void, results: Iterable<R>): CombineResultsIterable<R>;
266
- combineWithAllErrors<T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
267
- combineWithAllErrors<T extends readonly Result<unknown, unknown>[]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
268
- combineWithAllErrors<T extends ResultRecord>(this: void, resultRecord: T): CombineResultsRecordWithAllErrors<T>;
269
- combineWithAllErrors<R extends Result<unknown, unknown>>(this: void, results: Iterable<R>): CombineResultsIterableWithAllErrors<R>;
270
- validateAll<T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
271
- validateAll<T extends readonly Result<unknown, unknown>[]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
272
- validateAll<Item, R extends Result<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R): ResultValidatedAll<R>;
273
- zip<Left extends Result<unknown, unknown>, Right extends Result<unknown, unknown>>(this: void, left: Left, right: Right): ResultZipped<Left, Right>;
274
- firstSuccessOf<Candidates extends Iterable<ResultCandidate>>(this: void, candidates: Candidates): FirstSuccessOf<Candidates>;
275
- if<OnTrue extends Result<unknown, unknown>, OnFalse extends Result<unknown, unknown>>(this: void, condition: ResultBooleanCondition, options: ResultIfOptions<OnTrue, OnFalse>): ResultIf<never, OnTrue, OnFalse>;
276
- if<Condition extends Result<boolean, unknown>, OnTrue extends Result<unknown, unknown>, OnFalse extends Result<unknown, unknown>>(this: void, condition: Condition, options: ResultIfOptions<OnTrue, OnFalse>): ResultIf<InferErrTypes<Condition>, OnTrue, OnFalse>;
277
- when<R extends Result<unknown, unknown>>(this: void, condition: ResultBooleanCondition, body: () => R): ResultWhen<R>;
278
- whenResult<Condition extends Result<boolean, unknown>, R extends Result<unknown, unknown>>(this: void, condition: Condition, body: () => R): ResultWhenWithCondition<Condition, R>;
279
- unless<R extends Result<unknown, unknown>>(this: void, condition: ResultBooleanCondition, body: () => R): ResultWhen<R>;
280
- unlessResult<Condition extends Result<boolean, unknown>, R extends Result<unknown, unknown>>(this: void, condition: Condition, body: () => R): ResultWhenWithCondition<Condition, R>;
281
- loop<State, BodyState extends State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopOptions<State, BodyState, R>): ResultLoopCollected<R>;
282
- loop<State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopBooleanOptions<State, R>): ResultLoopCollected<R>;
283
- loop<State, BodyState extends State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopDiscardOptions<State, BodyState, R>): ResultLoopDiscarded<R>;
284
- loop<State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopBooleanDiscardOptions<State, R>): ResultLoopDiscarded<R>;
285
- iterate<State, BodyState extends WidenLiteral$1<State>, R extends Result<WidenLiteral$1<State>, unknown>>(this: void, initial: State, options: ResultIterateOptions<WidenLiteral$1<State>, BodyState, R>): ResultIterated<WidenLiteral$1<State>, R>;
286
- iterate<State, R extends Result<WidenLiteral$1<State>, unknown>>(this: void, initial: State, options: ResultIterateBooleanOptions<WidenLiteral$1<State>, R>): ResultIterated<WidenLiteral$1<State>, R>;
287
- forEach<Item, R extends Result<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options?: ResultForEachOptions): ResultForEachCollected<R>;
288
- forEach<Item, R extends Result<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options: ResultForEachDiscardOptions): ResultForEachDiscarded<R>;
413
+ tryCatch: <T, E>(this: void, fn: () => Exclude<T, Promise<unknown>>, errorFn?: (e: unknown) => E) => Result<T, E>;
414
+ /**
415
+ * Wraps a throwing synchronous function so every later call returns a Result.
416
+ */
417
+ fromThrowable: <Fn extends (...args: readonly any[]) => unknown, E>(this: void, fn: Fn, errorFn?: (e: any) => E) => (...args: Parameters<Fn>) => Result<ReturnType<Fn>, E>;
418
+ /**
419
+ * Creates an Ok result.
420
+ */
421
+ ok: {
422
+ <T, E = never>(this: void, value: T): OkResult<T, E>;
423
+ <E = never>(this: void, value: void): OkResult<void, E>;
424
+ };
425
+ /**
426
+ * Creates an Ok result with `undefined`.
427
+ */
428
+ unit: <E = never>(this: void) => Result<undefined, E>;
429
+ /**
430
+ * Creates an Err result.
431
+ */
432
+ err: {
433
+ <T = never, E extends string = string>(this: void, err: E): ErrResult<T, E>;
434
+ <T = never, E = unknown>(this: void, err: E): ErrResult<T, E>;
435
+ <T = never>(this: void, err: void): ErrResult<T, void>;
436
+ };
437
+ /**
438
+ * Combines many Result values and stops at the first Err.
439
+ *
440
+ * Arrays return an Ok array, records return an Ok record with the same keys, and iterables return
441
+ * an Ok readonly array.
442
+ */
443
+ combine: {
444
+ <T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(this: void, resultList: T): CombineResults<T>;
445
+ <T extends readonly Result<unknown, unknown>[]>(this: void, resultList: T): CombineResults<T>;
446
+ <T extends ResultRecord>(this: void, resultRecord: T): CombineResultsRecord<T>;
447
+ <R extends Result<unknown, unknown>>(this: void, results: Iterable<R>): CombineResultsIterable<R>;
448
+ };
449
+ /**
450
+ * Combines many Result values and collects every Err instead of stopping at the first one.
451
+ */
452
+ combineWithAllErrors: {
453
+ <T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
454
+ <T extends readonly Result<unknown, unknown>[]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
455
+ <T extends ResultRecord>(this: void, resultRecord: T): CombineResultsRecordWithAllErrors<T>;
456
+ <R extends Result<unknown, unknown>>(this: void, results: Iterable<R>): CombineResultsIterableWithAllErrors<R>;
457
+ };
458
+ /**
459
+ * Validates many Result values and collects every Err.
460
+ *
461
+ * When passed items plus a mapper, the mapper must return a Result for each item.
462
+ */
463
+ validateAll: {
464
+ <T extends readonly [Result<unknown, unknown>, ...Result<unknown, unknown>[]]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
465
+ <T extends readonly Result<unknown, unknown>[]>(this: void, resultList: T): CombineResultsWithAllErrorsArray<T>;
466
+ <Item, R extends Result<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R): ResultValidatedAll<R>;
467
+ };
468
+ /**
469
+ * Combines exactly two Result values into an Ok tuple or the first Err.
470
+ */
471
+ zip: <Left extends Result<unknown, unknown>, Right extends Result<unknown, unknown>>(this: void, left: Left, right: Right) => ResultZipped<Left, Right>;
472
+ /**
473
+ * Runs candidates until the first Ok and returns the last Err if every candidate fails.
474
+ */
475
+ firstSuccessOf: <Candidates extends Iterable<ResultCandidate>>(this: void, candidates: Candidates) => FirstSuccessOf<Candidates>;
476
+ /**
477
+ * Chooses one of two Result branches from a boolean or Result boolean condition.
478
+ */
479
+ if: {
480
+ <OnTrue extends Result<unknown, unknown>, OnFalse extends Result<unknown, unknown>>(this: void, condition: ResultBooleanCondition, options: ResultIfOptions<OnTrue, OnFalse>): ResultIf<never, OnTrue, OnFalse>;
481
+ <Condition extends Result<boolean, unknown>, OnTrue extends Result<unknown, unknown>, OnFalse extends Result<unknown, unknown>>(this: void, condition: Condition, options: ResultIfOptions<OnTrue, OnFalse>): ResultIf<InferErrTypes<Condition>, OnTrue, OnFalse>;
482
+ };
483
+ /**
484
+ * Runs `body` only when the condition is true; otherwise returns Ok(undefined).
485
+ */
486
+ when: <R extends Result<unknown, unknown>>(this: void, condition: ResultBooleanCondition, body: () => R) => ResultWhen<R>;
487
+ /**
488
+ * Runs `body` only when a Result boolean condition is Ok(true).
489
+ */
490
+ whenResult: <Condition extends Result<boolean, unknown>, R extends Result<unknown, unknown>>(this: void, condition: Condition, body: () => R) => ResultWhenWithCondition<Condition, R>;
491
+ /**
492
+ * Runs `body` only when the condition is false; otherwise returns Ok(undefined).
493
+ */
494
+ unless: <R extends Result<unknown, unknown>>(this: void, condition: ResultBooleanCondition, body: () => R) => ResultWhen<R>;
495
+ /**
496
+ * Runs `body` only when a Result boolean condition is Ok(false).
497
+ */
498
+ unlessResult: <Condition extends Result<boolean, unknown>, R extends Result<unknown, unknown>>(this: void, condition: Condition, body: () => R) => ResultWhenWithCondition<Condition, R>;
499
+ /**
500
+ * Repeats a Result-producing body while a condition holds.
501
+ *
502
+ * Use `discard: true` when only failure matters and collected Ok values are not needed.
503
+ */
504
+ loop: {
505
+ <State, BodyState extends State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopOptions<State, BodyState, R>): ResultLoopCollected<R>;
506
+ <State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopBooleanOptions<State, R>): ResultLoopCollected<R>;
507
+ <State, BodyState extends State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopDiscardOptions<State, BodyState, R>): ResultLoopDiscarded<R>;
508
+ <State, R extends Result<unknown, unknown>>(this: void, initial: State, options: ResultLoopBooleanDiscardOptions<State, R>): ResultLoopDiscarded<R>;
509
+ };
510
+ /**
511
+ * Repeatedly transforms state with a Result-producing body until the condition fails.
512
+ */
513
+ iterate: {
514
+ <State, BodyState extends WidenLiteral$1<State>, R extends Result<WidenLiteral$1<State>, unknown>>(this: void, initial: State, options: ResultIterateOptions<WidenLiteral$1<State>, BodyState, R>): ResultIterated<WidenLiteral$1<State>, R>;
515
+ <State, R extends Result<WidenLiteral$1<State>, unknown>>(this: void, initial: State, options: ResultIterateBooleanOptions<WidenLiteral$1<State>, R>): ResultIterated<WidenLiteral$1<State>, R>;
516
+ };
517
+ /**
518
+ * Runs a Result-producing mapper for each item.
519
+ *
520
+ * Use `discard: true` when only failure matters and collected Ok values are not needed.
521
+ */
522
+ forEach: {
523
+ <Item, R extends Result<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options?: ResultForEachOptions): ResultForEachCollected<R>;
524
+ <Item, R extends Result<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options: ResultForEachDiscardOptions): ResultForEachDiscarded<R>;
525
+ };
289
526
  }
290
527
  declare const Result: ResultStatic;
291
528
  /**
@@ -295,28 +532,54 @@ declare const Result: ResultStatic;
295
532
  declare class DisposableResult<T, E> implements Resultable<T, E>, Disposable {
296
533
  private disposed;
297
534
  private readonly finalizer;
535
+ /**
536
+ * Wrapped Result value.
537
+ */
298
538
  readonly result: Result<T, E>;
539
+ /**
540
+ * Creates a disposable wrapper around a Result.
541
+ */
299
542
  constructor(result: Result<T, E>, finalizer: ResultFinalizer<T, E>);
543
+ /**
544
+ * Ok value when present, otherwise undefined cast to `T` for compatibility.
545
+ */
300
546
  get value(): T;
547
+ /**
548
+ * Err value when present, otherwise undefined cast to `E` for compatibility.
549
+ */
301
550
  get error(): E;
551
+ /**
552
+ * Delegates to the wrapped Result `_unsafeUnwrap`.
553
+ */
302
554
  _unsafeUnwrap(config?: ErrorConfig): T;
555
+ /**
556
+ * Delegates to the wrapped Result `_unsafeUnwrapErr`.
557
+ */
303
558
  _unsafeUnwrapErr(config?: ErrorConfig): E;
559
+ /**
560
+ * Returns whether the wrapped Result is Ok.
561
+ */
304
562
  isOk(): boolean;
563
+ /**
564
+ * Returns whether the wrapped Result is Err.
565
+ */
305
566
  isErr(): boolean;
567
+ /**
568
+ * Returns the wrapped Ok value, or `defaultValue` when Err.
569
+ */
306
570
  unwrapOr<A>(defaultValue: A): T | A;
571
+ /**
572
+ * Runs the finalizer once.
573
+ *
574
+ * Finalizer exceptions are intentionally swallowed.
575
+ */
307
576
  [Symbol.dispose](): void;
308
577
  }
309
578
  /**
310
- * Evaluates the given generator to a Result returned or an Err yielded from it,
311
- * whichever comes first.
579
+ * Evaluates a synchronous generator and returns the first yielded Err or returned Result.
312
580
  *
313
- * This function, in combination with `Result.safeUnwrap()`, is intended to emulate
314
- * Rust's ? operator.
315
- * See `/tests/safeTry.test.ts` for examples.
316
- *
317
- * @param body - What is evaluated. In body, `yield* result.safeUnwrap()` works as
318
- * Rust's `result?` expression.
319
- * @returns The first occurence of either an yielded Err or a returned Result.
581
+ * Inside the generator, use `yield* result` to unwrap Ok values and short-circuit on Err. The object
582
+ * form can map thrown setup errors into the Result error channel.
320
583
  */
321
584
  declare function safeTry<T, E, CatchErr = E>(input: SafeTryOptions<Result<never, E>, Result<T, E>, CatchErr> & {
322
585
  readonly catch: (e: unknown) => CatchErr;
@@ -327,16 +590,12 @@ declare function safeTry<YieldErr extends Result<never, unknown>, GeneratorRetur
327
590
  }): Result<InferOkTypes<GeneratorReturnResult>, InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult> | CatchErr>;
328
591
  declare function safeTry<YieldErr extends Result<never, unknown>, GeneratorReturnResult extends Result<unknown, unknown>>(input: (() => Generator<YieldErr, GeneratorReturnResult>) | SafeTryOptions<YieldErr, GeneratorReturnResult>): Result<InferOkTypes<GeneratorReturnResult>, InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult>>;
329
592
  /**
330
- * Evaluates the given generator to a Result returned or an Err yielded from it,
331
- * whichever comes first.
332
- *
333
- * This function, in combination with `Result.safeUnwrap()`, is intended to emulate
334
- * Rust's ? operator.
335
- * See `/tests/safeTry.test.ts` for examples.
593
+ * Evaluates an async generator and returns a ResultAsync for the first yielded Err or returned
594
+ * Result.
336
595
  *
337
- * @param body - What is evaluated. In body, `yield* result.safeUnwrap()`,
338
- * `yield* result`, and `yield* resultAsync` work as Rust's `result?` expression.
339
- * @returns The first occurence of either an yielded Err or a returned Result.
596
+ * Inside the generator, use `yield* result` or `yield* resultAsync` to unwrap Ok values and
597
+ * short-circuit on Err. The object form can map thrown or rejected setup errors into the ResultAsync
598
+ * error channel.
340
599
  */
341
600
  declare function safeTry<T, E, CatchErr = E>(input: SafeTryAsyncOptions<Result<never, E>, Result<T, E>, CatchErr> & {
342
601
  readonly catch: (e: unknown) => CatchErr;
@@ -346,18 +605,66 @@ declare function safeTry<YieldErr extends Result<never, unknown>, GeneratorRetur
346
605
  readonly catch: (e: unknown) => CatchErr;
347
606
  }): ResultAsync<InferOkTypes<GeneratorReturnResult>, InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult> | CatchErr>;
348
607
  declare function safeTry<YieldErr extends Result<never, unknown>, GeneratorReturnResult extends Result<unknown, unknown>>(input: (() => AsyncGenerator<YieldErr, GeneratorReturnResult>) | SafeTryAsyncOptions<YieldErr, GeneratorReturnResult>): ResultAsync<InferOkTypes<GeneratorReturnResult>, InferErrTypes<YieldErr> | InferErrTypes<GeneratorReturnResult>>;
608
+ /**
609
+ * Creates an Ok result.
610
+ */
349
611
  declare function ok<T, E = never>(value: T): OkResult<T, E>;
350
612
  declare function ok<E = never>(value: void): OkResult<void, E>;
613
+ /**
614
+ * Creates an Err result.
615
+ */
351
616
  declare function err<T = never, E extends string = string>(err: E): ErrResult<T, E>;
352
617
  declare function err<T = never, E = unknown>(err: E): ErrResult<T, E>;
353
618
  declare function err<T = never>(err: void): ErrResult<T, void>;
619
+ /**
620
+ * Wraps a throwing synchronous function so every later call returns a Result.
621
+ *
622
+ * Prefer `tryResult` when you want to run the operation immediately.
623
+ */
354
624
  declare const fromThrowable: typeof Result.fromThrowable;
625
+ /**
626
+ * Runs synchronous work and captures thrown values into `Result<T, E>`.
627
+ *
628
+ * Use `tryResult` at the edge of uncontrolled synchronous code: JSON parsing, environment parsing,
629
+ * platform APIs, or third-party functions that may throw. The mapper receives the thrown `unknown`
630
+ * cause and returns the typed error for the Resultar channel.
631
+ *
632
+ * @example
633
+ * ```ts
634
+ * const config = tryResult(
635
+ * () => JSON.parse(input) as Config,
636
+ * (cause) => new ParseConfigError({ cause }),
637
+ * )
638
+ * ```
639
+ */
355
640
  declare function tryResult<T, E>(fn: () => Exclude<T, Promise<unknown>>, errorFn: (e: unknown) => E): Result<T, E>;
641
+ /**
642
+ * Captures a synchronous boundary with named `try` and `catch` fields.
643
+ *
644
+ * This is equivalent to `tryResult(() => ..., toError)`, but it reads better when the boundary has
645
+ * a clear domain name or label.
646
+ */
356
647
  declare function tryResult<T, E>(options: TryResultOptions<T, E> & {
357
648
  readonly catch: (e: unknown) => E;
358
649
  }): Result<T, E>;
650
+ /**
651
+ * Runs synchronous work and captures thrown values into `Result<T, unknown>`.
652
+ *
653
+ * Prefer the overload with a catch mapper in application code so the error channel stays documented.
654
+ * This overload is useful while adapting unknown external failures or during migration.
655
+ */
359
656
  declare function tryResult<T>(input: (() => Exclude<T, Promise<unknown>>) | TryResultOptions<T>): Result<T, unknown>;
657
+ /**
658
+ * Creates an Ok result with `undefined`.
659
+ */
360
660
  declare function unit<E = never>(): OkResult<undefined, E>;
661
+ /**
662
+ * Runs a `Result` at an application boundary and returns the success value.
663
+ *
664
+ * If the result is `Err`, this throws the error. Use it at final framework, CLI, test, or bootstrap
665
+ * boundaries after the error channel has already been modeled with Resultar.
666
+ */
667
+ declare const runSync: <T, E>(result: Result<T, E>) => T;
361
668
  /** Compatibility alias. Prefer `tryResult` in new code. */
362
669
  declare const tryCatch: typeof tryResult;
363
670
  type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, ...0[]];
@@ -378,81 +685,264 @@ type CombineResults<T extends readonly Result<unknown, unknown>[]> = IsLiteralAr
378
685
  type CombineResultsWithAllErrorsArray<T extends readonly Result<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseWithAllErrors<T> : Result<ExtractOkTypes<T>, ExtractErrTypes<T>[number][]>;
379
686
  //#endregion
380
687
  //#region src/abort-error.d.ts
688
+ /**
689
+ * Standard cancellation error used by ResultAsync retry, race, timeout, and resource helpers.
690
+ */
381
691
  declare class AbortError extends Error {
692
+ /**
693
+ * Creates an AbortError.
694
+ */
382
695
  constructor(message?: string, options?: ErrorOptions);
383
696
  }
697
+ /**
698
+ * Checks whether a value is an AbortError or abort-shaped platform error.
699
+ */
384
700
  declare const isAbortError: (value: unknown) => value is AbortError;
385
701
  //#endregion
386
702
  //#region src/result-async.d.ts
387
703
  type ResultAsyncFinalizer<T, E> = (value: T | undefined, error: E | undefined) => void | Promise<void>;
704
+ /**
705
+ * Object form accepted by `tryResultAsync`.
706
+ *
707
+ * Use this form when named `try` and `catch` fields make an async boundary easier to read, or when
708
+ * you want the mapper next to the promise factory.
709
+ */
388
710
  interface TryResultAsyncOptions<T, E = unknown> {
711
+ /**
712
+ * Creates the promise whose rejection should become `Err<E>`.
713
+ *
714
+ * Synchronous throws from this function are also captured.
715
+ */
389
716
  readonly try: () => Promise<T>;
717
+ /**
718
+ * Converts a rejected or thrown `unknown` cause into the typed Resultar error channel.
719
+ *
720
+ * If omitted, the error channel is `unknown`.
721
+ */
390
722
  readonly catch?: (e: unknown) => E;
391
723
  }
392
724
  interface ResultAsyncAbortSignal {
725
+ /**
726
+ * Whether the cooperative async operation has been aborted.
727
+ */
393
728
  readonly aborted: boolean;
729
+ /**
730
+ * Optional abort cause provided by the losing race, timeout, or caller.
731
+ */
394
732
  readonly reason?: unknown;
395
- addEventListener(type: "abort", listener: () => void, options?: {
733
+ /**
734
+ * Registers an abort listener.
735
+ */
736
+ addEventListener: (type: "abort", listener: () => void, options?: {
396
737
  readonly once?: boolean;
397
- }): void;
398
- removeEventListener(type: "abort", listener: () => void): void;
738
+ }) => void;
739
+ /**
740
+ * Removes an abort listener.
741
+ */
742
+ removeEventListener: (type: "abort", listener: () => void) => void;
399
743
  }
744
+ /**
745
+ * Context passed to `ResultAsync.fromCallback` subscriptions.
746
+ */
747
+ interface ResultAsyncCallbackContext<T> {
748
+ /**
749
+ * Completes the operation with `Ok(value)`.
750
+ */
751
+ readonly resolve: (value: T) => void;
752
+ /**
753
+ * Completes the operation with a cause mapped by the subscription's `catch` function.
754
+ */
755
+ readonly reject: (cause: unknown) => void;
756
+ /**
757
+ * Cooperative cancellation signal for the subscription.
758
+ */
759
+ readonly signal: ResultAsyncAbortSignal;
760
+ }
761
+ /**
762
+ * Synchronous cleanup returned by a `ResultAsync.fromCallback` subscription.
763
+ */
764
+ type ResultAsyncCallbackCleanup = () => void;
765
+ /**
766
+ * Options for adapting a callback or subscription API into `ResultAsync`.
767
+ */
768
+ interface ResultAsyncFromCallbackOptions<T, E> {
769
+ /**
770
+ * Maps callback failures and synchronous subscription throws into the typed error channel.
771
+ */
772
+ readonly catch: (cause: unknown) => E;
773
+ /**
774
+ * Optional external signal that cancels the subscription with `AbortError`.
775
+ */
776
+ readonly signal?: ResultAsyncAbortSignal;
777
+ /**
778
+ * Registers the callback source and optionally returns a synchronous unsubscribe function.
779
+ */
780
+ readonly subscribe: (context: ResultAsyncCallbackContext<T>) => ResultAsyncCallbackCleanup | void;
781
+ }
782
+ /**
783
+ * Concurrency setting for async collection helpers.
784
+ *
785
+ * Use a number for bounded parallelism or `'unbounded'` when every task may start immediately.
786
+ */
400
787
  type ResultAsyncConcurrency = number | "unbounded";
401
788
  type HandlerOk<R> = InferOkTypes<R> | InferAsyncOkTypes<R>;
402
789
  type HandlerErr<R> = InferErrTypes<R> | InferAsyncErrTypes<R>;
403
790
  type IterableElement<T> = T extends Iterable<infer Element> ? Element : never;
791
+ /**
792
+ * Candidate used by `ResultAsync.firstSuccessOf`.
793
+ */
404
794
  type ResultAsyncCandidate = () => ResultAsync<unknown, unknown>;
405
795
  type ResultAsyncRecord = Readonly<Record<string, ResultAsync<unknown, unknown>>>;
406
796
  type CombineResultAsyncsRecord<T extends ResultAsyncRecord> = ResultAsync<{ readonly [Key in keyof T]: InferAsyncOkTypes<T[Key]> }, InferAsyncErrTypes<T[keyof T]>>;
407
797
  type CombineResultAsyncsRecordWithAllErrors<T extends ResultAsyncRecord> = ResultAsync<{ readonly [Key in keyof T]: InferAsyncOkTypes<T[Key]> }, InferAsyncErrTypes<T[keyof T]>[]>;
408
798
  type CombineResultAsyncsIterable<R extends ResultAsync<unknown, unknown>> = ResultAsync<readonly InferAsyncOkTypes<R>[], InferAsyncErrTypes<R>>;
409
799
  type CombineResultAsyncsIterableWithAllErrors<R extends ResultAsync<unknown, unknown>> = ResultAsync<readonly InferAsyncOkTypes<R>[], InferAsyncErrTypes<R>[]>;
800
+ /**
801
+ * Task used by race, timeout, and retry helpers.
802
+ *
803
+ * The signal lets the task cooperate with cancellation when another task wins or a timeout fires.
804
+ */
410
805
  type ResultAsyncRaceTask<T, E> = (signal: ResultAsyncAbortSignal) => ResultAsync<T, E>;
411
806
  type ResultAsyncRaceTaskOk<Task> = Task extends ResultAsyncRaceTask<infer T, unknown> ? T : never;
412
807
  type ResultAsyncRaceTaskErr<Task> = Task extends ResultAsyncRaceTask<unknown, infer E> ? E : never;
413
808
  type ResultAsyncRaceTasksOk<Tasks extends readonly ResultAsyncRaceTask<unknown, unknown>[]> = ResultAsyncRaceTaskOk<Tasks[number]>;
414
809
  type ResultAsyncRaceTasksErr<Tasks extends readonly ResultAsyncRaceTask<unknown, unknown>[]> = ResultAsyncRaceTaskErr<Tasks[number]>;
415
810
  interface ResultAsyncRaceHandle<T, E> {
811
+ /**
812
+ * Abort signal associated with the running task.
813
+ */
416
814
  readonly signal: ResultAsyncAbortSignal;
417
- abort(reason?: unknown): void;
418
- wait(): ResultAsync<T, E>;
815
+ /**
816
+ * Aborts the running task with an optional reason.
817
+ */
818
+ abort: (reason?: unknown) => void;
819
+ /**
820
+ * Waits for the task to settle as a ResultAsync.
821
+ */
822
+ wait: () => ResultAsync<T, E>;
419
823
  }
824
+ /**
825
+ * Options for `ResultAsync.timeout`.
826
+ */
420
827
  interface ResultAsyncTimeoutOptions<E> {
828
+ /**
829
+ * Creates the typed timeout error when the timeout wins.
830
+ */
421
831
  readonly onTimeout: () => E;
832
+ /**
833
+ * Timeout duration in milliseconds.
834
+ */
422
835
  readonly timeoutMs: number;
423
836
  }
837
+ /**
838
+ * Metadata passed to retry predicates, delays, callbacks, and fallback handlers.
839
+ */
424
840
  interface ResultAsyncRetryContext {
841
+ /**
842
+ * Current attempt number, starting at 1.
843
+ */
425
844
  readonly attempt: number;
845
+ /**
846
+ * Next attempt number if another retry is scheduled.
847
+ */
426
848
  readonly nextAttempt: number;
849
+ /**
850
+ * Number of retries still available after the current failure.
851
+ */
427
852
  readonly retriesRemaining: number;
428
853
  }
854
+ /**
855
+ * Task used by `ResultAsync.retry` and `ResultAsync.retryOrElse`.
856
+ */
429
857
  type ResultAsyncRetryTask<T, E> = (attempt: number, signal: ResultAsyncAbortSignal) => ResultAsync<T, E>;
430
858
  type ResultAsyncRetryTaskOk<Task> = Task extends ResultAsyncRetryTask<infer T, unknown> ? T : never;
431
859
  type ResultAsyncRetryTaskErr<Task> = Task extends ResultAsyncRetryTask<unknown, infer E> ? E : never;
432
860
  type ResultAsyncRetryDelay = number | ((context: ResultAsyncRetryContext) => number);
433
861
  interface ResultAsyncRetryOptions<E> {
862
+ /**
863
+ * Delay in milliseconds before retrying. Functions receive retry context.
864
+ */
434
865
  readonly delayMs?: ResultAsyncRetryDelay;
866
+ /**
867
+ * Randomizes the computed delay by this percentage factor.
868
+ *
869
+ * For example, `0.5` means 50% below to 50% above the computed delay.
870
+ */
435
871
  readonly jittered?: number;
872
+ /**
873
+ * Side effect called after a failed attempt that will be retried.
874
+ */
436
875
  readonly onRetry?: (error: E, context: ResultAsyncRetryContext) => void | Promise<void>;
876
+ /**
877
+ * Optional external abort signal for the retry loop.
878
+ */
437
879
  readonly signal?: ResultAsyncAbortSignal;
880
+ /**
881
+ * Maximum number of retries after the initial attempt.
882
+ */
438
883
  readonly times: number;
884
+ /**
885
+ * Predicate deciding whether a failure is retryable.
886
+ */
439
887
  readonly while?: (error: E, context: ResultAsyncRetryContext) => boolean | Promise<boolean>;
440
888
  }
889
+ /**
890
+ * Options for `ResultAsync.retryOrElse`.
891
+ */
441
892
  interface ResultAsyncRetryOrElseOptions<E, F, U> extends ResultAsyncRetryOptions<E> {
893
+ /**
894
+ * Fallback Resultar operation used after retry exhaustion.
895
+ */
442
896
  readonly orElse: (error: E, context: ResultAsyncRetryContext) => Result<U, F> | ResultAsync<U, F>;
443
897
  }
898
+ /**
899
+ * Acquires a resource for `ResultAsync.withResource`.
900
+ */
444
901
  type ResultAsyncResourceAcquire<Resource, E> = (signal: ResultAsyncAbortSignal) => ResultAsync<Resource, E>;
902
+ /**
903
+ * Operation accepted by `ResultAsync.withResource` use/release callbacks.
904
+ */
445
905
  type ResultAsyncResourceEffect<T, E> = Result<T, E> | ResultAsync<T, E>;
906
+ /**
907
+ * Uses an acquired resource inside `ResultAsync.withResource`.
908
+ */
446
909
  type ResultAsyncResourceUse<Resource, T, E> = (resource: Resource, signal: ResultAsyncAbortSignal) => ResultAsyncResourceEffect<T, E>;
910
+ /**
911
+ * Context passed to resource release callbacks.
912
+ */
447
913
  interface ResultAsyncResourceReleaseContext {
914
+ /**
915
+ * Result produced by the use phase, or undefined when acquisition failed.
916
+ */
448
917
  readonly result: Result<unknown, unknown> | undefined;
918
+ /**
919
+ * Abort signal shared by the resource lifecycle.
920
+ */
449
921
  readonly signal: ResultAsyncAbortSignal;
450
922
  }
923
+ /**
924
+ * Releases a resource after use, regardless of success or failure.
925
+ */
451
926
  type ResultAsyncResourceRelease<Resource> = (resource: Resource, context: ResultAsyncResourceReleaseContext) => ResultAsyncResourceEffect<unknown, unknown> | Promise<void> | void;
927
+ /**
928
+ * Options for `ResultAsync.withResource`.
929
+ */
452
930
  interface ResultAsyncWithResourceOptions<Resource, AcquireError, T, UseError> {
931
+ /**
932
+ * Acquires the resource.
933
+ */
453
934
  readonly acquire: ResultAsyncResourceAcquire<Resource, AcquireError>;
935
+ /**
936
+ * Releases the resource after use.
937
+ */
454
938
  readonly release: ResultAsyncResourceRelease<Resource>;
939
+ /**
940
+ * Optional external abort signal for the full lifecycle.
941
+ */
455
942
  readonly signal?: ResultAsyncAbortSignal;
943
+ /**
944
+ * Uses the acquired resource.
945
+ */
456
946
  readonly use: ResultAsyncResourceUse<Resource, T, UseError>;
457
947
  }
458
948
  type FirstSuccessOfAsync<Candidates extends Iterable<ResultAsyncCandidate>> = ResultAsync<InferAsyncOkTypes<ReturnType<IterableElement<Candidates>>>, InferAsyncErrTypes<ReturnType<IterableElement<Candidates>>>>;
@@ -521,8 +1011,19 @@ declare class DisposableResultAsync<T, E> implements PromiseLike<Result<T, E>>,
521
1011
  private readonly innerPromise;
522
1012
  private readonly finalizer;
523
1013
  private disposed;
1014
+ /**
1015
+ * Creates an async disposable wrapper around a ResultAsync promise.
1016
+ */
524
1017
  constructor(res: Promise<Result<T, E>>, finalizer: ResultAsyncFinalizer<T, E>);
1018
+ /**
1019
+ * PromiseLike integration. Resolves to the wrapped Result.
1020
+ */
525
1021
  then<A, B>(successCallback?: (res: Result<T, E>) => A | PromiseLike<A>, failureCallback?: (reason: unknown) => B | PromiseLike<B>): PromiseLike<A | B>;
1022
+ /**
1023
+ * Runs the finalizer once after the wrapped Result resolves.
1024
+ *
1025
+ * Finalizer exceptions and rejections are intentionally swallowed.
1026
+ */
526
1027
  [Symbol.asyncDispose](): Promise<void>;
527
1028
  }
528
1029
  /**
@@ -556,7 +1057,7 @@ declare class DisposableResultAsync<T, E> implements PromiseLike<Result<T, E>>,
556
1057
  * but operating in an asynchronous context.
557
1058
  *
558
1059
  * The class includes methods for:
559
- * - Creating ResultAsync instances (okAsync, errAsync, fromPromise)
1060
+ * - Creating ResultAsync instances (okAsync, errAsync, fromPromise, fromCallback)
560
1061
  * - Transforming values (map, mapErr)
561
1062
  * - Chaining operations (andThen, orElse)
562
1063
  * - Error handling (tapError)
@@ -618,86 +1119,241 @@ declare class ResultAsync<T, E> extends Pipeable implements PromiseLike<Result<T
618
1119
  * @return {ResultAsync<T, E>} A ResultAsync instance with the given promise and error type E.
619
1120
  */
620
1121
  static fromPromise<T, E>(this: void, promise: PromiseLike<T>, errorFn: (e: unknown) => E): ResultAsync<T, E>;
1122
+ /**
1123
+ * Adapts a callback or subscription API into a cancellable ResultAsync.
1124
+ *
1125
+ * The returned cleanup function runs once after resolve, reject, cancellation, or synchronous
1126
+ * subscription failure. Cleanup errors are ignored.
1127
+ */
1128
+ static fromCallback<T, E>(this: void, options: ResultAsyncFromCallbackOptions<T, E>): ResultAsync<T, E | AbortError>;
1129
+ /**
1130
+ * Combines many ResultAsync values and stops at the first Err.
1131
+ *
1132
+ * Arrays return an Ok array, records return an Ok record with the same keys, and iterables return
1133
+ * an Ok readonly array.
1134
+ */
621
1135
  static combine<T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]]>(this: void, asyncResultList: T): CombineResultAsyncs<T>;
622
1136
  static combine<T extends readonly ResultAsync<unknown, unknown>[]>(this: void, asyncResultList: T): CombineResultAsyncs<T>;
623
1137
  static combine<T extends ResultAsyncRecord>(this: void, asyncResultRecord: T): CombineResultAsyncsRecord<T>;
624
1138
  static combine<R extends ResultAsync<unknown, unknown>>(this: void, asyncResults: Iterable<R>): CombineResultAsyncsIterable<R>;
1139
+ /**
1140
+ * Combines many ResultAsync values and collects every Err instead of stopping at the first one.
1141
+ */
625
1142
  static combineWithAllErrors<T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]]>(this: void, asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>;
626
1143
  static combineWithAllErrors<T extends readonly ResultAsync<unknown, unknown>[]>(this: void, asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>;
627
1144
  static combineWithAllErrors<T extends ResultAsyncRecord>(this: void, asyncResultRecord: T): CombineResultAsyncsRecordWithAllErrors<T>;
628
1145
  static combineWithAllErrors<R extends ResultAsync<unknown, unknown>>(this: void, asyncResults: Iterable<R>): CombineResultAsyncsIterableWithAllErrors<R>;
1146
+ /**
1147
+ * Validates many ResultAsync values and collects every Err.
1148
+ *
1149
+ * When passed items plus a mapper, the mapper must return a ResultAsync for each item. Use the
1150
+ * optional concurrency setting to bound parallel work.
1151
+ */
629
1152
  static validateAll<T extends readonly [ResultAsync<unknown, unknown>, ...ResultAsync<unknown, unknown>[]]>(this: void, asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>;
630
1153
  static validateAll<T extends readonly ResultAsync<unknown, unknown>[]>(this: void, asyncResultList: T): CombineResultsWithAllErrorsArrayAsync<T>;
631
1154
  static validateAll<Item, R extends ResultAsync<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options?: ResultAsyncValidateAllOptions): ResultAsyncValidatedAll<R>;
1155
+ /**
1156
+ * Combines exactly two ResultAsync values into an Ok tuple or the first Err.
1157
+ */
632
1158
  static zip<Left extends ResultAsync<unknown, unknown>, Right extends ResultAsync<unknown, unknown>>(this: void, left: Left, right: Right): ResultAsyncZipped<Left, Right>;
1159
+ /**
1160
+ * Retries a ResultAsync task according to a typed retry policy.
1161
+ *
1162
+ * The returned error channel includes the task error and `AbortError`.
1163
+ */
633
1164
  static retry<Task extends ResultAsyncRetryTask<unknown, unknown>>(this: void, task: Task, options: ResultAsyncRetryOptions<ResultAsyncRetryTaskErr<Task>>): ResultAsync<ResultAsyncRetryTaskOk<Task>, ResultAsyncRetryTaskErr<Task> | AbortError>;
1165
+ /**
1166
+ * Retries a ResultAsync task and falls back to another Resultar operation after retry exhaustion.
1167
+ */
634
1168
  static retryOrElse<Task extends ResultAsyncRetryTask<unknown, unknown>, U, F>(this: void, task: Task, options: ResultAsyncRetryOrElseOptions<ResultAsyncRetryTaskErr<Task>, F, U>): ResultAsync<ResultAsyncRetryTaskOk<Task> | U, F | AbortError>;
1169
+ /**
1170
+ * Acquires, uses, and releases a resource with cleanup on every path.
1171
+ *
1172
+ * Release errors are intentionally not part of the success/error channel; model cleanup failures
1173
+ * in `use` when they should affect control flow.
1174
+ */
635
1175
  static withResource<Resource, AcquireError, T, UseError>(this: void, options: ResultAsyncWithResourceOptions<Resource, AcquireError, T, UseError>): ResultAsync<T, AcquireError | UseError | AbortError>;
1176
+ /**
1177
+ * Races two cooperative ResultAsync tasks and returns the first settled Result.
1178
+ */
636
1179
  static race<Left extends ResultAsyncRaceTask<unknown, unknown>, Right extends ResultAsyncRaceTask<unknown, unknown>>(this: void, left: Left, right: Right): ResultAsync<ResultAsyncRaceTaskOk<Left> | ResultAsyncRaceTaskOk<Right>, ResultAsyncRaceTaskErr<Left> | ResultAsyncRaceTaskErr<Right>>;
1180
+ /**
1181
+ * Races multiple cooperative ResultAsync tasks and returns the first settled Result.
1182
+ */
637
1183
  static raceAll<Tasks extends readonly [ResultAsyncRaceTask<unknown, unknown>, ...ResultAsyncRaceTask<unknown, unknown>[]]>(this: void, tasks: Tasks): ResultAsync<ResultAsyncRaceTasksOk<Tasks>, ResultAsyncRaceTasksErr<Tasks>>;
1184
+ /**
1185
+ * Races two cooperative ResultAsync tasks and returns the first successful Ok.
1186
+ *
1187
+ * If both fail, the returned error is the final observed Err.
1188
+ */
638
1189
  static raceFirst<Left extends ResultAsyncRaceTask<unknown, unknown>, Right extends ResultAsyncRaceTask<unknown, unknown>>(this: void, left: Left, right: Right): ResultAsync<ResultAsyncRaceTaskOk<Left> | ResultAsyncRaceTaskOk<Right>, ResultAsyncRaceTaskErr<Left> | ResultAsyncRaceTaskErr<Right>>;
1190
+ /**
1191
+ * Races two cooperative ResultAsync tasks and lets handlers decide what to do when either side
1192
+ * settles first.
1193
+ *
1194
+ * Handlers receive the settled Result and a handle to the still-running opposite task.
1195
+ */
639
1196
  static raceWith<Left extends ResultAsyncRaceTask<unknown, unknown>, Right extends ResultAsyncRaceTask<unknown, unknown>, OnLeftDone extends ResultAsyncConditional, OnRightDone extends ResultAsyncConditional>(this: void, left: Left, right: Right, handlers: {
640
1197
  readonly onLeftDone: (result: Result<ResultAsyncRaceTaskOk<Left>, ResultAsyncRaceTaskErr<Left>>, right: ResultAsyncRaceHandle<ResultAsyncRaceTaskOk<Right>, ResultAsyncRaceTaskErr<Right>>) => OnLeftDone;
641
1198
  readonly onRightDone: (result: Result<ResultAsyncRaceTaskOk<Right>, ResultAsyncRaceTaskErr<Right>>, left: ResultAsyncRaceHandle<ResultAsyncRaceTaskOk<Left>, ResultAsyncRaceTaskErr<Left>>) => OnRightDone;
642
1199
  }): ResultAsync<HandlerOk<OnLeftDone> | HandlerOk<OnRightDone>, HandlerErr<OnLeftDone> | HandlerErr<OnRightDone>>;
1200
+ /**
1201
+ * Runs a cooperative ResultAsync task with a typed timeout error.
1202
+ */
643
1203
  static timeout<Task extends ResultAsyncRaceTask<unknown, unknown>, TimeoutError>(this: void, task: Task, options: ResultAsyncTimeoutOptions<TimeoutError>): ResultAsync<ResultAsyncRaceTaskOk<Task>, ResultAsyncRaceTaskErr<Task> | TimeoutError>;
1204
+ /**
1205
+ * Runs async candidates until the first Ok and returns the last Err if every candidate fails.
1206
+ */
644
1207
  static firstSuccessOf<Candidates extends Iterable<ResultAsyncCandidate>>(this: void, candidates: Candidates): FirstSuccessOfAsync<Candidates>;
1208
+ /**
1209
+ * Chooses one of two Resultar async branches from a boolean or Resultar boolean condition.
1210
+ */
645
1211
  static if<OnTrue extends ResultAsyncConditional, OnFalse extends ResultAsyncConditional>(this: void, condition: ResultAsyncBooleanCondition, options: ResultAsyncIfOptions<OnTrue, OnFalse>): ResultAsyncIf<never, OnTrue, OnFalse>;
646
1212
  static if<Condition extends ResultAsyncConditionResult, OnTrue extends ResultAsyncConditional, OnFalse extends ResultAsyncConditional>(this: void, condition: Condition, options: ResultAsyncIfOptions<OnTrue, OnFalse>): ResultAsyncIf<HandlerErr<Condition>, OnTrue, OnFalse>;
1213
+ /**
1214
+ * Runs `body` only when the condition is true; otherwise returns Ok(undefined).
1215
+ */
647
1216
  static when<R extends ResultAsyncConditional>(this: void, condition: ResultAsyncBooleanCondition, body: () => R): ResultAsyncWhen<R>;
1217
+ /**
1218
+ * Runs `body` only when a Resultar boolean condition is Ok(true).
1219
+ */
648
1220
  static whenResult<Condition extends ResultAsyncConditionResult, R extends ResultAsyncConditional>(this: void, condition: Condition, body: () => R): ResultAsyncWhenWithCondition<Condition, R>;
1221
+ /**
1222
+ * Runs `body` only when the condition is false; otherwise returns Ok(undefined).
1223
+ */
649
1224
  static unless<R extends ResultAsyncConditional>(this: void, condition: ResultAsyncBooleanCondition, body: () => R): ResultAsyncWhen<R>;
1225
+ /**
1226
+ * Runs `body` only when a Resultar boolean condition is Ok(false).
1227
+ */
650
1228
  static unlessResult<Condition extends ResultAsyncConditionResult, R extends ResultAsyncConditional>(this: void, condition: Condition, body: () => R): ResultAsyncWhenWithCondition<Condition, R>;
1229
+ /**
1230
+ * Repeats a ResultAsync-producing body while a condition holds.
1231
+ *
1232
+ * Use `discard: true` when only failure matters and collected Ok values are not needed.
1233
+ */
651
1234
  static loop<State, BodyState extends State, R extends ResultAsync<unknown, unknown>>(this: void, initial: State, options: ResultAsyncLoopOptions<State, BodyState, R>): ResultAsyncLoopCollected<R>;
652
1235
  static loop<State, R extends ResultAsync<unknown, unknown>>(this: void, initial: State, options: ResultAsyncLoopBooleanOptions<State, R>): ResultAsyncLoopCollected<R>;
653
1236
  static loop<State, BodyState extends State, R extends ResultAsync<unknown, unknown>>(this: void, initial: State, options: ResultAsyncLoopDiscardOptions<State, BodyState, R>): ResultAsyncLoopDiscarded<R>;
654
1237
  static loop<State, R extends ResultAsync<unknown, unknown>>(this: void, initial: State, options: ResultAsyncLoopBooleanDiscardOptions<State, R>): ResultAsyncLoopDiscarded<R>;
1238
+ /**
1239
+ * Repeatedly transforms state with a ResultAsync-producing body until the condition fails.
1240
+ */
655
1241
  static iterate<State, BodyState extends WidenLiteral<State>, R extends ResultAsync<WidenLiteral<State>, unknown>>(this: void, initial: State, options: ResultAsyncIterateOptions<WidenLiteral<State>, BodyState, R>): ResultAsyncIterated<WidenLiteral<State>, R>;
656
1242
  static iterate<State, R extends ResultAsync<WidenLiteral<State>, unknown>>(this: void, initial: State, options: ResultAsyncIterateBooleanOptions<WidenLiteral<State>, R>): ResultAsyncIterated<WidenLiteral<State>, R>;
1243
+ /**
1244
+ * Runs a ResultAsync-producing mapper for each item.
1245
+ *
1246
+ * Use `discard: true` when only failure matters and collected Ok values are not needed. Use
1247
+ * `concurrency` to bound parallel work.
1248
+ */
657
1249
  static forEach<Item, R extends ResultAsync<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options?: ResultAsyncForEachOptions): ResultAsyncForEachCollected<R>;
658
1250
  static forEach<Item, R extends ResultAsync<unknown, unknown>>(this: void, items: Iterable<Item>, f: (value: Item, index: number) => R, options: ResultAsyncForEachDiscardOptions): ResultAsyncForEachDiscarded<R>;
659
1251
  /**
660
- * Wraps a async function with a try catch, creating a new function with the same
661
- * arguments but returning `Ok` if successful, `Err` if the function throws
1252
+ * Wraps an async function so every later call returns a ResultAsync.
662
1253
  *
663
- * @param fn function to wrap with ok on success or err on failure
664
- * @param errorFn when an error is thrown, this will wrap the error result if provided
665
- * @returns a new function that returns a `ResultAsync`
1254
+ * Prefer `tryResultAsync` when you want to run the operation immediately.
666
1255
  */
667
1256
  static fromThrowable<A extends readonly unknown[], T, E>(this: void, fn: (...args: A) => Promise<T>, errorFn?: (err: unknown) => E): (...args: A) => ResultAsync<T, E>;
668
1257
  private readonly innerPromise;
1258
+ /**
1259
+ * Creates a ResultAsync from a Promise that resolves to a Result.
1260
+ *
1261
+ * Most application code should prefer `tryResultAsync`, `fromPromise`, `okAsync`, or `errAsync`.
1262
+ */
669
1263
  constructor(res: Promise<Result<T, E>>);
1264
+ /**
1265
+ * PromiseLike integration. Resolves to the underlying `Result<T, E>`.
1266
+ *
1267
+ * Prefer ResultAsync combinators for application flow; this exists so ResultAsync can be awaited
1268
+ * and used by Promise APIs.
1269
+ */
670
1270
  then<A, B>(successCallback?: (res: Result<T, E>) => A | PromiseLike<A>, failureCallback?: (reason: unknown) => B | PromiseLike<B>): PromiseLike<A | B>;
1271
+ /**
1272
+ * Maps the Err value while preserving the Ok value.
1273
+ */
671
1274
  mapErr<U>(f: (t: E) => U | Promise<U>): ResultAsync<T, U>;
1275
+ /**
1276
+ * Maps the Ok value while preserving the error channel.
1277
+ */
672
1278
  map<X>(f: (t: T) => X | Promise<X>): ResultAsync<X, E>;
1279
+ /**
1280
+ * Replaces the Ok value with a constant while preserving the error channel.
1281
+ */
673
1282
  as<X>(value: X): ResultAsync<X, E>;
1283
+ /**
1284
+ * Keeps the Ok value only when the predicate passes; otherwise returns an Err from `onFalse`.
1285
+ */
674
1286
  filterOrElse<U extends T, F>(predicate: (value: T) => value is U, onFalse: (value: T) => F | Promise<F>): ResultAsync<U, E | F>;
675
1287
  filterOrElse<F>(predicate: (value: T) => boolean | Promise<boolean>, onFalse: (value: T) => F | Promise<F>): ResultAsync<T, E | F>;
1288
+ /**
1289
+ * Chains another fallible sync or async operation from the Ok value.
1290
+ *
1291
+ * Use this instead of `map` when the callback returns `Result` or `ResultAsync`.
1292
+ */
676
1293
  andThen<R extends Result<unknown, unknown>>(f: (t: T) => R): ResultAsync<InferOkTypes<R>, InferErrTypes<R> | E>;
677
1294
  andThen<R extends ResultAsync<unknown, unknown>>(f: (t: T) => R): ResultAsync<InferAsyncOkTypes<R>, InferAsyncErrTypes<R> | E>;
678
1295
  andThen<U, F>(f: (t: T) => Result<U, F> | ResultAsync<U, F>): ResultAsync<U, E | F>;
1296
+ /**
1297
+ * Branches from the Ok value into one of two async fallible Result branches.
1298
+ */
679
1299
  if(fCondition: (t: T) => boolean): {
680
1300
  true: <X1, Y1>(fTrue: (t: T) => ResultAsync<X1, Y1>) => {
681
1301
  false: <X2, Y2>(fFalse: (t: T) => ResultAsync<X2, Y2>) => ResultAsync<X1 | X2, Y1 | Y2 | E>;
682
1302
  };
683
1303
  };
1304
+ /**
1305
+ * Recovers from Err with another Result or ResultAsync.
1306
+ */
684
1307
  orElse<R extends Result<unknown, unknown>>(f: (e: E) => R): ResultAsync<InferOkTypes<R> | T, InferErrTypes<R>>;
685
1308
  orElse<R extends ResultAsync<unknown, unknown>>(f: (e: E) => R): ResultAsync<InferAsyncOkTypes<R> | T, InferAsyncErrTypes<R>>;
686
1309
  orElse<U, A>(f: (e: E) => Result<U, A> | ResultAsync<U, A>): ResultAsync<U | T, A>;
1310
+ /**
1311
+ * Recovers from a specific tagged error by `_tag`.
1312
+ */
687
1313
  catchTag<const Tag extends TagsOf<E>, R extends Result<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => R): ResultAsync<T | InferOkTypes<R>, ExcludeTag<E, Tag> | InferErrTypes<R>>;
688
1314
  catchTag<const Tag extends TagsOf<E>, R extends ResultAsync<unknown, unknown>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => R): ResultAsync<T | InferAsyncOkTypes<R>, ExcludeTag<E, Tag> | InferAsyncErrTypes<R>>;
689
1315
  catchTag<U, F, const Tag extends TagsOf<E>>(tag: Tag, f: (error: ErrorForTag$1<E, Tag>) => Result<U, F> | ResultAsync<U, F>): ResultAsync<T | U, ExcludeTag<E, Tag> | F>;
1316
+ /**
1317
+ * Recovers from multiple tagged errors by `_tag`.
1318
+ */
690
1319
  catchTags<const Handlers extends object>(handlers: Handlers & ResultAsyncCatchTagHandlers<E, Handlers>): ResultAsync<T | HandlerOk<CatchTagHandlerResult<Handlers>>, ExcludeTag<E, keyof Handlers & string> | HandlerErr<CatchTagHandlerResult<Handlers>>>;
1320
+ /**
1321
+ * Recovers from a nested tagged `reason` on a specific tagged error.
1322
+ */
691
1323
  catchReason<const ErrorTag extends TagsWithReasonOf<E>, const ReasonTag extends ReasonTagsOf<E, ErrorTag>, R extends Result<unknown, unknown>>(errorTag: ErrorTag, reasonTag: ReasonTag, f: (reason: ReasonForTag<E, ErrorTag, ReasonTag>, error: ErrorForTag$1<E, ErrorTag>) => R): ResultAsync<T | InferOkTypes<R>, ExcludeReasonTag<E, ErrorTag, ReasonTag> | InferErrTypes<R>>;
692
1324
  catchReason<const ErrorTag extends TagsWithReasonOf<E>, const ReasonTag extends ReasonTagsOf<E, ErrorTag>, R extends ResultAsync<unknown, unknown>>(errorTag: ErrorTag, reasonTag: ReasonTag, f: (reason: ReasonForTag<E, ErrorTag, ReasonTag>, error: ErrorForTag$1<E, ErrorTag>) => R): ResultAsync<T | InferAsyncOkTypes<R>, ExcludeReasonTag<E, ErrorTag, ReasonTag> | InferAsyncErrTypes<R>>;
693
1325
  catchReason<U, F, const ErrorTag extends TagsWithReasonOf<E>, const ReasonTag extends ReasonTagsOf<E, ErrorTag>>(errorTag: ErrorTag, reasonTag: ReasonTag, f: (reason: ReasonForTag<E, ErrorTag, ReasonTag>, error: ErrorForTag$1<E, ErrorTag>) => Result<U, F> | ResultAsync<U, F>): ResultAsync<T | U, ExcludeReasonTag<E, ErrorTag, ReasonTag> | F>;
1326
+ /**
1327
+ * Recovers from multiple nested tagged `reason` variants on a specific tagged error.
1328
+ */
694
1329
  catchReasons<const ErrorTag extends TagsWithReasonOf<E>, const Handlers extends object>(errorTag: ErrorTag, handlers: Handlers & ResultAsyncCatchReasonHandlers<E, ErrorTag, Handlers>): ResultAsync<T | HandlerOk<CatchReasonHandlerResult<Handlers>>, ExcludeReasonTag<E, ErrorTag, keyof Handlers & string> | HandlerErr<CatchReasonHandlerResult<Handlers>>>;
1330
+ /**
1331
+ * Moves the nested `reason` of a tagged error into the ResultAsync error channel.
1332
+ */
695
1333
  unwrapReason<const ErrorTag extends TagsWithReasonOf<E>>(errorTag: ErrorTag): ResultAsync<T, ExcludeTag<E, ErrorTag> | ReasonsOf<E, ErrorTag>>;
1334
+ /**
1335
+ * Converts this ResultAsync into a Promise of a plain value by handling both Ok and Err.
1336
+ */
696
1337
  match<A, B = A>(handlers: MatchHandlers$1<T, E, A, B>): Promise<A | B>;
697
1338
  match<A, B = A>(ok: (t: T) => A, fnErr: (e: E) => B): Promise<A | B>;
1339
+ /**
1340
+ * Converts this ResultAsync into a Promise of a plain value with exhaustive tagged-error handlers.
1341
+ */
698
1342
  matchTags<A, const Handlers extends object>(ok: (t: T) => A, handlers: Handlers & MatchTagHandlers<E, Handlers>): Promise<A | MatchTagHandlerResult<Handlers>>;
1343
+ /**
1344
+ * Converts this ResultAsync into a Promise of a plain value with partial tagged-error handlers and
1345
+ * a fallback.
1346
+ */
699
1347
  matchTagsPartial<A, B, const Handlers extends object>(ok: (t: T) => A, handlers: Handlers & PartialMatchTagHandlers<E, Handlers>, fallback: (error: E) => B): Promise<A | MatchTagHandlerResult<Handlers> | B>;
1348
+ /**
1349
+ * Resolves to the Ok value, or `t` when this ResultAsync is Err.
1350
+ */
700
1351
  unwrapOr<A>(t: A): Promise<T | A>;
1352
+ /**
1353
+ * Resolves to the Ok value or rejects with the Err value.
1354
+ *
1355
+ * Use this at final application boundaries after the error channel has been modeled.
1356
+ */
701
1357
  unwrapOrThrow(): Promise<T>;
702
1358
  /**
703
1359
  * Runs a side effect for either variant and preserves the original async result.
@@ -724,21 +1380,95 @@ declare class ResultAsync<T, E> extends Pipeable implements PromiseLike<Result<T
724
1380
  * Use `mapErr` or `orElse` when the callback should transform the error.
725
1381
  */
726
1382
  tapError(f: (e: E) => void | Promise<void>): ResultAsync<T, E>;
1383
+ /**
1384
+ * Attaches an async disposal finalizer to this ResultAsync.
1385
+ */
727
1386
  toAsyncDisposable(f: ResultAsyncFinalizer<T, E>): DisposableResultAsync<T, E>;
1387
+ /**
1388
+ * Enables `yield* resultAsync` inside async `safeTry` generators.
1389
+ */
728
1390
  [Symbol.asyncIterator](): AsyncGenerator<Result<never, E>, T>;
729
1391
  }
730
1392
  type StrictResultAsync<T, E extends Error = Error> = ResultAsync<T, E>;
1393
+ /**
1394
+ * Creates an Ok ResultAsync.
1395
+ */
731
1396
  declare const okAsync: typeof ResultAsync.okAsync;
1397
+ /**
1398
+ * Creates an Err ResultAsync.
1399
+ */
732
1400
  declare const errAsync: typeof ResultAsync.errAsync;
1401
+ /**
1402
+ * Adapts a callback or subscription API into a cancellable ResultAsync.
1403
+ */
1404
+ declare const fromCallback: typeof ResultAsync.fromCallback;
1405
+ /**
1406
+ * Converts an existing promise into a ResultAsync and maps rejection into a typed Err.
1407
+ */
733
1408
  declare const fromPromise: typeof ResultAsync.fromPromise;
1409
+ /**
1410
+ * Converts an existing promise that is expected not to reject into a ResultAsync.
1411
+ *
1412
+ * Use `fromPromise` or `tryResultAsync` when rejection should become a typed Err.
1413
+ */
734
1414
  declare const fromSafePromise: typeof ResultAsync.fromSafePromise;
1415
+ /**
1416
+ * Creates an Ok ResultAsync with `undefined`.
1417
+ */
735
1418
  declare const unitAsync: typeof ResultAsync.unitAsync;
1419
+ /**
1420
+ * Wraps an async function so every later call returns a ResultAsync.
1421
+ */
736
1422
  declare const fromThrowableAsync: typeof ResultAsync.fromThrowable;
1423
+ /**
1424
+ * Captures a promise or async factory into `ResultAsync<T, E>`.
1425
+ *
1426
+ * Use `tryResultAsync` at the edge of uncontrolled async code: network calls, file I/O,
1427
+ * third-party SDKs, JSON parsing promises, and framework APIs that can reject. The mapper receives
1428
+ * the rejected or thrown `unknown` cause and returns the typed error for the Resultar channel.
1429
+ *
1430
+ * Passing a factory is preferred when creating the promise can throw synchronously.
1431
+ *
1432
+ * @example
1433
+ * ```ts
1434
+ * const user = tryResultAsync(
1435
+ * () => fetchUser(id),
1436
+ * (cause) => new FetchUserError({ cause, id }),
1437
+ * )
1438
+ * ```
1439
+ */
737
1440
  declare function tryResultAsync<T, E>(fn: Promise<T> | (() => Promise<T>), errorFn: (e: unknown) => E): ResultAsync<T, E>;
1441
+ /**
1442
+ * Captures an async boundary with named `try` and `catch` fields.
1443
+ *
1444
+ * This is equivalent to `tryResultAsync(() => ..., toError)`, but it reads better for reusable
1445
+ * infrastructure helpers where the label, task, and mapper live together.
1446
+ *
1447
+ * @example
1448
+ * ```ts
1449
+ * const startup = tryResultAsync({
1450
+ * try: () => fastify.register(plugin),
1451
+ * catch: (cause) => new StartupTaskError({ cause, label: "register plugin" }),
1452
+ * })
1453
+ * ```
1454
+ */
738
1455
  declare function tryResultAsync<T, E>(options: TryResultAsyncOptions<T, E> & {
739
1456
  readonly catch: (e: unknown) => E;
740
1457
  }): ResultAsync<T, E>;
1458
+ /**
1459
+ * Captures a promise or async factory into `ResultAsync<T, unknown>`.
1460
+ *
1461
+ * Prefer the overload with a catch mapper in application code so the error channel stays documented.
1462
+ * This overload is useful while adapting unknown external failures or during migration.
1463
+ */
741
1464
  declare function tryResultAsync<T>(input: Promise<T> | (() => Promise<T>) | TryResultAsyncOptions<T>): ResultAsync<T, unknown>;
1465
+ /**
1466
+ * Runs a `ResultAsync` at an application boundary and returns the success value.
1467
+ *
1468
+ * If the result is `Err`, this rejects with the error. Use it at final framework, CLI, test, or
1469
+ * bootstrap boundaries after the error channel has already been modeled with Resultar.
1470
+ */
1471
+ declare const runPromise: <T, E>(result: ResultAsync<T, E>) => Promise<T>;
742
1472
  /** Compatibility alias. Prefer `tryResultAsync` in new code. */
743
1473
  declare const tryCatchAsync: typeof tryResultAsync;
744
1474
  type CombineResultAsyncs<T extends readonly ResultAsync<unknown, unknown>[]> = IsLiteralArray<T> extends 1 ? TraverseAsync<UnwrapAsync<T>> : ResultAsync<ExtractOkAsyncTypes<T>, ExtractErrAsyncTypes<T>[number]>;
@@ -749,15 +1479,39 @@ type TraverseWithAllErrorsAsync<T, Depth extends number = 5> = TraverseAsync<T,
749
1479
  type Writable<T> = T extends readonly unknown[] ? [...T] : T;
750
1480
  //#endregion
751
1481
  //#region src/redacted.d.ts
1482
+ /**
1483
+ * String-like wrapper that hides a sensitive value in messages and JSON output.
1484
+ */
752
1485
  type Redacted<T> = string & {
1486
+ /**
1487
+ * Internal marker used by `isRedacted`.
1488
+ */
753
1489
  readonly __resultarRedacted: true;
754
1490
  readonly __resultarRedactedType?: T;
1491
+ /**
1492
+ * Optional label shown as `<redacted:label>`.
1493
+ */
755
1494
  readonly label: string | undefined;
756
- toJSON(): string;
757
- toString(): string;
1495
+ /**
1496
+ * Serializes to the redacted placeholder.
1497
+ */
1498
+ toJSON: () => string;
1499
+ /**
1500
+ * Converts to the redacted placeholder.
1501
+ */
1502
+ toString: () => string;
758
1503
  };
1504
+ /**
1505
+ * Wraps a sensitive value so tagged-error messages and JSON output show only a placeholder.
1506
+ */
759
1507
  declare const redact: <T>(value: T, label?: string) => Redacted<T>;
1508
+ /**
1509
+ * Checks whether a value was created by `redact`.
1510
+ */
760
1511
  declare const isRedacted: (value: unknown) => value is Redacted<unknown>;
1512
+ /**
1513
+ * Returns the original sensitive value from a Redacted wrapper.
1514
+ */
761
1515
  declare const revealRedacted: <T>(value: Redacted<T>) => T;
762
1516
  //#endregion
763
1517
  //#region src/tagged-error.d.ts
@@ -789,23 +1543,65 @@ type TaggedErrorConstructorArgs<Template extends string> = [ExtractTemplateVaria
789
1543
  readonly cause?: unknown;
790
1544
  }] : [props: ConstructorProps<Template>];
791
1545
  interface TaggedErrorOptions<Tag extends string, MessageTemplate extends string, Base extends Error = Error> {
1546
+ /**
1547
+ * Optional base Error class to extend instead of native Error.
1548
+ */
792
1549
  readonly extends?: ErrorBaseConstructor<Base>;
1550
+ /**
1551
+ * Message template. `$prop` placeholders are filled from constructor props.
1552
+ */
793
1553
  readonly message?: MessageTemplate;
1554
+ /**
1555
+ * Stable runtime tag and Error name.
1556
+ */
794
1557
  readonly name: Tag;
795
1558
  }
1559
+ /**
1560
+ * Instance type produced by `createTaggedError`.
1561
+ */
796
1562
  type TaggedErrorInstance<Tag extends string, MessageTemplate extends string, Base extends Error = Error> = Base & Readonly<TemplateProps<MessageTemplate>> & {
1563
+ /**
1564
+ * Stable runtime tag.
1565
+ */
797
1566
  readonly _tag: Tag;
1567
+ /**
1568
+ * Stable identity for grouping errors by tag and message template.
1569
+ */
798
1570
  readonly fingerprint: readonly [Tag, MessageTemplate];
1571
+ /**
1572
+ * Original message template before interpolation.
1573
+ */
799
1574
  readonly messageTemplate: MessageTemplate;
800
- findCause<T extends Error>(ErrorClass: ErrorClass<T>): T | undefined;
801
- toJSON(): object;
1575
+ /**
1576
+ * Finds a matching cause in the error cause chain.
1577
+ */
1578
+ findCause: <T extends Error>(ErrorClass: ErrorClass<T>) => T | undefined;
1579
+ /**
1580
+ * Serializes the tagged error, metadata, and cause chain.
1581
+ */
1582
+ toJSON: () => object;
802
1583
  };
1584
+ /**
1585
+ * Class type returned by `createTaggedError`.
1586
+ */
803
1587
  type TaggedErrorClass<Tag extends string, MessageTemplate extends string, Base extends Error = Error> = {
804
1588
  new (...args: TaggedErrorConstructorArgs<MessageTemplate>): TaggedErrorInstance<Tag, MessageTemplate, Base>;
1589
+ /**
1590
+ * Stable runtime tag.
1591
+ */
805
1592
  readonly tag: Tag;
806
- err<This extends new (...args: TaggedErrorConstructorArgs<MessageTemplate>) => Error>(this: This, ...args: TaggedErrorConstructorArgs<MessageTemplate>): ErrResult<never, ErrorClassInstance<This>>;
807
- is(value: unknown): value is TaggedErrorInstance<Tag, MessageTemplate, Base>;
1593
+ /**
1594
+ * Creates an Err containing this tagged error.
1595
+ */
1596
+ err: <This extends new (...args: TaggedErrorConstructorArgs<MessageTemplate>) => Error>(this: This, ...args: TaggedErrorConstructorArgs<MessageTemplate>) => ErrResult<never, ErrorClassInstance<This>>;
1597
+ /**
1598
+ * Narrows a value to this tagged error class.
1599
+ */
1600
+ is: (value: unknown) => value is TaggedErrorInstance<Tag, MessageTemplate, Base>;
808
1601
  };
1602
+ /**
1603
+ * Union of members produced by `taggedEnum`.
1604
+ */
809
1605
  type TaggedEnum<Members extends Record<string, object>> = { readonly [Tag in keyof Members]: Readonly<Members[Tag]> & {
810
1606
  readonly _tag: Tag;
811
1607
  } }[keyof Members];
@@ -813,9 +1609,18 @@ type TaggedEnumMember<Members extends Record<string, object>, Tag extends keyof
813
1609
  readonly _tag: Tag;
814
1610
  };
815
1611
  type TaggedEnumConstructor<Members extends Record<string, object>, Tag extends keyof Members> = keyof Members[Tag] extends never ? (props?: Readonly<Members[Tag]>) => TaggedEnumMember<Members, Tag> : (props: Readonly<Members[Tag]>) => TaggedEnumMember<Members, Tag>;
1612
+ /**
1613
+ * Factory returned by `taggedEnum`.
1614
+ */
816
1615
  type TaggedEnumFactory<Members extends Record<string, object>> = { readonly [Tag in keyof Members]: TaggedEnumConstructor<Members, Tag> } & {
817
- $is<Tag extends keyof Members>(tag: Tag, value: unknown): value is TaggedEnumMember<Members, Tag>;
818
- $match<ReturnType>(value: TaggedEnum<Members>, handlers: { readonly [Tag in keyof Members]: (value: TaggedEnumMember<Members, Tag>) => ReturnType }): ReturnType;
1616
+ /**
1617
+ * Narrows a value to a tagged enum member.
1618
+ */
1619
+ $is: <Tag extends keyof Members>(tag: Tag, value: unknown) => value is TaggedEnumMember<Members, Tag>;
1620
+ /**
1621
+ * Exhaustively matches a tagged enum value.
1622
+ */
1623
+ $match: <ReturnType>(value: TaggedEnum<Members>, handlers: { readonly [Tag in keyof Members]: (value: TaggedEnumMember<Members, Tag>) => ReturnType }) => ReturnType;
819
1624
  };
820
1625
  type TaggedErrorLike = Error & {
821
1626
  readonly _tag: string;
@@ -832,15 +1637,44 @@ type MatchHandlers<ErrorType extends Error, ReturnType> = { readonly [Tag in Tag
832
1637
  });
833
1638
  type PartialMatchHandlers<ErrorType extends Error, ReturnType> = Partial<MatchHandlers<ErrorType, ReturnType>>;
834
1639
  declare const defaultMessageTemplate = "$message";
1640
+ /**
1641
+ * Narrows a value to native or platform-recognized Error.
1642
+ */
835
1643
  declare function isError(value: unknown): value is Error;
836
1644
  declare function isError<Value>(value: Value): value is Extract<Value, Error>;
1645
+ /**
1646
+ * Finds the first cause in an Error cause chain that is an instance of `ErrorClass`.
1647
+ */
837
1648
  declare const findCause: <T extends Error>(error: Error, ErrorClass: ErrorClass<T>) => T | undefined;
1649
+ /**
1650
+ * Creates an Error class with a stable `_tag`, typed template props, cause support, and JSON output.
1651
+ *
1652
+ * Prefer tagged errors for domain failures that travel through Resultar error channels.
1653
+ *
1654
+ * @example
1655
+ * ```ts
1656
+ * class UserNotFoundError extends createTaggedError({
1657
+ * name: "UserNotFoundError",
1658
+ * message: "User $id was not found",
1659
+ * }) {}
1660
+ * ```
1661
+ */
838
1662
  declare function createTaggedError<const Tag extends string, const MessageTemplate extends string = typeof defaultMessageTemplate, Base extends Error = Error>(options: Omit<TaggedErrorOptions<Tag, MessageTemplate, Base>, "message"> & {
839
1663
  readonly message?: RejectReservedTemplateVariables<MessageTemplate>;
840
1664
  }): TaggedErrorClass<Tag, MessageTemplate, Base>;
1665
+ /**
1666
+ * Creates a small tagged-union factory with member constructors, `$is`, and `$match`.
1667
+ */
841
1668
  declare const taggedEnum: <Members extends Record<string, object>>() => TaggedEnumFactory<Members>;
1669
+ /**
1670
+ * Matches an Error by tagged `_tag`, with optional native `Error` fallback.
1671
+ *
1672
+ * Throws the original error when no handler matches.
1673
+ */
842
1674
  declare const matchError: <ErrorType extends Error, ReturnType>(error: ErrorType, handlers: MatchHandlers<ErrorType, ReturnType>) => ReturnType;
1675
+ /**
1676
+ * Matches an Error by tagged `_tag`, then native `Error`, then the provided fallback.
1677
+ */
843
1678
  declare const matchErrorPartial: <ErrorType extends Error, ReturnType>(error: ErrorType, handlers: PartialMatchHandlers<ErrorType, ReturnType>, fallback: (error: ErrorType) => ReturnType) => ReturnType;
844
1679
  //#endregion
845
- export { AbortError, DisposableResult, DisposableResultAsync, type ErrResult, type OkResult, type Redacted, Result, ResultAsync, type ResultAsyncAbortSignal, type ResultAsyncConcurrency, type ResultAsyncRaceHandle, type ResultAsyncRaceTask, type ResultAsyncResourceAcquire, type ResultAsyncResourceEffect, type ResultAsyncResourceRelease, type ResultAsyncResourceReleaseContext, type ResultAsyncResourceUse, type ResultAsyncRetryContext, type ResultAsyncRetryOptions, type ResultAsyncRetryOrElseOptions, type ResultAsyncRetryTask, type ResultAsyncTimeoutOptions, type ResultAsyncWithResourceOptions, type ResultOperations, type SafeTryAsyncOptions, type SafeTryOptions, type StrictResult, type StrictResultAsync, type TaggedEnum, type TaggedEnumFactory, type TaggedErrorClass, type TaggedErrorInstance, type TaggedErrorOptions, type TryResultAsyncOptions, type TryResultOptions, createTaggedError, tryResult as default, tryResult as try, tryResult, err, errAsync, findCause, fromPromise, fromSafePromise, fromThrowable, fromThrowableAsync, isAbortError, isError, isRedacted, matchError, matchErrorPartial, ok, okAsync, redact, revealRedacted, safeTry, taggedEnum, tryResultAsync as tryAsync, tryResultAsync, tryCatch, tryCatchAsync, unit, unitAsync };
846
- //# sourceMappingURL=index.d.ts.map
1680
+ export { AbortError, DisposableResult, DisposableResultAsync, type ErrResult, type OkResult, type Redacted, Result, ResultAsync, type ResultAsyncAbortSignal, type ResultAsyncCallbackCleanup, type ResultAsyncCallbackContext, type ResultAsyncConcurrency, type ResultAsyncFromCallbackOptions, type ResultAsyncRaceHandle, type ResultAsyncRaceTask, type ResultAsyncResourceAcquire, type ResultAsyncResourceEffect, type ResultAsyncResourceRelease, type ResultAsyncResourceReleaseContext, type ResultAsyncResourceUse, type ResultAsyncRetryContext, type ResultAsyncRetryOptions, type ResultAsyncRetryOrElseOptions, type ResultAsyncRetryTask, type ResultAsyncTimeoutOptions, type ResultAsyncWithResourceOptions, type ResultOperations, type SafeTryAsyncOptions, type SafeTryOptions, type StrictResult, type StrictResultAsync, type TaggedEnum, type TaggedEnumFactory, type TaggedErrorClass, type TaggedErrorInstance, type TaggedErrorOptions, type TryResultAsyncOptions, type TryResultOptions, createTaggedError, tryResult as default, tryResult as try, tryResult, err, errAsync, findCause, fromCallback, fromPromise, fromSafePromise, fromThrowable, fromThrowableAsync, isAbortError, isError, isRedacted, matchError, matchErrorPartial, ok, okAsync, redact, revealRedacted, runPromise, runSync, safeTry, taggedEnum, tryResultAsync as tryAsync, tryResultAsync, tryCatch, tryCatchAsync, unit, unitAsync };