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/ratelimit.d.ts
DELETED
|
@@ -1,458 +0,0 @@
|
|
|
1
|
-
import { R as Result, c as AsyncResult } from './run-entry-BOuNyVoO.js';
|
|
2
|
-
import './errors.js';
|
|
3
|
-
import './tagged-error.js';
|
|
4
|
-
import './slugs.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Rate Limiting / Concurrency Control
|
|
8
|
-
*
|
|
9
|
-
* Control throughput for steps that hit rate-limited APIs or shared resources.
|
|
10
|
-
*
|
|
11
|
-
* @example
|
|
12
|
-
* ```typescript
|
|
13
|
-
* import { createRateLimiter, createConcurrencyLimiter } from 'awaitly';
|
|
14
|
-
*
|
|
15
|
-
* // Rate limiting (requests per second)
|
|
16
|
-
* const rateLimiter = createRateLimiter({ maxPerSecond: 10 });
|
|
17
|
-
*
|
|
18
|
-
* // Concurrency limiting (max concurrent)
|
|
19
|
-
* const concurrencyLimiter = createConcurrencyLimiter({ maxConcurrent: 5 });
|
|
20
|
-
*
|
|
21
|
-
* const result = await workflow(async ({ step }) => {
|
|
22
|
-
* // Wrap operations with rate limiting
|
|
23
|
-
* const data = await rateLimiter.execute(() =>
|
|
24
|
-
* step(() => callRateLimitedApi())
|
|
25
|
-
* );
|
|
26
|
-
*
|
|
27
|
-
* // Wrap batch operations with concurrency control
|
|
28
|
-
* const results = await concurrencyLimiter.executeAll(
|
|
29
|
-
* ids.map(id => () => step(() => fetchItem(id)))
|
|
30
|
-
* );
|
|
31
|
-
*
|
|
32
|
-
* return { data, results };
|
|
33
|
-
* });
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Configuration for rate limiter.
|
|
39
|
-
*/
|
|
40
|
-
interface RateLimiterConfig {
|
|
41
|
-
/**
|
|
42
|
-
* Maximum operations per second.
|
|
43
|
-
*/
|
|
44
|
-
maxPerSecond: number;
|
|
45
|
-
/**
|
|
46
|
-
* Burst capacity - allows brief spikes above the rate.
|
|
47
|
-
* @default maxPerSecond * 2
|
|
48
|
-
*/
|
|
49
|
-
burstCapacity?: number;
|
|
50
|
-
/**
|
|
51
|
-
* Strategy when rate limit is exceeded.
|
|
52
|
-
* - 'wait': Wait until a slot is available (default)
|
|
53
|
-
* - 'reject': Reject immediately with error
|
|
54
|
-
* @default 'wait'
|
|
55
|
-
*/
|
|
56
|
-
strategy?: "wait" | "reject";
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Configuration for concurrency limiter.
|
|
60
|
-
*/
|
|
61
|
-
interface ConcurrencyLimiterConfig {
|
|
62
|
-
/**
|
|
63
|
-
* Maximum concurrent operations.
|
|
64
|
-
*/
|
|
65
|
-
maxConcurrent: number;
|
|
66
|
-
/**
|
|
67
|
-
* Strategy when limit is reached.
|
|
68
|
-
* - 'queue': Queue and wait (default)
|
|
69
|
-
* - 'reject': Reject immediately
|
|
70
|
-
* @default 'queue'
|
|
71
|
-
*/
|
|
72
|
-
strategy?: "queue" | "reject";
|
|
73
|
-
/**
|
|
74
|
-
* Maximum queue size (only for 'queue' strategy).
|
|
75
|
-
* @default Infinity
|
|
76
|
-
*/
|
|
77
|
-
maxQueueSize?: number;
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Error when rate/concurrency limit is exceeded and strategy is 'reject'.
|
|
81
|
-
*/
|
|
82
|
-
interface RateLimitExceededError {
|
|
83
|
-
type: "RATE_LIMIT_EXCEEDED";
|
|
84
|
-
limiterName: string;
|
|
85
|
-
retryAfterMs?: number;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Error when concurrency limit queue is full.
|
|
89
|
-
*/
|
|
90
|
-
interface QueueFullError {
|
|
91
|
-
type: "QUEUE_FULL";
|
|
92
|
-
limiterName: string;
|
|
93
|
-
queueSize: number;
|
|
94
|
-
maxQueueSize: number;
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Type guard for RateLimitExceededError.
|
|
98
|
-
*/
|
|
99
|
-
declare function isRateLimitExceededError(error: unknown): error is RateLimitExceededError;
|
|
100
|
-
/**
|
|
101
|
-
* Type guard for QueueFullError.
|
|
102
|
-
*/
|
|
103
|
-
declare function isQueueFullError(error: unknown): error is QueueFullError;
|
|
104
|
-
/**
|
|
105
|
-
* Statistics for rate limiter.
|
|
106
|
-
*/
|
|
107
|
-
interface RateLimiterStats {
|
|
108
|
-
availableTokens: number;
|
|
109
|
-
maxTokens: number;
|
|
110
|
-
tokensPerSecond: number;
|
|
111
|
-
waitingCount: number;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Statistics for concurrency limiter.
|
|
115
|
-
*/
|
|
116
|
-
interface ConcurrencyLimiterStats {
|
|
117
|
-
activeCount: number;
|
|
118
|
-
maxConcurrent: number;
|
|
119
|
-
queueSize: number;
|
|
120
|
-
maxQueueSize: number;
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* Rate limiter interface.
|
|
124
|
-
*/
|
|
125
|
-
interface RateLimiter {
|
|
126
|
-
/**
|
|
127
|
-
* Execute an operation with rate limiting.
|
|
128
|
-
* @param operation - The operation to execute
|
|
129
|
-
* @returns The operation result
|
|
130
|
-
*/
|
|
131
|
-
execute<T>(operation: () => T | Promise<T>): Promise<T>;
|
|
132
|
-
/**
|
|
133
|
-
* Execute a Result-returning operation with rate limiting.
|
|
134
|
-
*/
|
|
135
|
-
executeResult<T, E>(operation: () => Result<T, E> | AsyncResult<T, E>): AsyncResult<T, E | RateLimitExceededError>;
|
|
136
|
-
/**
|
|
137
|
-
* Get current statistics.
|
|
138
|
-
*/
|
|
139
|
-
getStats(): RateLimiterStats;
|
|
140
|
-
/**
|
|
141
|
-
* Reset the rate limiter.
|
|
142
|
-
*/
|
|
143
|
-
reset(): void;
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Create a token bucket rate limiter.
|
|
147
|
-
*
|
|
148
|
-
* @param name - Name for the limiter (used in errors)
|
|
149
|
-
* @param config - Rate limiter configuration
|
|
150
|
-
* @returns A RateLimiter instance
|
|
151
|
-
*
|
|
152
|
-
* @example
|
|
153
|
-
* ```typescript
|
|
154
|
-
* const limiter = createRateLimiter('api-calls', {
|
|
155
|
-
* maxPerSecond: 10,
|
|
156
|
-
* burstCapacity: 20,
|
|
157
|
-
* });
|
|
158
|
-
*
|
|
159
|
-
* // In workflow
|
|
160
|
-
* const data = await limiter.execute(() =>
|
|
161
|
-
* step(() => callApi())
|
|
162
|
-
* );
|
|
163
|
-
* ```
|
|
164
|
-
*/
|
|
165
|
-
declare function createRateLimiter(name: string, config: RateLimiterConfig): RateLimiter;
|
|
166
|
-
/**
|
|
167
|
-
* Concurrency limiter interface.
|
|
168
|
-
*/
|
|
169
|
-
interface ConcurrencyLimiter {
|
|
170
|
-
/**
|
|
171
|
-
* Execute an operation with concurrency limiting.
|
|
172
|
-
* @param operation - The operation to execute
|
|
173
|
-
* @returns The operation result
|
|
174
|
-
*/
|
|
175
|
-
execute<T>(operation: () => T | Promise<T>): Promise<T>;
|
|
176
|
-
/**
|
|
177
|
-
* Execute multiple operations with concurrency control.
|
|
178
|
-
* @param operations - Array of operation factories
|
|
179
|
-
* @returns Array of results (in order)
|
|
180
|
-
*/
|
|
181
|
-
executeAll<T>(operations: Array<() => T | Promise<T>>): Promise<T[]>;
|
|
182
|
-
/**
|
|
183
|
-
* Execute a Result-returning operation with concurrency limiting.
|
|
184
|
-
*/
|
|
185
|
-
executeResult<T, E>(operation: () => Result<T, E> | AsyncResult<T, E>): AsyncResult<T, E | QueueFullError>;
|
|
186
|
-
/**
|
|
187
|
-
* Get current statistics.
|
|
188
|
-
*/
|
|
189
|
-
getStats(): ConcurrencyLimiterStats;
|
|
190
|
-
/**
|
|
191
|
-
* Reset the concurrency limiter.
|
|
192
|
-
*/
|
|
193
|
-
reset(): void;
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* Create a concurrency limiter.
|
|
197
|
-
*
|
|
198
|
-
* @param name - Name for the limiter (used in errors)
|
|
199
|
-
* @param config - Concurrency limiter configuration
|
|
200
|
-
* @returns A ConcurrencyLimiter instance
|
|
201
|
-
*
|
|
202
|
-
* @example
|
|
203
|
-
* ```typescript
|
|
204
|
-
* const limiter = createConcurrencyLimiter('db-pool', {
|
|
205
|
-
* maxConcurrent: 10,
|
|
206
|
-
* });
|
|
207
|
-
*
|
|
208
|
-
* // Execute with concurrency control
|
|
209
|
-
* const results = await limiter.executeAll(
|
|
210
|
-
* ids.map(id => () => fetchItem(id))
|
|
211
|
-
* );
|
|
212
|
-
* ```
|
|
213
|
-
*/
|
|
214
|
-
declare function createConcurrencyLimiter(name: string, config: ConcurrencyLimiterConfig): ConcurrencyLimiter;
|
|
215
|
-
/**
|
|
216
|
-
* Configuration for combined rate + concurrency limiter.
|
|
217
|
-
*/
|
|
218
|
-
interface CombinedLimiterConfig {
|
|
219
|
-
/**
|
|
220
|
-
* Rate limiting configuration.
|
|
221
|
-
*/
|
|
222
|
-
rate?: RateLimiterConfig;
|
|
223
|
-
/**
|
|
224
|
-
* Concurrency limiting configuration.
|
|
225
|
-
*/
|
|
226
|
-
concurrency?: ConcurrencyLimiterConfig;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Create a combined rate + concurrency limiter.
|
|
230
|
-
*
|
|
231
|
-
* Operations are first rate-limited, then concurrency-limited.
|
|
232
|
-
*
|
|
233
|
-
* @param name - Name for the limiter
|
|
234
|
-
* @param config - Combined limiter configuration
|
|
235
|
-
* @returns An object with both limiters and a combined execute function
|
|
236
|
-
*
|
|
237
|
-
* @example
|
|
238
|
-
* ```typescript
|
|
239
|
-
* const limiter = createCombinedLimiter('api', {
|
|
240
|
-
* rate: { maxPerSecond: 10 },
|
|
241
|
-
* concurrency: { maxConcurrent: 5 },
|
|
242
|
-
* });
|
|
243
|
-
*
|
|
244
|
-
* const result = await limiter.execute(() => callApi());
|
|
245
|
-
* ```
|
|
246
|
-
*/
|
|
247
|
-
declare function createCombinedLimiter(name: string, config: CombinedLimiterConfig): {
|
|
248
|
-
rate?: RateLimiter;
|
|
249
|
-
concurrency?: ConcurrencyLimiter;
|
|
250
|
-
execute: <T>(operation: () => T | Promise<T>) => Promise<T>;
|
|
251
|
-
};
|
|
252
|
-
/**
|
|
253
|
-
* Configuration for fixed window rate limiter.
|
|
254
|
-
*/
|
|
255
|
-
interface FixedWindowLimiterConfig {
|
|
256
|
-
/**
|
|
257
|
-
* Maximum requests allowed per window.
|
|
258
|
-
*/
|
|
259
|
-
limit: number;
|
|
260
|
-
/**
|
|
261
|
-
* Window duration in milliseconds.
|
|
262
|
-
* @default 1000 (1 second)
|
|
263
|
-
*/
|
|
264
|
-
windowMs?: number;
|
|
265
|
-
/**
|
|
266
|
-
* Strategy when rate limit is exceeded.
|
|
267
|
-
* - 'wait': Wait until window resets (default)
|
|
268
|
-
* - 'reject': Reject immediately with error
|
|
269
|
-
* @default 'wait'
|
|
270
|
-
*/
|
|
271
|
-
strategy?: "wait" | "reject";
|
|
272
|
-
}
|
|
273
|
-
/**
|
|
274
|
-
* Statistics for fixed window rate limiter.
|
|
275
|
-
*/
|
|
276
|
-
interface FixedWindowLimiterStats {
|
|
277
|
-
/** Requests made in current window */
|
|
278
|
-
requestCount: number;
|
|
279
|
-
/** Maximum requests allowed per window */
|
|
280
|
-
limit: number;
|
|
281
|
-
/** Window duration in milliseconds */
|
|
282
|
-
windowMs: number;
|
|
283
|
-
/** Time remaining until window reset (ms) */
|
|
284
|
-
remainingMs: number;
|
|
285
|
-
/** Number of requests waiting for next window */
|
|
286
|
-
waitingCount: number;
|
|
287
|
-
}
|
|
288
|
-
/**
|
|
289
|
-
* Fixed window rate limiter interface.
|
|
290
|
-
*/
|
|
291
|
-
interface FixedWindowLimiter {
|
|
292
|
-
/**
|
|
293
|
-
* Execute an operation with rate limiting.
|
|
294
|
-
* @param operation - The operation to execute
|
|
295
|
-
* @param cost - Optional cost for this operation (default: 1)
|
|
296
|
-
* @returns The operation result
|
|
297
|
-
*/
|
|
298
|
-
execute<T>(operation: () => T | Promise<T>, cost?: number): Promise<T>;
|
|
299
|
-
/**
|
|
300
|
-
* Execute a Result-returning operation with rate limiting.
|
|
301
|
-
* @param operation - The operation to execute
|
|
302
|
-
* @param cost - Optional cost for this operation (default: 1)
|
|
303
|
-
*/
|
|
304
|
-
executeResult<T, E>(operation: () => Result<T, E> | AsyncResult<T, E>, cost?: number): AsyncResult<T, E | RateLimitExceededError>;
|
|
305
|
-
/**
|
|
306
|
-
* Get current statistics.
|
|
307
|
-
*/
|
|
308
|
-
getStats(): FixedWindowLimiterStats;
|
|
309
|
-
/**
|
|
310
|
-
* Reset the rate limiter.
|
|
311
|
-
*/
|
|
312
|
-
reset(): void;
|
|
313
|
-
}
|
|
314
|
-
/**
|
|
315
|
-
* Create a fixed window rate limiter.
|
|
316
|
-
*
|
|
317
|
-
* Unlike token bucket, fixed window resets at fixed intervals.
|
|
318
|
-
* Simpler to reason about but can allow bursts at window boundaries.
|
|
319
|
-
*
|
|
320
|
-
* @param name - Name for the limiter (used in errors)
|
|
321
|
-
* @param config - Rate limiter configuration
|
|
322
|
-
* @returns A FixedWindowLimiter instance
|
|
323
|
-
*
|
|
324
|
-
* @example
|
|
325
|
-
* ```typescript
|
|
326
|
-
* const limiter = createFixedWindowLimiter('api-calls', {
|
|
327
|
-
* limit: 100, // 100 requests
|
|
328
|
-
* windowMs: 60000, // per minute
|
|
329
|
-
* });
|
|
330
|
-
*
|
|
331
|
-
* // In workflow
|
|
332
|
-
* const data = await limiter.execute(() => callApi());
|
|
333
|
-
*
|
|
334
|
-
* // Cost-based limiting (e.g., batch operations cost more)
|
|
335
|
-
* const batchData = await limiter.execute(() => callBatchApi(), 10);
|
|
336
|
-
* ```
|
|
337
|
-
*/
|
|
338
|
-
declare function createFixedWindowLimiter(name: string, config: FixedWindowLimiterConfig): FixedWindowLimiter;
|
|
339
|
-
/**
|
|
340
|
-
* Configuration for cost-based rate limiter.
|
|
341
|
-
*/
|
|
342
|
-
interface CostBasedRateLimiterConfig {
|
|
343
|
-
/**
|
|
344
|
-
* Maximum tokens (credits) per second refill rate.
|
|
345
|
-
*/
|
|
346
|
-
tokensPerSecond: number;
|
|
347
|
-
/**
|
|
348
|
-
* Maximum token capacity (burst capacity).
|
|
349
|
-
* @default tokensPerSecond * 2
|
|
350
|
-
*/
|
|
351
|
-
maxTokens?: number;
|
|
352
|
-
/**
|
|
353
|
-
* Strategy when rate limit is exceeded.
|
|
354
|
-
* - 'wait': Wait until tokens are available (default)
|
|
355
|
-
* - 'reject': Reject immediately with error
|
|
356
|
-
* @default 'wait'
|
|
357
|
-
*/
|
|
358
|
-
strategy?: "wait" | "reject";
|
|
359
|
-
}
|
|
360
|
-
/**
|
|
361
|
-
* Statistics for cost-based rate limiter.
|
|
362
|
-
*/
|
|
363
|
-
interface CostBasedRateLimiterStats {
|
|
364
|
-
/** Available tokens (can be fractional) */
|
|
365
|
-
availableTokens: number;
|
|
366
|
-
/** Maximum token capacity */
|
|
367
|
-
maxTokens: number;
|
|
368
|
-
/** Token refill rate per second */
|
|
369
|
-
tokensPerSecond: number;
|
|
370
|
-
/** Number of operations waiting */
|
|
371
|
-
waitingCount: number;
|
|
372
|
-
}
|
|
373
|
-
/**
|
|
374
|
-
* Cost-based rate limiter interface.
|
|
375
|
-
*/
|
|
376
|
-
interface CostBasedRateLimiter {
|
|
377
|
-
/**
|
|
378
|
-
* Execute an operation with cost-based rate limiting.
|
|
379
|
-
* @param operation - The operation to execute
|
|
380
|
-
* @param cost - Token cost for this operation (default: 1)
|
|
381
|
-
* @returns The operation result
|
|
382
|
-
*/
|
|
383
|
-
execute<T>(operation: () => T | Promise<T>, cost?: number): Promise<T>;
|
|
384
|
-
/**
|
|
385
|
-
* Execute a Result-returning operation with cost-based rate limiting.
|
|
386
|
-
* @param operation - The operation to execute
|
|
387
|
-
* @param cost - Token cost for this operation (default: 1)
|
|
388
|
-
*/
|
|
389
|
-
executeResult<T, E>(operation: () => Result<T, E> | AsyncResult<T, E>, cost?: number): AsyncResult<T, E | RateLimitExceededError>;
|
|
390
|
-
/**
|
|
391
|
-
* Get current statistics.
|
|
392
|
-
*/
|
|
393
|
-
getStats(): CostBasedRateLimiterStats;
|
|
394
|
-
/**
|
|
395
|
-
* Reset the rate limiter.
|
|
396
|
-
*/
|
|
397
|
-
reset(): void;
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Create a cost-based token bucket rate limiter.
|
|
401
|
-
*
|
|
402
|
-
* Different operations can have different costs, allowing fine-grained
|
|
403
|
-
* control over resource usage. For example, a batch API call might cost
|
|
404
|
-
* 10 tokens while a simple query costs 1.
|
|
405
|
-
*
|
|
406
|
-
* @param name - Name for the limiter (used in errors)
|
|
407
|
-
* @param config - Rate limiter configuration
|
|
408
|
-
* @returns A CostBasedRateLimiter instance
|
|
409
|
-
*
|
|
410
|
-
* @example
|
|
411
|
-
* ```typescript
|
|
412
|
-
* const limiter = createCostBasedRateLimiter('api', {
|
|
413
|
-
* tokensPerSecond: 100, // 100 tokens/second refill
|
|
414
|
-
* maxTokens: 200, // Can burst up to 200 tokens
|
|
415
|
-
* });
|
|
416
|
-
*
|
|
417
|
-
* // Simple query costs 1 token
|
|
418
|
-
* await limiter.execute(() => simpleQuery());
|
|
419
|
-
*
|
|
420
|
-
* // Batch operation costs 10 tokens
|
|
421
|
-
* await limiter.execute(() => batchOperation(), 10);
|
|
422
|
-
*
|
|
423
|
-
* // Heavy export costs 50 tokens
|
|
424
|
-
* await limiter.execute(() => exportData(), 50);
|
|
425
|
-
* ```
|
|
426
|
-
*/
|
|
427
|
-
declare function createCostBasedRateLimiter(name: string, config: CostBasedRateLimiterConfig): CostBasedRateLimiter;
|
|
428
|
-
/**
|
|
429
|
-
* Preset configurations for common use cases.
|
|
430
|
-
*/
|
|
431
|
-
declare const rateLimiterPresets: {
|
|
432
|
-
/**
|
|
433
|
-
* Typical API rate limit (10 req/s).
|
|
434
|
-
*/
|
|
435
|
-
readonly api: {
|
|
436
|
-
maxPerSecond: number;
|
|
437
|
-
burstCapacity: number;
|
|
438
|
-
strategy: "wait";
|
|
439
|
-
};
|
|
440
|
-
/**
|
|
441
|
-
* Database pool limit (concurrent connections).
|
|
442
|
-
*/
|
|
443
|
-
readonly database: {
|
|
444
|
-
maxConcurrent: number;
|
|
445
|
-
strategy: "queue";
|
|
446
|
-
maxQueueSize: number;
|
|
447
|
-
};
|
|
448
|
-
/**
|
|
449
|
-
* Aggressive rate limit for external APIs (5 req/s).
|
|
450
|
-
*/
|
|
451
|
-
readonly external: {
|
|
452
|
-
maxPerSecond: number;
|
|
453
|
-
burstCapacity: number;
|
|
454
|
-
strategy: "wait";
|
|
455
|
-
};
|
|
456
|
-
};
|
|
457
|
-
|
|
458
|
-
export { type CombinedLimiterConfig, type ConcurrencyLimiter, type ConcurrencyLimiterConfig, type ConcurrencyLimiterStats, type CostBasedRateLimiter, type CostBasedRateLimiterConfig, type CostBasedRateLimiterStats, type FixedWindowLimiter, type FixedWindowLimiterConfig, type FixedWindowLimiterStats, type QueueFullError, type RateLimitExceededError, type RateLimiter, type RateLimiterConfig, type RateLimiterStats, createCombinedLimiter, createConcurrencyLimiter, createCostBasedRateLimiter, createFixedWindowLimiter, createRateLimiter, isQueueFullError, isRateLimitExceededError, rateLimiterPresets };
|
package/dist/ratelimit.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
var je={"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 we(e){return`https://jagreehal.github.io/awaitly/rules/#${e}`}var ar=Object.keys(je);var oe=class extends Error{_tag};function j(e,r){return class extends oe{_tag=e;constructor(p,T){let k=r?.message?r.message(p??{}):e;if(super(k),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:we(r.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),p&&typeof p=="object"){let a;if(r?.slug!==void 0){let{_tag:M,name:g,message:v,stack:t,code:f,hint:I,docsUrl:K,...W}=p;a=W}else{let{_tag:M,name:g,message:v,stack:t,...f}=p;a=f}let l=Object.prototype.hasOwnProperty.call(a,"cause"),R=l?a.cause:void 0;l&&delete a.cause;let S=T?.cause!==void 0;if(l&&S)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,a),l&&(this.cause=R),S&&(this.cause=T?.cause)}else T?.cause!==void 0&&(this.cause=T.cause)}}}Object.defineProperty(j,Symbol.hasInstance,{value:e=>e instanceof oe});(k=>{function e(a){return a instanceof Error}k.isError=e;function r(a){return a instanceof oe}k.isTaggedError=r;function p(a,l){let R=a._tag,S=l[R];return S(a)}k.match=p;function T(a,l,R){let S=a._tag,M=l[S];return M?M(a):R(a)}k.matchPartial=T})(j||={});var fe=class extends j("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`}){},Te=class extends j("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`}){},ke=class extends j("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`:""}`}){},Re=class extends j("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`:""}`}){},ge=class extends j("ValidationError",{message:r=>`ValidationError: Invalid ${r.field} - ${r.reason}`}){},xe=class extends j("NotFoundError",{message:r=>r.id?`NotFoundError: ${r.resource} with id ${r.id} not found`:`NotFoundError: ${r.resource} not found`}){},Ce=class extends j("UnauthorizedError",{message:r=>r.reason?`UnauthorizedError: ${r.reason}`:r.action&&r.resource?`UnauthorizedError: Not authorized to ${r.action} ${r.resource}`:"UnauthorizedError: Access denied"}){},he=class extends j("NetworkError",{message:r=>r.url?`NetworkError: ${r.reason} (${r.url})`:`NetworkError: ${r.reason}`}){},be=class extends j("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}`}){},ae=class extends j("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")}`}){};function Ae(e){return{ok:!0,value:e}}var Ke=e=>typeof e=="object"&&e!==null&&"ok"in e&&typeof e.ok=="boolean"&&(e.ok?"value"in e:"error"in e),Se=(e,r)=>{let p={},T=new Map;for(let k of Object.keys(e)){let a=e[k];typeof a=="function"&&(p[k]=(...l)=>{let R=(T.get(k)??0)+1;T.set(k,R);let S=R===1?k:`${k}#${R}`;return r(S,async()=>{let M=await a(...l);return Ke(M)?M:Ae(M)})})}return p};function Be(e){let r=e.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!r)return;let p=parseFloat(r[1]),T=r[2].toLowerCase();return{_tag:"Duration",millis:p*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[T]??1)}}function Ve(e){return new ae({cause:e})}function $(e){return{ok:!0,value:e}}function F(e,r){let p=r?.cause;return{ok:!1,error:e,...p!==void 0?{cause:p}:{}}}function We(e){if(e==null)return"unknown";if(typeof e=="string")return e.trim()||"unknown";if(typeof e=="object"){let r=e;if(typeof r._tag=="string"){let p=r._tag.trim();if(p)return p}if(typeof r.tag=="string"){let p=r.tag.trim();if(p)return p}if(typeof r.code=="string"){let p=r.code.trim();if(p)return p}else if(typeof r.code=="number")return String(r.code);if(e instanceof Error&&e.name){let p=e.name.trim();if(p)return p}}return"unknown"}function qe(e,r){if(!(!r||!e))return r[e]}function $e(e){let{intent:r,domain:p,owner:T,tags:k,stateChanges:a,emits:l,calls:R}=e;if(!r&&!p&&!T&&!k?.length&&!a?.length&&!l?.length&&!R?.length)return;let S={};return r&&(S.intent=r),p&&(S.domain=p),T&&(S.owner=T),k?.length&&(S.tags=k),a?.length&&(S.stateChanges=a),l?.length&&(S.emits=l),R?.length&&(S.calls=R),S}function V(e,r,p,T,k){let a=We(e),l=qe(a,r),R={tag:a,origin:p};return l!==void 0&&(R.classification=l),T!==void 0&&(R.attempt=T),k!==void 0&&(R.cumulativeDurationMs=k),R}var te=Symbol.for("step_timeout_marker");function Pe(e){return typeof e!="object"||e===null?!1:e.type==="STEP_TIMEOUT"?!0:te in e}function He(e){if(!(typeof e!="object"||e===null)){if(e.type==="STEP_TIMEOUT"){let r=e;return{timeoutMs:r.timeoutMs,stepName:r.stepName,stepKey:r.stepKey,attempt:r.attempt}}if(te in e)return e[te]}}var Oe=Symbol("early-exit");function ze(e,r){return{[Oe]:!0,error:e,meta:r}}function Ye(e){return typeof e=="object"&&e!==null&&e[Oe]===!0}var Me=Symbol("mapper-exception");function ee(e){return{[Me]:!0,thrown:e}}function Je(e){return typeof e=="object"&&e!==null&&e[Me]===!0}function me(e,r){let{backoff:p,initialDelay:T,maxDelay:k,jitter:a}=r,l;switch(p){case"fixed":l=T;break;case"linear":l=T*e;break;case"exponential":l=T*Math.pow(2,e-1);break}if(l=Math.min(l,k),a){let R=l*.25*Math.random();l=l+R}return Math.floor(l)}function de(e){return new Promise(r=>setTimeout(r,e))}var ve=Symbol("timeout"),ie=Symbol("timeout-option");function Qe(e){return typeof e=="object"&&e!==null&&e[ie]===!0}async function Xe(e,r,p,T){let k=new AbortController,a=r.onTimeout??"error",l=()=>typeof a=="function"?a({name:p.name,key:p.key,ms:r.ms}):r.error??{type:"STEP_TIMEOUT",stepName:p.name,stepKey:p.key,timeoutMs:r.ms,attempt:p.attempt},R;T?.aborted&&k.abort(T.reason);let S;T&&!T.aborted&&(S=()=>k.abort(T.reason),T.addEventListener("abort",S,{once:!0}));let M=new Promise((v,t)=>{R=setTimeout(()=>{if(a!=="disconnect"&&k.abort(),a==="option"){t({[ie]:!0,ms:r.ms});return}t({[ve]:!0,error:l()})},r.ms)}),g;r.signal?g=Promise.resolve(e(k.signal)):g=Promise.resolve(e());try{return await Promise.race([g,M])}catch(v){if(typeof v=="object"&&v!==null&&v[ie]===!0)throw{[ie]:!0,ms:r.ms};if(typeof v=="object"&&v!==null&&v[ve]===!0){a==="disconnect"&&g.catch(()=>{});let t=v.error;if(typeof t=="object"&&t!==null&&t.type!=="STEP_TIMEOUT"){let f={timeoutMs:r.ms,stepName:p.name,stepKey:p.key,attempt:p.attempt};te in t?t[te]=f:Object.defineProperty(t,te,{value:f,enumerable:!1,writable:!0,configurable:!1})}throw t}throw v}finally{clearTimeout(R),S&&T&&T.removeEventListener("abort",S)}}var re={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function ye(e,r,p){if(typeof e!="function"){let m=e,B=r;if(typeof B!="function")throw new TypeError("[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))");return ye(({step:G})=>B(Se(m,G),{step:G}),p)}let T=e,k=r,{onError:a,onEvent:l,catchUnexpected:R,workflowId:S,workflowName:M,context:g,_workflowSignal:v}=k&&typeof k=="object"?k:{},t=S??crypto.randomUUID(),f=R??Ve,I=[],K=0,W=m=>m??`step_${++K}`,c=m=>{let B=m.context!==void 0||g===void 0?m:{...m,context:g},H=M!==void 0&&B.workflowName===void 0?{...B,workflowName:M}:B;if(H.type==="step_success"){let G=H.stepId;for(let se=I.length-1;se>=0;se--){let q=I[se];if(q.type==="race"&&!q.winnerId){q.winnerId=G;break}}}l?.(H,g)},N=ze,X=m=>Ye(m),Y=(m,B)=>m,Le=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 B=function(i){let d={};for(let[o,s]of Object.entries(i))if(typeof s=="function")d[o]=s;else if(s&&typeof s=="object"&&"fn"in s)d[o]=s.fn;else throw new TypeError(`step.all: operation "${o}" must be a function or { fn, errors? } object`);return d},H=function(i,d){let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),n=!1;I.push({scopeId:o,type:"parallel"});let u=()=>{if(n)return;n=!0;let E=I.findIndex(y=>y.scopeId===o);E!==-1&&I.splice(E,1),c({type:"scope_end",workflowId:t,scopeId:o,ts:Date.now(),durationMs:performance.now()-s})};c({type:"scope_start",workflowId:t,scopeId:o,scopeType:"parallel",name:i,ts:Date.now()});try{let E=await d();if(u(),!E.ok)throw a?.(E.error,i,g),N(E.error,{origin:"result",resultCause:E.cause});return E.value}catch(E){throw u(),E}})()},G=function(i,d){let o=Object.keys(i),s=d.name??`Parallel(${o.join(", ")})`,n=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let u=performance.now(),E=!1;I.push({scopeId:n,type:"parallel"});let y=()=>{if(E)return;E=!0;let w=I.findIndex(x=>x.scopeId===n);w!==-1&&I.splice(w,1),c({type:"scope_end",workflowId:t,scopeId:n,ts:Date.now(),durationMs:performance.now()-u})};c({type:"scope_start",workflowId:t,scopeId:n,scopeType:"parallel",name:s,ts:Date.now()});try{let w=await new Promise(h=>{if(o.length===0){h([]);return}let O=!1,L=o.length,b=new Array(o.length);for(let U=0;U<o.length;U++){let A=o[U],_=U;Promise.resolve(i[A]()).catch(P=>F({type:"PROMISE_REJECTED",cause:P},{cause:{type:"PROMISE_REJECTION",reason:P}})).then(P=>{if(!O){if(!P.ok){O=!0,h([{key:A,result:P}]);return}b[_]={key:A,result:P},L--,L===0&&h(b)}})}});y();let x={};for(let{key:h,result:O}of w){if(!O.ok)throw a?.(O.error,h,g),N(O.error,{origin:"result",resultCause:O.cause});x[h]=O.value}return x}catch(w){throw y(),w}})()};var nr=B,or=H,sr=G;let m=(i,d,o)=>(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 s=o??{},n=$e(s),u=i,E=s.key??i,y=s.key??i,{description:w,retry:x,timeout:h}=s,O=W(E),L=l,b=L?performance.now():0,A=Le(d)?()=>d:d,P={attempts:Math.max(1,x?.attempts??1),backoff:x?.backoff??re.backoff,initialDelay:x?.initialDelay??re.initialDelay,maxDelay:x?.maxDelay??re.maxDelay,jitter:x?.jitter??re.jitter,shouldRetry:x?.shouldRetry??re.shouldRetry,onRetry:x?.onRetry??re.onRetry};l&&c({type:"step_start",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),...n&&{metadata:n}});let Z;for(let D=1;D<=P.attempts;D++){let Fe=L?performance.now():0;try{let C;if(h?C=await Xe(A,h,{name:u,key:E,attempt:D},v):C=await A(),C.ok){let Q=performance.now()-b;return c({type:"step_success",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),durationMs:Q,...n&&{metadata:n}}),y&&c({type:"step_complete",workflowId:t,stepKey:y,name:u,description:w,ts:Date.now(),durationMs:Q,result:C,...n&&{metadata:n}}),C.value}if(Z=C,D<P.attempts&&P.shouldRetry(C.error,D)){let Q=me(D,P);c({type:"step_retry",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),attempt:D+1,maxAttempts:P.attempts,delayMs:Q,error:C.error,...n&&{metadata:n},diagnostics:V(C.error,s.errorMeta,"result",D,performance.now()-b)}),P.onRetry(C.error,D,Q),await de(Q);continue}P.attempts>1&&c({type:"step_retries_exhausted",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),durationMs:performance.now()-b,attempts:D,lastError:C.error,...n&&{metadata:n},diagnostics:V(C.error,s.errorMeta,"result",D,performance.now()-b)});break}catch(C){let Q=performance.now()-Fe;if(Qe(C)){let z=C.ms;c({type:"step_timeout",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),timeoutMs:z,attempt:D,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"timeout",D)}),c({type:"step_success",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),durationMs:performance.now()-b,...n&&{metadata:n}}),y&&c({type:"step_complete",workflowId:t,stepKey:y,name:u,description:w,ts:Date.now(),durationMs:performance.now()-b,result:$(void 0),...n&&{metadata:n}});return}if(X(C))throw c({type:"step_aborted",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),durationMs:Q,...n&&{metadata:n}}),C;if(Pe(C)){let z=He(C),Ne=h?.ms??z?.timeoutMs??0;if(c({type:"step_timeout",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),timeoutMs:Ne,attempt:D,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"timeout",D)}),D<P.attempts&&P.shouldRetry(C,D)){let Ee=me(D,P);c({type:"step_retry",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),attempt:D+1,maxAttempts:P.attempts,delayMs:Ee,error:C,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"timeout",D,performance.now()-b)}),P.onRetry(C,D,Ee),await de(Ee);continue}P.attempts>1&&c({type:"step_retries_exhausted",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),durationMs:performance.now()-b,attempts:D,lastError:C,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"timeout",D,performance.now()-b)});let pe=performance.now()-b;throw c({type:"step_error",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),durationMs:pe,error:C,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"timeout",D,pe)}),y&&c({type:"step_complete",workflowId:t,stepKey:y,name:u,description:w,ts:Date.now(),durationMs:pe,result:F(C,{cause:C}),meta:{origin:"throw",thrown:C},...n&&{metadata:n}}),a?.(C,u,g),N(C,{origin:"throw",thrown:C})}if(D<P.attempts&&P.shouldRetry(C,D)){let z=me(D,P);c({type:"step_retry",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),attempt:D+1,maxAttempts:P.attempts,delayMs:z,error:C,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"throw",D,performance.now()-b)}),P.onRetry(C,D,z),await de(z);continue}P.attempts>1&&!Pe(C)&&c({type:"step_retries_exhausted",workflowId:t,stepId:O,stepKey:E,name:u,ts:Date.now(),durationMs:performance.now()-b,attempts:D,lastError:C,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"throw",D,performance.now()-b)});let le=performance.now()-b,ne;try{ne=f(C)}catch(z){throw ee(z)}throw c({type:"step_error",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),durationMs:le,error:ne,...n&&{metadata:n},diagnostics:V(C,s.errorMeta,"throw",D,le)}),y&&c({type:"step_complete",workflowId:t,stepKey:y,name:u,description:w,ts:Date.now(),durationMs:le,result:F(ne,{cause:C}),meta:{origin:"throw",thrown:C},...n&&{metadata:n}}),a?.(ne,u,g),N(ne,{origin:"throw",thrown:C})}}let J=Z,ue=performance.now()-b,ce=Y(J.error,{origin:"result",resultCause:J.cause});throw c({type:"step_error",workflowId:t,stepId:O,stepKey:E,name:u,description:w,ts:Date.now(),durationMs:ue,error:ce,...n&&{metadata:n},diagnostics:V(J.error,s.errorMeta,"result",P.attempts,ue)}),y&&c({type:"step_complete",workflowId:t,stepKey:y,name:u,description:w,ts:Date.now(),durationMs:ue,result:J,meta:{origin:"result",resultCause:J.cause},...n&&{metadata:n}}),a?.(ce,u,g),N(ce,{origin:"result",resultCause:J.cause})})();m.try=(i,d,o)=>{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 s="error"in o?()=>o.error:o.onError;if(o.retry||o.timeout)return m.retry(i,async()=>{try{return $(await d())}catch(w){return F(s(w),{cause:w})}},{attempts:o.retry?.attempts??1,...o.retry??{},key:o.key,timeout:o.timeout});let n=o.key??i,u=i,E=i,y=l;return(async()=>{let w=y?performance.now():0;l&&c({type:"step_start",workflowId:t,stepId:E,stepKey:n,name:u,ts:Date.now()});try{let x=await d(),h=performance.now()-w;return c({type:"step_success",workflowId:t,stepId:E,stepKey:n,name:u,ts:Date.now(),durationMs:h}),n&&c({type:"step_complete",workflowId:t,stepKey:n,name:u,ts:Date.now(),durationMs:h,result:$(x)}),x}catch(x){let h=s(x),O=performance.now()-w,L=Y(h,{origin:"throw",thrown:x});throw c({type:"step_error",workflowId:t,stepId:E,stepKey:n,name:u,ts:Date.now(),durationMs:O,error:L}),n&&c({type:"step_complete",workflowId:t,stepKey:n,name:u,ts:Date.now(),durationMs:O,result:F(h,{cause:x}),meta:{origin:"throw",thrown:x}}),a?.(L,u,g),N(L,{origin:"throw",thrown:x})}})()},m.fromResult=(i,d,o)=>{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 s=o.key??i,n=i,u=i,E="error"in o?()=>o.error:o.onError,y=l;return(async()=>{let w=y?performance.now():0;l&&c({type:"step_start",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now()});let x=await d();if(x.ok){let h=performance.now()-w;return c({type:"step_success",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:h}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:h,result:$(x.value)}),x.value}else{let h=E(x.error),O=performance.now()-w,L=Y(h,{origin:"result",resultCause:x.error});throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:O,error:L}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:O,result:F(h,{cause:x.error}),meta:{origin:"result",resultCause:x.error}}),a?.(L,n,g),N(L,{origin:"result",resultCause:x.error})}})()},m.fromNullable=(i,d,o,s)=>{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 n=await d();return n!=null?$(n):F(o())},s)},m.retry=(i,d,o)=>{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,d,{key:o.key??i,retry:{attempts:o.attempts,backoff:o.backoff,initialDelay:o.initialDelay,maxDelay:o.maxDelay,jitter:o.jitter,shouldRetry:o.shouldRetry,onRetry:o.onRetry},timeout:o.timeout})},m.withTimeout=(i,d,o)=>{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,d,{key:o.key??i,timeout:o})},m.sleep=(i,d,o)=>{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 s=typeof d=="string"?Be(d):d;if(!s)throw new Error(`step.sleep: invalid duration '${d}'`);let n=s.millis,u=o?.signal;return m(i,async()=>{if(v?.aborted||u?.aborted){let E=new Error("Sleep aborted");throw E.name="AbortError",E}return new Promise((E,y)=>{let w={timeoutId:void 0},x=()=>{w.timeoutId&&clearTimeout(w.timeoutId);let h=new Error("Sleep aborted");h.name="AbortError",y(h)};v?.addEventListener("abort",x,{once:!0}),u?.addEventListener("abort",x,{once:!0}),w.timeoutId=setTimeout(()=>{v?.removeEventListener("abort",x),u?.removeEventListener("abort",x),E($(void 0))},n)})},{key:o?.key??i,description:o?.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 d=i[0],o=i[1];if(typeof o=="function")return H(d,o);if(o&&typeof o=="object"&&!Array.isArray(o)){let n=B(o);return G(n,{name:d})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),m.race=(i,d)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),n=!1,u={scopeId:o,type:"race",winnerId:void 0};I.push(u);let E=()=>{if(n)return;n=!0;let y=I.findIndex(w=>w.scopeId===o);y!==-1&&I.splice(y,1),c({type:"scope_end",workflowId:t,scopeId:o,ts:Date.now(),durationMs:performance.now()-s,winnerId:u.winnerId})};c({type:"scope_start",workflowId:t,scopeId:o,scopeType:"race",name:i,ts:Date.now()});try{let y=await d();if(E(),!y.ok)throw a?.(y.error,i,g),N(y.error,{origin:"result",resultCause:y.cause});return y.value}catch(y){throw E(),y}})()},m.if=(i,d,o)=>o(),m.label=m.if,m.branch=async(i,d)=>{let{condition:o,then:s,else:n}=d;if(o())return await s();if(n)return await n()},m.arm=(i,d)=>({fn:i,errors:d}),m.forEach=async(i,d,o)=>{let s=[],n=o.maxIterations,u=0,E="run"in o,y=Symbol.asyncIterator in d?d:(async function*(){yield*d})();for await(let w of y){if(n!==void 0&&u>=n)break;let x;E?x=await o.run(w,u):x=await o.item.handler(w,u,m),s.push(x),u++}return s},m.item=i=>({__forEachItemHandler:!0,handler:i}),m.dep=(i,d)=>d,m.workflow=(i,d,o)=>m(i,d,o),m.map=async(i,d,o,s)=>{let n=s?.concurrency??d.length;return m(i,()=>n>=d.length?_e(d.map((u,E)=>o(u,E))):(async()=>{let u=[];for(let E=0;E<d.length;E+=n){let y=d.slice(E,E+n),w=await _e(y.map((x,h)=>o(x,E+h)));if(!w.ok)return w;u.push(...w.value)}return $(u)})(),{key:s?.key})},m.withFallback=(i,d,o)=>{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 s=o.key??i,n=i,u=W(s),E=l;return(async()=>{let y=E?performance.now():0;l&&c({type:"step_start",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now()});let w;try{w=await d()}catch(b){if(X(b))throw c({type:"step_aborted",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:performance.now()-y}),b;let U;try{U=f(b)}catch(_){throw ee(_)}if(o.on!==void 0&&o.on!==U){let _=performance.now()-y;throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:_,error:U}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:_,result:F(U,{cause:b}),meta:{origin:"throw",thrown:b}}),a?.(U,n,g),N(U,{origin:"throw",thrown:b})}let A;try{A=await o.fallback()}catch(_){if(X(_))throw c({type:"step_aborted",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:performance.now()-y}),_;let P;try{P=f(_)}catch(J){throw ee(J)}let Z=performance.now()-y;throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:Z,error:P}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:Z,result:F(P,{cause:_}),meta:{origin:"throw",thrown:_}}),a?.(P,n,g),N(P,{origin:"throw",thrown:_})}if(A.ok){let _=performance.now()-y;return c({type:"step_success",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:_}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:_,result:A,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(U)}}),A.value}else{let _=performance.now()-y,P=Y(A.error,{origin:"result",resultCause:A.cause});throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:_,error:P}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:_,result:A,meta:{origin:"result",resultCause:A.cause}}),a?.(P,n,g),N(P,{origin:"result",resultCause:A.cause})}}if(w.ok){let b=performance.now()-y;return c({type:"step_success",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:b}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:b,result:w}),w.value}let x=w.error;if(o.on!==void 0&&o.on!==x){let b=performance.now()-y,U=Y(x,{origin:"result",resultCause:w.cause});throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:b,error:U}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:b,result:w,meta:{origin:"result",resultCause:w.cause}}),a?.(U,n,g),N(U,{origin:"result",resultCause:w.cause})}let h;try{h=await o.fallback()}catch(b){if(X(b))throw c({type:"step_aborted",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:performance.now()-y}),b;let U;try{U=f(b)}catch(_){throw ee(_)}let A=performance.now()-y;throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:A,error:U}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:A,result:F(U,{cause:b}),meta:{origin:"throw",thrown:b}}),a?.(U,n,g),N(U,{origin:"throw",thrown:b})}if(h.ok){let b=performance.now()-y;return c({type:"step_success",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:b}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:b,result:h,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(x)}}),h.value}let O=performance.now()-y,L=Y(h.error,{origin:"result",resultCause:h.cause});throw c({type:"step_error",workflowId:t,stepId:u,stepKey:s,name:n,ts:Date.now(),durationMs:O,error:L}),s&&c({type:"step_complete",workflowId:t,stepKey:s,name:n,ts:Date.now(),durationMs:O,result:h,meta:{origin:"result",resultCause:h.cause}}),a?.(L,n,g),N(L,{origin:"result",resultCause:h.cause})})()},m.withResource=(i,d)=>{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 o=i,s=i,n=W(o),u=l;return(async()=>{let E=u?performance.now():0;l&&c({type:"step_start",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now()});let y;try{y=await d.acquire()}catch(A){if(X(A))throw c({type:"step_aborted",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now(),durationMs:performance.now()-E}),A;let _;try{_=f(A)}catch(Z){throw ee(Z)}let P=performance.now()-E;throw c({type:"step_error",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now(),durationMs:P,error:_}),o&&c({type:"step_complete",workflowId:t,stepKey:o,name:s,ts:Date.now(),durationMs:P,result:F(_,{cause:A}),meta:{origin:"throw",thrown:A}}),a?.(_,s,g),N(_,{origin:"throw",thrown:A})}if(!y.ok){let A=performance.now()-E,_=Y(y.error,{origin:"result",resultCause:y.cause});throw c({type:"step_error",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now(),durationMs:A,error:_}),o&&c({type:"step_complete",workflowId:t,stepKey:o,name:s,ts:Date.now(),durationMs:A,result:y,meta:{origin:"result",resultCause:y.cause}}),a?.(_,s,g),N(_,{origin:"result",resultCause:y.cause})}let w=y.value,x,h,O=!1;try{x=await d.use(w)}catch(A){if(X(A)){try{await d.release(w)}catch(_){console.warn(`[awaitly] step.withResource("${i}"): release threw after earlyExit:`,_)}throw A}h=A,O=!0}try{await d.release(w)}catch(A){console.warn(`[awaitly] step.withResource("${i}"): release threw:`,A)}if(O){let A;try{A=f(h)}catch(P){throw ee(P)}let _=performance.now()-E;throw c({type:"step_error",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now(),durationMs:_,error:A}),o&&c({type:"step_complete",workflowId:t,stepKey:o,name:s,ts:Date.now(),durationMs:_,result:F(A,{cause:h}),meta:{origin:"throw",thrown:h}}),a?.(A,s,g),N(A,{origin:"throw",thrown:h})}let L=x;if(L.ok){let A=performance.now()-E;return c({type:"step_success",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now(),durationMs:A}),o&&c({type:"step_complete",workflowId:t,stepKey:o,name:s,ts:Date.now(),durationMs:A,result:L}),L.value}let b=performance.now()-E,U=Y(L.error,{origin:"result",resultCause:L.cause});throw c({type:"step_error",workflowId:t,stepId:n,stepKey:o,name:s,ts:Date.now(),durationMs:b,error:U}),o&&c({type:"step_complete",workflowId:t,stepKey:o,name:s,ts:Date.now(),durationMs:b,result:L,meta:{origin:"result",resultCause:L.cause}}),a?.(U,s,g),N(U,{origin:"result",resultCause:L.cause})})()};let q=await T({step:m});if(process.env.NODE_ENV!=="production"&&q!==null&&typeof q=="object"&&"ok"in q&&typeof q.ok=="boolean"){let i=q;(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 $(q)}catch(m){if(Je(m))throw m.thrown;if(X(m)){let H=m.meta.origin==="throw"?m.meta.thrown:m.meta.origin==="result"?m.meta.resultCause:void 0;return F(m.error,{cause:H})}let B=f(m);return a?.(B,"unexpected",g),F(B,{cause:m})}}ye.strict=(e,r)=>ye(e,r);async function _e(e){return e.length===0?$([]):new Promise(r=>{let p=!1,T=e.length,k=new Array(e.length);for(let a=0;a<e.length;a++){let l=a;Promise.resolve(e[l]).catch(R=>F({type:"PROMISE_REJECTED",cause:R},{cause:{type:"PROMISE_REJECTION",reason:R}})).then(R=>{if(!p){if(!R.ok){p=!0,r(R);return}k[l]=R.value,T--,T===0&&r($(k))}})}})}function Ge(e){return typeof e=="object"&&e!==null&&e.type==="RATE_LIMIT_EXCEEDED"}function Ie(e){return typeof e=="object"&&e!==null&&e.type==="QUEUE_FULL"}function De(e,r){let{maxPerSecond:p,strategy:T="wait"}=r,k=r.burstCapacity??p*2,a=k,l=Date.now(),R=p/1e3,S=[];function M(){let t=Date.now(),I=(t-l)*R;a=Math.min(k,a+I),l=t}function g(){if(M(),a>=1)return a-=1,0;let t=1-a;return Math.ceil(t/R)}async function v(){return new Promise(t=>{let f=()=>{let I=g();I===0?t():(S.push(f),setTimeout(()=>{let K=S.indexOf(f);K!==-1&&(S.splice(K,1),f())},I))};f()})}return{async execute(t){let f=g();if(f>0){if(T==="reject")throw{type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:f};await v()}return t()},async executeResult(t){let f=g();if(f>0){if(T==="reject")return F({type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:f});await v()}return t()},getStats(){return M(),{availableTokens:Math.floor(a),maxTokens:k,tokensPerSecond:p,waitingCount:S.length}},reset(){a=k,l=Date.now(),S.length=0}}}function Ue(e,r){let{maxConcurrent:p,strategy:T="queue",maxQueueSize:k=1/0}=r,a=0,l=[];async function R(){if(a<p){a++;return}if(T==="reject")throw{type:"QUEUE_FULL",limiterName:e,queueSize:l.length,maxQueueSize:k};if(l.length>=k)throw{type:"QUEUE_FULL",limiterName:e,queueSize:l.length,maxQueueSize:k};return new Promise((M,g)=>{l.push({resolve:M,reject:g})})}function S(){a--,l.length>0&&a<p&&(a++,l.shift()?.resolve())}return{async execute(M){await R();try{return await M()}finally{S()}},async executeAll(M){let g=new Array(M.length),v=[];for(let t=0;t<M.length;t++){let f=t,I=this.execute(M[f]).then(K=>{g[f]=K});v.push(I)}return await Promise.all(v),g},async executeResult(M){try{await R()}catch(g){if(Ie(g))return F(g);throw g}try{return await M()}finally{S()}},getStats(){return{activeCount:a,maxConcurrent:p,queueSize:l.length,maxQueueSize:k}},reset(){for(a=0;l.length>0;)l.shift()?.reject(new Error("Limiter reset"))}}}function Ze(e,r){let p=r.rate?De(`${e}-rate`,r.rate):void 0,T=r.concurrency?Ue(`${e}-concurrency`,r.concurrency):void 0;return{rate:p,concurrency:T,async execute(k){let a=k;if(p){let l=a;a=()=>p.execute(l)}return T?T.execute(a):a()}}}function er(e,r){let{limit:p,windowMs:T=1e3,strategy:k="wait"}=r,a=Date.now(),l=0,R=[];function S(){let v=Date.now(),t=v-a;return t>=T?(a=v,l=0,0):T-t}function M(v){let t=S();return l+v<=p?(l+=v,0):t}async function g(v){return new Promise(t=>{let f=()=>{let I=M(v);I===0?t():(R.push({resolve:f,cost:v}),setTimeout(()=>{let K=R.findIndex(W=>W.resolve===f);K!==-1&&(R.splice(K,1),f())},I))};f()})}return{async execute(v,t=1){if(t>p)throw{type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:T};let f=M(t);if(f>0){if(k==="reject")throw{type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:f};await g(t)}return v()},async executeResult(v,t=1){if(t>p)return F({type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:T});let f=M(t);if(f>0){if(k==="reject")return F({type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:f});await g(t)}return v()},getStats(){let v=S();return{requestCount:l,limit:p,windowMs:T,remainingMs:v,waitingCount:R.length}},reset(){a=Date.now(),l=0,R.length=0}}}function rr(e,r){let{tokensPerSecond:p,strategy:T="wait"}=r,k=r.maxTokens??p*2,a=k,l=Date.now(),R=p/1e3,S=[];function M(){let t=Date.now(),I=(t-l)*R;a=Math.min(k,a+I),l=t}function g(t){if(M(),a>=t)return a-=t,0;let f=t-a;return Math.ceil(f/R)}async function v(t){return new Promise(f=>{let I=()=>{let K=g(t);K===0?f():(S.push({check:I,cost:t}),setTimeout(()=>{let W=S.findIndex(c=>c.check===I);W!==-1&&(S.splice(W,1),I())},K))};I()})}return{async execute(t,f=1){if(f>k)throw{type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:Math.ceil(f/R)};let I=g(f);if(I>0){if(T==="reject")throw{type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:I};await v(f)}return t()},async executeResult(t,f=1){if(f>k)return F({type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:Math.ceil(f/R)});let I=g(f);if(I>0){if(T==="reject")return F({type:"RATE_LIMIT_EXCEEDED",limiterName:e,retryAfterMs:I});await v(f)}return t()},getStats(){return M(),{availableTokens:a,maxTokens:k,tokensPerSecond:p,waitingCount:S.length}},reset(){a=k,l=Date.now(),S.length=0}}}var tr={api:{maxPerSecond:10,burstCapacity:20,strategy:"wait"},database:{maxConcurrent:10,strategy:"queue",maxQueueSize:100},external:{maxPerSecond:5,burstCapacity:10,strategy:"wait"}};export{Ze as createCombinedLimiter,Ue as createConcurrencyLimiter,rr as createCostBasedRateLimiter,er as createFixedWindowLimiter,De as createRateLimiter,Ie as isQueueFullError,Ge as isRateLimitExceededError,tr as rateLimiterPresets};
|
|
7
|
-
//# sourceMappingURL=ratelimit.js.map
|