awaitly 1.34.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 +35 -5
- package/dist/result.d.ts +35 -5
- 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-D2MmJFj9.d.cts → types-B8NfNRGX.d.ts} +1152 -1499
- package/dist/{run-entry-Dduz-is2.d.ts → types-BZ2f4MRR.d.cts} +1152 -1499
- 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 +13 -178
- 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-COl5oFnR.d.cts +0 -15
- package/dist/di-CyDj_JyZ.d.ts +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-BodHXLzX.d.cts +0 -72
- package/dist/guards-CeWoQ8fn.d.ts +0 -72
- package/dist/hitl-BPE_1UiM.d.cts +0 -468
- package/dist/hitl-byp570uC.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-BYT3amEz.d.ts +0 -417
- package/dist/index-C_ak66jy.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-DOMx3woy.d.ts +0 -822
- package/dist/persistence-entry-ymCA4iDu.d.cts +0 -822
- 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-DQmzO9f4.d.ts +0 -323
- package/dist/types-qBUOYi-4.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/policies.d.ts
DELETED
|
@@ -1,379 +0,0 @@
|
|
|
1
|
-
import { ai as StepOptions, af as RetryOptions, aq as TimeoutOptions } from './run-entry-Dduz-is2.js';
|
|
2
|
-
import './errors.js';
|
|
3
|
-
import './tagged-error.js';
|
|
4
|
-
import './slugs.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* awaitly/policies
|
|
8
|
-
*
|
|
9
|
-
* Policy-Driven Step Middleware - Reusable bundles of StepOptions
|
|
10
|
-
* that can be composed and applied per-workflow or per-step.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* A policy is a partial StepOptions that can be merged with other policies.
|
|
15
|
-
*/
|
|
16
|
-
type Policy = Partial<StepOptions>;
|
|
17
|
-
/**
|
|
18
|
-
* A policy factory that creates policies based on context.
|
|
19
|
-
*/
|
|
20
|
-
type PolicyFactory<T = void> = T extends void ? () => Policy : (context: T) => Policy;
|
|
21
|
-
/**
|
|
22
|
-
* Named policy with metadata.
|
|
23
|
-
*/
|
|
24
|
-
interface NamedPolicy {
|
|
25
|
-
name: string;
|
|
26
|
-
policy: Policy;
|
|
27
|
-
description?: string;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Merge multiple policies into a single StepOptions object.
|
|
31
|
-
* Later policies override earlier ones for conflicting properties.
|
|
32
|
-
* Retry and timeout options are deep-merged.
|
|
33
|
-
*
|
|
34
|
-
* @param policies - Policies to merge (in order of precedence)
|
|
35
|
-
* @returns Merged StepOptions
|
|
36
|
-
*
|
|
37
|
-
* @example
|
|
38
|
-
* ```typescript
|
|
39
|
-
* const merged = mergePolicies(
|
|
40
|
-
* timeoutPolicies.api, // timeout: 5000ms
|
|
41
|
-
* retryPolicies.transient, // retry: 3 attempts
|
|
42
|
-
* { name: 'fetch-user' } // name override
|
|
43
|
-
* );
|
|
44
|
-
* ```
|
|
45
|
-
*/
|
|
46
|
-
declare function mergePolicies(...policies: Policy[]): StepOptions;
|
|
47
|
-
/**
|
|
48
|
-
* Create a policy applier that merges base policies with step-specific options.
|
|
49
|
-
*
|
|
50
|
-
* @param basePolicies - Base policies to apply to all steps
|
|
51
|
-
* @returns A function that applies policies to step options
|
|
52
|
-
*
|
|
53
|
-
* @example
|
|
54
|
-
* ```typescript
|
|
55
|
-
* const applyPolicy = createPolicyApplier(
|
|
56
|
-
* timeoutPolicies.api,
|
|
57
|
-
* retryPolicies.transient
|
|
58
|
-
* );
|
|
59
|
-
*
|
|
60
|
-
* // In workflow
|
|
61
|
-
* const user = await step(
|
|
62
|
-
* 'fetch-user',
|
|
63
|
-
* () => fetchUser(id),
|
|
64
|
-
* applyPolicy({ key: 'user:' + id })
|
|
65
|
-
* );
|
|
66
|
-
* ```
|
|
67
|
-
*/
|
|
68
|
-
declare function createPolicyApplier(...basePolicies: Policy[]): (stepOptions?: StepOptions) => StepOptions;
|
|
69
|
-
/**
|
|
70
|
-
* Create a named policy bundle for reuse across workflows.
|
|
71
|
-
*
|
|
72
|
-
* @param name - Policy bundle name
|
|
73
|
-
* @param policies - Policies to include in the bundle
|
|
74
|
-
* @returns Named policy object
|
|
75
|
-
*/
|
|
76
|
-
declare function createPolicyBundle(name: string, ...policies: Policy[]): NamedPolicy;
|
|
77
|
-
/**
|
|
78
|
-
* Create a retry policy with the given options.
|
|
79
|
-
*/
|
|
80
|
-
declare function retryPolicy(options: RetryOptions): Policy;
|
|
81
|
-
/**
|
|
82
|
-
* Pre-built retry policies for common scenarios.
|
|
83
|
-
*/
|
|
84
|
-
declare const retryPolicies: {
|
|
85
|
-
/**
|
|
86
|
-
* No retry - fail immediately on error.
|
|
87
|
-
*/
|
|
88
|
-
readonly none: Partial<StepOptions>;
|
|
89
|
-
/**
|
|
90
|
-
* Quick retry for transient errors (3 attempts, fast backoff).
|
|
91
|
-
*/
|
|
92
|
-
readonly transient: Partial<StepOptions>;
|
|
93
|
-
/**
|
|
94
|
-
* Standard retry for API calls (3 attempts, moderate backoff).
|
|
95
|
-
*/
|
|
96
|
-
readonly standard: Partial<StepOptions>;
|
|
97
|
-
/**
|
|
98
|
-
* Aggressive retry for critical operations (5 attempts, longer backoff).
|
|
99
|
-
*/
|
|
100
|
-
readonly aggressive: Partial<StepOptions>;
|
|
101
|
-
/**
|
|
102
|
-
* Fixed interval retry (useful for polling).
|
|
103
|
-
*/
|
|
104
|
-
readonly fixed: (attempts: number, delayMs: number) => Policy;
|
|
105
|
-
/**
|
|
106
|
-
* Linear backoff retry.
|
|
107
|
-
*/
|
|
108
|
-
readonly linear: (attempts: number, initialDelay: number) => Policy;
|
|
109
|
-
/**
|
|
110
|
-
* Custom retry policy builder.
|
|
111
|
-
*/
|
|
112
|
-
readonly custom: (options: Partial<RetryOptions> & {
|
|
113
|
-
attempts: number;
|
|
114
|
-
}) => Policy;
|
|
115
|
-
};
|
|
116
|
-
/**
|
|
117
|
-
* Create a timeout policy with the given options.
|
|
118
|
-
*/
|
|
119
|
-
declare function timeoutPolicy(options: TimeoutOptions): Policy;
|
|
120
|
-
/**
|
|
121
|
-
* Pre-built timeout policies for common scenarios.
|
|
122
|
-
*/
|
|
123
|
-
declare const timeoutPolicies: {
|
|
124
|
-
/**
|
|
125
|
-
* No timeout.
|
|
126
|
-
*/
|
|
127
|
-
readonly none: Policy;
|
|
128
|
-
/**
|
|
129
|
-
* Fast timeout for quick operations (1 second).
|
|
130
|
-
*/
|
|
131
|
-
readonly fast: Partial<StepOptions>;
|
|
132
|
-
/**
|
|
133
|
-
* Standard API timeout (5 seconds).
|
|
134
|
-
*/
|
|
135
|
-
readonly api: Partial<StepOptions>;
|
|
136
|
-
/**
|
|
137
|
-
* Extended timeout for slower operations (30 seconds).
|
|
138
|
-
*/
|
|
139
|
-
readonly extended: Partial<StepOptions>;
|
|
140
|
-
/**
|
|
141
|
-
* Long timeout for batch operations (2 minutes).
|
|
142
|
-
*/
|
|
143
|
-
readonly long: Partial<StepOptions>;
|
|
144
|
-
/**
|
|
145
|
-
* Custom timeout in milliseconds.
|
|
146
|
-
*/
|
|
147
|
-
readonly ms: (ms: number) => Policy;
|
|
148
|
-
/**
|
|
149
|
-
* Custom timeout in seconds.
|
|
150
|
-
*/
|
|
151
|
-
readonly seconds: (seconds: number) => Policy;
|
|
152
|
-
/**
|
|
153
|
-
* Timeout with custom error.
|
|
154
|
-
*/
|
|
155
|
-
readonly withError: <E>(ms: number, error: E) => Policy;
|
|
156
|
-
/**
|
|
157
|
-
* Timeout with AbortSignal support.
|
|
158
|
-
*/
|
|
159
|
-
readonly withSignal: (ms: number) => Policy;
|
|
160
|
-
};
|
|
161
|
-
/**
|
|
162
|
-
* Pre-built combined policies for common service patterns.
|
|
163
|
-
*/
|
|
164
|
-
declare const servicePolicies: {
|
|
165
|
-
/**
|
|
166
|
-
* Policy for external HTTP APIs.
|
|
167
|
-
* - 5 second timeout
|
|
168
|
-
* - 3 retries with exponential backoff
|
|
169
|
-
*/
|
|
170
|
-
readonly httpApi: StepOptions;
|
|
171
|
-
/**
|
|
172
|
-
* Policy for database operations.
|
|
173
|
-
* - 30 second timeout
|
|
174
|
-
* - 2 retries for transient errors
|
|
175
|
-
*/
|
|
176
|
-
readonly database: StepOptions;
|
|
177
|
-
/**
|
|
178
|
-
* Policy for cache operations.
|
|
179
|
-
* - 1 second timeout
|
|
180
|
-
* - No retry (cache misses are not errors)
|
|
181
|
-
*/
|
|
182
|
-
readonly cache: StepOptions;
|
|
183
|
-
/**
|
|
184
|
-
* Policy for message queue operations.
|
|
185
|
-
* - 30 second timeout
|
|
186
|
-
* - 5 retries with longer backoff
|
|
187
|
-
*/
|
|
188
|
-
readonly messageQueue: StepOptions;
|
|
189
|
-
/**
|
|
190
|
-
* Policy for file operations.
|
|
191
|
-
* - 2 minute timeout
|
|
192
|
-
* - 3 retries
|
|
193
|
-
*/
|
|
194
|
-
readonly fileSystem: StepOptions;
|
|
195
|
-
/**
|
|
196
|
-
* Policy for third-party services with rate limits.
|
|
197
|
-
* - 10 second timeout
|
|
198
|
-
* - 5 retries with linear backoff
|
|
199
|
-
*/
|
|
200
|
-
readonly rateLimited: StepOptions;
|
|
201
|
-
};
|
|
202
|
-
/**
|
|
203
|
-
* Options for withPolicies workflow wrapper.
|
|
204
|
-
*/
|
|
205
|
-
interface WithPoliciesOptions {
|
|
206
|
-
/**
|
|
207
|
-
* Base policies applied to all steps.
|
|
208
|
-
*/
|
|
209
|
-
policies: Policy[];
|
|
210
|
-
/**
|
|
211
|
-
* Step-specific policy overrides by name or key pattern.
|
|
212
|
-
*/
|
|
213
|
-
overrides?: Record<string, Policy>;
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Create step options with policies applied.
|
|
217
|
-
* This is a helper for applying policies inline.
|
|
218
|
-
*
|
|
219
|
-
* @param policies - Policies to apply
|
|
220
|
-
* @param stepOptions - Step-specific options
|
|
221
|
-
* @returns Merged StepOptions
|
|
222
|
-
*
|
|
223
|
-
* @example
|
|
224
|
-
* ```typescript
|
|
225
|
-
* const user = await step(
|
|
226
|
-
* () => fetchUser(id),
|
|
227
|
-
* withPolicy(servicePolicies.httpApi, { name: 'fetch-user' })
|
|
228
|
-
* );
|
|
229
|
-
* ```
|
|
230
|
-
*/
|
|
231
|
-
declare function withPolicy(policy: Policy, stepOptions?: StepOptions): StepOptions;
|
|
232
|
-
/**
|
|
233
|
-
* Create step options with multiple policies applied.
|
|
234
|
-
*
|
|
235
|
-
* @param policies - Policies to apply (in order)
|
|
236
|
-
* @param stepOptions - Step-specific options
|
|
237
|
-
* @returns Merged StepOptions
|
|
238
|
-
*
|
|
239
|
-
* @example
|
|
240
|
-
* ```typescript
|
|
241
|
-
* const user = await step(
|
|
242
|
-
* 'fetch-user',
|
|
243
|
-
* () => fetchUser(id),
|
|
244
|
-
* withPolicies([timeoutPolicies.api, retryPolicies.standard])
|
|
245
|
-
* );
|
|
246
|
-
* ```
|
|
247
|
-
*/
|
|
248
|
-
declare function withPolicies(policies: Policy[], stepOptions?: StepOptions): StepOptions;
|
|
249
|
-
/**
|
|
250
|
-
* Create a policy that applies conditionally.
|
|
251
|
-
*
|
|
252
|
-
* @param condition - Condition to check
|
|
253
|
-
* @param policy - Policy to apply if condition is true
|
|
254
|
-
* @param elsePolicy - Policy to apply if condition is false (optional)
|
|
255
|
-
* @returns The selected policy
|
|
256
|
-
*
|
|
257
|
-
* @example
|
|
258
|
-
* ```typescript
|
|
259
|
-
* const policy = conditionalPolicy(
|
|
260
|
-
* isProduction,
|
|
261
|
-
* servicePolicies.httpApi, // Use in production
|
|
262
|
-
* retryPolicies.none // Skip in development
|
|
263
|
-
* );
|
|
264
|
-
* ```
|
|
265
|
-
*/
|
|
266
|
-
declare function conditionalPolicy(condition: boolean, policy: Policy, elsePolicy?: Policy): Policy;
|
|
267
|
-
/**
|
|
268
|
-
* Create a policy based on environment.
|
|
269
|
-
*
|
|
270
|
-
* @param envPolicies - Map of environment names to policies
|
|
271
|
-
* @param currentEnv - Current environment (defaults to NODE_ENV)
|
|
272
|
-
* @param defaultPolicy - Default policy if environment not found
|
|
273
|
-
* @returns The selected policy
|
|
274
|
-
*
|
|
275
|
-
* @example
|
|
276
|
-
* ```typescript
|
|
277
|
-
* const policy = envPolicy({
|
|
278
|
-
* production: servicePolicies.httpApi,
|
|
279
|
-
* development: retryPolicies.none,
|
|
280
|
-
* test: retryPolicies.none,
|
|
281
|
-
* });
|
|
282
|
-
* ```
|
|
283
|
-
*/
|
|
284
|
-
declare function envPolicy(envPolicies: Record<string, Policy>, currentEnv?: string, defaultPolicy?: Policy): Policy;
|
|
285
|
-
/**
|
|
286
|
-
* A registry for managing named policies.
|
|
287
|
-
*/
|
|
288
|
-
interface PolicyRegistry {
|
|
289
|
-
/**
|
|
290
|
-
* Register a named policy.
|
|
291
|
-
*/
|
|
292
|
-
register(name: string, policy: Policy): void;
|
|
293
|
-
/**
|
|
294
|
-
* Get a policy by name.
|
|
295
|
-
*/
|
|
296
|
-
get(name: string): Policy | undefined;
|
|
297
|
-
/**
|
|
298
|
-
* Check if a policy exists.
|
|
299
|
-
*/
|
|
300
|
-
has(name: string): boolean;
|
|
301
|
-
/**
|
|
302
|
-
* Get all registered policy names.
|
|
303
|
-
*/
|
|
304
|
-
names(): string[];
|
|
305
|
-
/**
|
|
306
|
-
* Create step options using a registered policy.
|
|
307
|
-
*/
|
|
308
|
-
apply(policyName: string, stepOptions?: StepOptions): StepOptions;
|
|
309
|
-
}
|
|
310
|
-
/**
|
|
311
|
-
* Create a policy registry for managing named policies.
|
|
312
|
-
*
|
|
313
|
-
* @returns PolicyRegistry instance
|
|
314
|
-
*
|
|
315
|
-
* @example
|
|
316
|
-
* ```typescript
|
|
317
|
-
* const registry = createPolicyRegistry();
|
|
318
|
-
*
|
|
319
|
-
* // Register policies
|
|
320
|
-
* registry.register('api', servicePolicies.httpApi);
|
|
321
|
-
* registry.register('db', servicePolicies.database);
|
|
322
|
-
*
|
|
323
|
-
* // Use in workflow
|
|
324
|
-
* const user = await step(
|
|
325
|
-
* 'fetch-user',
|
|
326
|
-
* () => fetchUser(id),
|
|
327
|
-
* registry.apply('api')
|
|
328
|
-
* );
|
|
329
|
-
* ```
|
|
330
|
-
*/
|
|
331
|
-
declare function createPolicyRegistry(): PolicyRegistry;
|
|
332
|
-
/**
|
|
333
|
-
* Fluent builder for constructing step options.
|
|
334
|
-
*/
|
|
335
|
-
interface StepOptionsBuilder {
|
|
336
|
-
/**
|
|
337
|
-
* Set step key for caching.
|
|
338
|
-
*/
|
|
339
|
-
key(key: string): StepOptionsBuilder;
|
|
340
|
-
/**
|
|
341
|
-
* Apply a policy.
|
|
342
|
-
*/
|
|
343
|
-
policy(policy: Policy): StepOptionsBuilder;
|
|
344
|
-
/**
|
|
345
|
-
* Set timeout in milliseconds.
|
|
346
|
-
*/
|
|
347
|
-
timeout(ms: number): StepOptionsBuilder;
|
|
348
|
-
/**
|
|
349
|
-
* Set retry options.
|
|
350
|
-
*/
|
|
351
|
-
retry(options: RetryOptions): StepOptionsBuilder;
|
|
352
|
-
/**
|
|
353
|
-
* Set retry attempts (with default exponential backoff).
|
|
354
|
-
*/
|
|
355
|
-
retries(attempts: number): StepOptionsBuilder;
|
|
356
|
-
/**
|
|
357
|
-
* Build the final StepOptions.
|
|
358
|
-
*/
|
|
359
|
-
build(): StepOptions;
|
|
360
|
-
}
|
|
361
|
-
/**
|
|
362
|
-
* Create a fluent builder for step options.
|
|
363
|
-
*
|
|
364
|
-
* @returns StepOptionsBuilder instance
|
|
365
|
-
*
|
|
366
|
-
* @example
|
|
367
|
-
* ```typescript
|
|
368
|
-
* const options = stepOptions()
|
|
369
|
-
* .key('user:123')
|
|
370
|
-
* .timeout(5000)
|
|
371
|
-
* .retries(3)
|
|
372
|
-
* .build();
|
|
373
|
-
*
|
|
374
|
-
* const user = await step('fetch-user', () => fetchUser(id), options);
|
|
375
|
-
* ```
|
|
376
|
-
*/
|
|
377
|
-
declare function stepOptions(): StepOptionsBuilder;
|
|
378
|
-
|
|
379
|
-
export { type NamedPolicy, type Policy, type PolicyFactory, type PolicyRegistry, type StepOptionsBuilder, type WithPoliciesOptions, conditionalPolicy, createPolicyApplier, createPolicyBundle, createPolicyRegistry, envPolicy, mergePolicies, retryPolicies, retryPolicy, servicePolicies, stepOptions, timeoutPolicies, timeoutPolicy, withPolicies, withPolicy };
|
package/dist/policies.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function o(...t){let e={};for(let i of t)i.key!==void 0&&(e.key=i.key),i.retry!==void 0&&(e.retry=e.retry?{...e.retry,...i.retry}:{...i.retry}),i.timeout!==void 0&&(e.timeout=e.timeout?{...e.timeout,...i.timeout}:{...i.timeout});return e}function y(...t){let e=o(...t);return i=>o(e,i??{})}function a(t,...e){return{name:t,policy:o(...e)}}function n(t){return{retry:t}}var p={none:n({attempts:1}),transient:n({attempts:3,backoff:"exponential",initialDelay:100,maxDelay:1e3,jitter:!0}),standard:n({attempts:3,backoff:"exponential",initialDelay:200,maxDelay:5e3,jitter:!0}),aggressive:n({attempts:5,backoff:"exponential",initialDelay:500,maxDelay:3e4,jitter:!0}),fixed:(t,e)=>n({attempts:t,backoff:"fixed",initialDelay:e,jitter:!1}),linear:(t,e)=>n({attempts:t,backoff:"linear",initialDelay:e,jitter:!0}),custom:t=>n({backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,...t})};function r(t){return{timeout:t}}var s={none:{},fast:r({ms:1e3}),api:r({ms:5e3}),extended:r({ms:3e4}),long:r({ms:12e4}),ms:t=>r({ms:t}),seconds:t=>r({ms:t*1e3}),withError:(t,e)=>r({ms:t,error:e}),withSignal:t=>r({ms:t,signal:!0})},u={httpApi:o(s.api,p.standard),database:o(s.extended,n({attempts:2,backoff:"exponential",initialDelay:100,maxDelay:2e3,jitter:!0})),cache:o(s.fast,p.none),messageQueue:o(s.extended,p.aggressive),fileSystem:o(s.long,p.standard),rateLimited:o(r({ms:1e4}),n({attempts:5,backoff:"linear",initialDelay:1e3,maxDelay:1e4,jitter:!0}))};function l(t,e){return o(t,e??{})}function P(t,e){let i=e??{};return o(...t,i)}function m(t,e,i={}){return t?e:i}function d(t,e=process.env.NODE_ENV??"development",i={}){return t[e]??i}function f(){let t=new Map;return{register(e,i){t.set(e,i)},get(e){return t.get(e)},has(e){return t.has(e)},names(){return Array.from(t.keys())},apply(e,i){let c=t.get(e);if(!c)throw new Error(`Policy not found: ${e}`);return l(c,i)}}}function g(){let t=[],e={key(i){return t.push({key:i}),e},policy(i){return t.push(i),e},timeout(i){return t.push(r({ms:i})),e},retry(i){return t.push(n(i)),e},retries(i){return t.push(p.custom({attempts:i})),e},build(){return o(...t)}};return e}export{m as conditionalPolicy,y as createPolicyApplier,a as createPolicyBundle,f as createPolicyRegistry,d as envPolicy,o as mergePolicies,p as retryPolicies,n as retryPolicy,u as servicePolicies,g as stepOptions,s as timeoutPolicies,r as timeoutPolicy,P as withPolicies,l as withPolicy};
|
|
2
|
-
//# sourceMappingURL=policies.js.map
|
package/dist/policies.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/policies.ts"],"sourcesContent":["/**\n * awaitly/policies\n *\n * Policy-Driven Step Middleware - Reusable bundles of StepOptions\n * that can be composed and applied per-workflow or per-step.\n */\n\nimport type { StepOptions, RetryOptions, TimeoutOptions } from \"./core\";\n\n// =============================================================================\n// Policy Types\n// =============================================================================\n\n/**\n * A policy is a partial StepOptions that can be merged with other policies.\n */\nexport type Policy = Partial<StepOptions>;\n\n/**\n * A policy factory that creates policies based on context.\n */\nexport type PolicyFactory<T = void> = T extends void\n ? () => Policy\n : (context: T) => Policy;\n\n/**\n * Named policy with metadata.\n */\nexport interface NamedPolicy {\n name: string;\n policy: Policy;\n description?: string;\n}\n\n// =============================================================================\n// Policy Composition\n// =============================================================================\n\n/**\n * Merge multiple policies into a single StepOptions object.\n * Later policies override earlier ones for conflicting properties.\n * Retry and timeout options are deep-merged.\n *\n * @param policies - Policies to merge (in order of precedence)\n * @returns Merged StepOptions\n *\n * @example\n * ```typescript\n * const merged = mergePolicies(\n * timeoutPolicies.api, // timeout: 5000ms\n * retryPolicies.transient, // retry: 3 attempts\n * { name: 'fetch-user' } // name override\n * );\n * ```\n */\nexport function mergePolicies(...policies: Policy[]): StepOptions {\n const result: StepOptions = {};\n\n for (const policy of policies) {\n if (policy.key !== undefined) result.key = policy.key;\n\n // Deep merge retry options\n if (policy.retry !== undefined) {\n result.retry = result.retry\n ? { ...result.retry, ...policy.retry }\n : { ...policy.retry };\n }\n\n // Deep merge timeout options\n if (policy.timeout !== undefined) {\n result.timeout = result.timeout\n ? { ...result.timeout, ...policy.timeout }\n : { ...policy.timeout };\n }\n }\n\n return result;\n}\n\n/**\n * Create a policy applier that merges base policies with step-specific options.\n *\n * @param basePolicies - Base policies to apply to all steps\n * @returns A function that applies policies to step options\n *\n * @example\n * ```typescript\n * const applyPolicy = createPolicyApplier(\n * timeoutPolicies.api,\n * retryPolicies.transient\n * );\n *\n * // In workflow\n * const user = await step(\n * 'fetch-user',\n * () => fetchUser(id),\n * applyPolicy({ key: 'user:' + id })\n * );\n * ```\n */\nexport function createPolicyApplier(\n ...basePolicies: Policy[]\n): (stepOptions?: StepOptions) => StepOptions {\n const basePolicy = mergePolicies(...basePolicies);\n\n return (stepOptions?: StepOptions): StepOptions => {\n const opts = stepOptions ?? {};\n return mergePolicies(basePolicy, opts);\n };\n}\n\n/**\n * Create a named policy bundle for reuse across workflows.\n *\n * @param name - Policy bundle name\n * @param policies - Policies to include in the bundle\n * @returns Named policy object\n */\nexport function createPolicyBundle(\n name: string,\n ...policies: Policy[]\n): NamedPolicy {\n return {\n name,\n policy: mergePolicies(...policies),\n };\n}\n\n// =============================================================================\n// Retry Policies\n// =============================================================================\n\n/**\n * Create a retry policy with the given options.\n */\nexport function retryPolicy(options: RetryOptions): Policy {\n return { retry: options };\n}\n\n/**\n * Pre-built retry policies for common scenarios.\n */\nexport const retryPolicies = {\n /**\n * No retry - fail immediately on error.\n */\n none: retryPolicy({ attempts: 1 }),\n\n /**\n * Quick retry for transient errors (3 attempts, fast backoff).\n */\n transient: retryPolicy({\n attempts: 3,\n backoff: \"exponential\",\n initialDelay: 100,\n maxDelay: 1000,\n jitter: true,\n }),\n\n /**\n * Standard retry for API calls (3 attempts, moderate backoff).\n */\n standard: retryPolicy({\n attempts: 3,\n backoff: \"exponential\",\n initialDelay: 200,\n maxDelay: 5000,\n jitter: true,\n }),\n\n /**\n * Aggressive retry for critical operations (5 attempts, longer backoff).\n */\n aggressive: retryPolicy({\n attempts: 5,\n backoff: \"exponential\",\n initialDelay: 500,\n maxDelay: 30000,\n jitter: true,\n }),\n\n /**\n * Fixed interval retry (useful for polling).\n */\n fixed: (attempts: number, delayMs: number): Policy =>\n retryPolicy({\n attempts,\n backoff: \"fixed\",\n initialDelay: delayMs,\n jitter: false,\n }),\n\n /**\n * Linear backoff retry.\n */\n linear: (attempts: number, initialDelay: number): Policy =>\n retryPolicy({\n attempts,\n backoff: \"linear\",\n initialDelay,\n jitter: true,\n }),\n\n /**\n * Custom retry policy builder.\n */\n custom: (options: Partial<RetryOptions> & { attempts: number }): Policy =>\n retryPolicy({\n backoff: \"exponential\",\n initialDelay: 100,\n maxDelay: 30000,\n jitter: true,\n ...options,\n }),\n} as const;\n\n// =============================================================================\n// Timeout Policies\n// =============================================================================\n\n/**\n * Create a timeout policy with the given options.\n */\nexport function timeoutPolicy(options: TimeoutOptions): Policy {\n return { timeout: options };\n}\n\n/**\n * Pre-built timeout policies for common scenarios.\n */\nexport const timeoutPolicies = {\n /**\n * No timeout.\n */\n none: {} as Policy,\n\n /**\n * Fast timeout for quick operations (1 second).\n */\n fast: timeoutPolicy({ ms: 1000 }),\n\n /**\n * Standard API timeout (5 seconds).\n */\n api: timeoutPolicy({ ms: 5000 }),\n\n /**\n * Extended timeout for slower operations (30 seconds).\n */\n extended: timeoutPolicy({ ms: 30000 }),\n\n /**\n * Long timeout for batch operations (2 minutes).\n */\n long: timeoutPolicy({ ms: 120000 }),\n\n /**\n * Custom timeout in milliseconds.\n */\n ms: (ms: number): Policy => timeoutPolicy({ ms }),\n\n /**\n * Custom timeout in seconds.\n */\n seconds: (seconds: number): Policy => timeoutPolicy({ ms: seconds * 1000 }),\n\n /**\n * Timeout with custom error.\n */\n withError: <E>(ms: number, error: E): Policy =>\n timeoutPolicy({ ms, error }),\n\n /**\n * Timeout with AbortSignal support.\n */\n withSignal: (ms: number): Policy =>\n timeoutPolicy({ ms, signal: true }),\n} as const;\n\n// =============================================================================\n// Combined Policies\n// =============================================================================\n\n/**\n * Pre-built combined policies for common service patterns.\n */\nexport const servicePolicies = {\n /**\n * Policy for external HTTP APIs.\n * - 5 second timeout\n * - 3 retries with exponential backoff\n */\n httpApi: mergePolicies(\n timeoutPolicies.api,\n retryPolicies.standard\n ),\n\n /**\n * Policy for database operations.\n * - 30 second timeout\n * - 2 retries for transient errors\n */\n database: mergePolicies(\n timeoutPolicies.extended,\n retryPolicy({\n attempts: 2,\n backoff: \"exponential\",\n initialDelay: 100,\n maxDelay: 2000,\n jitter: true,\n })\n ),\n\n /**\n * Policy for cache operations.\n * - 1 second timeout\n * - No retry (cache misses are not errors)\n */\n cache: mergePolicies(\n timeoutPolicies.fast,\n retryPolicies.none\n ),\n\n /**\n * Policy for message queue operations.\n * - 30 second timeout\n * - 5 retries with longer backoff\n */\n messageQueue: mergePolicies(\n timeoutPolicies.extended,\n retryPolicies.aggressive\n ),\n\n /**\n * Policy for file operations.\n * - 2 minute timeout\n * - 3 retries\n */\n fileSystem: mergePolicies(\n timeoutPolicies.long,\n retryPolicies.standard\n ),\n\n /**\n * Policy for third-party services with rate limits.\n * - 10 second timeout\n * - 5 retries with linear backoff\n */\n rateLimited: mergePolicies(\n timeoutPolicy({ ms: 10000 }),\n retryPolicy({\n attempts: 5,\n backoff: \"linear\",\n initialDelay: 1000,\n maxDelay: 10000,\n jitter: true,\n })\n ),\n} as const;\n\n// =============================================================================\n// Policy Decorators\n// =============================================================================\n\n/**\n * Options for withPolicies workflow wrapper.\n */\nexport interface WithPoliciesOptions {\n /**\n * Base policies applied to all steps.\n */\n policies: Policy[];\n\n /**\n * Step-specific policy overrides by name or key pattern.\n */\n overrides?: Record<string, Policy>;\n}\n\n/**\n * Create step options with policies applied.\n * This is a helper for applying policies inline.\n *\n * @param policies - Policies to apply\n * @param stepOptions - Step-specific options\n * @returns Merged StepOptions\n *\n * @example\n * ```typescript\n * const user = await step(\n * () => fetchUser(id),\n * withPolicy(servicePolicies.httpApi, { name: 'fetch-user' })\n * );\n * ```\n */\nexport function withPolicy(\n policy: Policy,\n stepOptions?: StepOptions\n): StepOptions {\n const opts = stepOptions ?? {};\n return mergePolicies(policy, opts);\n}\n\n/**\n * Create step options with multiple policies applied.\n *\n * @param policies - Policies to apply (in order)\n * @param stepOptions - Step-specific options\n * @returns Merged StepOptions\n *\n * @example\n * ```typescript\n * const user = await step(\n * 'fetch-user',\n * () => fetchUser(id),\n * withPolicies([timeoutPolicies.api, retryPolicies.standard])\n * );\n * ```\n */\nexport function withPolicies(\n policies: Policy[],\n stepOptions?: StepOptions\n): StepOptions {\n const opts = stepOptions ?? {};\n return mergePolicies(...policies, opts);\n}\n\n// =============================================================================\n// Conditional Policies\n// =============================================================================\n\n/**\n * Create a policy that applies conditionally.\n *\n * @param condition - Condition to check\n * @param policy - Policy to apply if condition is true\n * @param elsePolicy - Policy to apply if condition is false (optional)\n * @returns The selected policy\n *\n * @example\n * ```typescript\n * const policy = conditionalPolicy(\n * isProduction,\n * servicePolicies.httpApi, // Use in production\n * retryPolicies.none // Skip in development\n * );\n * ```\n */\nexport function conditionalPolicy(\n condition: boolean,\n policy: Policy,\n elsePolicy: Policy = {}\n): Policy {\n return condition ? policy : elsePolicy;\n}\n\n/**\n * Create a policy based on environment.\n *\n * @param envPolicies - Map of environment names to policies\n * @param currentEnv - Current environment (defaults to NODE_ENV)\n * @param defaultPolicy - Default policy if environment not found\n * @returns The selected policy\n *\n * @example\n * ```typescript\n * const policy = envPolicy({\n * production: servicePolicies.httpApi,\n * development: retryPolicies.none,\n * test: retryPolicies.none,\n * });\n * ```\n */\nexport function envPolicy(\n envPolicies: Record<string, Policy>,\n currentEnv: string = process.env.NODE_ENV ?? \"development\",\n defaultPolicy: Policy = {}\n): Policy {\n return envPolicies[currentEnv] ?? defaultPolicy;\n}\n\n// =============================================================================\n// Policy Registry\n// =============================================================================\n\n/**\n * A registry for managing named policies.\n */\nexport interface PolicyRegistry {\n /**\n * Register a named policy.\n */\n register(name: string, policy: Policy): void;\n\n /**\n * Get a policy by name.\n */\n get(name: string): Policy | undefined;\n\n /**\n * Check if a policy exists.\n */\n has(name: string): boolean;\n\n /**\n * Get all registered policy names.\n */\n names(): string[];\n\n /**\n * Create step options using a registered policy.\n */\n apply(policyName: string, stepOptions?: StepOptions): StepOptions;\n}\n\n/**\n * Create a policy registry for managing named policies.\n *\n * @returns PolicyRegistry instance\n *\n * @example\n * ```typescript\n * const registry = createPolicyRegistry();\n *\n * // Register policies\n * registry.register('api', servicePolicies.httpApi);\n * registry.register('db', servicePolicies.database);\n *\n * // Use in workflow\n * const user = await step(\n * 'fetch-user',\n * () => fetchUser(id),\n * registry.apply('api')\n * );\n * ```\n */\nexport function createPolicyRegistry(): PolicyRegistry {\n const policies = new Map<string, Policy>();\n\n return {\n register(name: string, policy: Policy): void {\n policies.set(name, policy);\n },\n\n get(name: string): Policy | undefined {\n return policies.get(name);\n },\n\n has(name: string): boolean {\n return policies.has(name);\n },\n\n names(): string[] {\n return Array.from(policies.keys());\n },\n\n apply(policyName: string, stepOptions?: StepOptions): StepOptions {\n const policy = policies.get(policyName);\n if (!policy) {\n throw new Error(`Policy not found: ${policyName}`);\n }\n return withPolicy(policy, stepOptions);\n },\n };\n}\n\n// =============================================================================\n// Step Options Builder (Fluent API)\n// =============================================================================\n\n/**\n * Fluent builder for constructing step options.\n */\nexport interface StepOptionsBuilder {\n /**\n * Set step key for caching.\n */\n key(key: string): StepOptionsBuilder;\n\n /**\n * Apply a policy.\n */\n policy(policy: Policy): StepOptionsBuilder;\n\n /**\n * Set timeout in milliseconds.\n */\n timeout(ms: number): StepOptionsBuilder;\n\n /**\n * Set retry options.\n */\n retry(options: RetryOptions): StepOptionsBuilder;\n\n /**\n * Set retry attempts (with default exponential backoff).\n */\n retries(attempts: number): StepOptionsBuilder;\n\n /**\n * Build the final StepOptions.\n */\n build(): StepOptions;\n}\n\n/**\n * Create a fluent builder for step options.\n *\n * @returns StepOptionsBuilder instance\n *\n * @example\n * ```typescript\n * const options = stepOptions()\n * .key('user:123')\n * .timeout(5000)\n * .retries(3)\n * .build();\n *\n * const user = await step('fetch-user', () => fetchUser(id), options);\n * ```\n */\nexport function stepOptions(): StepOptionsBuilder {\n const policies: Policy[] = [];\n\n const builder: StepOptionsBuilder = {\n key(key: string) {\n policies.push({ key });\n return builder;\n },\n\n policy(policy: Policy) {\n policies.push(policy);\n return builder;\n },\n\n timeout(ms: number) {\n policies.push(timeoutPolicy({ ms }));\n return builder;\n },\n\n retry(options: RetryOptions) {\n policies.push(retryPolicy(options));\n return builder;\n },\n\n retries(attempts: number) {\n policies.push(retryPolicies.custom({ attempts }));\n return builder;\n },\n\n build(): StepOptions {\n return mergePolicies(...policies);\n },\n };\n\n return builder;\n}\n"],"mappings":"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","names":["mergePolicies","policies","result","policy","createPolicyApplier","basePolicies","basePolicy","stepOptions","createPolicyBundle","name","retryPolicy","options","retryPolicies","attempts","delayMs","initialDelay","timeoutPolicy","timeoutPolicies","ms","seconds","error","servicePolicies","withPolicy","withPolicies","opts","conditionalPolicy","condition","elsePolicy","envPolicy","envPolicies","currentEnv","defaultPolicy","createPolicyRegistry","policyName","builder","key"]}
|
package/dist/ratelimit.cjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
"use strict";var le=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var We=Object.prototype.hasOwnProperty;var qe=(t,e)=>{for(var i in e)le(t,i,{get:e[i],enumerable:!0})},$e=(t,e,i,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let k of Be(e))!We.call(t,k)&&k!==i&&le(t,k,{get:()=>e[k],enumerable:!(d=Ke(e,k))||d.enumerable});return t};var Ve=t=>$e(le({},"__esModule",{value:!0}),t);var ot={};qe(ot,{createCombinedLimiter:()=>Ie,createConcurrencyLimiter:()=>ye,createCostBasedRateLimiter:()=>Ue,createFixedWindowLimiter:()=>De,createRateLimiter:()=>Ee,isQueueFullError:()=>de,isRateLimitExceededError:()=>Oe,rateLimiterPresets:()=>Le});module.exports=Ve(ot);var He={"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(t){return`https://jagreehal.github.io/awaitly/rules/#${t}`}var ct=Object.keys(He);var ee=class extends Error{_tag};function j(t,e){return class extends ee{_tag=t;constructor(i,d){let k=e?.message?e.message(i??{}):t;if(super(k),this.name=t,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:we(e.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),i&&typeof i=="object"){let l;if(e?.slug!==void 0){let{_tag:s,name:O,message:x,stack:w,code:R,hint:a,docsUrl:D,...F}=i;l=F}else{let{_tag:s,name:O,message:x,stack:w,...R}=i;l=R}let E=Object.prototype.hasOwnProperty.call(l,"cause"),p=E?l.cause:void 0;E&&delete l.cause;let P=d?.cause!==void 0;if(E&&P)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,l),E&&(this.cause=p),P&&(this.cause=d?.cause)}else d?.cause!==void 0&&(this.cause=d.cause)}}}Object.defineProperty(j,Symbol.hasInstance,{value:t=>t instanceof ee});(k=>{function t(l){return l instanceof Error}k.isError=t;function e(l){return l instanceof ee}k.isTaggedError=e;function i(l,E){let p=l._tag,P=E[p];return P(l)}k.match=i;function d(l,E,p){let P=l._tag,s=E[P];return s?s(l):p(l)}k.matchPartial=d})(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:e=>e.operation?`TimeoutError: ${e.operation} timed out after ${e.ms}ms`:`TimeoutError: Operation timed out after ${e.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:e=>e.operation?`RetryExhaustedError: ${e.operation} failed after ${e.attempts} attempts`:`RetryExhaustedError: Operation failed after ${e.attempts} attempts`}){},ge=class extends j("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`:""}`}){},ke=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:e=>`CircuitBreakerOpenError: Circuit ${e.circuitName} is ${e.state??"OPEN"}${e.retryAfterMs?`, retry after ${Math.ceil(e.retryAfterMs/1e3)}s`:""}`}){},Re=class extends j("ValidationError",{message:e=>`ValidationError: Invalid ${e.field} - ${e.reason}`}){},xe=class extends j("NotFoundError",{message:e=>e.id?`NotFoundError: ${e.resource} with id ${e.id} not found`:`NotFoundError: ${e.resource} not found`}){},Ce=class extends j("UnauthorizedError",{message:e=>e.reason?`UnauthorizedError: ${e.reason}`:e.action&&e.resource?`UnauthorizedError: Not authorized to ${e.action} ${e.resource}`:"UnauthorizedError: Access denied"}){},he=class extends j("NetworkError",{message:e=>e.url?`NetworkError: ${e.reason} (${e.url})`:`NetworkError: ${e.reason}`}){},be=class extends j("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}`}){},ne=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:e=>`UnexpectedError: ${e.cause instanceof Error?e.cause.message:String(e.cause??"unknown")}`}){};function ze(t){let e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!e)return;let i=parseFloat(e[1]),d=e[2].toLowerCase();return{_tag:"Duration",millis:i*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[d]??1)}}function Ye(t){return new ne({cause:t})}function $(t){return{ok:!0,value:t}}function N(t,e){let i=e?.cause;return{ok:!1,error:t,...i!==void 0?{cause:i}:{}}}function Qe(t){if(t==null)return"unknown";if(typeof t=="string")return t.trim()||"unknown";if(typeof t=="object"){let e=t;if(typeof e._tag=="string"){let i=e._tag.trim();if(i)return i}if(typeof e.tag=="string"){let i=e.tag.trim();if(i)return i}if(typeof e.code=="string"){let i=e.code.trim();if(i)return i}else if(typeof e.code=="number")return String(e.code);if(t instanceof Error&&t.name){let i=t.name.trim();if(i)return i}}return"unknown"}function Xe(t,e){if(!(!e||!t))return e[t]}function Je(t){let{intent:e,domain:i,owner:d,tags:k,stateChanges:l,emits:E,calls:p}=t;if(!e&&!i&&!d&&!k?.length&&!l?.length&&!E?.length&&!p?.length)return;let P={};return e&&(P.intent=e),i&&(P.domain=i),d&&(P.owner=d),k?.length&&(P.tags=k),l?.length&&(P.stateChanges=l),E?.length&&(P.emits=E),p?.length&&(P.calls=p),P}function K(t,e,i,d,k){let l=Qe(t),E=Xe(l,e),p={tag:l,origin:i};return E!==void 0&&(p.classification=E),d!==void 0&&(p.attempt=d),k!==void 0&&(p.cumulativeDurationMs=k),p}var G=Symbol.for("step_timeout_marker");function Se(t){return typeof t!="object"||t===null?!1:t.type==="STEP_TIMEOUT"?!0:G in t}function Ge(t){if(!(typeof t!="object"||t===null)){if(t.type==="STEP_TIMEOUT"){let e=t;return{timeoutMs:e.timeoutMs,stepName:e.stepName,stepKey:e.stepKey,attempt:e.attempt}}if(G in t)return t[G]}}var ve=Symbol("early-exit");function Ze(t,e){return{[ve]:!0,error:t,meta:e}}function et(t){return typeof t=="object"&&t!==null&&t[ve]===!0}var Me=Symbol("mapper-exception");function X(t){return{[Me]:!0,thrown:t}}function tt(t){return typeof t=="object"&&t!==null&&t[Me]===!0}function pe(t,e){let{backoff:i,initialDelay:d,maxDelay:k,jitter:l}=e,E;switch(i){case"fixed":E=d;break;case"linear":E=d*t;break;case"exponential":E=d*Math.pow(2,t-1);break}if(E=Math.min(E,k),l){let p=E*.25*Math.random();E=E+p}return Math.floor(E)}function me(t){return new Promise(e=>setTimeout(e,t))}var Ae=Symbol("timeout"),oe=Symbol("timeout-option");function rt(t){return typeof t=="object"&&t!==null&&t[oe]===!0}async function nt(t,e,i,d){let k=new AbortController,l=e.onTimeout??"error",E=()=>typeof l=="function"?l({name:i.name,key:i.key,ms:e.ms}):e.error??{type:"STEP_TIMEOUT",stepName:i.name,stepKey:i.key,timeoutMs:e.ms,attempt:i.attempt},p;d?.aborted&&k.abort(d.reason);let P;d&&!d.aborted&&(P=()=>k.abort(d.reason),d.addEventListener("abort",P,{once:!0}));let s=new Promise((x,w)=>{p=setTimeout(()=>{if(l!=="disconnect"&&k.abort(),l==="option"){w({[oe]:!0,ms:e.ms});return}w({[Ae]:!0,error:E()})},e.ms)}),O;e.signal?O=Promise.resolve(t(k.signal)):O=Promise.resolve(t());try{return await Promise.race([O,s])}catch(x){if(typeof x=="object"&&x!==null&&x[oe]===!0)throw{[oe]:!0,ms:e.ms};if(typeof x=="object"&&x!==null&&x[Ae]===!0){l==="disconnect"&&O.catch(()=>{});let w=x.error;if(typeof w=="object"&&w!==null&&w.type!=="STEP_TIMEOUT"){let R={timeoutMs:e.ms,stepName:i.name,stepKey:i.key,attempt:i.attempt};G in w?w[G]=R:Object.defineProperty(w,G,{value:R,enumerable:!1,writable:!0,configurable:!1})}throw w}throw x}finally{clearTimeout(p),P&&d&&d.removeEventListener("abort",P)}}var J={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function Pe(t,e){let{onError:i,onEvent:d,catchUnexpected:k,workflowId:l,workflowName:E,context:p,_workflowSignal:P}=e&&typeof e=="object"?e:{},s=l??crypto.randomUUID(),O=k??Ye,x=[],w=0,R=y=>y??`step_${++w}`,a=y=>{let W=y.context!==void 0||p===void 0?y:{...y,context:p},H=E!==void 0&&W.workflowName===void 0?{...W,workflowName:E}:W;if(H.type==="step_success"){let te=H.stepId;for(let re=x.length-1;re>=0;re--){let q=x[re];if(q.type==="race"&&!q.winnerId){q.winnerId=te;break}}}d?.(H,p)},D=Ze,F=y=>et(y),B=(y,W)=>y,Ne=y=>typeof y=="function"?!1:!!(y&&typeof y=="object"&&"ok"in y||y&&typeof y=="object"&&"then"in y&&typeof y.then=="function");try{let W=function(u){let f={};for(let[n,o]of Object.entries(u))if(typeof o=="function")f[n]=o;else if(o&&typeof o=="object"&&"fn"in o)f[n]=o.fn;else throw new TypeError(`step.all: operation "${n}" must be a function or { fn, errors? } object`);return f},H=function(u,f){let n=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),r=!1;x.push({scopeId:n,type:"parallel"});let c=()=>{if(r)return;r=!0;let m=x.findIndex(T=>T.scopeId===n);m!==-1&&x.splice(m,1),a({type:"scope_end",workflowId:s,scopeId:n,ts:Date.now(),durationMs:performance.now()-o})};a({type:"scope_start",workflowId:s,scopeId:n,scopeType:"parallel",name:u,ts:Date.now()});try{let m=await f();if(c(),!m.ok)throw i?.(m.error,u,p),D(m.error,{origin:"result",resultCause:m.cause});return m.value}catch(m){throw c(),m}})()},te=function(u,f){let n=Object.keys(u),o=f.name??`Parallel(${n.join(", ")})`,r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let c=performance.now(),m=!1;x.push({scopeId:r,type:"parallel"});let T=()=>{if(m)return;m=!0;let g=x.findIndex(C=>C.scopeId===r);g!==-1&&x.splice(g,1),a({type:"scope_end",workflowId:s,scopeId:r,ts:Date.now(),durationMs:performance.now()-c})};a({type:"scope_start",workflowId:s,scopeId:r,scopeType:"parallel",name:o,ts:Date.now()});try{let g=await new Promise(b=>{if(n.length===0){b([]);return}let M=!1,L=n.length,S=new Array(n.length);for(let U=0;U<n.length;U++){let A=n[U],v=U;Promise.resolve(u[A]()).catch(_=>N({type:"PROMISE_REJECTED",cause:_},{cause:{type:"PROMISE_REJECTION",reason:_}})).then(_=>{if(!M){if(!_.ok){M=!0,b([{key:A,result:_}]);return}S[v]={key:A,result:_},L--,L===0&&b(S)}})}});T();let C={};for(let{key:b,result:M}of g){if(!M.ok)throw i?.(M.error,b,p),D(M.error,{origin:"result",resultCause:M.cause});C[b]=M.value}return C}catch(g){throw T(),g}})()};var st=W,at=H,it=te;let y=(u,f,n)=>(async()=>{if(typeof u!="string"||u.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let o=n??{},r=Je(o),c=u,m=o.key??u,T=o.key??u,{description:g,retry:C,timeout:b}=o,M=R(m),L=d,S=L?performance.now():0,A=Ne(f)?()=>f:f,_={attempts:Math.max(1,C?.attempts??1),backoff:C?.backoff??J.backoff,initialDelay:C?.initialDelay??J.initialDelay,maxDelay:C?.maxDelay??J.maxDelay,jitter:C?.jitter??J.jitter,shouldRetry:C?.shouldRetry??J.shouldRetry,onRetry:C?.onRetry??J.onRetry};d&&a({type:"step_start",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),...r&&{metadata:r}});let Q;for(let I=1;I<=_.attempts;I++){let Fe=L?performance.now():0;try{let h;if(b?h=await nt(A,b,{name:c,key:m,attempt:I},P):h=await A(),h.ok){let Y=performance.now()-S;return a({type:"step_success",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),durationMs:Y,...r&&{metadata:r}}),T&&a({type:"step_complete",workflowId:s,stepKey:T,name:c,description:g,ts:Date.now(),durationMs:Y,result:h,...r&&{metadata:r}}),h.value}if(Q=h,I<_.attempts&&_.shouldRetry(h.error,I)){let Y=pe(I,_);a({type:"step_retry",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),attempt:I+1,maxAttempts:_.attempts,delayMs:Y,error:h.error,...r&&{metadata:r},diagnostics:K(h.error,o.errorMeta,"result",I,performance.now()-S)}),_.onRetry(h.error,I,Y),await me(Y);continue}_.attempts>1&&a({type:"step_retries_exhausted",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),durationMs:performance.now()-S,attempts:I,lastError:h.error,...r&&{metadata:r},diagnostics:K(h.error,o.errorMeta,"result",I,performance.now()-S)});break}catch(h){let Y=performance.now()-Fe;if(rt(h)){let V=h.ms;a({type:"step_timeout",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),timeoutMs:V,attempt:I,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"timeout",I)}),a({type:"step_success",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),durationMs:performance.now()-S,...r&&{metadata:r}}),T&&a({type:"step_complete",workflowId:s,stepKey:T,name:c,description:g,ts:Date.now(),durationMs:performance.now()-S,result:$(void 0),...r&&{metadata:r}});return}if(F(h))throw a({type:"step_aborted",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),durationMs:Y,...r&&{metadata:r}}),h;if(Se(h)){let V=Ge(h),je=b?.ms??V?.timeoutMs??0;if(a({type:"step_timeout",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),timeoutMs:je,attempt:I,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"timeout",I)}),I<_.attempts&&_.shouldRetry(h,I)){let ce=pe(I,_);a({type:"step_retry",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),attempt:I+1,maxAttempts:_.attempts,delayMs:ce,error:h,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"timeout",I,performance.now()-S)}),_.onRetry(h,I,ce),await me(ce);continue}_.attempts>1&&a({type:"step_retries_exhausted",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),durationMs:performance.now()-S,attempts:I,lastError:h,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"timeout",I,performance.now()-S)});let ue=performance.now()-S;throw a({type:"step_error",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),durationMs:ue,error:h,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"timeout",I,ue)}),T&&a({type:"step_complete",workflowId:s,stepKey:T,name:c,description:g,ts:Date.now(),durationMs:ue,result:N(h,{cause:h}),meta:{origin:"throw",thrown:h},...r&&{metadata:r}}),i?.(h,c,p),D(h,{origin:"throw",thrown:h})}if(I<_.attempts&&_.shouldRetry(h,I)){let V=pe(I,_);a({type:"step_retry",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),attempt:I+1,maxAttempts:_.attempts,delayMs:V,error:h,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"throw",I,performance.now()-S)}),_.onRetry(h,I,V),await me(V);continue}_.attempts>1&&!Se(h)&&a({type:"step_retries_exhausted",workflowId:s,stepId:M,stepKey:m,name:c,ts:Date.now(),durationMs:performance.now()-S,attempts:I,lastError:h,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"throw",I,performance.now()-S)});let ie=performance.now()-S,Z;try{Z=O(h)}catch(V){throw X(V)}throw a({type:"step_error",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),durationMs:ie,error:Z,...r&&{metadata:r},diagnostics:K(h,o.errorMeta,"throw",I,ie)}),T&&a({type:"step_complete",workflowId:s,stepKey:T,name:c,description:g,ts:Date.now(),durationMs:ie,result:N(Z,{cause:h}),meta:{origin:"throw",thrown:h},...r&&{metadata:r}}),i?.(Z,c,p),D(Z,{origin:"throw",thrown:h})}}let z=Q,se=performance.now()-S,ae=B(z.error,{origin:"result",resultCause:z.cause});throw a({type:"step_error",workflowId:s,stepId:M,stepKey:m,name:c,description:g,ts:Date.now(),durationMs:se,error:ae,...r&&{metadata:r},diagnostics:K(z.error,o.errorMeta,"result",_.attempts,se)}),T&&a({type:"step_complete",workflowId:s,stepKey:T,name:c,description:g,ts:Date.now(),durationMs:se,result:z,meta:{origin:"result",resultCause:z.cause},...r&&{metadata:r}}),i?.(ae,c,p),D(ae,{origin:"result",resultCause:z.cause})})();y.try=(u,f,n)=>{if(typeof u!="string"||u.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 y.retry(u,async()=>{try{return $(await f())}catch(g){return N(o(g),{cause:g})}},{attempts:n.retry?.attempts??1,...n.retry??{},key:n.key,timeout:n.timeout});let r=n.key??u,c=u,m=u,T=d;return(async()=>{let g=T?performance.now():0;d&&a({type:"step_start",workflowId:s,stepId:m,stepKey:r,name:c,ts:Date.now()});try{let C=await f(),b=performance.now()-g;return a({type:"step_success",workflowId:s,stepId:m,stepKey:r,name:c,ts:Date.now(),durationMs:b}),r&&a({type:"step_complete",workflowId:s,stepKey:r,name:c,ts:Date.now(),durationMs:b,result:$(C)}),C}catch(C){let b=o(C),M=performance.now()-g,L=B(b,{origin:"throw",thrown:C});throw a({type:"step_error",workflowId:s,stepId:m,stepKey:r,name:c,ts:Date.now(),durationMs:M,error:L}),r&&a({type:"step_complete",workflowId:s,stepKey:r,name:c,ts:Date.now(),durationMs:M,result:N(b,{cause:C}),meta:{origin:"throw",thrown:C}}),i?.(L,c,p),D(L,{origin:"throw",thrown:C})}})()},y.fromResult=(u,f,n)=>{if(typeof u!="string"||u.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??u,r=u,c=u,m="error"in n?()=>n.error:n.onError,T=d;return(async()=>{let g=T?performance.now():0;d&&a({type:"step_start",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now()});let C=await f();if(C.ok){let b=performance.now()-g;return a({type:"step_success",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:b}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:b,result:$(C.value)}),C.value}else{let b=m(C.error),M=performance.now()-g,L=B(b,{origin:"result",resultCause:C.error});throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:M,error:L}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:M,result:N(b,{cause:C.error}),meta:{origin:"result",resultCause:C.error}}),i?.(L,r,p),D(L,{origin:"result",resultCause:C.error})}})()},y.fromNullable=(u,f,n,o)=>{if(typeof u!="string"||u.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 y(u,async()=>{let r=await f();return r!=null?$(r):N(n())},o)},y.retry=(u,f,n)=>{if(typeof u!="string"||u.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 y(u,f,{key:n.key??u,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})},y.withTimeout=(u,f,n)=>{if(typeof u!="string"||u.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 y(u,f,{key:n.key??u,timeout:n})},y.sleep=(u,f,n)=>{if(typeof u!="string"||u.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 f=="string"?ze(f):f;if(!o)throw new Error(`step.sleep: invalid duration '${f}'`);let r=o.millis,c=n?.signal;return y(u,async()=>{if(P?.aborted||c?.aborted){let m=new Error("Sleep aborted");throw m.name="AbortError",m}return new Promise((m,T)=>{let g={timeoutId:void 0},C=()=>{g.timeoutId&&clearTimeout(g.timeoutId);let b=new Error("Sleep aborted");b.name="AbortError",T(b)};P?.addEventListener("abort",C,{once:!0}),c?.addEventListener("abort",C,{once:!0}),g.timeoutId=setTimeout(()=>{P?.removeEventListener("abort",C),c?.removeEventListener("abort",C),m($(void 0))},r)})},{key:n?.key??u,description:n?.description})},y.all=((...u)=>{if(typeof u[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 f=u[0],n=u[1];if(typeof n=="function")return H(f,n);if(n&&typeof n=="object"&&!Array.isArray(n)){let r=W(n);return te(r,{name:f})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),y.race=(u,f)=>{let n=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),r=!1,c={scopeId:n,type:"race",winnerId:void 0};x.push(c);let m=()=>{if(r)return;r=!0;let T=x.findIndex(g=>g.scopeId===n);T!==-1&&x.splice(T,1),a({type:"scope_end",workflowId:s,scopeId:n,ts:Date.now(),durationMs:performance.now()-o,winnerId:c.winnerId})};a({type:"scope_start",workflowId:s,scopeId:n,scopeType:"race",name:u,ts:Date.now()});try{let T=await f();if(m(),!T.ok)throw i?.(T.error,u,p),D(T.error,{origin:"result",resultCause:T.cause});return T.value}catch(T){throw m(),T}})()},y.if=(u,f,n)=>n(),y.label=y.if,y.branch=async(u,f)=>{let{condition:n,then:o,else:r}=f;if(n())return await o();if(r)return await r()},y.arm=(u,f)=>({fn:u,errors:f}),y.forEach=async(u,f,n)=>{let o=[],r=n.maxIterations,c=0,m="run"in n,T=Symbol.asyncIterator in f?f:(async function*(){yield*f})();for await(let g of T){if(r!==void 0&&c>=r)break;let C;m?C=await n.run(g,c):C=await n.item.handler(g,c,y),o.push(C),c++}return o},y.item=u=>({__forEachItemHandler:!0,handler:u}),y.dep=(u,f)=>f,y.workflow=(u,f,n)=>y(u,f,n),y.map=async(u,f,n,o)=>{let r=o?.concurrency??f.length;return y(u,()=>r>=f.length?_e(f.map((c,m)=>n(c,m))):(async()=>{let c=[];for(let m=0;m<f.length;m+=r){let T=f.slice(m,m+r),g=await _e(T.map((C,b)=>n(C,m+b)));if(!g.ok)return g;c.push(...g.value)}return $(c)})(),{key:o?.key})},y.withFallback=(u,f,n)=>{if(typeof u!="string"||u.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??u,r=u,c=R(o),m=d;return(async()=>{let T=m?performance.now():0;d&&a({type:"step_start",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now()});let g;try{g=await f()}catch(S){if(F(S))throw a({type:"step_aborted",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:performance.now()-T}),S;let U;try{U=O(S)}catch(v){throw X(v)}if(n.on!==void 0&&n.on!==U){let v=performance.now()-T;throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:v,error:U}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:v,result:N(U,{cause:S}),meta:{origin:"throw",thrown:S}}),i?.(U,r,p),D(U,{origin:"throw",thrown:S})}let A;try{A=await n.fallback()}catch(v){if(F(v))throw a({type:"step_aborted",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:performance.now()-T}),v;let _;try{_=O(v)}catch(z){throw X(z)}let Q=performance.now()-T;throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:Q,error:_}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:Q,result:N(_,{cause:v}),meta:{origin:"throw",thrown:v}}),i?.(_,r,p),D(_,{origin:"throw",thrown:v})}if(A.ok){let v=performance.now()-T;return a({type:"step_success",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:v}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:v,result:A,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(U)}}),A.value}else{let v=performance.now()-T,_=B(A.error,{origin:"result",resultCause:A.cause});throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:v,error:_}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:v,result:A,meta:{origin:"result",resultCause:A.cause}}),i?.(_,r,p),D(_,{origin:"result",resultCause:A.cause})}}if(g.ok){let S=performance.now()-T;return a({type:"step_success",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:S}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:S,result:g}),g.value}let C=g.error;if(n.on!==void 0&&n.on!==C){let S=performance.now()-T,U=B(C,{origin:"result",resultCause:g.cause});throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:S,error:U}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:S,result:g,meta:{origin:"result",resultCause:g.cause}}),i?.(U,r,p),D(U,{origin:"result",resultCause:g.cause})}let b;try{b=await n.fallback()}catch(S){if(F(S))throw a({type:"step_aborted",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:performance.now()-T}),S;let U;try{U=O(S)}catch(v){throw X(v)}let A=performance.now()-T;throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:A,error:U}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:A,result:N(U,{cause:S}),meta:{origin:"throw",thrown:S}}),i?.(U,r,p),D(U,{origin:"throw",thrown:S})}if(b.ok){let S=performance.now()-T;return a({type:"step_success",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:S}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:S,result:b,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(C)}}),b.value}let M=performance.now()-T,L=B(b.error,{origin:"result",resultCause:b.cause});throw a({type:"step_error",workflowId:s,stepId:c,stepKey:o,name:r,ts:Date.now(),durationMs:M,error:L}),o&&a({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:M,result:b,meta:{origin:"result",resultCause:b.cause}}),i?.(L,r,p),D(L,{origin:"result",resultCause:b.cause})})()},y.withResource=(u,f)=>{if(typeof u!="string"||u.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=u,o=u,r=R(n),c=d;return(async()=>{let m=c?performance.now():0;d&&a({type:"step_start",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now()});let T;try{T=await f.acquire()}catch(A){if(F(A))throw a({type:"step_aborted",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now(),durationMs:performance.now()-m}),A;let v;try{v=O(A)}catch(Q){throw X(Q)}let _=performance.now()-m;throw a({type:"step_error",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now(),durationMs:_,error:v}),n&&a({type:"step_complete",workflowId:s,stepKey:n,name:o,ts:Date.now(),durationMs:_,result:N(v,{cause:A}),meta:{origin:"throw",thrown:A}}),i?.(v,o,p),D(v,{origin:"throw",thrown:A})}if(!T.ok){let A=performance.now()-m,v=B(T.error,{origin:"result",resultCause:T.cause});throw a({type:"step_error",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now(),durationMs:A,error:v}),n&&a({type:"step_complete",workflowId:s,stepKey:n,name:o,ts:Date.now(),durationMs:A,result:T,meta:{origin:"result",resultCause:T.cause}}),i?.(v,o,p),D(v,{origin:"result",resultCause:T.cause})}let g=T.value,C,b,M=!1;try{C=await f.use(g)}catch(A){if(F(A)){try{await f.release(g)}catch(v){console.warn(`[awaitly] step.withResource("${u}"): release threw after earlyExit:`,v)}throw A}b=A,M=!0}try{await f.release(g)}catch(A){console.warn(`[awaitly] step.withResource("${u}"): release threw:`,A)}if(M){let A;try{A=O(b)}catch(_){throw X(_)}let v=performance.now()-m;throw a({type:"step_error",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now(),durationMs:v,error:A}),n&&a({type:"step_complete",workflowId:s,stepKey:n,name:o,ts:Date.now(),durationMs:v,result:N(A,{cause:b}),meta:{origin:"throw",thrown:b}}),i?.(A,o,p),D(A,{origin:"throw",thrown:b})}let L=C;if(L.ok){let A=performance.now()-m;return a({type:"step_success",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now(),durationMs:A}),n&&a({type:"step_complete",workflowId:s,stepKey:n,name:o,ts:Date.now(),durationMs:A,result:L}),L.value}let S=performance.now()-m,U=B(L.error,{origin:"result",resultCause:L.cause});throw a({type:"step_error",workflowId:s,stepId:r,stepKey:n,name:o,ts:Date.now(),durationMs:S,error:U}),n&&a({type:"step_complete",workflowId:s,stepKey:n,name:o,ts:Date.now(),durationMs:S,result:L,meta:{origin:"result",resultCause:L.cause}}),i?.(U,o,p),D(U,{origin:"result",resultCause:L.cause})})()};let q=await t({step:y});if(process.env.NODE_ENV!=="production"&&q!==null&&typeof q=="object"&&"ok"in q&&typeof q.ok=="boolean"){let u=q;(u.ok===!0&&"value"in u||u.ok===!1&&"error"in u)&&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(y){if(tt(y))throw y.thrown;if(F(y)){let H=y.meta.origin==="throw"?y.meta.thrown:y.meta.origin==="result"?y.meta.resultCause:void 0;return N(y.error,{cause:H})}let W=O(y);return i?.(W,"unexpected",p),N(W,{cause:y})}}Pe.strict=(t,e)=>Pe(t,e);async function _e(t){return t.length===0?$([]):new Promise(e=>{let i=!1,d=t.length,k=new Array(t.length);for(let l=0;l<t.length;l++){let E=l;Promise.resolve(t[E]).catch(p=>N({type:"PROMISE_REJECTED",cause:p},{cause:{type:"PROMISE_REJECTION",reason:p}})).then(p=>{if(!i){if(!p.ok){i=!0,e(p);return}k[E]=p.value,d--,d===0&&e($(k))}})}})}function Oe(t){return typeof t=="object"&&t!==null&&t.type==="RATE_LIMIT_EXCEEDED"}function de(t){return typeof t=="object"&&t!==null&&t.type==="QUEUE_FULL"}function Ee(t,e){let{maxPerSecond:i,strategy:d="wait"}=e,k=e.burstCapacity??i*2,l=k,E=Date.now(),p=i/1e3,P=[];function s(){let w=Date.now(),a=(w-E)*p;l=Math.min(k,l+a),E=w}function O(){if(s(),l>=1)return l-=1,0;let w=1-l;return Math.ceil(w/p)}async function x(){return new Promise(w=>{let R=()=>{let a=O();a===0?w():(P.push(R),setTimeout(()=>{let D=P.indexOf(R);D!==-1&&(P.splice(D,1),R())},a))};R()})}return{async execute(w){let R=O();if(R>0){if(d==="reject")throw{type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:R};await x()}return w()},async executeResult(w){let R=O();if(R>0){if(d==="reject")return N({type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:R});await x()}return w()},getStats(){return s(),{availableTokens:Math.floor(l),maxTokens:k,tokensPerSecond:i,waitingCount:P.length}},reset(){l=k,E=Date.now(),P.length=0}}}function ye(t,e){let{maxConcurrent:i,strategy:d="queue",maxQueueSize:k=1/0}=e,l=0,E=[];async function p(){if(l<i){l++;return}if(d==="reject")throw{type:"QUEUE_FULL",limiterName:t,queueSize:E.length,maxQueueSize:k};if(E.length>=k)throw{type:"QUEUE_FULL",limiterName:t,queueSize:E.length,maxQueueSize:k};return new Promise((s,O)=>{E.push({resolve:s,reject:O})})}function P(){l--,E.length>0&&l<i&&(l++,E.shift()?.resolve())}return{async execute(s){await p();try{return await s()}finally{P()}},async executeAll(s){let O=new Array(s.length),x=[];for(let w=0;w<s.length;w++){let R=w,a=this.execute(s[R]).then(D=>{O[R]=D});x.push(a)}return await Promise.all(x),O},async executeResult(s){try{await p()}catch(O){if(de(O))return N(O);throw O}try{return await s()}finally{P()}},getStats(){return{activeCount:l,maxConcurrent:i,queueSize:E.length,maxQueueSize:k}},reset(){for(l=0;E.length>0;)E.shift()?.reject(new Error("Limiter reset"))}}}function Ie(t,e){let i=e.rate?Ee(`${t}-rate`,e.rate):void 0,d=e.concurrency?ye(`${t}-concurrency`,e.concurrency):void 0;return{rate:i,concurrency:d,async execute(k){let l=k;if(i){let E=l;l=()=>i.execute(E)}return d?d.execute(l):l()}}}function De(t,e){let{limit:i,windowMs:d=1e3,strategy:k="wait"}=e,l=Date.now(),E=0,p=[];function P(){let x=Date.now(),w=x-l;return w>=d?(l=x,E=0,0):d-w}function s(x){let w=P();return E+x<=i?(E+=x,0):w}async function O(x){return new Promise(w=>{let R=()=>{let a=s(x);a===0?w():(p.push({resolve:R,cost:x}),setTimeout(()=>{let D=p.findIndex(F=>F.resolve===R);D!==-1&&(p.splice(D,1),R())},a))};R()})}return{async execute(x,w=1){if(w>i)throw{type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:d};let R=s(w);if(R>0){if(k==="reject")throw{type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:R};await O(w)}return x()},async executeResult(x,w=1){if(w>i)return N({type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:d});let R=s(w);if(R>0){if(k==="reject")return N({type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:R});await O(w)}return x()},getStats(){let x=P();return{requestCount:E,limit:i,windowMs:d,remainingMs:x,waitingCount:p.length}},reset(){l=Date.now(),E=0,p.length=0}}}function Ue(t,e){let{tokensPerSecond:i,strategy:d="wait"}=e,k=e.maxTokens??i*2,l=k,E=Date.now(),p=i/1e3,P=[];function s(){let w=Date.now(),a=(w-E)*p;l=Math.min(k,l+a),E=w}function O(w){if(s(),l>=w)return l-=w,0;let R=w-l;return Math.ceil(R/p)}async function x(w){return new Promise(R=>{let a=()=>{let D=O(w);D===0?R():(P.push({check:a,cost:w}),setTimeout(()=>{let F=P.findIndex(B=>B.check===a);F!==-1&&(P.splice(F,1),a())},D))};a()})}return{async execute(w,R=1){if(R>k)throw{type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:Math.ceil(R/p)};let a=O(R);if(a>0){if(d==="reject")throw{type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:a};await x(R)}return w()},async executeResult(w,R=1){if(R>k)return N({type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:Math.ceil(R/p)});let a=O(R);if(a>0){if(d==="reject")return N({type:"RATE_LIMIT_EXCEEDED",limiterName:t,retryAfterMs:a});await x(R)}return w()},getStats(){return s(),{availableTokens:l,maxTokens:k,tokensPerSecond:i,waitingCount:P.length}},reset(){l=k,E=Date.now(),P.length=0}}}var Le={api:{maxPerSecond:10,burstCapacity:20,strategy:"wait"},database:{maxConcurrent:10,strategy:"queue",maxQueueSize:100},external:{maxPerSecond:5,burstCapacity:10,strategy:"wait"}};0&&(module.exports={createCombinedLimiter,createConcurrencyLimiter,createCostBasedRateLimiter,createFixedWindowLimiter,createRateLimiter,isQueueFullError,isRateLimitExceededError,rateLimiterPresets});
|
|
7
|
-
//# sourceMappingURL=ratelimit.cjs.map
|