awaitly 1.35.0 → 2.0.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/{duration.d.ts → di-BDlT7InM.d.cts} +15 -1
- package/dist/{duration.d.cts → di-BbFFfO8y.d.ts} +15 -1
- package/dist/errors-DtXvrCiO.d.cts +708 -0
- package/dist/errors-DtXvrCiO.d.ts +708 -0
- package/dist/index.cjs +4594 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1970 -141
- package/dist/index.d.ts +1970 -141
- package/dist/index.js +4398 -1
- package/dist/index.js.map +1 -1
- package/dist/result.cjs +641 -1
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +29 -4
- package/dist/result.d.ts +29 -4
- package/dist/result.js +561 -1
- package/dist/result.js.map +1 -1
- package/dist/testing.cjs +4202 -8
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -6
- package/dist/testing.d.ts +2 -6
- package/dist/testing.js +4154 -8
- package/dist/testing.js.map +1 -1
- package/dist/{run-entry-DGs0tySr.d.cts → types-B8NfNRGX.d.ts} +1078 -1502
- package/dist/{run-entry-BOuNyVoO.d.ts → types-BZ2f4MRR.d.cts} +1078 -1502
- package/dist/workflow.cjs +7096 -6
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +3346 -22
- package/dist/workflow.d.ts +3346 -22
- package/dist/workflow.js +6929 -6
- package/dist/workflow.js.map +1 -1
- package/package.json +3 -168
- package/dist/adapters.cjs +0 -7
- package/dist/adapters.cjs.map +0 -1
- package/dist/adapters.d.cts +0 -179
- package/dist/adapters.d.ts +0 -179
- package/dist/adapters.js +0 -7
- package/dist/adapters.js.map +0 -1
- package/dist/batch.cjs +0 -7
- package/dist/batch.cjs.map +0 -1
- package/dist/batch.d.cts +0 -200
- package/dist/batch.d.ts +0 -200
- package/dist/batch.js +0 -7
- package/dist/batch.js.map +0 -1
- package/dist/bind-deps.cjs +0 -2
- package/dist/bind-deps.cjs.map +0 -1
- package/dist/bind-deps.d.cts +0 -28
- package/dist/bind-deps.d.ts +0 -28
- package/dist/bind-deps.js +0 -2
- package/dist/bind-deps.js.map +0 -1
- package/dist/cache.cjs +0 -2
- package/dist/cache.cjs.map +0 -1
- package/dist/cache.d.cts +0 -269
- package/dist/cache.d.ts +0 -269
- package/dist/cache.js +0 -2
- package/dist/cache.js.map +0 -1
- package/dist/circuit-breaker.cjs +0 -7
- package/dist/circuit-breaker.cjs.map +0 -1
- package/dist/circuit-breaker.d.cts +0 -211
- package/dist/circuit-breaker.d.ts +0 -211
- package/dist/circuit-breaker.js +0 -7
- package/dist/circuit-breaker.js.map +0 -1
- package/dist/conditional.cjs +0 -2
- package/dist/conditional.cjs.map +0 -1
- package/dist/conditional.d.cts +0 -252
- package/dist/conditional.d.ts +0 -252
- package/dist/conditional.js +0 -2
- package/dist/conditional.js.map +0 -1
- package/dist/core.cjs +0 -7
- package/dist/core.cjs.map +0 -1
- package/dist/core.d.cts +0 -5
- package/dist/core.d.ts +0 -5
- package/dist/core.js +0 -7
- package/dist/core.js.map +0 -1
- package/dist/di-By77n4Fa.d.ts +0 -15
- package/dist/di-OJfsohf-.d.cts +0 -15
- package/dist/diagnostics.cjs +0 -8
- package/dist/diagnostics.cjs.map +0 -1
- package/dist/diagnostics.d.cts +0 -68
- package/dist/diagnostics.d.ts +0 -68
- package/dist/diagnostics.js +0 -8
- package/dist/diagnostics.js.map +0 -1
- package/dist/durable.cjs +0 -11
- package/dist/durable.cjs.map +0 -1
- package/dist/durable.d.cts +0 -9
- package/dist/durable.d.ts +0 -9
- package/dist/durable.js +0 -11
- package/dist/durable.js.map +0 -1
- package/dist/duration.cjs +0 -2
- package/dist/duration.cjs.map +0 -1
- package/dist/duration.js +0 -2
- package/dist/duration.js.map +0 -1
- package/dist/engine.cjs +0 -11
- package/dist/engine.cjs.map +0 -1
- package/dist/engine.d.cts +0 -115
- package/dist/engine.d.ts +0 -115
- package/dist/engine.js +0 -11
- package/dist/engine.js.map +0 -1
- package/dist/errors.cjs +0 -2
- package/dist/errors.cjs.map +0 -1
- package/dist/errors.d.cts +0 -361
- package/dist/errors.d.ts +0 -361
- package/dist/errors.js +0 -2
- package/dist/errors.js.map +0 -1
- package/dist/fetch.cjs +0 -7
- package/dist/fetch.cjs.map +0 -1
- package/dist/fetch.d.cts +0 -86
- package/dist/fetch.d.ts +0 -86
- package/dist/fetch.js +0 -7
- package/dist/fetch.js.map +0 -1
- package/dist/flow.cjs +0 -7
- package/dist/flow.cjs.map +0 -1
- package/dist/flow.d.cts +0 -163
- package/dist/flow.d.ts +0 -163
- package/dist/flow.js +0 -7
- package/dist/flow.js.map +0 -1
- package/dist/functional.cjs +0 -2
- package/dist/functional.cjs.map +0 -1
- package/dist/functional.d.cts +0 -444
- package/dist/functional.d.ts +0 -444
- package/dist/functional.js +0 -2
- package/dist/functional.js.map +0 -1
- package/dist/guards-4sV7mTqj.d.cts +0 -72
- package/dist/guards-BIX05ALH.d.ts +0 -72
- package/dist/hitl-DFn4Xa_l.d.cts +0 -468
- package/dist/hitl-DU5VpKq7.d.ts +0 -468
- package/dist/hitl.cjs +0 -7
- package/dist/hitl.cjs.map +0 -1
- package/dist/hitl.d.cts +0 -442
- package/dist/hitl.d.ts +0 -442
- package/dist/hitl.js +0 -7
- package/dist/hitl.js.map +0 -1
- package/dist/index-CnvBryQB.d.ts +0 -417
- package/dist/index-DEZEf8Fs.d.cts +0 -417
- package/dist/match-entry-DjI2bLpD.d.cts +0 -209
- package/dist/match-entry-DjI2bLpD.d.ts +0 -209
- package/dist/match.cjs +0 -2
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -1
- package/dist/match.d.ts +0 -1
- package/dist/match.js +0 -2
- package/dist/match.js.map +0 -1
- package/dist/otel.cjs +0 -2
- package/dist/otel.cjs.map +0 -1
- package/dist/otel.d.cts +0 -188
- package/dist/otel.d.ts +0 -188
- package/dist/otel.js +0 -2
- package/dist/otel.js.map +0 -1
- package/dist/persistence-entry-B-8PjnSR.d.cts +0 -831
- package/dist/persistence-entry-D8zRkLiT.d.ts +0 -831
- package/dist/persistence.cjs +0 -2
- package/dist/persistence.cjs.map +0 -1
- package/dist/persistence.d.cts +0 -7
- package/dist/persistence.d.ts +0 -7
- package/dist/persistence.js +0 -2
- package/dist/persistence.js.map +0 -1
- package/dist/policies.cjs +0 -2
- package/dist/policies.cjs.map +0 -1
- package/dist/policies.d.cts +0 -379
- package/dist/policies.d.ts +0 -379
- package/dist/policies.js +0 -2
- package/dist/policies.js.map +0 -1
- package/dist/ratelimit.cjs +0 -7
- package/dist/ratelimit.cjs.map +0 -1
- package/dist/ratelimit.d.cts +0 -458
- package/dist/ratelimit.d.ts +0 -458
- package/dist/ratelimit.js +0 -7
- package/dist/ratelimit.js.map +0 -1
- package/dist/reliability.cjs +0 -11
- package/dist/reliability.cjs.map +0 -1
- package/dist/reliability.d.cts +0 -11
- package/dist/reliability.d.ts +0 -11
- package/dist/reliability.js +0 -11
- package/dist/reliability.js.map +0 -1
- package/dist/resolver.cjs +0 -7
- package/dist/resolver.cjs.map +0 -1
- package/dist/resolver.d.cts +0 -68
- package/dist/resolver.d.ts +0 -68
- package/dist/resolver.js +0 -7
- package/dist/resolver.js.map +0 -1
- package/dist/resource.cjs +0 -7
- package/dist/resource.cjs.map +0 -1
- package/dist/resource.d.cts +0 -174
- package/dist/resource.d.ts +0 -174
- package/dist/resource.js +0 -7
- package/dist/resource.js.map +0 -1
- package/dist/result/retry.cjs +0 -2
- package/dist/result/retry.cjs.map +0 -1
- package/dist/result/retry.d.cts +0 -70
- package/dist/result/retry.d.ts +0 -70
- package/dist/result/retry.js +0 -2
- package/dist/result/retry.js.map +0 -1
- package/dist/retry.cjs +0 -2
- package/dist/retry.cjs.map +0 -1
- package/dist/retry.d.cts +0 -388
- package/dist/retry.d.ts +0 -388
- package/dist/retry.js +0 -2
- package/dist/retry.js.map +0 -1
- package/dist/run.cjs +0 -7
- package/dist/run.cjs.map +0 -1
- package/dist/run.d.cts +0 -4
- package/dist/run.d.ts +0 -4
- package/dist/run.js +0 -7
- package/dist/run.js.map +0 -1
- package/dist/saga.cjs +0 -11
- package/dist/saga.cjs.map +0 -1
- package/dist/saga.d.cts +0 -164
- package/dist/saga.d.ts +0 -164
- package/dist/saga.js +0 -11
- package/dist/saga.js.map +0 -1
- package/dist/singleflight.cjs +0 -2
- package/dist/singleflight.cjs.map +0 -1
- package/dist/singleflight.d.cts +0 -145
- package/dist/singleflight.d.ts +0 -145
- package/dist/singleflight.js +0 -2
- package/dist/singleflight.js.map +0 -1
- package/dist/slugs.cjs +0 -2
- package/dist/slugs.cjs.map +0 -1
- package/dist/slugs.d.cts +0 -67
- package/dist/slugs.d.ts +0 -67
- package/dist/slugs.js +0 -2
- package/dist/slugs.js.map +0 -1
- package/dist/streaming.cjs +0 -9
- package/dist/streaming.cjs.map +0 -1
- package/dist/streaming.d.cts +0 -596
- package/dist/streaming.d.ts +0 -596
- package/dist/streaming.js +0 -9
- package/dist/streaming.js.map +0 -1
- package/dist/tagged-error.cjs +0 -2
- package/dist/tagged-error.cjs.map +0 -1
- package/dist/tagged-error.d.cts +0 -275
- package/dist/tagged-error.d.ts +0 -275
- package/dist/tagged-error.js +0 -2
- package/dist/tagged-error.js.map +0 -1
- package/dist/types-BziYHFkD.d.ts +0 -323
- package/dist/types-C5jLEUqY.d.cts +0 -323
- package/dist/webhook.cjs +0 -7
- package/dist/webhook.cjs.map +0 -1
- package/dist/webhook.d.cts +0 -499
- package/dist/webhook.d.ts +0 -499
- package/dist/webhook.js +0 -7
- package/dist/webhook.js.map +0 -1
package/dist/errors.d.ts
DELETED
|
@@ -1,361 +0,0 @@
|
|
|
1
|
-
import { TaggedErrorConstructor } from './tagged-error.js';
|
|
2
|
-
import { AwaitlySlug } from './slugs.js';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* awaitly/errors
|
|
6
|
-
*
|
|
7
|
-
* Pre-built error types for common failure scenarios.
|
|
8
|
-
* Uses TaggedError for type-safe exhaustive matching.
|
|
9
|
-
*
|
|
10
|
-
* @example
|
|
11
|
-
* ```typescript
|
|
12
|
-
* import { TimeoutError, RetryExhaustedError, RateLimitError, CircuitBreakerOpenError } from 'awaitly/errors';
|
|
13
|
-
*
|
|
14
|
-
* // Create errors
|
|
15
|
-
* const timeout = new TimeoutError({ operation: 'fetchUser', ms: 5000 });
|
|
16
|
-
* const retryFailed = new RetryExhaustedError({ operation: 'sendEmail', attempts: 3 });
|
|
17
|
-
*
|
|
18
|
-
* // Pattern match
|
|
19
|
-
* TaggedError.match(error, {
|
|
20
|
-
* TimeoutError: (e) => `${e.operation} timed out after ${e.ms}ms`,
|
|
21
|
-
* RetryExhaustedError: (e) => `${e.operation} failed after ${e.attempts} attempts`,
|
|
22
|
-
* RateLimitError: (e) => `Rate limit exceeded, retry after ${e.retryAfterMs}ms`,
|
|
23
|
-
* CircuitBreakerOpenError: (e) => `Circuit ${e.circuitName} is open`,
|
|
24
|
-
* });
|
|
25
|
-
* ```
|
|
26
|
-
*/
|
|
27
|
-
/**
|
|
28
|
-
* Factory function to create tagged error classes with default values.
|
|
29
|
-
*
|
|
30
|
-
* This is a convenience wrapper around TaggedError that allows specifying
|
|
31
|
-
* default property values for error types.
|
|
32
|
-
*
|
|
33
|
-
* @example
|
|
34
|
-
* ```typescript
|
|
35
|
-
* const NetworkError = makeError('NetworkError', {
|
|
36
|
-
* defaults: { retryable: true },
|
|
37
|
-
* message: (p) => `Network error: ${p.reason}`,
|
|
38
|
-
* });
|
|
39
|
-
*
|
|
40
|
-
* class MyNetworkError extends NetworkError<{ reason: string; code?: number }> {}
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
declare function makeError<Tag extends string>(tag: Tag, options?: {
|
|
44
|
-
message?: (props: Record<string, unknown>) => string;
|
|
45
|
-
defaults?: Record<string, unknown>;
|
|
46
|
-
}): {
|
|
47
|
-
new (props?: Record<string, unknown>): {
|
|
48
|
-
readonly [x: string]: unknown;
|
|
49
|
-
readonly _tag: Tag;
|
|
50
|
-
readonly code?: AwaitlySlug;
|
|
51
|
-
readonly hint?: string;
|
|
52
|
-
readonly docsUrl?: string;
|
|
53
|
-
name: string;
|
|
54
|
-
message: string;
|
|
55
|
-
stack?: string;
|
|
56
|
-
cause?: unknown;
|
|
57
|
-
};
|
|
58
|
-
};
|
|
59
|
-
declare const TimeoutError_base: TaggedErrorConstructor<"TimeoutError", {
|
|
60
|
-
/** Name of the operation that timed out */
|
|
61
|
-
operation?: string;
|
|
62
|
-
/** Timeout duration in milliseconds */
|
|
63
|
-
ms: number;
|
|
64
|
-
}>;
|
|
65
|
-
/**
|
|
66
|
-
* Error thrown when an operation times out.
|
|
67
|
-
*
|
|
68
|
-
* @example
|
|
69
|
-
* ```typescript
|
|
70
|
-
* const error = new TimeoutError({
|
|
71
|
-
* operation: 'fetchUser',
|
|
72
|
-
* ms: 5000,
|
|
73
|
-
* });
|
|
74
|
-
* console.log(error.message); // "TimeoutError: fetchUser timed out after 5000ms"
|
|
75
|
-
* ```
|
|
76
|
-
*/
|
|
77
|
-
declare class TimeoutError extends TimeoutError_base {
|
|
78
|
-
}
|
|
79
|
-
declare const RetryExhaustedError_base: TaggedErrorConstructor<"RetryExhaustedError", {
|
|
80
|
-
/** Name of the operation that failed */
|
|
81
|
-
operation?: string;
|
|
82
|
-
/** Total number of retry attempts made */
|
|
83
|
-
attempts: number;
|
|
84
|
-
/** The last error encountered before giving up */
|
|
85
|
-
lastError?: unknown;
|
|
86
|
-
}>;
|
|
87
|
-
/**
|
|
88
|
-
* Error thrown when all retry attempts are exhausted.
|
|
89
|
-
*
|
|
90
|
-
* @example
|
|
91
|
-
* ```typescript
|
|
92
|
-
* const error = new RetryExhaustedError({
|
|
93
|
-
* operation: 'sendEmail',
|
|
94
|
-
* attempts: 3,
|
|
95
|
-
* lastError: originalError,
|
|
96
|
-
* });
|
|
97
|
-
* console.log(error.message); // "RetryExhaustedError: sendEmail failed after 3 attempts"
|
|
98
|
-
* ```
|
|
99
|
-
*/
|
|
100
|
-
declare class RetryExhaustedError extends RetryExhaustedError_base {
|
|
101
|
-
}
|
|
102
|
-
declare const RateLimitError_base: TaggedErrorConstructor<"RateLimitError", {
|
|
103
|
-
/** Name of the rate limiter that was exceeded */
|
|
104
|
-
limiterName?: string;
|
|
105
|
-
/** Time in milliseconds until the rate limit resets */
|
|
106
|
-
retryAfterMs?: number;
|
|
107
|
-
}>;
|
|
108
|
-
/**
|
|
109
|
-
* Error thrown when a rate limit is exceeded.
|
|
110
|
-
*
|
|
111
|
-
* @example
|
|
112
|
-
* ```typescript
|
|
113
|
-
* const error = new RateLimitError({
|
|
114
|
-
* limiterName: 'api-calls',
|
|
115
|
-
* retryAfterMs: 1000,
|
|
116
|
-
* });
|
|
117
|
-
* console.log(error.message); // "RateLimitError: Rate limit exceeded for api-calls"
|
|
118
|
-
* ```
|
|
119
|
-
*/
|
|
120
|
-
declare class RateLimitError extends RateLimitError_base {
|
|
121
|
-
}
|
|
122
|
-
declare const CircuitBreakerOpenError_base: TaggedErrorConstructor<"CircuitBreakerOpenError", {
|
|
123
|
-
/** Name of the circuit breaker */
|
|
124
|
-
circuitName: string;
|
|
125
|
-
/** Current state of the circuit */
|
|
126
|
-
state?: "OPEN" | "HALF_OPEN";
|
|
127
|
-
/** Time in milliseconds until the circuit may close */
|
|
128
|
-
retryAfterMs?: number;
|
|
129
|
-
}>;
|
|
130
|
-
/**
|
|
131
|
-
* Error thrown when a circuit breaker is open.
|
|
132
|
-
*
|
|
133
|
-
* @example
|
|
134
|
-
* ```typescript
|
|
135
|
-
* const error = new CircuitBreakerOpenError({
|
|
136
|
-
* circuitName: 'payment-api',
|
|
137
|
-
* state: 'OPEN',
|
|
138
|
-
* retryAfterMs: 30000,
|
|
139
|
-
* });
|
|
140
|
-
* console.log(error.message); // "CircuitBreakerOpenError: Circuit payment-api is OPEN"
|
|
141
|
-
* ```
|
|
142
|
-
*/
|
|
143
|
-
declare class CircuitBreakerOpenError extends CircuitBreakerOpenError_base {
|
|
144
|
-
}
|
|
145
|
-
declare const ValidationError_base: TaggedErrorConstructor<"ValidationError", {
|
|
146
|
-
/** Field that failed validation */
|
|
147
|
-
field: string;
|
|
148
|
-
/** Reason for validation failure */
|
|
149
|
-
reason: string;
|
|
150
|
-
/** Raw value that failed validation */
|
|
151
|
-
value?: unknown;
|
|
152
|
-
}>;
|
|
153
|
-
/**
|
|
154
|
-
* Error thrown when validation fails.
|
|
155
|
-
*
|
|
156
|
-
* @example
|
|
157
|
-
* ```typescript
|
|
158
|
-
* const error = new ValidationError({
|
|
159
|
-
* field: 'email',
|
|
160
|
-
* reason: 'Invalid email format',
|
|
161
|
-
* });
|
|
162
|
-
* console.log(error.message); // "ValidationError: Invalid email - Invalid email format"
|
|
163
|
-
* ```
|
|
164
|
-
*/
|
|
165
|
-
declare class ValidationError extends ValidationError_base {
|
|
166
|
-
}
|
|
167
|
-
declare const NotFoundError_base: TaggedErrorConstructor<"NotFoundError", {
|
|
168
|
-
/** Type of resource that was not found */
|
|
169
|
-
resource: string;
|
|
170
|
-
/** Identifier of the missing resource */
|
|
171
|
-
id?: string;
|
|
172
|
-
}>;
|
|
173
|
-
/**
|
|
174
|
-
* Error thrown when a resource is not found.
|
|
175
|
-
*
|
|
176
|
-
* @example
|
|
177
|
-
* ```typescript
|
|
178
|
-
* const error = new NotFoundError({
|
|
179
|
-
* resource: 'User',
|
|
180
|
-
* id: '123',
|
|
181
|
-
* });
|
|
182
|
-
* console.log(error.message); // "NotFoundError: User with id 123 not found"
|
|
183
|
-
* ```
|
|
184
|
-
*/
|
|
185
|
-
declare class NotFoundError extends NotFoundError_base {
|
|
186
|
-
}
|
|
187
|
-
declare const UnauthorizedError_base: TaggedErrorConstructor<"UnauthorizedError", {
|
|
188
|
-
/** Action that was attempted */
|
|
189
|
-
action?: string;
|
|
190
|
-
/** Resource that was being accessed */
|
|
191
|
-
resource?: string;
|
|
192
|
-
/** Reason for denial */
|
|
193
|
-
reason?: string;
|
|
194
|
-
}>;
|
|
195
|
-
/**
|
|
196
|
-
* Error thrown when access is denied.
|
|
197
|
-
*
|
|
198
|
-
* @example
|
|
199
|
-
* ```typescript
|
|
200
|
-
* const error = new UnauthorizedError({
|
|
201
|
-
* action: 'delete',
|
|
202
|
-
* resource: 'User',
|
|
203
|
-
* });
|
|
204
|
-
* console.log(error.message); // "UnauthorizedError: Not authorized to delete User"
|
|
205
|
-
* ```
|
|
206
|
-
*/
|
|
207
|
-
declare class UnauthorizedError extends UnauthorizedError_base {
|
|
208
|
-
}
|
|
209
|
-
declare const NetworkError_base: TaggedErrorConstructor<"NetworkError", {
|
|
210
|
-
/** URL that was being accessed */
|
|
211
|
-
url?: string;
|
|
212
|
-
/** Reason for the network failure */
|
|
213
|
-
reason: string;
|
|
214
|
-
/** Whether this error is retryable */
|
|
215
|
-
retryable?: boolean;
|
|
216
|
-
/** HTTP status code if applicable */
|
|
217
|
-
statusCode?: number;
|
|
218
|
-
}>;
|
|
219
|
-
/**
|
|
220
|
-
* Error thrown for network-related failures.
|
|
221
|
-
*
|
|
222
|
-
* @example
|
|
223
|
-
* ```typescript
|
|
224
|
-
* const error = new NetworkError({
|
|
225
|
-
* url: 'https://api.example.com/users',
|
|
226
|
-
* reason: 'Connection refused',
|
|
227
|
-
* retryable: true,
|
|
228
|
-
* });
|
|
229
|
-
* ```
|
|
230
|
-
*/
|
|
231
|
-
declare class NetworkError extends NetworkError_base {
|
|
232
|
-
}
|
|
233
|
-
declare const CompensationError_base: TaggedErrorConstructor<"CompensationError", {
|
|
234
|
-
/** Step that triggered compensation */
|
|
235
|
-
step: string;
|
|
236
|
-
/** The original error that caused compensation */
|
|
237
|
-
originalError?: unknown;
|
|
238
|
-
/** Error that occurred during compensation */
|
|
239
|
-
compensationError?: unknown;
|
|
240
|
-
}>;
|
|
241
|
-
/**
|
|
242
|
-
* Error thrown when a saga compensation fails.
|
|
243
|
-
*
|
|
244
|
-
* @example
|
|
245
|
-
* ```typescript
|
|
246
|
-
* const error = new CompensationError({
|
|
247
|
-
* step: 'chargeCard',
|
|
248
|
-
* originalError: paymentError,
|
|
249
|
-
* compensationError: refundError,
|
|
250
|
-
* });
|
|
251
|
-
* ```
|
|
252
|
-
*/
|
|
253
|
-
declare class CompensationError extends CompensationError_base {
|
|
254
|
-
}
|
|
255
|
-
declare const UnexpectedError_base: TaggedErrorConstructor<"UnexpectedError", {
|
|
256
|
-
/** The original thrown value or cancellation error */
|
|
257
|
-
cause?: unknown;
|
|
258
|
-
}>;
|
|
259
|
-
/**
|
|
260
|
-
* Default error type for uncaught exceptions and cancellation in workflows.
|
|
261
|
-
* This is the default `U` type when `catchUnexpected` is not provided.
|
|
262
|
-
*
|
|
263
|
-
* @example
|
|
264
|
-
* ```typescript
|
|
265
|
-
* // Automatically used as the default — no need to pass catchUnexpected:
|
|
266
|
-
* const workflow = createWorkflow("checkout", { chargeCard, sendEmail });
|
|
267
|
-
*
|
|
268
|
-
* // Equivalent to:
|
|
269
|
-
* const workflow = createWorkflow("checkout", { chargeCard, sendEmail }, {
|
|
270
|
-
* catchUnexpected: (cause) => new UnexpectedError({ cause }),
|
|
271
|
-
* });
|
|
272
|
-
* ```
|
|
273
|
-
*/
|
|
274
|
-
declare class UnexpectedError extends UnexpectedError_base {
|
|
275
|
-
}
|
|
276
|
-
/**
|
|
277
|
-
* Union of all pre-built error types.
|
|
278
|
-
* Useful for exhaustive pattern matching.
|
|
279
|
-
*
|
|
280
|
-
* @example
|
|
281
|
-
* ```typescript
|
|
282
|
-
* function handleError(error: AwaitlyError): string {
|
|
283
|
-
* return TaggedError.match(error, {
|
|
284
|
-
* TimeoutError: (e) => `Timeout: ${e.ms}ms`,
|
|
285
|
-
* RetryExhaustedError: (e) => `Retries: ${e.attempts}`,
|
|
286
|
-
* RateLimitError: (e) => `Rate limited`,
|
|
287
|
-
* CircuitBreakerOpenError: (e) => `Circuit open: ${e.circuitName}`,
|
|
288
|
-
* ValidationError: (e) => `Invalid: ${e.field}`,
|
|
289
|
-
* NotFoundError: (e) => `Not found: ${e.resource}`,
|
|
290
|
-
* UnauthorizedError: (e) => `Unauthorized`,
|
|
291
|
-
* NetworkError: (e) => `Network: ${e.reason}`,
|
|
292
|
-
* CompensationError: (e) => `Compensation failed: ${e.step}`,
|
|
293
|
-
* UnexpectedError: (e) => e.message,
|
|
294
|
-
* });
|
|
295
|
-
* }
|
|
296
|
-
* ```
|
|
297
|
-
*/
|
|
298
|
-
type AwaitlyError = TimeoutError | RetryExhaustedError | RateLimitError | CircuitBreakerOpenError | ValidationError | NotFoundError | UnauthorizedError | NetworkError | CompensationError | UnexpectedError;
|
|
299
|
-
/**
|
|
300
|
-
* The six awaitly-system errors that carry slug + hint + docsUrl spine fields.
|
|
301
|
-
*
|
|
302
|
-
* Distinguishes spine-bearing errors from user-domain convenience errors
|
|
303
|
-
* (ValidationError, NotFoundError, UnauthorizedError, NetworkError) so that
|
|
304
|
-
* downstream tooling (lint, analyzer, docs generator) can target the spine
|
|
305
|
-
* roster without duplicating the class list.
|
|
306
|
-
*/
|
|
307
|
-
type AwaitlySystemError = TimeoutError | RetryExhaustedError | RateLimitError | CircuitBreakerOpenError | CompensationError | UnexpectedError;
|
|
308
|
-
/**
|
|
309
|
-
* Roster of awaitly-system error classes that participate in the slug spine.
|
|
310
|
-
*
|
|
311
|
-
* Adding a new system error means adding it to `AwaitlySystemError`, this
|
|
312
|
-
* roster, and `slugs.ts`. The integrity test in `spine-integrity.test.ts`
|
|
313
|
-
* iterates this roster, so a missing entry there is caught at CI time.
|
|
314
|
-
*
|
|
315
|
-
* @internal Tooling integration point (docs generator, integrity tests). Not
|
|
316
|
-
* a stable user-facing API — application code should not depend on this
|
|
317
|
-
* array's identity or order.
|
|
318
|
-
*/
|
|
319
|
-
declare const AWAITLY_SYSTEM_ERROR_CLASSES: ReadonlyArray<new (...args: any[]) => AwaitlySystemError>;
|
|
320
|
-
/**
|
|
321
|
-
* Check if an error is a TimeoutError.
|
|
322
|
-
*/
|
|
323
|
-
declare function isTimeoutError(error: unknown): error is TimeoutError;
|
|
324
|
-
/**
|
|
325
|
-
* Check if an error is a RetryExhaustedError.
|
|
326
|
-
*/
|
|
327
|
-
declare function isRetryExhaustedError(error: unknown): error is RetryExhaustedError;
|
|
328
|
-
/**
|
|
329
|
-
* Check if an error is a RateLimitError.
|
|
330
|
-
*/
|
|
331
|
-
declare function isRateLimitError(error: unknown): error is RateLimitError;
|
|
332
|
-
/**
|
|
333
|
-
* Check if an error is a CircuitBreakerOpenError.
|
|
334
|
-
*/
|
|
335
|
-
declare function isCircuitBreakerOpenError(error: unknown): error is CircuitBreakerOpenError;
|
|
336
|
-
/**
|
|
337
|
-
* Check if an error is a ValidationError.
|
|
338
|
-
*/
|
|
339
|
-
declare function isValidationError(error: unknown): error is ValidationError;
|
|
340
|
-
/**
|
|
341
|
-
* Check if an error is a NotFoundError.
|
|
342
|
-
*/
|
|
343
|
-
declare function isNotFoundError(error: unknown): error is NotFoundError;
|
|
344
|
-
/**
|
|
345
|
-
* Check if an error is an UnauthorizedError.
|
|
346
|
-
*/
|
|
347
|
-
declare function isUnauthorizedError(error: unknown): error is UnauthorizedError;
|
|
348
|
-
/**
|
|
349
|
-
* Check if an error is a NetworkError.
|
|
350
|
-
*/
|
|
351
|
-
declare function isNetworkError(error: unknown): error is NetworkError;
|
|
352
|
-
/**
|
|
353
|
-
* Check if an error is a CompensationError.
|
|
354
|
-
*/
|
|
355
|
-
declare function isCompensationError(error: unknown): error is CompensationError;
|
|
356
|
-
/**
|
|
357
|
-
* Check if an error is any AwaitlyError.
|
|
358
|
-
*/
|
|
359
|
-
declare function isAwaitlyError(error: unknown): error is AwaitlyError;
|
|
360
|
-
|
|
361
|
-
export { AWAITLY_SYSTEM_ERROR_CLASSES, type AwaitlyError, type AwaitlySystemError, CircuitBreakerOpenError, CompensationError, NetworkError, NotFoundError, RateLimitError, RetryExhaustedError, TimeoutError, UnauthorizedError, UnexpectedError, ValidationError, isAwaitlyError, isCircuitBreakerOpenError, isCompensationError, isNetworkError, isNotFoundError, isRateLimitError, isRetryExhaustedError, isTimeoutError, isUnauthorizedError, isValidationError, makeError };
|
package/dist/errors.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var O={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function R(e){return`https://jagreehal.github.io/awaitly/rules/#${e}`}var M=Object.keys(O);var c=class extends Error{_tag};function t(e,r){return class extends c{_tag=e;constructor(s,n){let g=r?.message?r.message(s??{}):e;if(super(g),this.name=e,r?.slug!==void 0){if(!r.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${r.slug}")`);Object.defineProperty(this,"code",{value:r.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:r.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:R(r.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),s&&typeof s=="object"){let o;if(r?.slug!==void 0){let{_tag:d,name:_,message:A,stack:b,code:h,hint:I,docsUrl:j,...C}=s;o=C}else{let{_tag:d,name:_,message:A,stack:b,...h}=s;o=h}let a=Object.prototype.hasOwnProperty.call(o,"cause"),u=a?o.cause:void 0;a&&delete o.cause;let i=n?.cause!==void 0;if(a&&i)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,o),a&&(this.cause=u),i&&(this.cause=n?.cause)}else n?.cause!==void 0&&(this.cause=n.cause)}}}Object.defineProperty(t,Symbol.hasInstance,{value:e=>e instanceof c});(g=>{function e(o){return o instanceof Error}g.isError=e;function r(o){return o instanceof c}g.isTaggedError=r;function s(o,a){let u=o._tag,i=a[u];return i(o)}g.match=s;function n(o,a,u){let i=o._tag,d=a[i];return d?d(o):u(o)}g.matchPartial=n})(t||={});function P(e,r){let s=r?.message??(()=>e),n=r?.defaults??{},g=t(e,{message:o=>s({...n,...o})});return class extends g{constructor(o){super({...n,...o}),Object.assign(this,{...n,...o})}}}var l=class extends t("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:r=>r.operation?`TimeoutError: ${r.operation} timed out after ${r.ms}ms`:`TimeoutError: Operation timed out after ${r.ms}ms`}){},p=class extends t("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:r=>r.operation?`RetryExhaustedError: ${r.operation} failed after ${r.attempts} attempts`:`RetryExhaustedError: Operation failed after ${r.attempts} attempts`}){},E=class extends t("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:r=>r.limiterName?`RateLimitError: Rate limit exceeded for ${r.limiterName}${r.retryAfterMs?`, retry after ${r.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${r.retryAfterMs?`, retry after ${r.retryAfterMs}ms`:""}`}){},m=class extends t("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:r=>`CircuitBreakerOpenError: Circuit ${r.circuitName} is ${r.state??"OPEN"}${r.retryAfterMs?`, retry after ${Math.ceil(r.retryAfterMs/1e3)}s`:""}`}){},w=class extends t("ValidationError",{message:r=>`ValidationError: Invalid ${r.field} - ${r.reason}`}){},x=class extends t("NotFoundError",{message:r=>r.id?`NotFoundError: ${r.resource} with id ${r.id} not found`:`NotFoundError: ${r.resource} not found`}){},k=class extends t("UnauthorizedError",{message:r=>r.reason?`UnauthorizedError: ${r.reason}`:r.action&&r.resource?`UnauthorizedError: Not authorized to ${r.action} ${r.resource}`:"UnauthorizedError: Access denied"}){},T=class extends t("NetworkError",{message:r=>r.url?`NetworkError: ${r.reason} (${r.url})`:`NetworkError: ${r.reason}`}){},y=class extends t("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:r=>`CompensationError: Failed to compensate step ${r.step}`}){},f=class extends t("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:r=>`UnexpectedError: ${r.cause instanceof Error?r.cause.message:String(r.cause??"unknown")}`}){},S=[l,p,E,m,y,f];function $(e){return t.isTaggedError(e)&&e._tag==="TimeoutError"}function H(e){return t.isTaggedError(e)&&e._tag==="RetryExhaustedError"}function N(e){return t.isTaggedError(e)&&e._tag==="RateLimitError"}function U(e){return t.isTaggedError(e)&&e._tag==="CircuitBreakerOpenError"}function L(e){return t.isTaggedError(e)&&e._tag==="ValidationError"}function v(e){return t.isTaggedError(e)&&e._tag==="NotFoundError"}function B(e){return t.isTaggedError(e)&&e._tag==="UnauthorizedError"}function F(e){return t.isTaggedError(e)&&e._tag==="NetworkError"}function K(e){return t.isTaggedError(e)&&e._tag==="CompensationError"}function z(e){if(!t.isTaggedError(e))return!1;let r=e._tag;return["TimeoutError","RetryExhaustedError","RateLimitError","CircuitBreakerOpenError","ValidationError","NotFoundError","UnauthorizedError","NetworkError","CompensationError","UnexpectedError"].includes(r)}export{S as AWAITLY_SYSTEM_ERROR_CLASSES,m as CircuitBreakerOpenError,y as CompensationError,T as NetworkError,x as NotFoundError,E as RateLimitError,p as RetryExhaustedError,l as TimeoutError,k as UnauthorizedError,f as UnexpectedError,w as ValidationError,z as isAwaitlyError,U as isCircuitBreakerOpenError,K as isCompensationError,F as isNetworkError,v as isNotFoundError,N as isRateLimitError,H as isRetryExhaustedError,$ as isTimeoutError,B as isUnauthorizedError,L as isValidationError,P as makeError};
|
|
2
|
-
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/slugs.ts","../src/tagged-error.ts","../src/errors.ts"],"sourcesContent":["/**\n * awaitly/slugs\n *\n * Source-of-truth slug namespace. Every concept that surfaces as a runtime\n * error, lint rule, static-analyzer diagnostic, visualizer event, or skill rule\n * has exactly one canonical kebab-case slug here.\n *\n * Slugs are public API. Renames are a major version bump. Adds are non-breaking.\n *\n * Categories:\n * - step-* step() discipline\n * - workflow-* createWorkflow / run / runWithState shape\n * - result-* Result usage\n * - error-* Boundary handling\n * - concurrency-* step.all/map/race vs Promise.*\n * - runtime-* Failures only observable at runtime\n */\n\nexport const AWAITLY_SLUGS = {\n // --- step-* ---\n \"step-require-id\": \"step-require-id\",\n \"step-no-immediate-execution\": \"step-no-immediate-execution\",\n \"step-require-thunk-for-key\": \"step-require-thunk-for-key\",\n \"step-no-bare-await\": \"step-no-bare-await\",\n \"step-no-try-catch-wrap\": \"step-no-try-catch-wrap\",\n \"step-stable-cache-keys\": \"step-stable-cache-keys\",\n\n // --- workflow-* ---\n \"workflow-no-floating\": \"workflow-no-floating\",\n \"workflow-options-position\": \"workflow-options-position\",\n \"workflow-callback-shape\": \"workflow-callback-shape\",\n \"workflow-no-callable-form\": \"workflow-no-callable-form\",\n \"workflow-no-dynamic-import\": \"workflow-no-dynamic-import\",\n\n // --- result-* ---\n \"result-no-floating\": \"result-no-floating\",\n \"result-require-handling\": \"result-require-handling\",\n \"result-no-double-wrap\": \"result-no-double-wrap\",\n \"result-no-manual-propagation\": \"result-no-manual-propagation\",\n \"result-no-direct-ok-err\": \"result-no-direct-ok-err\",\n\n // --- error-* ---\n \"error-check-unexpected-first\": \"error-check-unexpected-first\",\n \"error-access-cause\": \"error-access-cause\",\n \"error-normalize\": \"error-normalize\",\n \"error-no-throw-in-deps\": \"error-no-throw-in-deps\",\n\n // --- concurrency-* ---\n \"concurrency-no-promise-all\": \"concurrency-no-promise-all\",\n \"concurrency-no-promise-race\": \"concurrency-no-promise-race\",\n \"concurrency-no-promise-allsettled\": \"concurrency-no-promise-allsettled\",\n\n // --- runtime-* ---\n \"runtime-step-timeout\": \"runtime-step-timeout\",\n \"runtime-step-aborted\": \"runtime-step-aborted\",\n \"runtime-retry-exhausted\": \"runtime-retry-exhausted\",\n \"runtime-rate-limit\": \"runtime-rate-limit\",\n \"runtime-circuit-open\": \"runtime-circuit-open\",\n \"runtime-unexpected\": \"runtime-unexpected\",\n \"runtime-resolver-not-found\": \"runtime-resolver-not-found\",\n \"runtime-saga-compensation\": \"runtime-saga-compensation\",\n} as const;\n\n/** All canonical awaitly slugs as a string-literal union. */\nexport type AwaitlySlug = keyof typeof AWAITLY_SLUGS;\n\n/** Categories derived from slug prefixes. */\nexport type AwaitlySlugCategory =\n | \"step\"\n | \"workflow\"\n | \"result\"\n | \"error\"\n | \"concurrency\"\n | \"runtime\";\n\n/** Returns the category (prefix) of a slug. */\nexport function slugCategory(slug: AwaitlySlug): AwaitlySlugCategory {\n return slug.split(\"-\")[0] as AwaitlySlugCategory;\n}\n\n/**\n * Returns the canonical docs URL for a slug. Resolves to the matching\n * anchored section on the consolidated rule index page.\n */\nexport function slugDocsUrl(slug: AwaitlySlug): string {\n return `https://jagreehal.github.io/awaitly/rules/#${slug}`;\n}\n\n/** Type guard: is a string a known awaitly slug? */\nexport function isAwaitlySlug(value: string): value is AwaitlySlug {\n return Object.prototype.hasOwnProperty.call(AWAITLY_SLUGS, value);\n}\n\n/** All slugs as an array. */\n// Object.keys returns string[] — cast is safe because AWAITLY_SLUGS is `as const`\n// and the module's keys are never mutated.\nexport const ALL_SLUGS: readonly AwaitlySlug[] = Object.keys(\n AWAITLY_SLUGS\n) as AwaitlySlug[];\n","/**\n * awaitly/tagged-error\n *\n * Factory for creating tagged error types with exhaustive pattern matching.\n * Enables TypeScript to enforce that all error variants are handled.\n *\n * @example\n * ```typescript\n * // Define error types (Props via generic)\n * class NotFoundError extends TaggedError(\"NotFoundError\")<{\n * id: string;\n * resource: string;\n * }> {}\n *\n * // Define with type-safe message (Props inferred from callback annotation)\n * class ValidationError extends TaggedError(\"ValidationError\", {\n * message: (p: { field: string; reason: string }) => `Invalid ${p.field}: ${p.reason}`,\n * }) {}\n *\n * // Create instances\n * const error = new NotFoundError({ id: \"123\", resource: \"User\" });\n *\n * // Runtime type check: instanceof TaggedError works!\n * console.log(error instanceof TaggedError); // true\n *\n * // Exhaustive matching\n * type AppError = NotFoundError | ValidationError;\n * const message = TaggedError.match(error as AppError, {\n * NotFoundError: (e) => `Missing: ${e.resource} ${e.id}`,\n * ValidationError: (e) => `Invalid ${e.field}: ${e.reason}`,\n * });\n * ```\n */\n\nimport { type AwaitlySlug, slugDocsUrl } from \"./slugs\";\n\n/**\n * Options for Error constructor (compatible with ES2022 ErrorOptions).\n */\nexport interface TaggedErrorOptions {\n cause?: unknown;\n}\n\n/**\n * Options for TaggedError factory with type-safe message callback.\n */\nexport interface TaggedErrorCreateOptions<Props extends Record<string, unknown>> {\n /** Custom message generator from props. Annotate parameter for type safety. */\n message: (props: Props) => string;\n /**\n * Canonical awaitly slug for this error class. When set, instances carry\n * `code`, `hint`, and `docsUrl` populated from the slugs namespace.\n * Required together with `hint` for awaitly-system errors.\n */\n slug?: AwaitlySlug;\n /**\n * One-line \"do X instead\" guidance shown alongside the error.\n * Required when `slug` is set.\n */\n hint?: string;\n}\n\n/**\n * Base interface for all tagged errors.\n */\nexport interface TaggedErrorBase extends Error {\n readonly _tag: string;\n /** Canonical slug for awaitly-system errors. Undefined for user errors that opt out. */\n readonly code?: AwaitlySlug;\n /** One-line guidance. Undefined when no slug is set. */\n readonly hint?: string;\n /** Canonical docs URL. Undefined when no slug is set. */\n readonly docsUrl?: string;\n}\n\n/**\n * Internal base class for instanceof checks.\n * All TaggedError-created classes extend this.\n * @internal\n */\nclass InternalTaggedErrorBase extends Error implements TaggedErrorBase {\n readonly _tag!: string;\n}\n\n/**\n * Instance type for factory-created TaggedErrors.\n */\ntype TaggedErrorInstance<Tag extends string, Props> = TaggedErrorBase & {\n readonly _tag: Tag;\n} & Readonly<Props>;\n\n/**\n * Constructor args type - conditionally optional based on whether Props has required fields.\n * - If Props is empty or all properties are optional: props argument is optional\n * - If Props has any required properties: props argument is required\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ntype ConstructorArgs<Props extends Record<string, unknown>> = {} extends Props\n ? [props?: Props | void, options?: TaggedErrorOptions]\n : [props: Props, options?: TaggedErrorOptions];\n\n/**\n * Constructor type returned by TaggedError factory.\n */\nexport interface TaggedErrorConstructor<\n Tag extends string,\n Props extends Record<string, unknown>,\n> {\n new (...args: ConstructorArgs<Props>): TaggedErrorInstance<Tag, Props>;\n readonly prototype: TaggedErrorInstance<Tag, Props>;\n}\n\n/**\n * Generic class factory type that allows `<Props>` parameterization.\n * This enables the Effect.js-style syntax: `class X extends TaggedError(\"X\")<Props> {}`\n * @internal\n */\nexport interface TaggedErrorClassFactory<Tag extends string> {\n new <Props extends Record<string, unknown> = Record<string, never>>(\n ...args: ConstructorArgs<Props>\n ): TaggedErrorInstance<Tag, Props>;\n}\n\n/**\n * Helper type to extract return type from a function type.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype FnReturnType<T> = T extends (...args: any[]) => infer R ? R : never;\n\n/**\n * Helper type to get union of return types from all handlers.\n * @internal\n */\ntype HandlersReturnType<H> = { [K in keyof H]: FnReturnType<H[K]> }[keyof H];\n\n/**\n * Helper type to extract keys whose values are definitely functions (not undefined).\n * Only excludes a tag from the fallback type if its handler is guaranteed to be\n * a function. Keys where the value type includes undefined are NOT excluded,\n * ensuring type safety with dynamic/conditional handlers.\n * @internal\n */\ntype DefinitelyHandledKeys<H> = {\n [K in keyof H]-?: undefined extends H[K] ? never : K;\n}[keyof H];\n\n/**\n * Factory function to create tagged error classes.\n *\n * Two usage patterns:\n *\n * 1. **Props via generic** (default message is tag name):\n * ```typescript\n * class NotFoundError extends TaggedError(\"NotFoundError\")<{ id: string }> {}\n * ```\n *\n * 2. **Props inferred from message callback** (type-safe message):\n * ```typescript\n * class NotFoundError extends TaggedError(\"NotFoundError\", {\n * message: (p: { id: string }) => `Not found: ${p.id}`,\n * }) {}\n * ```\n *\n * Both support `instanceof TaggedError` checks at runtime.\n *\n * @param tag - The unique tag string for this error type\n * @param options - Optional configuration with message generator (annotate param for type safety)\n * @returns A class constructor that can be extended\n */\n\n// Overload 1: No options - use <Props> generic syntax, default message is tag\nfunction TaggedError<Tag extends string>(\n tag: Tag\n): TaggedErrorClassFactory<Tag>;\n\n// Overload 2: With message option - Props inferred from callback parameter annotation\nfunction TaggedError<Tag extends string, Props extends Record<string, unknown>>(\n tag: Tag,\n options: TaggedErrorCreateOptions<Props>\n): TaggedErrorConstructor<Tag, Props>;\n\n// Implementation\nfunction TaggedError<Tag extends string, Props extends Record<string, unknown>>(\n tag: Tag,\n options?: TaggedErrorCreateOptions<Props>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n return class extends InternalTaggedErrorBase {\n override readonly _tag: Tag = tag;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(props?: any, errorOptions?: TaggedErrorOptions) {\n // Generate message: call callback if provided (even for prop-less errors), else use tag\n const message = options?.message ? options.message(props ?? {}) : tag;\n\n super(message);\n this.name = tag;\n\n // Spine fields: populate when factory was given a slug\n if (options?.slug !== undefined) {\n if (!options.hint) {\n throw new TypeError(\n `TaggedError: 'hint' is required when 'slug' is set (slug: \"${options.slug}\")`\n );\n }\n Object.defineProperty(this, \"code\", {\n value: options.slug,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(this, \"hint\", {\n value: options.hint,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(this, \"docsUrl\", {\n value: slugDocsUrl(options.slug),\n enumerable: true,\n writable: false,\n configurable: false,\n });\n }\n\n // Maintains proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Assign props to instance, stripping reserved keys:\n // - _tag: discriminant for pattern matching (cannot be forged)\n // - name, message, stack: Error internals (preserve for logging/debugging)\n // - code, hint, docsUrl: spine fields stripped when slug is set, to prevent\n // Object.assign from clobbering the non-configurable/non-writable own props\n // Note: 'cause' is allowed as a user prop (common for domain errors)\n if (props && typeof props === \"object\") {\n let safeProps: Record<string, unknown>;\n if (options?.slug !== undefined) {\n const {\n _tag: _,\n name: _n,\n message: _m,\n stack: _s,\n code: _c,\n hint: _h,\n docsUrl: _d,\n ...rest\n } = props;\n safeProps = rest;\n } else {\n const {\n _tag: _,\n name: _n,\n message: _m,\n stack: _s,\n ...rest\n } = props;\n safeProps = rest;\n }\n\n const hasUserCause = Object.prototype.hasOwnProperty.call(\n safeProps,\n \"cause\"\n );\n const userCause = hasUserCause\n ? (safeProps as { cause?: unknown }).cause\n : undefined;\n if (hasUserCause) {\n delete (safeProps as { cause?: unknown }).cause;\n }\n\n const hasOptionsCause = errorOptions?.cause !== undefined;\n if (hasUserCause && hasOptionsCause) {\n throw new TypeError(\n \"TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause\"\n );\n }\n\n Object.assign(this, safeProps);\n\n if (hasUserCause) {\n (this as { cause?: unknown }).cause = userCause;\n }\n if (hasOptionsCause) {\n (this as { cause?: unknown }).cause = errorOptions?.cause;\n }\n } else if (errorOptions?.cause !== undefined) {\n (this as { cause?: unknown }).cause = errorOptions.cause;\n }\n }\n };\n}\n\n// Add Symbol.hasInstance so `instanceof TaggedError` works\nObject.defineProperty(TaggedError, Symbol.hasInstance, {\n value: (instance: unknown): boolean => instance instanceof InternalTaggedErrorBase,\n});\n\n/**\n * Namespace for static methods on TaggedError.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nnamespace TaggedError {\n /**\n * Type guard to check if a value is an Error instance.\n */\n export function isError(value: unknown): value is Error {\n return value instanceof Error;\n }\n\n /**\n * Type guard to check if a value is a TaggedError instance.\n * Uses the same check as `instanceof TaggedError` - only genuine\n * TaggedError instances (created via the factory) pass this guard.\n */\n export function isTaggedError(value: unknown): value is TaggedErrorBase {\n return value instanceof InternalTaggedErrorBase;\n }\n\n /**\n * Exhaustively matches on a tagged error, requiring handlers for all variants.\n *\n * TypeScript will error if any variant in the error union is not handled.\n *\n * @remarks When to use: You want compile-time enforcement that every tagged variant is handled.\n *\n * @param error - The tagged error to match\n * @param handlers - Object mapping _tag values to handler functions\n * @returns The return value of the matched handler\n *\n * @example\n * ```typescript\n * type AppError = NotFoundError | ValidationError;\n *\n * const message = TaggedError.match(error, {\n * NotFoundError: (e) => `Not found: ${e.id}`,\n * ValidationError: (e) => `Invalid: ${e.field}`,\n * });\n * ```\n */\n export function match<\n E extends TaggedErrorBase,\n H extends { [K in E[\"_tag\"]]: (e: Extract<E, { _tag: K }>) => unknown },\n >(error: E, handlers: H): HandlersReturnType<H> {\n const tag = error._tag as E[\"_tag\"];\n const handler = handlers[tag];\n return handler(\n error as Extract<E, { _tag: typeof tag }>\n ) as HandlersReturnType<H>;\n }\n\n /**\n * Partially matches on a tagged error with a fallback for unhandled variants.\n *\n * The fallback receives variants that are NOT definitely handled. A tag is\n * considered \"definitely handled\" only if its handler is a function (not\n * `undefined`). This ensures type safety even with dynamic/conditional handlers:\n *\n * ```typescript\n * const maybeHandle = featureFlag ? (e) => e.id : undefined;\n * TaggedError.matchPartial(\n * error,\n * { NotFoundError: maybeHandle }, // maybeHandle might be undefined\n * (e) => e._tag // e correctly includes NotFoundError\n * );\n * ```\n *\n * @param error - The tagged error to match\n * @param handlers - Partial object mapping _tag values to handler functions\n * @param otherwise - Fallback handler for unmatched variants\n * @returns The return value of the matched handler or fallback\n *\n * @example\n * ```typescript\n * const message = TaggedError.matchPartial(\n * error,\n * { NotFoundError: (e) => `Not found: ${e.id}` },\n * (e) => `Other error: ${e.message}`\n * );\n * ```\n */\n export function matchPartial<\n E extends TaggedErrorBase,\n H extends Partial<{\n [K in E[\"_tag\"]]: (e: Extract<E, { _tag: K }>) => unknown;\n }>,\n T,\n >(\n error: E,\n handlers: H,\n otherwise: (e: Exclude<E, { _tag: DefinitelyHandledKeys<H> }>) => T\n ): HandlersReturnType<H> | T {\n const tag = error._tag as E[\"_tag\"];\n const handler = handlers[tag];\n if (handler) {\n return handler(\n error as Extract<E, { _tag: typeof tag }>\n ) as HandlersReturnType<H>;\n }\n return otherwise(error as Exclude<E, { _tag: DefinitelyHandledKeys<H> }>);\n }\n}\n\nexport { TaggedError };\n\n/**\n * Helper type to extract the _tag literal type from a TaggedError.\n *\n * @example\n * ```typescript\n * class MyError extends TaggedError(\"MyError\")<{ id: string }> {}\n * type Tag = TagOf<MyError>; // \"MyError\"\n * ```\n */\nexport type TagOf<E extends TaggedErrorBase> = E[\"_tag\"];\n\n/**\n * Helper type to extract a specific variant from a TaggedError union by tag.\n *\n * @example\n * ```typescript\n * type AppError = NotFoundError | ValidationError;\n * type NotFound = ErrorByTag<AppError, \"NotFoundError\">; // NotFoundError\n * ```\n */\nexport type ErrorByTag<\n E extends TaggedErrorBase,\n Tag extends E[\"_tag\"],\n> = Extract<E, { _tag: Tag }>;\n\n/**\n * Reserved keys that are stripped from user props at runtime.\n * These keys cannot be used as user-defined properties:\n * - _tag: discriminant for pattern matching\n * - name, message, stack: Error internals (preserved for logging/debugging)\n * - code, hint, docsUrl: spine fields (non-configurable own properties when slug is set)\n *\n * Note: 'cause' is NOT reserved - it can be used as a user prop.\n */\ntype ReservedErrorKeys = \"_tag\" | \"name\" | \"message\" | \"stack\" | \"code\" | \"hint\" | \"docsUrl\";\n\n/**\n * Helper type to extract props from a TaggedError.\n * Excludes reserved keys that are stripped at runtime.\n *\n * @example\n * ```typescript\n * class MyError extends TaggedError(\"MyError\")<{ id: string }> {}\n * type Props = PropsOf<MyError>; // { id: string }\n *\n * // 'cause' is allowed as a user prop\n * class DomainError extends TaggedError(\"DomainError\")<{ cause: { field: string } }> {}\n * type DomainProps = PropsOf<DomainError>; // { cause: { field: string } }\n * ```\n */\nexport type PropsOf<E extends TaggedErrorBase> = Omit<E, ReservedErrorKeys>;\n","/**\n * awaitly/errors\n *\n * Pre-built error types for common failure scenarios.\n * Uses TaggedError for type-safe exhaustive matching.\n *\n * @example\n * ```typescript\n * import { TimeoutError, RetryExhaustedError, RateLimitError, CircuitBreakerOpenError } from 'awaitly/errors';\n *\n * // Create errors\n * const timeout = new TimeoutError({ operation: 'fetchUser', ms: 5000 });\n * const retryFailed = new RetryExhaustedError({ operation: 'sendEmail', attempts: 3 });\n *\n * // Pattern match\n * TaggedError.match(error, {\n * TimeoutError: (e) => `${e.operation} timed out after ${e.ms}ms`,\n * RetryExhaustedError: (e) => `${e.operation} failed after ${e.attempts} attempts`,\n * RateLimitError: (e) => `Rate limit exceeded, retry after ${e.retryAfterMs}ms`,\n * CircuitBreakerOpenError: (e) => `Circuit ${e.circuitName} is open`,\n * });\n * ```\n */\n\n/**\n * Spine policy:\n *\n * Awaitly-system errors (raised by awaitly internals on workflow execution\n * failure modes) carry a `slug` + `hint` so they participate in the\n * AI-DX spine: TimeoutError, RetryExhaustedError, RateLimitError,\n * CircuitBreakerOpenError, CompensationError, UnexpectedError.\n *\n * Convenience domain errors (ValidationError, NotFoundError,\n * UnauthorizedError, NetworkError) are deliberately NOT slugged — they\n * represent USER domain failures and would force user code into the\n * awaitly slug namespace. Users can opt in by adding `slug` + `hint`\n * to their own TaggedError subclasses.\n */\n\nimport { TaggedError } from \"./tagged-error\";\n\n// =============================================================================\n// Error Factory\n// =============================================================================\n\n/**\n * Factory function to create tagged error classes with default values.\n *\n * This is a convenience wrapper around TaggedError that allows specifying\n * default property values for error types.\n *\n * @example\n * ```typescript\n * const NetworkError = makeError('NetworkError', {\n * defaults: { retryable: true },\n * message: (p) => `Network error: ${p.reason}`,\n * });\n *\n * class MyNetworkError extends NetworkError<{ reason: string; code?: number }> {}\n * ```\n */\nexport function makeError<Tag extends string>(\n tag: Tag,\n options?: {\n message?: (props: Record<string, unknown>) => string;\n defaults?: Record<string, unknown>;\n }\n) {\n const messageGenerator = options?.message ?? (() => tag);\n const defaults = options?.defaults ?? {};\n\n const BaseClass = TaggedError(tag, {\n message: (props: Record<string, unknown>) =>\n messageGenerator({ ...defaults, ...props }),\n });\n\n return class extends BaseClass {\n constructor(props?: Record<string, unknown>) {\n super({ ...defaults, ...props } as Record<string, unknown>);\n Object.assign(this, { ...defaults, ...props });\n }\n };\n}\n\n// =============================================================================\n// Pre-built Error Types\n// =============================================================================\n\n/**\n * Error thrown when an operation times out.\n *\n * @example\n * ```typescript\n * const error = new TimeoutError({\n * operation: 'fetchUser',\n * ms: 5000,\n * });\n * console.log(error.message); // \"TimeoutError: fetchUser timed out after 5000ms\"\n * ```\n */\nexport class TimeoutError extends TaggedError(\"TimeoutError\", {\n slug: \"runtime-step-timeout\",\n hint: \"Increase the step's timeout option, or check why the upstream operation is slow.\",\n message: (p: {\n /** Name of the operation that timed out */\n operation?: string;\n /** Timeout duration in milliseconds */\n ms: number;\n }) =>\n p.operation\n ? `TimeoutError: ${p.operation} timed out after ${p.ms}ms`\n : `TimeoutError: Operation timed out after ${p.ms}ms`,\n}) {}\n\n/**\n * Error thrown when all retry attempts are exhausted.\n *\n * @example\n * ```typescript\n * const error = new RetryExhaustedError({\n * operation: 'sendEmail',\n * attempts: 3,\n * lastError: originalError,\n * });\n * console.log(error.message); // \"RetryExhaustedError: sendEmail failed after 3 attempts\"\n * ```\n */\nexport class RetryExhaustedError extends TaggedError(\"RetryExhaustedError\", {\n slug: \"runtime-retry-exhausted\",\n hint: \"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.\",\n message: (p: {\n /** Name of the operation that failed */\n operation?: string;\n /** Total number of retry attempts made */\n attempts: number;\n /** The last error encountered before giving up */\n lastError?: unknown;\n }) =>\n p.operation\n ? `RetryExhaustedError: ${p.operation} failed after ${p.attempts} attempts`\n : `RetryExhaustedError: Operation failed after ${p.attempts} attempts`,\n}) {}\n\n/**\n * Error thrown when a rate limit is exceeded.\n *\n * @example\n * ```typescript\n * const error = new RateLimitError({\n * limiterName: 'api-calls',\n * retryAfterMs: 1000,\n * });\n * console.log(error.message); // \"RateLimitError: Rate limit exceeded for api-calls\"\n * ```\n */\nexport class RateLimitError extends TaggedError(\"RateLimitError\", {\n slug: \"runtime-rate-limit\",\n hint: \"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.\",\n message: (p: {\n /** Name of the rate limiter that was exceeded */\n limiterName?: string;\n /** Time in milliseconds until the rate limit resets */\n retryAfterMs?: number;\n }) =>\n p.limiterName\n ? `RateLimitError: Rate limit exceeded for ${p.limiterName}${p.retryAfterMs ? `, retry after ${p.retryAfterMs}ms` : \"\"}`\n : `RateLimitError: Rate limit exceeded${p.retryAfterMs ? `, retry after ${p.retryAfterMs}ms` : \"\"}`,\n}) {}\n\n/**\n * Error thrown when a circuit breaker is open.\n *\n * @example\n * ```typescript\n * const error = new CircuitBreakerOpenError({\n * circuitName: 'payment-api',\n * state: 'OPEN',\n * retryAfterMs: 30000,\n * });\n * console.log(error.message); // \"CircuitBreakerOpenError: Circuit payment-api is OPEN\"\n * ```\n */\nexport class CircuitBreakerOpenError extends TaggedError(\n \"CircuitBreakerOpenError\",\n {\n slug: \"runtime-circuit-open\",\n hint: \"The circuit is open. Wait for it to half-open or fall back to a degraded path.\",\n message: (p: {\n /** Name of the circuit breaker */\n circuitName: string;\n /** Current state of the circuit */\n state?: \"OPEN\" | \"HALF_OPEN\";\n /** Time in milliseconds until the circuit may close */\n retryAfterMs?: number;\n }) =>\n `CircuitBreakerOpenError: Circuit ${p.circuitName} is ${p.state ?? \"OPEN\"}${p.retryAfterMs ? `, retry after ${Math.ceil(p.retryAfterMs / 1000)}s` : \"\"}`,\n }\n) {}\n\n/**\n * Error thrown when validation fails.\n *\n * @example\n * ```typescript\n * const error = new ValidationError({\n * field: 'email',\n * reason: 'Invalid email format',\n * });\n * console.log(error.message); // \"ValidationError: Invalid email - Invalid email format\"\n * ```\n */\nexport class ValidationError extends TaggedError(\"ValidationError\", {\n message: (p: {\n /** Field that failed validation */\n field: string;\n /** Reason for validation failure */\n reason: string;\n /** Raw value that failed validation */\n value?: unknown;\n }) => `ValidationError: Invalid ${p.field} - ${p.reason}`,\n}) {}\n\n/**\n * Error thrown when a resource is not found.\n *\n * @example\n * ```typescript\n * const error = new NotFoundError({\n * resource: 'User',\n * id: '123',\n * });\n * console.log(error.message); // \"NotFoundError: User with id 123 not found\"\n * ```\n */\nexport class NotFoundError extends TaggedError(\"NotFoundError\", {\n message: (p: {\n /** Type of resource that was not found */\n resource: string;\n /** Identifier of the missing resource */\n id?: string;\n }) =>\n p.id\n ? `NotFoundError: ${p.resource} with id ${p.id} not found`\n : `NotFoundError: ${p.resource} not found`,\n}) {}\n\n/**\n * Error thrown when access is denied.\n *\n * @example\n * ```typescript\n * const error = new UnauthorizedError({\n * action: 'delete',\n * resource: 'User',\n * });\n * console.log(error.message); // \"UnauthorizedError: Not authorized to delete User\"\n * ```\n */\nexport class UnauthorizedError extends TaggedError(\"UnauthorizedError\", {\n message: (p: {\n /** Action that was attempted */\n action?: string;\n /** Resource that was being accessed */\n resource?: string;\n /** Reason for denial */\n reason?: string;\n }) =>\n p.reason\n ? `UnauthorizedError: ${p.reason}`\n : p.action && p.resource\n ? `UnauthorizedError: Not authorized to ${p.action} ${p.resource}`\n : \"UnauthorizedError: Access denied\",\n}) {}\n\n/**\n * Error thrown for network-related failures.\n *\n * @example\n * ```typescript\n * const error = new NetworkError({\n * url: 'https://api.example.com/users',\n * reason: 'Connection refused',\n * retryable: true,\n * });\n * ```\n */\nexport class NetworkError extends TaggedError(\"NetworkError\", {\n message: (p: {\n /** URL that was being accessed */\n url?: string;\n /** Reason for the network failure */\n reason: string;\n /** Whether this error is retryable */\n retryable?: boolean;\n /** HTTP status code if applicable */\n statusCode?: number;\n }) =>\n p.url\n ? `NetworkError: ${p.reason} (${p.url})`\n : `NetworkError: ${p.reason}`,\n}) {}\n\n/**\n * Error thrown when a saga compensation fails.\n *\n * @example\n * ```typescript\n * const error = new CompensationError({\n * step: 'chargeCard',\n * originalError: paymentError,\n * compensationError: refundError,\n * });\n * ```\n */\nexport class CompensationError extends TaggedError(\"CompensationError\", {\n slug: \"runtime-saga-compensation\",\n hint: \"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.\",\n message: (p: {\n /** Step that triggered compensation */\n step: string;\n /** The original error that caused compensation */\n originalError?: unknown;\n /** Error that occurred during compensation */\n compensationError?: unknown;\n }) => `CompensationError: Failed to compensate step ${p.step}`,\n}) {}\n\n// =============================================================================\n// Unexpected Error\n// =============================================================================\n\n/**\n * Default error type for uncaught exceptions and cancellation in workflows.\n * This is the default `U` type when `catchUnexpected` is not provided.\n *\n * @example\n * ```typescript\n * // Automatically used as the default — no need to pass catchUnexpected:\n * const workflow = createWorkflow(\"checkout\", { chargeCard, sendEmail });\n *\n * // Equivalent to:\n * const workflow = createWorkflow(\"checkout\", { chargeCard, sendEmail }, {\n * catchUnexpected: (cause) => new UnexpectedError({ cause }),\n * });\n * ```\n */\nexport class UnexpectedError extends TaggedError(\"UnexpectedError\", {\n slug: \"runtime-unexpected\",\n hint: \"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.\",\n message: (p: {\n /** The original thrown value or cancellation error */\n cause?: unknown;\n }) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? \"unknown\")}`,\n}) {}\n\n// =============================================================================\n// Union Type for Common Errors\n// =============================================================================\n\n/**\n * Union of all pre-built error types.\n * Useful for exhaustive pattern matching.\n *\n * @example\n * ```typescript\n * function handleError(error: AwaitlyError): string {\n * return TaggedError.match(error, {\n * TimeoutError: (e) => `Timeout: ${e.ms}ms`,\n * RetryExhaustedError: (e) => `Retries: ${e.attempts}`,\n * RateLimitError: (e) => `Rate limited`,\n * CircuitBreakerOpenError: (e) => `Circuit open: ${e.circuitName}`,\n * ValidationError: (e) => `Invalid: ${e.field}`,\n * NotFoundError: (e) => `Not found: ${e.resource}`,\n * UnauthorizedError: (e) => `Unauthorized`,\n * NetworkError: (e) => `Network: ${e.reason}`,\n * CompensationError: (e) => `Compensation failed: ${e.step}`,\n * UnexpectedError: (e) => e.message,\n * });\n * }\n * ```\n */\nexport type AwaitlyError =\n | TimeoutError\n | RetryExhaustedError\n | RateLimitError\n | CircuitBreakerOpenError\n | ValidationError\n | NotFoundError\n | UnauthorizedError\n | NetworkError\n | CompensationError\n | UnexpectedError;\n\n/**\n * The six awaitly-system errors that carry slug + hint + docsUrl spine fields.\n *\n * Distinguishes spine-bearing errors from user-domain convenience errors\n * (ValidationError, NotFoundError, UnauthorizedError, NetworkError) so that\n * downstream tooling (lint, analyzer, docs generator) can target the spine\n * roster without duplicating the class list.\n */\nexport type AwaitlySystemError =\n | TimeoutError\n | RetryExhaustedError\n | RateLimitError\n | CircuitBreakerOpenError\n | CompensationError\n | UnexpectedError;\n\n/**\n * Roster of awaitly-system error classes that participate in the slug spine.\n *\n * Adding a new system error means adding it to `AwaitlySystemError`, this\n * roster, and `slugs.ts`. The integrity test in `spine-integrity.test.ts`\n * iterates this roster, so a missing entry there is caught at CI time.\n *\n * @internal Tooling integration point (docs generator, integrity tests). Not\n * a stable user-facing API — application code should not depend on this\n * array's identity or order.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const AWAITLY_SYSTEM_ERROR_CLASSES: ReadonlyArray<new (...args: any[]) => AwaitlySystemError> = [\n TimeoutError,\n RetryExhaustedError,\n RateLimitError,\n CircuitBreakerOpenError,\n CompensationError,\n UnexpectedError,\n];\n\n// =============================================================================\n// Type Guards\n// =============================================================================\n\n/**\n * Check if an error is a TimeoutError.\n */\nexport function isTimeoutError(error: unknown): error is TimeoutError {\n return TaggedError.isTaggedError(error) && error._tag === \"TimeoutError\";\n}\n\n/**\n * Check if an error is a RetryExhaustedError.\n */\nexport function isRetryExhaustedError(\n error: unknown\n): error is RetryExhaustedError {\n return (\n TaggedError.isTaggedError(error) && error._tag === \"RetryExhaustedError\"\n );\n}\n\n/**\n * Check if an error is a RateLimitError.\n */\nexport function isRateLimitError(error: unknown): error is RateLimitError {\n return TaggedError.isTaggedError(error) && error._tag === \"RateLimitError\";\n}\n\n/**\n * Check if an error is a CircuitBreakerOpenError.\n */\nexport function isCircuitBreakerOpenError(\n error: unknown\n): error is CircuitBreakerOpenError {\n return (\n TaggedError.isTaggedError(error) && error._tag === \"CircuitBreakerOpenError\"\n );\n}\n\n/**\n * Check if an error is a ValidationError.\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return TaggedError.isTaggedError(error) && error._tag === \"ValidationError\";\n}\n\n/**\n * Check if an error is a NotFoundError.\n */\nexport function isNotFoundError(error: unknown): error is NotFoundError {\n return TaggedError.isTaggedError(error) && error._tag === \"NotFoundError\";\n}\n\n/**\n * Check if an error is an UnauthorizedError.\n */\nexport function isUnauthorizedError(\n error: unknown\n): error is UnauthorizedError {\n return TaggedError.isTaggedError(error) && error._tag === \"UnauthorizedError\";\n}\n\n/**\n * Check if an error is a NetworkError.\n */\nexport function isNetworkError(error: unknown): error is NetworkError {\n return TaggedError.isTaggedError(error) && error._tag === \"NetworkError\";\n}\n\n/**\n * Check if an error is a CompensationError.\n */\nexport function isCompensationError(\n error: unknown\n): error is CompensationError {\n return TaggedError.isTaggedError(error) && error._tag === \"CompensationError\";\n}\n\n/**\n * Check if an error is any AwaitlyError.\n */\nexport function isAwaitlyError(error: unknown): error is AwaitlyError {\n if (!TaggedError.isTaggedError(error)) return false;\n const tag = error._tag;\n return [\n \"TimeoutError\",\n \"RetryExhaustedError\",\n \"RateLimitError\",\n \"CircuitBreakerOpenError\",\n \"ValidationError\",\n \"NotFoundError\",\n \"UnauthorizedError\",\n \"NetworkError\",\n \"CompensationError\",\n \"UnexpectedError\",\n ].includes(tag);\n}\n"],"mappings":"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","names":["AWAITLY_SLUGS","slugDocsUrl","slug","ALL_SLUGS","AWAITLY_SLUGS","InternalTaggedErrorBase","TaggedError","tag","options","props","errorOptions","message","slugDocsUrl","safeProps","_","_n","_m","_s","_c","_h","_d","rest","hasUserCause","userCause","hasOptionsCause","instance","isError","value","isTaggedError","match","error","handlers","handler","matchPartial","otherwise","makeError","tag","options","messageGenerator","defaults","BaseClass","TaggedError","props","TimeoutError","p","RetryExhaustedError","RateLimitError","CircuitBreakerOpenError","ValidationError","NotFoundError","UnauthorizedError","NetworkError","CompensationError","UnexpectedError","AWAITLY_SYSTEM_ERROR_CLASSES","isTimeoutError","error","isRetryExhaustedError","isRateLimitError","isCircuitBreakerOpenError","isValidationError","isNotFoundError","isUnauthorizedError","isNetworkError","isCompensationError","isAwaitlyError"]}
|
package/dist/fetch.cjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
"use strict";var fe=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Ze=(r,e)=>{for(var s in e)fe(r,s,{get:e[s],enumerable:!0})},Qe=(r,e,s,p)=>{if(e&&typeof e=="object"||typeof e=="function")for(let w of Ge(e))!Xe.call(r,w)&&w!==s&&fe(r,w,{get:()=>e[w],enumerable:!(p=ze(e,w))||p.enumerable});return r};var er=r=>Qe(fe({},"__esModule",{value:!0}),r);var wr={};Ze(wr,{fetchArrayBuffer:()=>qe,fetchBlob:()=>Ve,fetchJson:()=>He,fetchResponse:()=>We,fetchText:()=>Le});module.exports=er(wr);var rr={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function he(r){return`https://jagreehal.github.io/awaitly/rules/#${r}`}var xr=Object.keys(rr);var oe=class extends Error{_tag};function N(r,e){return class extends oe{_tag=r;constructor(s,p){let w=e?.message?e.message(s??{}):r;if(super(w),this.name=r,e?.slug!==void 0){if(!e.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${e.slug}")`);Object.defineProperty(this,"code",{value:e.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:e.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:he(e.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),s&&typeof s=="object"){let a;if(e?.slug!==void 0){let{_tag:B,name:O,message:U,stack:u,code:K,hint:H,docsUrl:xe,...te}=s;a=te}else{let{_tag:B,name:O,message:U,stack:u,...K}=s;a=K}let E=Object.prototype.hasOwnProperty.call(a,"cause"),k=E?a.cause:void 0;E&&delete a.cause;let P=p?.cause!==void 0;if(E&&P)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,a),E&&(this.cause=k),P&&(this.cause=p?.cause)}else p?.cause!==void 0&&(this.cause=p.cause)}}}Object.defineProperty(N,Symbol.hasInstance,{value:r=>r instanceof oe});(w=>{function r(a){return a instanceof Error}w.isError=r;function e(a){return a instanceof oe}w.isTaggedError=e;function s(a,E){let k=a._tag,P=E[k];return P(a)}w.match=s;function p(a,E,k){let P=a._tag,B=E[P];return B?B(a):k(a)}w.matchPartial=p})(N||={});var Ce=class extends N("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:e=>e.operation?`TimeoutError: ${e.operation} timed out after ${e.ms}ms`:`TimeoutError: Operation timed out after ${e.ms}ms`}){},be=class extends N("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:e=>e.operation?`RetryExhaustedError: ${e.operation} failed after ${e.attempts} attempts`:`RetryExhaustedError: Operation failed after ${e.attempts} attempts`}){},Ae=class extends N("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:e=>e.limiterName?`RateLimitError: Rate limit exceeded for ${e.limiterName}${e.retryAfterMs?`, retry after ${e.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${e.retryAfterMs?`, retry after ${e.retryAfterMs}ms`:""}`}){},Se=class extends N("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:e=>`CircuitBreakerOpenError: Circuit ${e.circuitName} is ${e.state??"OPEN"}${e.retryAfterMs?`, retry after ${Math.ceil(e.retryAfterMs/1e3)}s`:""}`}){},Pe=class extends N("ValidationError",{message:e=>`ValidationError: Invalid ${e.field} - ${e.reason}`}){},ve=class extends N("NotFoundError",{message:e=>e.id?`NotFoundError: ${e.resource} with id ${e.id} not found`:`NotFoundError: ${e.resource} not found`}){},Oe=class extends N("UnauthorizedError",{message:e=>e.reason?`UnauthorizedError: ${e.reason}`:e.action&&e.resource?`UnauthorizedError: Not authorized to ${e.action} ${e.resource}`:"UnauthorizedError: Access denied"}){},_e=class extends N("NetworkError",{message:e=>e.url?`NetworkError: ${e.reason} (${e.url})`:`NetworkError: ${e.reason}`}){},Fe=class extends N("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:e=>`CompensationError: Failed to compensate step ${e.step}`}){},ie=class extends N("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:e=>`UnexpectedError: ${e.cause instanceof Error?e.cause.message:String(e.cause??"unknown")}`}){};function Me(r){return{ok:!0,value:r}}var tr=r=>typeof r=="object"&&r!==null&&"ok"in r&&typeof r.ok=="boolean"&&(r.ok?"value"in r:"error"in r),Ie=(r,e)=>{let s={},p=new Map;for(let w of Object.keys(r)){let a=r[w];typeof a=="function"&&(s[w]=(...E)=>{let k=(p.get(w)??0)+1;p.set(w,k);let P=k===1?w:`${w}#${k}`;return e(P,async()=>{let B=await a(...E);return tr(B)?B:Me(B)})})}return s};function nr(r){let e=r.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!e)return;let s=parseFloat(e[1]),p=e[2].toLowerCase();return{_tag:"Duration",millis:s*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[p]??1)}}function or(r){return new ie({cause:r})}function D(r){return{ok:!0,value:r}}function _(r,e){let s=e?.cause;return{ok:!1,error:r,...s!==void 0?{cause:s}:{}}}function sr(r){if(r==null)return"unknown";if(typeof r=="string")return r.trim()||"unknown";if(typeof r=="object"){let e=r;if(typeof e._tag=="string"){let s=e._tag.trim();if(s)return s}if(typeof e.tag=="string"){let s=e.tag.trim();if(s)return s}if(typeof e.code=="string"){let s=e.code.trim();if(s)return s}else if(typeof e.code=="number")return String(e.code);if(r instanceof Error&&r.name){let s=r.name.trim();if(s)return s}}return"unknown"}function ar(r,e){if(!(!e||!r))return e[r]}function ur(r){let{intent:e,domain:s,owner:p,tags:w,stateChanges:a,emits:E,calls:k}=r;if(!e&&!s&&!p&&!w?.length&&!a?.length&&!E?.length&&!k?.length)return;let P={};return e&&(P.intent=e),s&&(P.domain=s),p&&(P.owner=p),w?.length&&(P.tags=w),a?.length&&(P.stateChanges=a),E?.length&&(P.emits=E),k?.length&&(P.calls=k),P}function L(r,e,s,p,w){let a=sr(r),E=ar(a,e),k={tag:a,origin:s};return E!==void 0&&(k.classification=E),p!==void 0&&(k.attempt=p),w!==void 0&&(k.cumulativeDurationMs=w),k}var re=Symbol.for("step_timeout_marker");function Ue(r){return typeof r!="object"||r===null?!1:r.type==="STEP_TIMEOUT"?!0:re in r}function ir(r){if(!(typeof r!="object"||r===null)){if(r.type==="STEP_TIMEOUT"){let e=r;return{timeoutMs:e.timeoutMs,stepName:e.stepName,stepKey:e.stepKey,attempt:e.attempt}}if(re in r)return r[re]}}var Ne=Symbol("early-exit");function cr(r,e){return{[Ne]:!0,error:r,meta:e}}function lr(r){return typeof r=="object"&&r!==null&&r[Ne]===!0}var Ke=Symbol("mapper-exception");function Z(r){return{[Ke]:!0,thrown:r}}function pr(r){return typeof r=="object"&&r!==null&&r[Ke]===!0}function se(r,e){let{backoff:s,initialDelay:p,maxDelay:w,jitter:a}=e,E;switch(s){case"fixed":E=p;break;case"linear":E=p*r;break;case"exponential":E=p*Math.pow(2,r-1);break}if(E=Math.min(E,w),a){let k=E*.25*Math.random();E=E+k}return Math.floor(E)}function ae(r){return new Promise(e=>setTimeout(e,r))}var Q={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:(r,e)=>!0,onRetry:(r,e,s)=>{}};async function le(r,e){let s=Math.max(1,e.attempts),p={backoff:e.backoff??Q.backoff,initialDelay:e.initialDelay??Q.initialDelay,maxDelay:e.maxDelay??Q.maxDelay,jitter:e.jitter??Q.jitter,shouldRetry:e.shouldRetry??Q.shouldRetry,onRetry:e.onRetry??Q.onRetry},w;for(let a=1;a<=s;a++)try{let E=await r();if(E.ok)return E;if(w=E,a<s&&p.shouldRetry(E.error,a)){let k=se(a,p);p.onRetry(E.error,a,k),await ae(k);continue}return E}catch(E){if(a<s&&p.shouldRetry(E,a)){let k=se(a,p);p.onRetry(E,a,k),await ae(k);continue}throw E}return w}var De=Symbol("timeout"),ce=Symbol("timeout-option");function Er(r){return typeof r=="object"&&r!==null&&r[ce]===!0}async function dr(r,e,s,p){let w=new AbortController,a=e.onTimeout??"error",E=()=>typeof a=="function"?a({name:s.name,key:s.key,ms:e.ms}):e.error??{type:"STEP_TIMEOUT",stepName:s.name,stepKey:s.key,timeoutMs:e.ms,attempt:s.attempt},k;p?.aborted&&w.abort(p.reason);let P;p&&!p.aborted&&(P=()=>w.abort(p.reason),p.addEventListener("abort",P,{once:!0}));let B=new Promise((U,u)=>{k=setTimeout(()=>{if(a!=="disconnect"&&w.abort(),a==="option"){u({[ce]:!0,ms:e.ms});return}u({[De]:!0,error:E()})},e.ms)}),O;e.signal?O=Promise.resolve(r(w.signal)):O=Promise.resolve(r());try{return await Promise.race([O,B])}catch(U){if(typeof U=="object"&&U!==null&&U[ce]===!0)throw{[ce]:!0,ms:e.ms};if(typeof U=="object"&&U!==null&&U[De]===!0){a==="disconnect"&&O.catch(()=>{});let u=U.error;if(typeof u=="object"&&u!==null&&u.type!=="STEP_TIMEOUT"){let K={timeoutMs:e.ms,stepName:s.name,stepKey:s.key,attempt:s.attempt};re in u?u[re]=K:Object.defineProperty(u,re,{value:K,enumerable:!1,writable:!0,configurable:!1})}throw u}throw U}finally{clearTimeout(k),P&&p&&p.removeEventListener("abort",P)}}var ee={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function we(r,e,s){if(typeof r!="function"){let m=r,j=e;if(typeof j!="function")throw new TypeError("[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))");return we(({step:G})=>j(Ie(m,G),{step:G}),s)}let p=r,w=e,{onError:a,onEvent:E,catchUnexpected:k,workflowId:P,workflowName:B,context:O,_workflowSignal:U}=w&&typeof w=="object"?w:{},u=P??crypto.randomUUID(),K=k??or,H=[],xe=0,te=m=>m??`step_${++xe}`,l=m=>{let j=m.context!==void 0||O===void 0?m:{...m,context:O},q=B!==void 0&&j.workflowName===void 0?{...j,workflowName:B}:j;if(q.type==="step_success"){let G=q.stepId;for(let ue=H.length-1;ue>=0;ue--){let V=H[ue];if(V.type==="race"&&!V.winnerId){V.winnerId=G;break}}}E?.(q,O)},I=cr,z=m=>lr(m),$=(m,j)=>m,$e=m=>typeof m=="function"?!1:!!(m&&typeof m=="object"&&"ok"in m||m&&typeof m=="object"&&"then"in m&&typeof m.then=="function");try{let j=function(i){let y={};for(let[n,o]of Object.entries(i))if(typeof o=="function")y[n]=o;else if(o&&typeof o=="object"&&"fn"in o)y[n]=o.fn;else throw new TypeError(`step.all: operation "${n}" must be a function or { fn, errors? } object`);return y},q=function(i,y){let n=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),t=!1;H.push({scopeId:n,type:"parallel"});let c=()=>{if(t)return;t=!0;let d=H.findIndex(f=>f.scopeId===n);d!==-1&&H.splice(d,1),l({type:"scope_end",workflowId:u,scopeId:n,ts:Date.now(),durationMs:performance.now()-o})};l({type:"scope_start",workflowId:u,scopeId:n,scopeType:"parallel",name:i,ts:Date.now()});try{let d=await y();if(c(),!d.ok)throw a?.(d.error,i,O),I(d.error,{origin:"result",resultCause:d.cause});return d.value}catch(d){throw c(),d}})()},G=function(i,y){let n=Object.keys(i),o=y.name??`Parallel(${n.join(", ")})`,t=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let c=performance.now(),d=!1;H.push({scopeId:t,type:"parallel"});let f=()=>{if(d)return;d=!0;let T=H.findIndex(R=>R.scopeId===t);T!==-1&&H.splice(T,1),l({type:"scope_end",workflowId:u,scopeId:t,ts:Date.now(),durationMs:performance.now()-c})};l({type:"scope_start",workflowId:u,scopeId:t,scopeType:"parallel",name:o,ts:Date.now()});try{let T=await new Promise(x=>{if(n.length===0){x([]);return}let S=!1,M=n.length,h=new Array(n.length);for(let F=0;F<n.length;F++){let C=n[F],A=F;Promise.resolve(i[C]()).catch(b=>_({type:"PROMISE_REJECTED",cause:b},{cause:{type:"PROMISE_REJECTION",reason:b}})).then(b=>{if(!S){if(!b.ok){S=!0,x([{key:C,result:b}]);return}h[A]={key:C,result:b},M--,M===0&&x(h)}})}});f();let R={};for(let{key:x,result:S}of T){if(!S.ok)throw a?.(S.error,x,O),I(S.error,{origin:"result",resultCause:S.cause});R[x]=S.value}return R}catch(T){throw f(),T}})()};var Tr=j,kr=q,Rr=G;let m=(i,y,n)=>(async()=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let o=n??{},t=ur(o),c=i,d=o.key??i,f=o.key??i,{description:T,retry:R,timeout:x}=o,S=te(d),M=E,h=M?performance.now():0,C=$e(y)?()=>y:y,b={attempts:Math.max(1,R?.attempts??1),backoff:R?.backoff??ee.backoff,initialDelay:R?.initialDelay??ee.initialDelay,maxDelay:R?.maxDelay??ee.maxDelay,jitter:R?.jitter??ee.jitter,shouldRetry:R?.shouldRetry??ee.shouldRetry,onRetry:R?.onRetry??ee.onRetry};E&&l({type:"step_start",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),...t&&{metadata:t}});let X;for(let v=1;v<=b.attempts;v++){let Je=M?performance.now():0;try{let g;if(x?g=await dr(C,x,{name:c,key:d,attempt:v},U):g=await C(),g.ok){let Y=performance.now()-h;return l({type:"step_success",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),durationMs:Y,...t&&{metadata:t}}),f&&l({type:"step_complete",workflowId:u,stepKey:f,name:c,description:T,ts:Date.now(),durationMs:Y,result:g,...t&&{metadata:t}}),g.value}if(X=g,v<b.attempts&&b.shouldRetry(g.error,v)){let Y=se(v,b);l({type:"step_retry",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),attempt:v+1,maxAttempts:b.attempts,delayMs:Y,error:g.error,...t&&{metadata:t},diagnostics:L(g.error,o.errorMeta,"result",v,performance.now()-h)}),b.onRetry(g.error,v,Y),await ae(Y);continue}b.attempts>1&&l({type:"step_retries_exhausted",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),durationMs:performance.now()-h,attempts:v,lastError:g.error,...t&&{metadata:t},diagnostics:L(g.error,o.errorMeta,"result",v,performance.now()-h)});break}catch(g){let Y=performance.now()-Je;if(Er(g)){let W=g.ms;l({type:"step_timeout",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),timeoutMs:W,attempt:v,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"timeout",v)}),l({type:"step_success",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),durationMs:performance.now()-h,...t&&{metadata:t}}),f&&l({type:"step_complete",workflowId:u,stepKey:f,name:c,description:T,ts:Date.now(),durationMs:performance.now()-h,result:D(void 0),...t&&{metadata:t}});return}if(z(g))throw l({type:"step_aborted",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),durationMs:Y,...t&&{metadata:t}}),g;if(Ue(g)){let W=ir(g),Ye=x?.ms??W?.timeoutMs??0;if(l({type:"step_timeout",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),timeoutMs:Ye,attempt:v,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"timeout",v)}),v<b.attempts&&b.shouldRetry(g,v)){let ye=se(v,b);l({type:"step_retry",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),attempt:v+1,maxAttempts:b.attempts,delayMs:ye,error:g,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"timeout",v,performance.now()-h)}),b.onRetry(g,v,ye),await ae(ye);continue}b.attempts>1&&l({type:"step_retries_exhausted",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),durationMs:performance.now()-h,attempts:v,lastError:g,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"timeout",v,performance.now()-h)});let me=performance.now()-h;throw l({type:"step_error",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),durationMs:me,error:g,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"timeout",v,me)}),f&&l({type:"step_complete",workflowId:u,stepKey:f,name:c,description:T,ts:Date.now(),durationMs:me,result:_(g,{cause:g}),meta:{origin:"throw",thrown:g},...t&&{metadata:t}}),a?.(g,c,O),I(g,{origin:"throw",thrown:g})}if(v<b.attempts&&b.shouldRetry(g,v)){let W=se(v,b);l({type:"step_retry",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),attempt:v+1,maxAttempts:b.attempts,delayMs:W,error:g,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"throw",v,performance.now()-h)}),b.onRetry(g,v,W),await ae(W);continue}b.attempts>1&&!Ue(g)&&l({type:"step_retries_exhausted",workflowId:u,stepId:S,stepKey:d,name:c,ts:Date.now(),durationMs:performance.now()-h,attempts:v,lastError:g,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"throw",v,performance.now()-h)});let de=performance.now()-h,ne;try{ne=K(g)}catch(W){throw Z(W)}throw l({type:"step_error",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),durationMs:de,error:ne,...t&&{metadata:t},diagnostics:L(g,o.errorMeta,"throw",v,de)}),f&&l({type:"step_complete",workflowId:u,stepKey:f,name:c,description:T,ts:Date.now(),durationMs:de,result:_(ne,{cause:g}),meta:{origin:"throw",thrown:g},...t&&{metadata:t}}),a?.(ne,c,O),I(ne,{origin:"throw",thrown:g})}}let J=X,pe=performance.now()-h,Ee=$(J.error,{origin:"result",resultCause:J.cause});throw l({type:"step_error",workflowId:u,stepId:S,stepKey:d,name:c,description:T,ts:Date.now(),durationMs:pe,error:Ee,...t&&{metadata:t},diagnostics:L(J.error,o.errorMeta,"result",b.attempts,pe)}),f&&l({type:"step_complete",workflowId:u,stepKey:f,name:c,description:T,ts:Date.now(),durationMs:pe,result:J,meta:{origin:"result",resultCause:J.cause},...t&&{metadata:t}}),a?.(Ee,c,O),I(Ee,{origin:"result",resultCause:J.cause})})();m.try=(i,y,n)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })');let o="error"in n?()=>n.error:n.onError;if(n.retry||n.timeout)return m.retry(i,async()=>{try{return D(await y())}catch(T){return _(o(T),{cause:T})}},{attempts:n.retry?.attempts??1,...n.retry??{},key:n.key,timeout:n.timeout});let t=n.key??i,c=i,d=i,f=E;return(async()=>{let T=f?performance.now():0;E&&l({type:"step_start",workflowId:u,stepId:d,stepKey:t,name:c,ts:Date.now()});try{let R=await y(),x=performance.now()-T;return l({type:"step_success",workflowId:u,stepId:d,stepKey:t,name:c,ts:Date.now(),durationMs:x}),t&&l({type:"step_complete",workflowId:u,stepKey:t,name:c,ts:Date.now(),durationMs:x,result:D(R)}),R}catch(R){let x=o(R),S=performance.now()-T,M=$(x,{origin:"throw",thrown:R});throw l({type:"step_error",workflowId:u,stepId:d,stepKey:t,name:c,ts:Date.now(),durationMs:S,error:M}),t&&l({type:"step_complete",workflowId:u,stepKey:t,name:c,ts:Date.now(),durationMs:S,result:_(x,{cause:R}),meta:{origin:"throw",thrown:R}}),a?.(M,c,O),I(M,{origin:"throw",thrown:R})}})()},m.fromResult=(i,y,n)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })');let o=n.key??i,t=i,c=i,d="error"in n?()=>n.error:n.onError,f=E;return(async()=>{let T=f?performance.now():0;E&&l({type:"step_start",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now()});let R=await y();if(R.ok){let x=performance.now()-T;return l({type:"step_success",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:x}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:x,result:D(R.value)}),R.value}else{let x=d(R.error),S=performance.now()-T,M=$(x,{origin:"result",resultCause:R.error});throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:S,error:M}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:S,result:_(x,{cause:R.error}),meta:{origin:"result",resultCause:R.error}}),a?.(M,t,O),I(M,{origin:"result",resultCause:R.error})}})()},m.fromNullable=(i,y,n,o)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))');return m(i,async()=>{let t=await y();return t!=null?D(t):_(n())},o)},m.retry=(i,y,n)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })');return m(i,y,{key:n.key??i,retry:{attempts:n.attempts,backoff:n.backoff,initialDelay:n.initialDelay,maxDelay:n.maxDelay,jitter:n.jitter,shouldRetry:n.shouldRetry,onRetry:n.onRetry},timeout:n.timeout})},m.withTimeout=(i,y,n)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })');return m(i,y,{key:n.key??i,timeout:n})},m.sleep=(i,y,n)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let o=typeof y=="string"?nr(y):y;if(!o)throw new Error(`step.sleep: invalid duration '${y}'`);let t=o.millis,c=n?.signal;return m(i,async()=>{if(U?.aborted||c?.aborted){let d=new Error("Sleep aborted");throw d.name="AbortError",d}return new Promise((d,f)=>{let T={timeoutId:void 0},R=()=>{T.timeoutId&&clearTimeout(T.timeoutId);let x=new Error("Sleep aborted");x.name="AbortError",f(x)};U?.addEventListener("abort",R,{once:!0}),c?.addEventListener("abort",R,{once:!0}),T.timeoutId=setTimeout(()=>{U?.removeEventListener("abort",R),c?.removeEventListener("abort",R),d(D(void 0))},t)})},{key:n?.key??i,description:n?.description})},m.all=((...i)=>{if(typeof i[0]!="string")throw new TypeError("step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })");let y=i[0],n=i[1];if(typeof n=="function")return q(y,n);if(n&&typeof n=="object"&&!Array.isArray(n)){let t=j(n);return G(t,{name:y})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),m.race=(i,y)=>{let n=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),t=!1,c={scopeId:n,type:"race",winnerId:void 0};H.push(c);let d=()=>{if(t)return;t=!0;let f=H.findIndex(T=>T.scopeId===n);f!==-1&&H.splice(f,1),l({type:"scope_end",workflowId:u,scopeId:n,ts:Date.now(),durationMs:performance.now()-o,winnerId:c.winnerId})};l({type:"scope_start",workflowId:u,scopeId:n,scopeType:"race",name:i,ts:Date.now()});try{let f=await y();if(d(),!f.ok)throw a?.(f.error,i,O),I(f.error,{origin:"result",resultCause:f.cause});return f.value}catch(f){throw d(),f}})()},m.if=(i,y,n)=>n(),m.label=m.if,m.branch=async(i,y)=>{let{condition:n,then:o,else:t}=y;if(n())return await o();if(t)return await t()},m.arm=(i,y)=>({fn:i,errors:y}),m.forEach=async(i,y,n)=>{let o=[],t=n.maxIterations,c=0,d="run"in n,f=Symbol.asyncIterator in y?y:(async function*(){yield*y})();for await(let T of f){if(t!==void 0&&c>=t)break;let R;d?R=await n.run(T,c):R=await n.item.handler(T,c,m),o.push(R),c++}return o},m.item=i=>({__forEachItemHandler:!0,handler:i}),m.dep=(i,y)=>y,m.workflow=(i,y,n)=>m(i,y,n),m.map=async(i,y,n,o)=>{let t=o?.concurrency??y.length;return m(i,()=>t>=y.length?Be(y.map((c,d)=>n(c,d))):(async()=>{let c=[];for(let d=0;d<y.length;d+=t){let f=y.slice(d,d+t),T=await Be(f.map((R,x)=>n(R,d+x)));if(!T.ok)return T;c.push(...T.value)}return D(c)})(),{key:o?.key})},m.withFallback=(i,y,n)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })');let o=n.key??i,t=i,c=te(o),d=E;return(async()=>{let f=d?performance.now():0;E&&l({type:"step_start",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now()});let T;try{T=await y()}catch(h){if(z(h))throw l({type:"step_aborted",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:performance.now()-f}),h;let F;try{F=K(h)}catch(A){throw Z(A)}if(n.on!==void 0&&n.on!==F){let A=performance.now()-f;throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:A,error:F}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:A,result:_(F,{cause:h}),meta:{origin:"throw",thrown:h}}),a?.(F,t,O),I(F,{origin:"throw",thrown:h})}let C;try{C=await n.fallback()}catch(A){if(z(A))throw l({type:"step_aborted",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:performance.now()-f}),A;let b;try{b=K(A)}catch(J){throw Z(J)}let X=performance.now()-f;throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:X,error:b}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:X,result:_(b,{cause:A}),meta:{origin:"throw",thrown:A}}),a?.(b,t,O),I(b,{origin:"throw",thrown:A})}if(C.ok){let A=performance.now()-f;return l({type:"step_success",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:A}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:A,result:C,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(F)}}),C.value}else{let A=performance.now()-f,b=$(C.error,{origin:"result",resultCause:C.cause});throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:A,error:b}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:A,result:C,meta:{origin:"result",resultCause:C.cause}}),a?.(b,t,O),I(b,{origin:"result",resultCause:C.cause})}}if(T.ok){let h=performance.now()-f;return l({type:"step_success",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:h}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:h,result:T}),T.value}let R=T.error;if(n.on!==void 0&&n.on!==R){let h=performance.now()-f,F=$(R,{origin:"result",resultCause:T.cause});throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:h,error:F}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:h,result:T,meta:{origin:"result",resultCause:T.cause}}),a?.(F,t,O),I(F,{origin:"result",resultCause:T.cause})}let x;try{x=await n.fallback()}catch(h){if(z(h))throw l({type:"step_aborted",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:performance.now()-f}),h;let F;try{F=K(h)}catch(A){throw Z(A)}let C=performance.now()-f;throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:C,error:F}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:C,result:_(F,{cause:h}),meta:{origin:"throw",thrown:h}}),a?.(F,t,O),I(F,{origin:"throw",thrown:h})}if(x.ok){let h=performance.now()-f;return l({type:"step_success",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:h}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:h,result:x,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(R)}}),x.value}let S=performance.now()-f,M=$(x.error,{origin:"result",resultCause:x.cause});throw l({type:"step_error",workflowId:u,stepId:c,stepKey:o,name:t,ts:Date.now(),durationMs:S,error:M}),o&&l({type:"step_complete",workflowId:u,stepKey:o,name:t,ts:Date.now(),durationMs:S,result:x,meta:{origin:"result",resultCause:x.cause}}),a?.(M,t,O),I(M,{origin:"result",resultCause:x.cause})})()},m.withResource=(i,y)=>{if(typeof i!="string"||i.length===0)throw new Error('[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })');let n=i,o=i,t=te(n),c=E;return(async()=>{let d=c?performance.now():0;E&&l({type:"step_start",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now()});let f;try{f=await y.acquire()}catch(C){if(z(C))throw l({type:"step_aborted",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now(),durationMs:performance.now()-d}),C;let A;try{A=K(C)}catch(X){throw Z(X)}let b=performance.now()-d;throw l({type:"step_error",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now(),durationMs:b,error:A}),n&&l({type:"step_complete",workflowId:u,stepKey:n,name:o,ts:Date.now(),durationMs:b,result:_(A,{cause:C}),meta:{origin:"throw",thrown:C}}),a?.(A,o,O),I(A,{origin:"throw",thrown:C})}if(!f.ok){let C=performance.now()-d,A=$(f.error,{origin:"result",resultCause:f.cause});throw l({type:"step_error",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now(),durationMs:C,error:A}),n&&l({type:"step_complete",workflowId:u,stepKey:n,name:o,ts:Date.now(),durationMs:C,result:f,meta:{origin:"result",resultCause:f.cause}}),a?.(A,o,O),I(A,{origin:"result",resultCause:f.cause})}let T=f.value,R,x,S=!1;try{R=await y.use(T)}catch(C){if(z(C)){try{await y.release(T)}catch(A){console.warn(`[awaitly] step.withResource("${i}"): release threw after earlyExit:`,A)}throw C}x=C,S=!0}try{await y.release(T)}catch(C){console.warn(`[awaitly] step.withResource("${i}"): release threw:`,C)}if(S){let C;try{C=K(x)}catch(b){throw Z(b)}let A=performance.now()-d;throw l({type:"step_error",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now(),durationMs:A,error:C}),n&&l({type:"step_complete",workflowId:u,stepKey:n,name:o,ts:Date.now(),durationMs:A,result:_(C,{cause:x}),meta:{origin:"throw",thrown:x}}),a?.(C,o,O),I(C,{origin:"throw",thrown:x})}let M=R;if(M.ok){let C=performance.now()-d;return l({type:"step_success",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now(),durationMs:C}),n&&l({type:"step_complete",workflowId:u,stepKey:n,name:o,ts:Date.now(),durationMs:C,result:M}),M.value}let h=performance.now()-d,F=$(M.error,{origin:"result",resultCause:M.cause});throw l({type:"step_error",workflowId:u,stepId:t,stepKey:n,name:o,ts:Date.now(),durationMs:h,error:F}),n&&l({type:"step_complete",workflowId:u,stepKey:n,name:o,ts:Date.now(),durationMs:h,result:M,meta:{origin:"result",resultCause:M.cause}}),a?.(F,o,O),I(F,{origin:"result",resultCause:M.cause})})()};let V=await p({step:m});if(process.env.NODE_ENV!=="production"&&V!==null&&typeof V=="object"&&"ok"in V&&typeof V.ok=="boolean"){let i=V;(i.ok===!0&&"value"in i||i.ok===!1&&"error"in i)&&console.warn(`awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
|
|
2
|
-
|
|
3
|
-
Incorrect: return ok({ data });
|
|
4
|
-
Correct: return { data };
|
|
5
|
-
|
|
6
|
-
See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`)}return D(V)}catch(m){if(pr(m))throw m.thrown;if(z(m)){let q=m.meta.origin==="throw"?m.meta.thrown:m.meta.origin==="result"?m.meta.resultCause:void 0;return _(m.error,{cause:q})}let j=K(m);return a?.(j,"unexpected",O),_(j,{cause:m})}}we.strict=(r,e)=>we(r,e);async function Be(r){return r.length===0?D([]):new Promise(e=>{let s=!1,p=r.length,w=new Array(r.length);for(let a=0;a<r.length;a++){let E=a;Promise.resolve(r[E]).catch(k=>_({type:"PROMISE_REJECTED",cause:k},{cause:{type:"PROMISE_REJECTION",reason:k}})).then(k=>{if(!s){if(!k.ok){s=!0,e(k);return}w[E]=k.value,p--,p===0&&e(D(w))}})}})}function mr(r,e){let s=new AbortController,p,w=!1,a;return r!==void 0&&(p=setTimeout(()=>{w=!0,s.abort({_tag:"Timeout",ms:r})},r)),e&&(e.aborted?s.abort(e.reason):(a=()=>s.abort(e.reason),e.addEventListener("abort",a,{once:!0}))),{signal:s.signal,cleanup(){p!==void 0&&clearTimeout(p),a&&e&&e.removeEventListener("abort",a)},timedOut:()=>w}}async function yr(r,e){if(e)return e(r);let s=await r.text();try{return JSON.parse(s)}catch{return s||void 0}}function fr(r){let e=r.headers.get("content-type");return e!==null&&/\bjson\b/i.test(e)}async function Te(r,e,s){let p=r instanceof Request?r.signal:null,w="signal"in e&&e.signal===null?null:e.signal??p,{signal:a,cleanup:E,timedOut:k}=mr(s,w);try{let P=await fetch(r,{...e,signal:a});return D(P)}catch(P){return k()?_({_tag:"FetchTimeoutError",ms:s}):a.aborted?_({_tag:"FetchAbortError",reason:a.reason??w?.reason??P}):_({_tag:"FetchNetworkError",cause:P})}finally{E()}}async function je(r,e){let s;try{s=await yr(r,e)}catch{s=void 0}return{_tag:"FetchHttpError",status:r.status,statusText:r.statusText,...s!==void 0?{body:s}:{}}}function ke(r){return typeof r=="number"?{attempts:r}:r}async function Re(r,e,s,p,w,a){let E=async()=>{let k=await Te(r,e,s);if(!k.ok)return k;let P=k.value;if(!P.ok)return _(await je(P,p));try{return D(await a(P))}catch(B){return _({_tag:"FetchNetworkError",cause:B})}};return w!==void 0?le(E,ke(w)):E()}async function ge(r,e){let s=await r;return s.ok?s:s.error._tag==="FetchHttpError"?_(e(s.error)):_(s.error)}function He(r,e){let s=async()=>{let p=await Te(r,e??{},e?.timeoutMs);if(!p.ok)return p;let w=p.value;if(!w.ok){let a=await je(w,e?.errorBody);return _(a)}if(w.status===204)return D(null);try{if(e?.strictContentType&&!fr(w)){let k=await w.text();return _({_tag:"FetchParseError",cause:new Error("Expected JSON Content-Type"),text:k})}let a=await w.text();if(a==="")return D(null);let E;try{E=JSON.parse(a)}catch(k){return _({_tag:"FetchParseError",cause:k,text:a})}if(e?.decode){let k=e.decode(E);return k.ok?D(k.value):_({_tag:"FetchDecodeError",issues:k.error.issues})}return D(E)}catch(a){return _({_tag:"FetchParseError",cause:a,text:""})}};return(async()=>{let p=e?.retry!==void 0?await le(s,ke(e.retry)):await s();return p.ok?p:p.error._tag==="FetchHttpError"&&e?.mapError?_(e.mapError(p.error)):p})()}function Le(r,e){let s=Re(r,e??{},e?.timeoutMs,e?.errorBody,e?.retry,p=>p.text());return e?.mapError?ge(s,e.mapError):s}function Ve(r,e){let s=Re(r,e??{},e?.timeoutMs,e?.errorBody,e?.retry,p=>p.blob());return e?.mapError?ge(s,e.mapError):s}function qe(r,e){let s=Re(r,e??{},e?.timeoutMs,e?.errorBody,e?.retry,p=>p.arrayBuffer());return e?.mapError?ge(s,e.mapError):s}function We(r,e){let s=()=>Te(r,e??{},e?.timeoutMs);return e?.retry!==void 0?le(s,ke(e.retry)):s()}0&&(module.exports={fetchArrayBuffer,fetchBlob,fetchJson,fetchResponse,fetchText});
|
|
7
|
-
//# sourceMappingURL=fetch.cjs.map
|