trybox 0.10.1 → 0.11.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.cts CHANGED
@@ -1,338 +1,334 @@
1
- type ResultErrorCode = "ABORTED" | "NETWORK" | "TIMEOUT" | "VALIDATION" | "HTTP" | "CIRCUIT_OPEN" | "UNKNOWN";
2
1
  /**
3
- * A normalized error shape returned by `run()`.
4
- *
5
- * - `code`: A stable identifier you can switch on (e.g. "HTTP", "VALIDATION").
6
- * - `message`: User-facing or log-friendly message.
7
- * - `status`: Optional numeric status (commonly HTTP status).
8
- * - `meta`: Optional payload with extra context (response body, validation fields, etc.).
9
- * - `cause`: The original thrown value for debugging.
2
+ * Branded types for enhanced type safety and runtime validation
3
+ * These provide compile-time guarantees while maintaining runtime checks
10
4
  */
11
- type ResultError<Code extends string = ResultErrorCode | (string & {}), Meta = unknown> = {
12
- code: Code;
13
- message: string;
14
- status?: number;
15
- meta?: Meta;
16
- cause?: unknown;
5
+ type Milliseconds = number & {
6
+ readonly __brand: 'Milliseconds';
17
7
  };
18
- type NonNull<T> = T extends null ? never : T;
19
- type RuleReturn<R> = R extends (err: unknown) => infer Out ? NonNull<Out> : never;
20
- type InferErrorFromRules<TRules extends readonly Rule<any>[]> = TRules extends readonly [] ? ResultError : RuleReturn<TRules[number]> | ResultError<"UNKNOWN">;
21
- type Rule<E extends ResultError = ResultError> = (err: unknown) => E | null;
22
-
23
- type RetryDelayFn<E> = (attempt: number, err: E) => number;
24
- type MaybePromise<T> = T | Promise<T>;
25
- type Jitter = boolean | number | {
26
- ratio?: number;
27
- mode?: "full" | "equal";
28
- rng?: () => number;
8
+ type RetryCount = number & {
9
+ readonly __brand: 'RetryCount';
29
10
  };
30
- /**
31
- * Backoff strategy to calculate the delay between retries.
32
- * - "linear": uses the base delay as is in each attempt.
33
- * - "exponential": multiplies the delay by 2^(attempt-1).
34
- * - "fibonacci": multiplies by F(attempt) (classic Fibonacci sequence).
35
- * - function: custom function based on the attempt number.
36
- */
37
- type BackoffStrategy = "linear" | "exponential" | "fibonacci" | ((attempt: number) => number);
38
- /**
39
- * Retry options for `run`, `runAll` and `runAllOrThrow`.
40
- */
41
- type RetryOptions<E extends ResultError = ResultError> = {
42
- /**
43
- * Number of retries to perform (does not include the initial attempt).
44
- * @default 0
45
- */
46
- retries?: number;
47
- /**
48
- * Delay between attempts:
49
- * - number: fixed delay (ms)
50
- * - () => number: lazy delay (evaluated per attempt)
51
- * - (attempt, err) => number: delay based on attempt and last error
52
- * @default 0 or a default baseDelay if retries are present
53
- */
54
- retryDelay?: number | (() => number) | RetryDelayFn<E>;
55
- /**
56
- * Decides whether to retry given a specific error.
57
- * Can be synchronous or asynchronous.
58
- * Receives the next attempt number and a context with accumulated metrics.
59
- * @default () => true
60
- */
61
- shouldRetry?: (attempt: number, error: E, context: RetryContext) => boolean | Promise<boolean>;
62
- /**
63
- * Random jitter to avoid thundering herd:
64
- * - true: default ratio 0.5
65
- * - false: no jitter
66
- * - number: ratio 0..1
67
- * - object: full control (ratio, mode, rng)
68
- * @default 0.5
69
- */
70
- jitter?: Jitter;
71
- /**
72
- * Backoff strategy to apply on the calculated delay.
73
- * @default "linear"
74
- */
75
- backoffStrategy?: BackoffStrategy;
76
- /**
77
- * Upper limit of the delay after backoff and before jitter.
78
- * @default undefined (no limit)
79
- */
80
- maxDelay?: number;
11
+ type ConcurrencyLimit = number & {
12
+ readonly __brand: 'ConcurrencyLimit';
81
13
  };
82
- /**
83
- * Context for `shouldRetry` with accumulated metrics of the current attempt.
84
- */
85
- type RetryContext = {
86
- /** Total attempts (including the next retry). */
87
- totalAttempts: number;
88
- /** Elapsed time in ms since the start of `run`. */
89
- elapsedTime: number;
90
- /** Timestamp (ms) when the execution started. */
91
- startTime: number;
92
- /** The delay (ms) applied before the last attempt, if any. */
93
- lastDelay?: number;
14
+ type Percentage = number & {
15
+ readonly __brand: 'Percentage';
94
16
  };
17
+
95
18
  /**
96
- * Main options for `run` and extended to `runAll`/`runAllOrThrow`.
19
+ * Modern typed error hierarchy with enhanced capabilities
20
+ * Provides type-safe error handling with fluent API and metadata support
97
21
  */
98
- type RunOptions<T, E extends ResultError = ResultError> = RetryOptions<E> & {
99
- /**
100
- * Normalizes an unknown error value to your type `E`.
101
- * If not provided, a default normalizer is used.
102
- */
103
- toError?: (err: unknown) => E;
104
- /**
105
- * Optional transformation applied after `toError`.
106
- * Useful for adjusting messages, codes, or adding metadata.
107
- */
108
- mapError?: (error: E) => E;
109
- /**
110
- * Callback on failure (not called if `ignoreAbort` and error is ABORTED).
111
- */
112
- onError?: (error: E) => void;
113
- /**
114
- * Callback on success.
115
- */
116
- onSuccess?: (data: T) => void;
117
- /**
118
- * Callback that always executes at the end (success or error).
119
- */
120
- onFinally?: () => void;
121
- /**
122
- * If true, aborts (ABORTED) are not considered fatal errors:
123
- * `onError` is not called and `{ ok: false, error }` is returned.
124
- * @default true
125
- */
126
- ignoreAbort?: boolean;
127
- /**
128
- * Signal for native work cancellation.
129
- * If aborted, it cuts with `AbortError`.
130
- */
131
- signal?: AbortSignal;
132
- /**
133
- * Maximum timeout in ms for the work; expires with `TimeoutError`.
134
- */
135
- timeout?: number;
136
- /**
137
- * Retry observability: receives attempt, error, and next delay.
138
- */
139
- onRetry?: (attempt: number, error: E, nextDelay: number) => void;
140
- /**
141
- * Optional structured logger for debug and errors.
142
- */
143
- logger?: {
144
- debug?: (msg: string, meta?: unknown) => void;
145
- error?: (msg: string, error: E) => void;
22
+
23
+ declare abstract class TypedError<Code extends string = string, Meta = unknown> extends Error {
24
+ abstract readonly code: Code;
25
+ readonly cause?: unknown;
26
+ readonly meta?: Meta;
27
+ readonly status?: number;
28
+ readonly timestamp: Date;
29
+ constructor(message: string, opts?: {
30
+ cause?: unknown;
31
+ meta?: Meta;
32
+ status?: number;
33
+ });
34
+ is<C extends string>(code: C): this is TypedError<C> & {
35
+ code: C;
146
36
  };
147
- /**
148
- * Callback on abort, useful for reacting to `AbortSignal`.
149
- */
150
- onAbort?: (signal: AbortSignal) => void;
151
- };
152
- /**
153
- * Circuit breaker configuration options:
154
- * - failureThreshold: number of consecutive failures to open the circuit
155
- * - resetTimeout: time in ms it remains open before attempting half-open
156
- * - halfOpenRequests: allowed quantity in half-open state
157
- */
158
- type CircuitBreakerOptions = {
159
- failureThreshold: number;
160
- resetTimeout: number;
161
- halfOpenRequests?: number;
162
- };
37
+ withMeta<const M>(meta: M): this & {
38
+ meta: M;
39
+ };
40
+ withStatus(status: number): this & {
41
+ status: number;
42
+ };
43
+ withCause(cause: unknown): this & {
44
+ cause: unknown;
45
+ };
46
+ toJSON(): Record<string, unknown>;
47
+ }
48
+
163
49
  /**
164
- * Execution metrics optionally returned in `RunResult`.
50
+ * Modern result types with enhanced discriminated unions
51
+ * Provides better type safety and more granular result categorization
165
52
  */
166
- type Metrics<E extends ResultError = ResultError> = {
167
- totalAttempts: number;
168
- totalRetries: number;
169
- totalDuration: number;
170
- lastError?: E;
171
- };
172
- type RunResult<T, E extends ResultError = ResultError> = {
173
- ok: true;
174
- data: T;
175
- error: null;
176
- metrics?: Metrics<E>;
177
- } | {
178
- ok: false;
179
- data: null;
180
- error: E;
181
- metrics?: Metrics<E>;
182
- };
53
+
54
+ type ExecutionResult<T, E extends TypedError = TypedError> = SuccessResult<T, E> | FailureResult<E> | AbortedResult<E> | TimeoutResult<E>;
55
+ interface SuccessResult<T, E extends TypedError> {
56
+ readonly type: 'success';
57
+ readonly ok: true;
58
+ readonly data: T;
59
+ readonly error: null;
60
+ readonly metrics?: ExecutionMetrics$1<E>;
61
+ }
62
+ interface FailureResult<E extends TypedError> {
63
+ readonly type: 'failure';
64
+ readonly ok: false;
65
+ readonly data: null;
66
+ readonly error: E;
67
+ readonly metrics?: ExecutionMetrics$1<E>;
68
+ }
69
+ interface AbortedResult<E extends TypedError> {
70
+ readonly type: 'aborted';
71
+ readonly ok: false;
72
+ readonly data: null;
73
+ readonly error: E;
74
+ readonly metrics?: ExecutionMetrics$1<E>;
75
+ }
76
+ interface TimeoutResult<E extends TypedError> {
77
+ readonly type: 'timeout';
78
+ readonly ok: false;
79
+ readonly data: null;
80
+ readonly error: E;
81
+ readonly metrics?: ExecutionMetrics$1<E>;
82
+ }
83
+ interface ExecutionMetrics$1<E extends TypedError> {
84
+ readonly totalAttempts: RetryCount;
85
+ readonly totalRetries: RetryCount;
86
+ readonly totalDuration: Milliseconds;
87
+ readonly lastError?: E;
88
+ readonly retryHistory: Array<{
89
+ readonly attempt: RetryCount;
90
+ readonly error: E;
91
+ readonly delay: Milliseconds;
92
+ readonly timestamp: Date;
93
+ }>;
94
+ }
183
95
 
184
96
  /**
185
- * Executes an async operation and returns a Result instead of throwing.
186
- *
187
- * Errors are normalized into an `ResultError` (or a custom error type `E`)
188
- * using the provided `toError` function.
189
- *
190
- * This utility is framework-agnostic and works in browsers, Node.js,
191
- * React effects, and any async context.
97
+ * Modern circuit breaker implementation with enhanced state management
98
+ * Provides circuit breaker pattern with type safety and observability
192
99
  */
193
- declare function run<T, E extends ResultError = ResultError>(fn: (ctx?: {
194
- signal: AbortSignal;
195
- }) => MaybePromise<T>, options?: RunOptions<T, E>): Promise<RunResult<T, E>>;
100
+
101
+ interface CircuitBreakerConfig<E extends TypedError = TypedError> {
102
+ /** Number of consecutive failures before opening circuit */
103
+ readonly failureThreshold: RetryCount;
104
+ /** How long to wait before attempting to close circuit */
105
+ readonly resetTimeout: Milliseconds;
106
+ /** Number of requests allowed in half-open state */
107
+ readonly halfOpenRequests: RetryCount;
108
+ /** Optional function to determine if error should count as failure */
109
+ readonly shouldCountAsFailure?: (error: E) => boolean;
110
+ }
111
+ type CircuitState$1 = 'closed' | 'open' | 'half-open';
112
+ interface CircuitBreakerState {
113
+ readonly state: CircuitState$1;
114
+ readonly failureCount: RetryCount;
115
+ readonly halfOpenCount: RetryCount;
116
+ readonly lastFailureTime?: Date;
117
+ readonly nextAttemptTime?: Date;
118
+ readonly canExecute: boolean;
119
+ }
196
120
 
197
121
  /**
198
- * Discriminated result per item in `runAll`:
199
- * - "ok": successful task with `data`
200
- * - "error": failed task with `error`
201
- * - "skipped": task not executed due to cancellation/fail-fast/concurrency
122
+ * Modern error normalization system
123
+ * Provides type-safe error transformation and normalization
202
124
  */
203
- type RunAllItemResult<T, E extends ResultError = ResultError> = {
204
- status: "ok";
205
- ok: true;
206
- data: T;
207
- error: null;
208
- } | {
209
- status: "error";
210
- ok: false;
211
- data: null;
212
- error: E;
213
- } | {
214
- status: "skipped";
215
- ok: false;
216
- data: null;
217
- error: null;
218
- };
219
- /** Helper to discriminate successful results. */
220
- type SuccessResult<T> = Extract<RunAllItemResult<T, any>, {
221
- status: "ok";
222
- }>;
223
- /** Helper to discriminate error results. */
224
- type ErrorResult<E> = Extract<RunAllItemResult<any, E extends ResultError ? E : ResultError>, {
225
- status: "error";
226
- }>;
227
- /** Type guard that detects `status: "ok"` with `data` typing. */
228
- declare const isSuccess: <T, E extends ResultError = ResultError>(r: RunAllItemResult<T, E>) => r is SuccessResult<T>;
229
- type RunAllOptions<T, E extends ResultError = ResultError> = RunOptions<T, E> & {
230
- /**
231
- * Maximum number of concurrent tasks to run.
232
- * @default Infinity
233
- */
234
- concurrency?: number;
235
- /**
236
- * Execution mode regarding errors.
237
- * - "settle": Run all tasks (default).
238
- * - "fail-fast": Stop starting new tasks if one fails.
239
- * @default "settle"
240
- */
241
- mode?: "settle" | "fail-fast";
242
- };
243
- declare function runAll<T, E extends ResultError = ResultError>(tasks: Array<() => MaybePromise<T>>, options?: RunAllOptions<T, E>): Promise<RunAllItemResult<T, E>[]>;
125
+
126
+ type ErrorNormalizer<E extends TypedError = TypedError> = (error: unknown) => E;
127
+ type ErrorRule<E extends TypedError = TypedError> = (error: unknown) => E | null;
244
128
 
245
129
  /**
246
- * Options for `runAllOrThrow`:
247
- * - Inherits all options from `RunOptions`
248
- * - `concurrency`: limit of simultaneous tasks; if one fails, it throws
130
+ * Modern retry strategies with enhanced capabilities
131
+ * Provides various retry patterns with type safety
249
132
  */
250
- type RunAllOrThrowOptions<T, E extends ResultError = ResultError> = RunOptions<T, E> & {
251
- /**
252
- * Maximum number of concurrent tasks to run.
253
- * @default Infinity
254
- */
255
- concurrency?: number;
256
- };
257
- declare function runAllOrThrow<T, E extends ResultError = ResultError>(tasks: Array<() => MaybePromise<T>>, options?: RunAllOrThrowOptions<T, E>): Promise<T[]>;
258
133
 
259
- declare function createNormalizer<E extends ResultError>(rules: Rule<E>[], fallback: (err: unknown) => E): (err: unknown) => E;
260
- declare function defaultFallback(err: unknown): ResultError;
261
- declare function toResultError(err: unknown): ResultError;
262
-
263
- declare const rules: {
264
- circuitOpen: Rule<ResultError<"CIRCUIT_OPEN">>;
265
- abort: Rule<ResultError<"ABORTED">>;
266
- timeout: Rule<ResultError<"TIMEOUT">>;
267
- httpStatus: Rule<ResultError<"HTTP">>;
268
- aggregate: Rule<ResultError<"UNKNOWN", {
269
- errors: unknown[];
270
- }>>;
271
- string: Rule<ResultError<"UNKNOWN">>;
272
- message: Rule<ResultError<"UNKNOWN">>;
273
- };
274
- declare const defaultRules: readonly [Rule<ResultError<"CIRCUIT_OPEN">>, Rule<ResultError<"ABORTED">>, Rule<ResultError<"TIMEOUT">>, Rule<ResultError<"HTTP">>, Rule<ResultError<"UNKNOWN", {
275
- errors: unknown[];
276
- }>>, Rule<ResultError<"UNKNOWN">>, Rule<ResultError<"UNKNOWN">>];
277
- type DefaultRules = typeof defaultRules;
278
- type DefaultError = InferErrorFromRules<DefaultRules>;
134
+ type RetryStrategy = FixedDelayStrategy | ExponentialBackoffStrategy | FibonacciBackoffStrategy | CustomDelayStrategy;
135
+ interface FixedDelayStrategy {
136
+ readonly type: 'fixed';
137
+ readonly delay: Milliseconds;
138
+ }
139
+ interface ExponentialBackoffStrategy {
140
+ readonly type: 'exponential';
141
+ readonly base: Milliseconds;
142
+ readonly factor: number;
143
+ readonly maxDelay?: Milliseconds;
144
+ }
145
+ interface FibonacciBackoffStrategy {
146
+ readonly type: 'fibonacci';
147
+ readonly base: Milliseconds;
148
+ readonly maxDelay?: Milliseconds;
149
+ }
150
+ interface CustomDelayStrategy {
151
+ readonly type: 'custom';
152
+ readonly calculate: (attempt: RetryCount, error: unknown) => Milliseconds;
153
+ }
279
154
 
280
- declare class ErrorRuleBuilder<E> {
281
- private readonly matcher;
282
- constructor(matcher: (err: unknown) => err is E);
283
- toError<const Out extends ResultError>(mapper: (err: E) => Out): Rule<Out>;
155
+ interface ExecutionConfig<E extends TypedError = TypedError> {
156
+ /** Abort signal passed to tasks */
157
+ readonly signal?: AbortSignal;
158
+ /** If true, aborts are treated as non-throwing failures */
159
+ readonly ignoreAbort?: boolean;
160
+ /** Timeout configuration */
161
+ readonly timeout?: Milliseconds;
162
+ /** Retry configuration */
163
+ readonly retry?: RetryConfig<E>;
164
+ /** Circuit breaker configuration */
165
+ readonly circuitBreaker?: CircuitBreakerConfig<E>;
166
+ /** Error handling configuration */
167
+ readonly errorHandling: ErrorHandlingConfig<E>;
168
+ /** Concurrency configuration for batch operations */
169
+ readonly concurrency?: ConcurrencyLimit;
170
+ /** Logging configuration */
171
+ readonly logger?: LoggerConfig<E>;
172
+ /** Callback hooks */
173
+ readonly hooks?: HookConfig<E>;
284
174
  }
285
- declare const errorRule: {
286
- instance<E extends new (...args: any[]) => unknown>(ctor: E): ErrorRuleBuilder<InstanceType<E>>;
287
- when<E = unknown>(predicate: (err: unknown) => err is E): ErrorRuleBuilder<E>;
175
+ interface RetryConfig<E extends TypedError> {
176
+ /** Maximum number of retry attempts */
177
+ readonly maxRetries: RetryCount;
178
+ /** Base delay strategy */
179
+ readonly strategy: RetryStrategy;
180
+ /** Jitter configuration to prevent thundering herd */
181
+ readonly jitter?: JitterConfig;
182
+ /** Function to determine if retry should be attempted */
183
+ readonly shouldRetry?: ShouldRetryPredicate<E>;
184
+ }
185
+ type ShouldRetryPredicate<E extends TypedError> = (attempt: RetryCount, error: E, context: RetryContext) => boolean;
186
+ interface RetryContext {
187
+ /** Total attempts made so far */
188
+ readonly totalAttempts: RetryCount;
189
+ /** Elapsed time since start */
190
+ readonly elapsedTime: Milliseconds;
191
+ /** Start timestamp */
192
+ readonly startTime: Date;
193
+ /** Last delay applied */
194
+ readonly lastDelay?: Milliseconds;
195
+ }
196
+ interface ErrorHandlingConfig<E extends TypedError> {
197
+ /** Error normalizer function */
198
+ readonly normalizer: ErrorNormalizer<E>;
199
+ /** Optional error mapping/transformation */
200
+ readonly mapError?: (error: E) => E;
201
+ }
202
+ interface LoggerConfig<E extends TypedError> {
203
+ /** Debug logging function */
204
+ readonly debug?: (message: string, meta?: unknown) => void;
205
+ /** Error logging function */
206
+ readonly error?: (message: string, error: E) => void;
207
+ /** Info logging function */
208
+ readonly info?: (message: string, meta?: unknown) => void;
209
+ /** Warning logging function */
210
+ readonly warn?: (message: string, meta?: unknown) => void;
211
+ }
212
+ interface HookConfig<E extends TypedError> {
213
+ /** Called on successful execution */
214
+ readonly onSuccess?: <T>(data: T, metrics?: ExecutionMetrics<E>) => void;
215
+ /** Called on failed execution */
216
+ readonly onError?: (error: E, metrics?: ExecutionMetrics<E>) => void;
217
+ /** Called always, success or failure */
218
+ readonly onFinally?: (metrics?: ExecutionMetrics<E>) => void;
219
+ /** Called on abort */
220
+ readonly onAbort?: (signal: AbortSignal) => void;
221
+ /** Called before retry attempt */
222
+ readonly onRetry?: (attempt: RetryCount, error: E, delay: Milliseconds) => void;
223
+ /** Called when circuit breaker state changes */
224
+ readonly onCircuitStateChange?: (from: CircuitState, to: CircuitState) => void;
225
+ }
226
+ type CircuitState = 'closed' | 'open' | 'half-open';
227
+ type ExecutionMetrics<E extends TypedError> = ExecutionMetrics$1<E>;
228
+ type JitterConfig = {
229
+ type: 'none';
230
+ } | {
231
+ type: 'full';
232
+ ratio: Percentage;
233
+ } | {
234
+ type: 'equal';
235
+ ratio: Percentage;
236
+ } | {
237
+ type: 'custom';
238
+ calculate: (delay: Milliseconds) => Milliseconds;
239
+ };
240
+ declare const JitterConfig: {
241
+ readonly none: () => JitterConfig;
242
+ readonly full: (ratio?: Percentage) => JitterConfig;
243
+ readonly equal: (ratio?: Percentage) => JitterConfig;
244
+ readonly custom: (calculate: (delay: Milliseconds) => Milliseconds) => JitterConfig;
288
245
  };
289
246
 
290
- type RulesMode = "extend" | "replace";
291
- type CreateRunnerOptions<E extends ResultError = ResultError> = {
292
- /**
293
- * Custom matchers to use for normalizing errors.
294
- * If not provided, the default matchers are used.
295
- */
296
- rules?: Rule<E>[];
297
- /**
298
- * How to treat provided rules in relation to default rules.
299
- * - "extend": Use default rules after custom rules (default).
300
- * - "replace": Use only custom rules (and fallback).
301
- */
247
+ type RulesMode = 'extend' | 'replace';
248
+ type ExecutorOptions<E extends TypedError = TypedError> = Omit<Partial<ExecutionConfig<E>>, 'errorHandling'> & {
249
+ rules?: Array<ErrorRule<E>>;
302
250
  rulesMode?: RulesMode;
303
- /**
304
- * Custom fallback function to use for normalizing errors.
305
- * If not provided, the default fallback is used.
306
- */
307
251
  fallback?: (err: unknown) => E;
308
- /**
309
- * If you want a completely custom normalizer, you can provide it directly.
310
- * If set, `matchers` and `fallback` are ignored.
311
- */
312
252
  toError?: (err: unknown) => E;
313
- /** Default for run options */
314
- ignoreAbort?: boolean;
315
- /** Optional default mapper for all runs */
316
253
  mapError?: (error: E) => E;
317
- /**
318
- * Circuit breaker configuration (applies to all executions of the Runner).
319
- */
320
- circuitBreaker?: CircuitBreakerOptions;
321
254
  };
322
- interface Runner<E extends ResultError> {
323
- run<T>(fn: () => Promise<T>, options?: RunOptions<T, E>): Promise<RunResult<T, E>>;
324
- all<T>(fns: Array<() => MaybePromise<T>>, options?: RunAllOptions<T, E>): Promise<RunAllItemResult<T, E>[]>;
325
- allOrThrow<T>(fns: Array<() => MaybePromise<T>>, options?: RunAllOrThrowOptions<T, E>): Promise<T[]>;
255
+ declare class Executor<E extends TypedError = TypedError> {
256
+ private readonly circuitBreaker?;
257
+ private readonly config;
258
+ constructor(options?: ExecutorOptions<E>);
259
+ execute<T>(task: (ctx: {
260
+ signal: AbortSignal;
261
+ }) => Promise<T>, options?: Partial<ExecutionConfig<E>>): Promise<ExecutionResult<T, E>>;
262
+ executeOrThrow<T>(task: (ctx: {
263
+ signal: AbortSignal;
264
+ }) => Promise<T>, options?: Partial<ExecutionConfig<E>>): Promise<T>;
265
+ executeAll<T>(tasks: Array<(ctx: {
266
+ signal: AbortSignal;
267
+ }) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
268
+ concurrency?: number;
269
+ }>): Promise<ExecutionResult<T, E>[]>;
270
+ executeAllOrThrow<T>(tasks: Array<(ctx: {
271
+ signal: AbortSignal;
272
+ }) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
273
+ concurrency?: number;
274
+ }>): Promise<T[]>;
275
+ getCircuitBreakerState(): CircuitBreakerState | undefined;
276
+ resetCircuitBreaker(): void;
277
+ getConfig(): ExecutionConfig<E>;
278
+ withConfig(additionalConfig: Partial<ExecutionConfig<E>>): Executor<E>;
279
+ withErrorType<T extends TypedError>(config?: Partial<ExecutionConfig<T>>): Executor<T>;
280
+ }
281
+
282
+ declare const getExecutor: <E extends TypedError = TypedError>(options?: ExecutorOptions<E>) => Executor<E>;
283
+ declare function execute<T, E extends TypedError = TypedError>(task: (ctx: {
284
+ signal: AbortSignal;
285
+ }) => Promise<T>, options?: Partial<ExecutionConfig<E>>): Promise<ExecutionResult<T, E>>;
286
+ declare function executeOrThrow<T, E extends TypedError = TypedError>(task: (ctx: {
287
+ signal: AbortSignal;
288
+ }) => Promise<T>, options?: Partial<ExecutionConfig<E>>): Promise<T>;
289
+ declare function executeAll<T, E extends TypedError = TypedError>(tasks: Array<(ctx: {
290
+ signal: AbortSignal;
291
+ }) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
292
+ concurrency?: number;
293
+ }>): Promise<ExecutionResult<T, E>[]>;
294
+ declare function executeAllOrThrow<T, E extends TypedError = TypedError>(tasks: Array<(ctx: {
295
+ signal: AbortSignal;
296
+ }) => Promise<T>>, options?: Partial<ExecutionConfig<E> & {
297
+ concurrency?: number;
298
+ }>): Promise<T[]>;
299
+
300
+ /**
301
+ * Modern fluent error rule builder
302
+ * Provides type-safe error rule creation with enhanced ergonomics
303
+ */
304
+
305
+ declare class ErrorRuleBuilder<T> {
306
+ private readonly predicate;
307
+ constructor(predicate: (err: unknown) => err is T);
308
+ toCode<const C extends string>(code: C): ErrorMapper<T, C>;
309
+ toError<const Out extends {
310
+ code: string;
311
+ message: string;
312
+ meta?: unknown;
313
+ status?: number;
314
+ cause?: unknown;
315
+ }>(mapper: (err: T) => Out): ErrorRule<TypedError<Out['code'], Out['meta']>>;
316
+ }
317
+ declare class ErrorMapper<T, C extends string> {
318
+ private readonly predicate;
319
+ private readonly errorCode;
320
+ constructor(predicate: (err: unknown) => err is T, errorCode: C);
321
+ with<const M = unknown>(mapper: (err: T) => {
322
+ message: string;
323
+ cause?: unknown;
324
+ meta?: M;
325
+ status?: number;
326
+ }): (err: unknown) => TypedError<C, M> | null;
326
327
  }
327
328
 
328
- declare function trybox(options?: Omit<CreateRunnerOptions<ResultError>, "rules">): Runner<ResultError>;
329
- declare function trybox<const TRules extends readonly Rule<any>[]>(options: {
330
- rules: TRules;
331
- rulesMode: "replace";
332
- } & Omit<CreateRunnerOptions<InferErrorFromRules<TRules>>, "rules" | "rulesMode">): Runner<InferErrorFromRules<TRules>>;
333
- declare function trybox<const TRules extends readonly Rule<any>[]>(options: {
334
- rules: TRules;
335
- rulesMode?: "extend";
336
- } & Omit<CreateRunnerOptions<InferErrorFromRules<TRules> | DefaultError>, "rules" | "rulesMode">): Runner<InferErrorFromRules<TRules> | DefaultError>;
329
+ declare const errorRule: {
330
+ readonly when: <T>(predicate: (err: unknown) => err is T) => ErrorRuleBuilder<T>;
331
+ readonly instance: <T extends new (...args: unknown[]) => unknown>(ErrorClass: T) => ErrorRuleBuilder<InstanceType<T>>;
332
+ };
337
333
 
338
- export { type BackoffStrategy, type CircuitBreakerOptions, type ErrorResult, type Metrics, type ResultError, type ResultErrorCode, type RetryContext, type RetryOptions, type RunAllItemResult, type RunAllOptions, type RunOptions, type RunResult, type SuccessResult, createNormalizer, trybox as default, defaultFallback, errorRule, isSuccess, rules, run, runAll, runAllOrThrow, toResultError };
334
+ export { type AbortedResult, type ExecutionConfig, type ExecutionMetrics$1 as ExecutionMetrics, type ExecutionResult, Executor, type ExecutorOptions, type FailureResult, type RulesMode, type SuccessResult, type TimeoutResult, errorRule, execute, executeAll, executeAllOrThrow, executeOrThrow, getExecutor };