vigor-fetch 4.0.3 → 4.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1963 -0
- package/dist/index.d.cts +4208 -0
- package/dist/index.d.ts +487 -1596
- package/dist/index.js +1790 -1892
- package/package.json +11 -16
- package/dist/index.mjs +0 -1927
package/dist/index.mjs
DELETED
|
@@ -1,1927 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds the literal brand string used by {@link VigorBrand}, preserving the
|
|
3
|
-
* `Branch`/`Name` literal types for use as a `__brand` value.
|
|
4
|
-
*/
|
|
5
|
-
function createBrand(b, n) {
|
|
6
|
-
return `@vigor-fetch:::${b} <- ${n}`;
|
|
7
|
-
}
|
|
8
|
-
const VigorDefault = Symbol("VigorDefault");
|
|
9
|
-
/** Type guard checking whether a value is the {@link VigorDefault} sentinel. */
|
|
10
|
-
const isVigorDefault = (v) => v === VigorDefault;
|
|
11
|
-
const VigorEmpty = Symbol("VigorEmpty");
|
|
12
|
-
/** Type guard checking whether a value is the {@link VigorEmpty} sentinel. */
|
|
13
|
-
const isVigorEmpty = (v) => v === VigorEmpty;
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Base class for Vigor's immutable, chainable builder objects.
|
|
17
|
-
*
|
|
18
|
-
* Each subclass holds a `base` config and a current `config`, and exposes
|
|
19
|
-
* `_next()` to derive a new instance with a patch merged in. Subclasses
|
|
20
|
-
* implement `_create()` to construct the concrete instance type, and the
|
|
21
|
-
* return type of `_next()` is computed through the `TL` type lambda so
|
|
22
|
-
* chained calls stay precisely typed.
|
|
23
|
-
*
|
|
24
|
-
* @typeParam Base - Shape of the full config for this builder.
|
|
25
|
-
* @typeParam Config - Concrete config type held by this instance (extends `Base`).
|
|
26
|
-
* @typeParam TL - Type lambda mapping a config type to the concrete instance type.
|
|
27
|
-
*/
|
|
28
|
-
class VigorStatus {
|
|
29
|
-
_base;
|
|
30
|
-
_config;
|
|
31
|
-
/**
|
|
32
|
-
* @param base - The default/base config for this builder.
|
|
33
|
-
* @param config - The (possibly partial) config to merge onto `base`.
|
|
34
|
-
*/
|
|
35
|
-
constructor(base, config) {
|
|
36
|
-
this._base = base;
|
|
37
|
-
this._config = this._merge(base, config);
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Derives a new instance by merging `patch` onto the current config.
|
|
41
|
-
*
|
|
42
|
-
* @param patch - Values to overwrite/merge in for this step.
|
|
43
|
-
* @param strategy - Optional tree mirroring the shape of `patch`, whose
|
|
44
|
-
* leaves may be `"replace" | "concat" | "merge"` to force the merge
|
|
45
|
-
* behavior at that path. Paths without a strategy fall back to the
|
|
46
|
-
* default behavior (deep merge for objects, concat for arrays).
|
|
47
|
-
*/
|
|
48
|
-
_next(patch, strategy) {
|
|
49
|
-
const merged = this._merge(this._config, patch, strategy);
|
|
50
|
-
return this._create(merged);
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Deep-merges `target` onto `source`, honoring an optional per-path
|
|
54
|
-
* `strategy` tree. Objects merge key by key, arrays concatenate (unless
|
|
55
|
-
* `"replace"` is specified), and any other value is overwritten.
|
|
56
|
-
*/
|
|
57
|
-
_merge(source, target, strategy) {
|
|
58
|
-
const isObj = (v) => v !== null &&
|
|
59
|
-
typeof v === "object" &&
|
|
60
|
-
Object.getPrototypeOf(v) === Object.prototype;
|
|
61
|
-
const merge = (a, b, s) => {
|
|
62
|
-
if (b === undefined || b === null)
|
|
63
|
-
return a;
|
|
64
|
-
if (s === "replace")
|
|
65
|
-
return b;
|
|
66
|
-
if (Array.isArray(a) && Array.isArray(b)) {
|
|
67
|
-
return s === "replace" ? b : [...a, ...b];
|
|
68
|
-
}
|
|
69
|
-
if (isObj(a) && isObj(b)) {
|
|
70
|
-
const r = { ...a };
|
|
71
|
-
const sObj = isObj(s) ? s : undefined;
|
|
72
|
-
for (const k of Object.keys(b)) {
|
|
73
|
-
r[k] = merge(a[k], b[k], sObj?.[k]);
|
|
74
|
-
}
|
|
75
|
-
return r;
|
|
76
|
-
}
|
|
77
|
-
return b;
|
|
78
|
-
};
|
|
79
|
-
return merge(source, target, strategy);
|
|
80
|
-
}
|
|
81
|
-
/** The default/base config this builder was constructed with. */
|
|
82
|
-
get base() {
|
|
83
|
-
return this._base;
|
|
84
|
-
}
|
|
85
|
-
/** The current, merged config for this builder instance. */
|
|
86
|
-
get config() {
|
|
87
|
-
return this._config;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const VigorAllPolicySettingsBase = {
|
|
92
|
-
__brand: createBrand("All", "Policy<Settings<Schema"),
|
|
93
|
-
concurrency: 5,
|
|
94
|
-
onlySuccess: false
|
|
95
|
-
};
|
|
96
|
-
/** Immutable builder for an all-policy's general settings. */
|
|
97
|
-
class VigorAllPolicySettings extends VigorStatus {
|
|
98
|
-
constructor(config = VigorAllBase) {
|
|
99
|
-
super(VigorAllBase, config);
|
|
100
|
-
}
|
|
101
|
-
_create(config) {
|
|
102
|
-
return new VigorAllPolicySettings(config);
|
|
103
|
-
}
|
|
104
|
-
/** Sets the maximum number of tasks run concurrently. */
|
|
105
|
-
concurrency(num) {
|
|
106
|
-
return this._next({ policy: { settings: { concurrency: num } } });
|
|
107
|
-
}
|
|
108
|
-
/** When enabled, filters the final result down to only the tasks that succeeded. */
|
|
109
|
-
onlySuccess(bool) {
|
|
110
|
-
return this._next({ policy: { settings: { onlySuccess: bool } } });
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
const VigorAllPolicyMiddlewaresBase = {
|
|
115
|
-
__brand: createBrand("All", "Policy<Middlewares<Schema"),
|
|
116
|
-
before: [],
|
|
117
|
-
after: [],
|
|
118
|
-
onError: []
|
|
119
|
-
};
|
|
120
|
-
/** Immutable builder for an all-policy's per-task middleware pipeline (`before`, `after`, `onError`). */
|
|
121
|
-
class VigorAllPolicyMiddlewares extends VigorStatus {
|
|
122
|
-
constructor(config = VigorAllBase) {
|
|
123
|
-
super(VigorAllBase, config);
|
|
124
|
-
}
|
|
125
|
-
_create(config) {
|
|
126
|
-
return new VigorAllPolicyMiddlewares(config);
|
|
127
|
-
}
|
|
128
|
-
/** Registers a middleware that runs before each task is invoked. */
|
|
129
|
-
before(func) {
|
|
130
|
-
return this._next({ policy: { middlewares: { before: [func] } } });
|
|
131
|
-
}
|
|
132
|
-
/** Registers a middleware that runs after each task settles successfully. */
|
|
133
|
-
after(func) {
|
|
134
|
-
return this._next({ policy: { middlewares: { after: [func] } } });
|
|
135
|
-
}
|
|
136
|
-
/** Registers a middleware that runs when an individual task fails. */
|
|
137
|
-
onError(func) {
|
|
138
|
-
return this._next({ policy: { middlewares: { onError: [func] } } });
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
const VigorAllPolicyBase = {
|
|
143
|
-
__brand: createBrand("All", "Policy<Schema"),
|
|
144
|
-
target: [],
|
|
145
|
-
settings: VigorAllPolicySettingsBase,
|
|
146
|
-
middlewares: VigorAllPolicyMiddlewaresBase
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
const VigorAllContextBase = {
|
|
150
|
-
__brand: createBrand("All", "Context<Schema"),
|
|
151
|
-
result: VigorDefault,
|
|
152
|
-
policy: VigorAllPolicyBase,
|
|
153
|
-
record: {}
|
|
154
|
-
};
|
|
155
|
-
const VigorAllEachContextBase = {
|
|
156
|
-
__brand: createBrand("All", "EachContext<Schema"),
|
|
157
|
-
result: VigorDefault,
|
|
158
|
-
error: VigorDefault,
|
|
159
|
-
flags: { overrided: false },
|
|
160
|
-
record: {}
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Base class for all Vigor error types. Subclasses (`VigorRetryError`,
|
|
165
|
-
* `VigorFetchError`, `VigorParseError`, `VigorAllError`) fix `C`, `D`, and
|
|
166
|
-
* `T` to their own error-code union, data shape, and context shape.
|
|
167
|
-
*
|
|
168
|
-
* @typeParam C - Union of error codes for the subclass.
|
|
169
|
-
* @typeParam D - Shape of the structured error data.
|
|
170
|
-
* @typeParam T - Shape of the domain context.
|
|
171
|
-
*/
|
|
172
|
-
class VigorError extends Error {
|
|
173
|
-
timestamp = new Date();
|
|
174
|
-
cause;
|
|
175
|
-
code;
|
|
176
|
-
data;
|
|
177
|
-
method;
|
|
178
|
-
context;
|
|
179
|
-
/**
|
|
180
|
-
* @param code - Machine-readable error code.
|
|
181
|
-
* @param message - Human-readable message (rendered after the `[code]` prefix).
|
|
182
|
-
* @param options - Additional error metadata (cause, data, method, context).
|
|
183
|
-
*/
|
|
184
|
-
constructor(code, message, options) {
|
|
185
|
-
super(`[${code}] ${message}`);
|
|
186
|
-
this.name = new.target.name;
|
|
187
|
-
this.code = code;
|
|
188
|
-
this.cause = options.cause;
|
|
189
|
-
this.data = options.data;
|
|
190
|
-
this.method = options.method;
|
|
191
|
-
this.context = options.context;
|
|
192
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
193
|
-
Error.captureStackTrace?.(this, new.target);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
const VigorAllErrorMessageFuncs = {
|
|
198
|
-
EMPTY_TARGET: (_) => `Empty target list`,
|
|
199
|
-
};
|
|
200
|
-
/** Error type thrown by the all module. */
|
|
201
|
-
class VigorAllError extends VigorError {
|
|
202
|
-
/**
|
|
203
|
-
* @param code - One of the all module's error codes.
|
|
204
|
-
* @param options - Error metadata, including the `data` payload for `code`.
|
|
205
|
-
*/
|
|
206
|
-
constructor(code, options) {
|
|
207
|
-
const messageFn = VigorAllErrorMessageFuncs[code];
|
|
208
|
-
super(code, messageFn(options.data), options);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
const VigorAllBase = {
|
|
213
|
-
__brand: createBrand("All", "Schema"),
|
|
214
|
-
policy: VigorAllPolicyBase,
|
|
215
|
-
context: VigorAllContextBase
|
|
216
|
-
};
|
|
217
|
-
/**
|
|
218
|
-
* Immutable builder that runs a list of independent tasks with bounded
|
|
219
|
-
* concurrency, per-task middleware, and either an all-results or
|
|
220
|
-
* only-successes result mode.
|
|
221
|
-
*/
|
|
222
|
-
class VigorAll extends VigorStatus {
|
|
223
|
-
constructor(config = VigorAllBase) {
|
|
224
|
-
super(VigorAllBase, config);
|
|
225
|
-
}
|
|
226
|
-
_create(config) {
|
|
227
|
-
return new VigorAll(config);
|
|
228
|
-
}
|
|
229
|
-
/** Sets the list of tasks to run. */
|
|
230
|
-
target(...funcs) {
|
|
231
|
-
return this._next({ policy: { target: funcs } });
|
|
232
|
-
}
|
|
233
|
-
/** Configures the all-policy's general settings (concurrency, onlySuccess). */
|
|
234
|
-
settings(input) {
|
|
235
|
-
if (typeof input === 'function' || input instanceof VigorAllPolicySettings) {
|
|
236
|
-
const result = typeof input === 'function'
|
|
237
|
-
? input(new VigorAllPolicySettings())
|
|
238
|
-
: input;
|
|
239
|
-
return this._next({
|
|
240
|
-
policy: { settings: result.config.policy.settings }
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
return this._next({ policy: { settings: input } });
|
|
244
|
-
}
|
|
245
|
-
/** Configures the all-policy's per-task middleware pipeline. */
|
|
246
|
-
middlewares(input) {
|
|
247
|
-
if (typeof input === 'function' || input instanceof VigorAllPolicyMiddlewares) {
|
|
248
|
-
const result = typeof input === 'function'
|
|
249
|
-
? input(new VigorAllPolicyMiddlewares())
|
|
250
|
-
: input;
|
|
251
|
-
return this._next({
|
|
252
|
-
policy: { middlewares: result.config.policy.middlewares }
|
|
253
|
-
});
|
|
254
|
-
}
|
|
255
|
-
return this._next({ policy: { middlewares: input } });
|
|
256
|
-
}
|
|
257
|
-
/** Runs a single task through the before/after/onError middleware pipeline. */
|
|
258
|
-
async _runTask(task, policy) {
|
|
259
|
-
let ctx = { ...VigorAllEachContextBase };
|
|
260
|
-
try {
|
|
261
|
-
for (const before of policy.middlewares.before)
|
|
262
|
-
await before(ctx);
|
|
263
|
-
ctx.result = await task();
|
|
264
|
-
for (const after of policy.middlewares.after)
|
|
265
|
-
await after(ctx);
|
|
266
|
-
return { success: true, value: ctx.result };
|
|
267
|
-
}
|
|
268
|
-
catch (error) {
|
|
269
|
-
ctx.error = error;
|
|
270
|
-
const setResult = (r) => { ctx.flags.overrided = true; ctx.result = r; };
|
|
271
|
-
for (const onError of policy.middlewares.onError)
|
|
272
|
-
await onError(ctx, { setResult });
|
|
273
|
-
if (ctx.flags.overrided)
|
|
274
|
-
return { success: true, value: ctx.result };
|
|
275
|
-
return { success: false, value: error };
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
/** Runs all tasks and returns the results array directly, throwing on final failure. */
|
|
279
|
-
async request() {
|
|
280
|
-
const res = await this.requestVerbose();
|
|
281
|
-
if (res.success)
|
|
282
|
-
return res.data;
|
|
283
|
-
throw res.error;
|
|
284
|
-
}
|
|
285
|
-
/** Runs all tasks and returns a result/error envelope instead of throwing. */
|
|
286
|
-
async requestVerbose() {
|
|
287
|
-
return await this.requestRuntime();
|
|
288
|
-
}
|
|
289
|
-
/** Internal execution loop implementing the bounded-concurrency worker pool. */
|
|
290
|
-
async requestRuntime(restartAttempt = 1) {
|
|
291
|
-
const config = this._merge(this.config, {});
|
|
292
|
-
const policy = config.policy;
|
|
293
|
-
try {
|
|
294
|
-
if (policy.target.length === 0)
|
|
295
|
-
throw new VigorAllError("EMPTY_TARGET", {
|
|
296
|
-
method: "request",
|
|
297
|
-
data: {}
|
|
298
|
-
});
|
|
299
|
-
const concurrency = Math.max(1, policy.settings.concurrency);
|
|
300
|
-
const results = new Array(policy.target.length);
|
|
301
|
-
let cursor = 0;
|
|
302
|
-
const worker = async () => {
|
|
303
|
-
while (true) {
|
|
304
|
-
const i = cursor++;
|
|
305
|
-
if (i >= policy.target.length)
|
|
306
|
-
return;
|
|
307
|
-
results[i] = await this._runTask(policy.target[i], policy);
|
|
308
|
-
}
|
|
309
|
-
};
|
|
310
|
-
await Promise.all(Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker()));
|
|
311
|
-
const result = policy.settings.onlySuccess
|
|
312
|
-
? results.filter(r => r.success).map(r => r.value)
|
|
313
|
-
: results.map(r => r.value);
|
|
314
|
-
return {
|
|
315
|
-
success: true,
|
|
316
|
-
data: result,
|
|
317
|
-
error: null
|
|
318
|
-
};
|
|
319
|
-
}
|
|
320
|
-
catch (error) {
|
|
321
|
-
return {
|
|
322
|
-
success: false,
|
|
323
|
-
data: null,
|
|
324
|
-
error
|
|
325
|
-
};
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
const VigorFetchPolicySettingsBase = {
|
|
331
|
-
__brand: createBrand("Fetch", "Policy<Settings<Schema"),
|
|
332
|
-
retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"],
|
|
333
|
-
unretryStatus: [400, 401, 403, 404, 405, 413, 422],
|
|
334
|
-
maxRestarts: 3,
|
|
335
|
-
default: VigorEmpty
|
|
336
|
-
};
|
|
337
|
-
/** Immutable builder for a fetch policy's general settings. */
|
|
338
|
-
class VigorFetchPolicySettings extends VigorStatus {
|
|
339
|
-
constructor(config = VigorFetchBase) {
|
|
340
|
-
super(VigorFetchBase, config);
|
|
341
|
-
}
|
|
342
|
-
_create(config) {
|
|
343
|
-
return new VigorFetchPolicySettings(config);
|
|
344
|
-
}
|
|
345
|
-
/** Sets response headers consulted to compute a server-suggested retry delay. */
|
|
346
|
-
retryHeaders(...strs) {
|
|
347
|
-
return this._next({ policy: { settings: { retryHeaders: strs } } });
|
|
348
|
-
}
|
|
349
|
-
/** Sets HTTP status codes that should never be retried. */
|
|
350
|
-
unretryStatus(...nums) {
|
|
351
|
-
return this._next({ policy: { settings: { unretryStatus: nums } } });
|
|
352
|
-
}
|
|
353
|
-
/** Sets the maximum number of full restarts allowed. */
|
|
354
|
-
maxRestarts(num) {
|
|
355
|
-
return this._next({ policy: { settings: { maxRestarts: num } } });
|
|
356
|
-
}
|
|
357
|
-
/** Sets the fallback value/factory used when the request ultimately fails. */
|
|
358
|
-
default(func) {
|
|
359
|
-
return this._next({ policy: { settings: { default: func } } });
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
const VigorFetchPolicyMiddlewaresBase = {
|
|
364
|
-
__brand: createBrand("Fetch", "Policy<Middlewares<Schema"),
|
|
365
|
-
before: [],
|
|
366
|
-
after: [],
|
|
367
|
-
onResult: [],
|
|
368
|
-
onError: []
|
|
369
|
-
};
|
|
370
|
-
/**
|
|
371
|
-
* Immutable builder for a fetch policy's middleware pipeline (`before`,
|
|
372
|
-
* `after`, `onResult`, `onError`). Each stage accepts either "fluent"
|
|
373
|
-
* middleware (returns a plain value merged into the context) or
|
|
374
|
-
* "intercept" middleware (receives an explicit API to mutate control flow).
|
|
375
|
-
*/
|
|
376
|
-
class VigorFetchPolicyMiddlewares extends VigorStatus {
|
|
377
|
-
constructor(config = VigorFetchBase) {
|
|
378
|
-
super(VigorFetchBase, config);
|
|
379
|
-
}
|
|
380
|
-
_create(config) {
|
|
381
|
-
return new VigorFetchPolicyMiddlewares(config);
|
|
382
|
-
}
|
|
383
|
-
before(type, func) {
|
|
384
|
-
return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
|
|
385
|
-
}
|
|
386
|
-
after(type, func) {
|
|
387
|
-
return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
|
|
388
|
-
}
|
|
389
|
-
onResult(type, func) {
|
|
390
|
-
return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
|
|
391
|
-
}
|
|
392
|
-
onError(type, func) {
|
|
393
|
-
return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
const VigorRetryPolicySettingsBase = {
|
|
398
|
-
__brand: createBrand("Retry", "Policy<Settings<Schema"),
|
|
399
|
-
default: VigorEmpty,
|
|
400
|
-
maxAttempts: 5,
|
|
401
|
-
maxRestarts: 3,
|
|
402
|
-
timeout: 20000
|
|
403
|
-
};
|
|
404
|
-
/** Immutable builder for a retry policy's general settings. */
|
|
405
|
-
class VigorRetryPolicySettings extends VigorStatus {
|
|
406
|
-
constructor(config = VigorRetryBase) {
|
|
407
|
-
super(VigorRetryBase, config);
|
|
408
|
-
}
|
|
409
|
-
_create(config) {
|
|
410
|
-
return new VigorRetryPolicySettings(config);
|
|
411
|
-
}
|
|
412
|
-
/** Sets the fallback value/factory used when the target ultimately fails. */
|
|
413
|
-
default(func) {
|
|
414
|
-
return this._next({
|
|
415
|
-
policy: { settings: { default: func } }
|
|
416
|
-
});
|
|
417
|
-
}
|
|
418
|
-
/** Sets the maximum number of retry attempts before giving up. */
|
|
419
|
-
maxAttempts(num) {
|
|
420
|
-
return this._next({
|
|
421
|
-
policy: { settings: { maxAttempts: num } }
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
/** Sets the maximum number of full restarts allowed. */
|
|
425
|
-
maxRestarts(num) {
|
|
426
|
-
return this._next({
|
|
427
|
-
policy: { settings: { maxRestarts: num } }
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
/** Sets the timeout, in milliseconds, for a single attempt. */
|
|
431
|
-
timeout(num) {
|
|
432
|
-
return this._next({
|
|
433
|
-
policy: { settings: { timeout: num } }
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
const VigorRetryPolicyMiddlewaresBase = {
|
|
439
|
-
__brand: createBrand("Retry", "Policy<Middlewares<Schema"),
|
|
440
|
-
before: [],
|
|
441
|
-
after: [],
|
|
442
|
-
onResult: [],
|
|
443
|
-
retryIf: [],
|
|
444
|
-
onRetry: [],
|
|
445
|
-
onError: []
|
|
446
|
-
};
|
|
447
|
-
/**
|
|
448
|
-
* Immutable builder for a retry policy's middleware pipeline (`before`,
|
|
449
|
-
* `after`, `onResult`, `retryIf`, `onRetry`, `onError`). Each stage accepts
|
|
450
|
-
* either "fluent" middleware (returns a plain value merged into the
|
|
451
|
-
* context) or "intercept" middleware (receives an explicit API to mutate
|
|
452
|
-
* control flow).
|
|
453
|
-
*/
|
|
454
|
-
class VigorRetryPolicyMiddlewares extends VigorStatus {
|
|
455
|
-
constructor(config = VigorRetryBase) {
|
|
456
|
-
super(VigorRetryBase, config);
|
|
457
|
-
}
|
|
458
|
-
_create(config) {
|
|
459
|
-
return new VigorRetryPolicyMiddlewares(config);
|
|
460
|
-
}
|
|
461
|
-
before(type, func) {
|
|
462
|
-
return this._next({
|
|
463
|
-
policy: { middlewares: { before: [{ _mode: type, func }] } }
|
|
464
|
-
});
|
|
465
|
-
}
|
|
466
|
-
after(type, func) {
|
|
467
|
-
return this._next({
|
|
468
|
-
policy: { middlewares: { after: [{ _mode: type, func }] } }
|
|
469
|
-
});
|
|
470
|
-
}
|
|
471
|
-
onResult(type, func) {
|
|
472
|
-
return this._next({
|
|
473
|
-
policy: { middlewares: { onResult: [{ _mode: type, func }] } }
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
retryIf(type, func) {
|
|
477
|
-
return this._next({
|
|
478
|
-
policy: { middlewares: { retryIf: [{ _mode: type, func }] } }
|
|
479
|
-
});
|
|
480
|
-
}
|
|
481
|
-
onRetry(type, func) {
|
|
482
|
-
return this._next({
|
|
483
|
-
policy: { middlewares: { onRetry: [{ _mode: type, func }] } }
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
onError(type, func) {
|
|
487
|
-
return this._next({
|
|
488
|
-
policy: { middlewares: { onError: [{ _mode: type, func }] } }
|
|
489
|
-
});
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
const VigorRetryErrorMessageFuncs = {
|
|
494
|
-
VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
|
|
495
|
-
RETRY_EXHAUSTED: ({ maxAttempts }) => `Retry exhausted, (max ${maxAttempts})`,
|
|
496
|
-
RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
|
|
497
|
-
TIMED_OUT: ({ limit }) => `Timeout: exceeded ${limit}ms`,
|
|
498
|
-
};
|
|
499
|
-
/** Error type thrown by the retry module. */
|
|
500
|
-
class VigorRetryError extends VigorError {
|
|
501
|
-
/**
|
|
502
|
-
* @param code - One of the retry module's error codes.
|
|
503
|
-
* @param options - Error metadata, including the `data` payload for `code`.
|
|
504
|
-
*/
|
|
505
|
-
constructor(code, options) {
|
|
506
|
-
const messageFn = VigorRetryErrorMessageFuncs[code];
|
|
507
|
-
super(code, messageFn(options.data), options);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
/** Returns a random offset in the range `[-jitter, +jitter]` to randomize a computed delay. */
|
|
512
|
-
function VigorJitter(jitter) {
|
|
513
|
-
return (Math.random() * 2 - 1) * jitter;
|
|
514
|
-
}
|
|
515
|
-
const VigorRetryPolicyAlgorithmsConstantBase = {
|
|
516
|
-
__brand: createBrand("Retry", "Policy<Algorithms<Constant<Schema"),
|
|
517
|
-
_tag: "constant",
|
|
518
|
-
jitter: 1000,
|
|
519
|
-
interval: 2000,
|
|
520
|
-
_calculateDelay: (att, config) => {
|
|
521
|
-
const { interval, jitter } = config;
|
|
522
|
-
const min = jitter;
|
|
523
|
-
let delay = Math.max(min, interval);
|
|
524
|
-
delay += VigorJitter(jitter);
|
|
525
|
-
return delay;
|
|
526
|
-
}
|
|
527
|
-
};
|
|
528
|
-
/** Immutable builder for the constant-interval retry delay algorithm. */
|
|
529
|
-
class VigorRetryPolicyAlgorithmsConstant extends VigorStatus {
|
|
530
|
-
constructor(config = VigorRetryPolicyAlgorithmsConstantBase) {
|
|
531
|
-
super(VigorRetryPolicyAlgorithmsConstantBase, config);
|
|
532
|
-
}
|
|
533
|
-
_create(config) {
|
|
534
|
-
return new VigorRetryPolicyAlgorithmsConstant(config);
|
|
535
|
-
}
|
|
536
|
-
/** Sets the amount of random jitter added to the computed delay. */
|
|
537
|
-
jitter(num) {
|
|
538
|
-
return this._next({ jitter: num });
|
|
539
|
-
}
|
|
540
|
-
/** Sets the fixed delay interval, in milliseconds. */
|
|
541
|
-
interval(num) {
|
|
542
|
-
return this._next({ interval: num });
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
const VigorRetryPolicyAlgorithmsLinearBase = {
|
|
546
|
-
__brand: createBrand("Retry", "Policy<Algorithms<Linear<Schema"),
|
|
547
|
-
_tag: "linear",
|
|
548
|
-
jitter: 1000,
|
|
549
|
-
initial: 500,
|
|
550
|
-
increment: 1000,
|
|
551
|
-
minDelay: 0,
|
|
552
|
-
maxDelay: 10000,
|
|
553
|
-
_calculateDelay: (att, config) => {
|
|
554
|
-
const { initial, jitter, increment, minDelay, maxDelay } = config;
|
|
555
|
-
const range = maxDelay - minDelay;
|
|
556
|
-
const j = Math.min(jitter, range / 2);
|
|
557
|
-
const min = minDelay + j;
|
|
558
|
-
const max = maxDelay - j;
|
|
559
|
-
let delay = initial + increment * att;
|
|
560
|
-
delay = Math.max(min, Math.min(max, delay));
|
|
561
|
-
delay += VigorJitter(j);
|
|
562
|
-
return delay;
|
|
563
|
-
}
|
|
564
|
-
};
|
|
565
|
-
/** Immutable builder for the linearly-increasing retry delay algorithm. */
|
|
566
|
-
class VigorRetryPolicyAlgorithmsLinear extends VigorStatus {
|
|
567
|
-
constructor(config = VigorRetryPolicyAlgorithmsLinearBase) {
|
|
568
|
-
super(VigorRetryPolicyAlgorithmsLinearBase, config);
|
|
569
|
-
}
|
|
570
|
-
_create(config) {
|
|
571
|
-
return new VigorRetryPolicyAlgorithmsLinear(config);
|
|
572
|
-
}
|
|
573
|
-
/** Sets the amount of random jitter added to the computed delay. */
|
|
574
|
-
jitter(num) {
|
|
575
|
-
return this._next({ jitter: num });
|
|
576
|
-
}
|
|
577
|
-
/** Sets the initial delay, in milliseconds, before the first retry. */
|
|
578
|
-
initial(num) {
|
|
579
|
-
return this._next({ initial: num });
|
|
580
|
-
}
|
|
581
|
-
/** Sets how much the delay grows, in milliseconds, per attempt. */
|
|
582
|
-
increment(num) {
|
|
583
|
-
return this._next({ increment: num });
|
|
584
|
-
}
|
|
585
|
-
/** Sets the minimum allowed delay, in milliseconds. */
|
|
586
|
-
minDelay(num) {
|
|
587
|
-
return this._next({ minDelay: num });
|
|
588
|
-
}
|
|
589
|
-
/** Sets the maximum allowed delay, in milliseconds. */
|
|
590
|
-
maxDelay(num) {
|
|
591
|
-
return this._next({ maxDelay: num });
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
const VigorRetryPolicyAlgorithmsBackoffBase = {
|
|
595
|
-
__brand: createBrand("Retry", "Policy<Algorithms<Backoff<Schema"),
|
|
596
|
-
_tag: "backoff",
|
|
597
|
-
jitter: 800,
|
|
598
|
-
initial: 0,
|
|
599
|
-
multiplier: 1.7,
|
|
600
|
-
unit: 1000,
|
|
601
|
-
minDelay: 500,
|
|
602
|
-
maxDelay: 10000,
|
|
603
|
-
_calculateDelay: (att, config) => {
|
|
604
|
-
const { jitter, initial, multiplier, unit, minDelay, maxDelay } = config;
|
|
605
|
-
const range = maxDelay - minDelay;
|
|
606
|
-
const j = Math.min(jitter, range / 2);
|
|
607
|
-
const min = minDelay + j;
|
|
608
|
-
const max = maxDelay - j;
|
|
609
|
-
let delay = initial + unit * Math.pow(multiplier, att);
|
|
610
|
-
delay = Math.max(min, Math.min(max, delay));
|
|
611
|
-
delay += VigorJitter(j);
|
|
612
|
-
return delay;
|
|
613
|
-
}
|
|
614
|
-
};
|
|
615
|
-
/** Immutable builder for the exponential-backoff retry delay algorithm. */
|
|
616
|
-
class VigorRetryPolicyAlgorithmsBackoff extends VigorStatus {
|
|
617
|
-
constructor(config = VigorRetryPolicyAlgorithmsBackoffBase) {
|
|
618
|
-
super(VigorRetryPolicyAlgorithmsBackoffBase, config);
|
|
619
|
-
}
|
|
620
|
-
_create(config) {
|
|
621
|
-
return new VigorRetryPolicyAlgorithmsBackoff(config);
|
|
622
|
-
}
|
|
623
|
-
/** Sets the amount of random jitter added to the computed delay. */
|
|
624
|
-
jitter(num) {
|
|
625
|
-
return this._next({ jitter: num });
|
|
626
|
-
}
|
|
627
|
-
/** Sets the initial delay, in milliseconds, before backoff growth is applied. */
|
|
628
|
-
initial(num) {
|
|
629
|
-
return this._next({ initial: num });
|
|
630
|
-
}
|
|
631
|
-
/** Sets the exponential growth factor applied per attempt. */
|
|
632
|
-
multiplier(num) {
|
|
633
|
-
return this._next({ multiplier: num });
|
|
634
|
-
}
|
|
635
|
-
/** Sets the base unit, in milliseconds, the multiplier is scaled by. */
|
|
636
|
-
unit(num) {
|
|
637
|
-
return this._next({ unit: num });
|
|
638
|
-
}
|
|
639
|
-
/** Sets the minimum allowed delay, in milliseconds. */
|
|
640
|
-
minDelay(num) {
|
|
641
|
-
return this._next({ minDelay: num });
|
|
642
|
-
}
|
|
643
|
-
/** Sets the maximum allowed delay, in milliseconds. */
|
|
644
|
-
maxDelay(num) {
|
|
645
|
-
return this._next({ maxDelay: num });
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
const VigorRetryPolicyAlgorithmsCustomBase = {
|
|
649
|
-
__brand: createBrand("Retry", "Policy<Algorithms<Custom<Schema"),
|
|
650
|
-
_tag: "custom",
|
|
651
|
-
jitter: 800,
|
|
652
|
-
minDelay: 500,
|
|
653
|
-
maxDelay: 10000,
|
|
654
|
-
target: VigorEmpty,
|
|
655
|
-
_calculateDelay: (att, config) => {
|
|
656
|
-
const { jitter, minDelay, maxDelay, target } = config;
|
|
657
|
-
if (isVigorEmpty(target))
|
|
658
|
-
throw new VigorRetryError("VALUE_REQUIRED", {
|
|
659
|
-
method: "_calculateDelay",
|
|
660
|
-
data: {
|
|
661
|
-
key: "target"
|
|
662
|
-
}
|
|
663
|
-
});
|
|
664
|
-
const range = maxDelay - minDelay;
|
|
665
|
-
const j = Math.min(jitter, range / 2);
|
|
666
|
-
const min = minDelay + j;
|
|
667
|
-
const max = maxDelay - j;
|
|
668
|
-
let delay = target(att);
|
|
669
|
-
delay = Math.max(min, Math.min(max, delay));
|
|
670
|
-
delay += VigorJitter(j);
|
|
671
|
-
return delay;
|
|
672
|
-
}
|
|
673
|
-
};
|
|
674
|
-
/** Immutable builder for a user-supplied custom retry delay algorithm. */
|
|
675
|
-
class VigorRetryPolicyAlgorithmsCustom extends VigorStatus {
|
|
676
|
-
constructor(config = VigorRetryPolicyAlgorithmsCustomBase) {
|
|
677
|
-
super(VigorRetryPolicyAlgorithmsCustomBase, config);
|
|
678
|
-
}
|
|
679
|
-
_create(config) {
|
|
680
|
-
return new VigorRetryPolicyAlgorithmsCustom(config);
|
|
681
|
-
}
|
|
682
|
-
/** Sets the amount of random jitter added to the computed delay. */
|
|
683
|
-
jitter(num) {
|
|
684
|
-
return this._next({ jitter: num });
|
|
685
|
-
}
|
|
686
|
-
/** Sets the minimum allowed delay, in milliseconds. */
|
|
687
|
-
minDelay(num) {
|
|
688
|
-
return this._next({ minDelay: num });
|
|
689
|
-
}
|
|
690
|
-
/** Sets the maximum allowed delay, in milliseconds. */
|
|
691
|
-
maxDelay(num) {
|
|
692
|
-
return this._next({ maxDelay: num });
|
|
693
|
-
}
|
|
694
|
-
/** Sets the user-supplied function computing the raw delay for an attempt. */
|
|
695
|
-
target(func) {
|
|
696
|
-
return this._next({ target: func });
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
const VigorRetryPolicyAlgorithmsBase = VigorRetryPolicyAlgorithmsConstantBase;
|
|
700
|
-
/**
|
|
701
|
-
* Immutable builder for selecting a retry policy's delay algorithm.
|
|
702
|
-
*
|
|
703
|
-
* Switching algorithms (`constant`/`linear`/`backoff`/`custom`) always
|
|
704
|
-
* replaces the previous algorithm's config wholesale via the `"replace"`
|
|
705
|
-
* merge strategy, since the different algorithms' fields are not
|
|
706
|
-
* compatible with one another.
|
|
707
|
-
*/
|
|
708
|
-
class VigorRetryPolicyAlgorithms extends VigorStatus {
|
|
709
|
-
constructor(config = VigorRetryBase) {
|
|
710
|
-
super(VigorRetryBase, config);
|
|
711
|
-
}
|
|
712
|
-
_create(config) {
|
|
713
|
-
return new VigorRetryPolicyAlgorithms(config);
|
|
714
|
-
}
|
|
715
|
-
/** Switches to the constant-interval delay algorithm. */
|
|
716
|
-
constant(input) {
|
|
717
|
-
const leaf = this._merge(VigorRetryPolicyAlgorithmsConstantBase, input ?? {});
|
|
718
|
-
return this._next({
|
|
719
|
-
policy: { algorithms: leaf }
|
|
720
|
-
}, { policy: { algorithms: "replace" } });
|
|
721
|
-
}
|
|
722
|
-
/** Switches to the linearly-increasing delay algorithm. */
|
|
723
|
-
linear(input) {
|
|
724
|
-
const leaf = this._merge(VigorRetryPolicyAlgorithmsLinearBase, input ?? {});
|
|
725
|
-
return this._next({
|
|
726
|
-
policy: { algorithms: leaf }
|
|
727
|
-
}, { policy: { algorithms: "replace" } });
|
|
728
|
-
}
|
|
729
|
-
/** Switches to the exponential-backoff delay algorithm. */
|
|
730
|
-
backoff(input) {
|
|
731
|
-
const leaf = this._merge(VigorRetryPolicyAlgorithmsBackoffBase, input ?? {});
|
|
732
|
-
return this._next({
|
|
733
|
-
policy: { algorithms: leaf }
|
|
734
|
-
}, { policy: { algorithms: "replace" } });
|
|
735
|
-
}
|
|
736
|
-
/** Switches to a user-supplied custom delay algorithm. */
|
|
737
|
-
custom(input) {
|
|
738
|
-
const leaf = this._merge(VigorRetryPolicyAlgorithmsCustomBase, input ?? {});
|
|
739
|
-
return this._next({
|
|
740
|
-
policy: { algorithms: leaf }
|
|
741
|
-
}, { policy: { algorithms: "replace" } });
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
|
|
745
|
-
const VigorRetryPolicyBase = {
|
|
746
|
-
__brand: createBrand("Retry", "Policy<Schema"),
|
|
747
|
-
target: VigorEmpty,
|
|
748
|
-
abortSignals: [],
|
|
749
|
-
settings: VigorRetryPolicySettingsBase,
|
|
750
|
-
middlewares: VigorRetryPolicyMiddlewaresBase,
|
|
751
|
-
algorithms: VigorRetryPolicyAlgorithmsBase
|
|
752
|
-
};
|
|
753
|
-
|
|
754
|
-
const VigorRetryContextBase = {
|
|
755
|
-
__brand: createBrand("Retry", "Context<Schema"),
|
|
756
|
-
result: VigorDefault,
|
|
757
|
-
error: VigorDefault,
|
|
758
|
-
system: {
|
|
759
|
-
delay: VigorDefault,
|
|
760
|
-
attempt: 0
|
|
761
|
-
},
|
|
762
|
-
flags: {
|
|
763
|
-
doRetry: true,
|
|
764
|
-
doRestart: false,
|
|
765
|
-
brokeRetry: false,
|
|
766
|
-
overridden: false
|
|
767
|
-
},
|
|
768
|
-
record: {},
|
|
769
|
-
policy: VigorRetryPolicyBase
|
|
770
|
-
};
|
|
771
|
-
|
|
772
|
-
const VigorRetryBase = {
|
|
773
|
-
__brand: createBrand("Retry", "Schema"),
|
|
774
|
-
policy: VigorRetryPolicyBase,
|
|
775
|
-
context: VigorRetryContextBase
|
|
776
|
-
};
|
|
777
|
-
/**
|
|
778
|
-
* Immutable builder that executes a target function with retry, restart,
|
|
779
|
-
* timeout, and abort support, driven by a configurable delay algorithm and
|
|
780
|
-
* middleware pipeline.
|
|
781
|
-
*/
|
|
782
|
-
class VigorRetry extends VigorStatus {
|
|
783
|
-
constructor(config = VigorRetryBase) {
|
|
784
|
-
super(VigorRetryBase, config);
|
|
785
|
-
}
|
|
786
|
-
_create(config) {
|
|
787
|
-
return new VigorRetry(config);
|
|
788
|
-
}
|
|
789
|
-
/** Sets the target function to invoke, with retry/timeout applied. */
|
|
790
|
-
target(func) {
|
|
791
|
-
return this._next({
|
|
792
|
-
policy: { target: func }
|
|
793
|
-
});
|
|
794
|
-
}
|
|
795
|
-
/** Sets external abort signals that, when aborted, stop retrying. */
|
|
796
|
-
abortSignals(...sig) {
|
|
797
|
-
return this._next({
|
|
798
|
-
policy: { abortSignals: sig }
|
|
799
|
-
});
|
|
800
|
-
}
|
|
801
|
-
/** Configures the retry policy's general settings (max attempts, timeout, etc). */
|
|
802
|
-
settings(input) {
|
|
803
|
-
if (typeof input === 'function' || input instanceof VigorRetryPolicySettings) {
|
|
804
|
-
const result = typeof input === 'function'
|
|
805
|
-
? input(new VigorRetryPolicySettings())
|
|
806
|
-
: input;
|
|
807
|
-
return this._next({
|
|
808
|
-
policy: { settings: result.config.policy.settings }
|
|
809
|
-
});
|
|
810
|
-
}
|
|
811
|
-
return this._next({
|
|
812
|
-
policy: { settings: input }
|
|
813
|
-
});
|
|
814
|
-
}
|
|
815
|
-
/** Configures the retry policy's middleware pipeline. */
|
|
816
|
-
middlewares(input) {
|
|
817
|
-
if (typeof input === 'function' || input instanceof VigorRetryPolicyMiddlewares) {
|
|
818
|
-
const result = typeof input === 'function'
|
|
819
|
-
? input(new VigorRetryPolicyMiddlewares())
|
|
820
|
-
: input;
|
|
821
|
-
return this._next({
|
|
822
|
-
policy: { middlewares: result.config.policy.middlewares }
|
|
823
|
-
});
|
|
824
|
-
}
|
|
825
|
-
return this._next({
|
|
826
|
-
policy: { middlewares: input }
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
/** Configures the retry policy's delay algorithm. */
|
|
830
|
-
algorithms(input) {
|
|
831
|
-
if (typeof input === 'function') {
|
|
832
|
-
const result = input(new VigorRetryPolicyAlgorithms());
|
|
833
|
-
const algoSlice = result.config.policy.algorithms;
|
|
834
|
-
return this._next({
|
|
835
|
-
policy: { algorithms: algoSlice }
|
|
836
|
-
}, { policy: { algorithms: "replace" } });
|
|
837
|
-
}
|
|
838
|
-
return this._next({
|
|
839
|
-
policy: { algorithms: input }
|
|
840
|
-
}, { policy: { algorithms: "replace" } });
|
|
841
|
-
}
|
|
842
|
-
/** Runs the target and returns its result directly, throwing on final failure. */
|
|
843
|
-
async request() {
|
|
844
|
-
const res = await this.requestVerbose();
|
|
845
|
-
if (res.success)
|
|
846
|
-
return res.data;
|
|
847
|
-
throw res.error;
|
|
848
|
-
}
|
|
849
|
-
/** Runs the target and returns a result/error envelope instead of throwing. */
|
|
850
|
-
async requestVerbose() {
|
|
851
|
-
return await this.requestRuntime();
|
|
852
|
-
}
|
|
853
|
-
/** Internal execution loop implementing the attempt/retry/restart lifecycle. */
|
|
854
|
-
async requestRuntime(restartAttempt = 1) {
|
|
855
|
-
const config = this._merge(this.config, {});
|
|
856
|
-
let ctx = {
|
|
857
|
-
...config.context,
|
|
858
|
-
policy: config.policy
|
|
859
|
-
};
|
|
860
|
-
if (isVigorEmpty(ctx.policy.target))
|
|
861
|
-
throw new VigorRetryError("VALUE_REQUIRED", {
|
|
862
|
-
method: "request",
|
|
863
|
-
data: {
|
|
864
|
-
key: "target"
|
|
865
|
-
},
|
|
866
|
-
context: ctx
|
|
867
|
-
});
|
|
868
|
-
const target = ctx.policy.target;
|
|
869
|
-
const throwError = (err) => {
|
|
870
|
-
throw err;
|
|
871
|
-
};
|
|
872
|
-
try {
|
|
873
|
-
while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
|
|
874
|
-
ctx.system.attempt++;
|
|
875
|
-
try {
|
|
876
|
-
const breakRetry = (err) => {
|
|
877
|
-
ctx.flags.brokeRetry = true;
|
|
878
|
-
throw err;
|
|
879
|
-
};
|
|
880
|
-
const userController = new AbortController();
|
|
881
|
-
const timeoutController = new AbortController();
|
|
882
|
-
const innerSignals = AbortSignal.any([
|
|
883
|
-
userController.signal,
|
|
884
|
-
timeoutController.signal
|
|
885
|
-
]);
|
|
886
|
-
const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
|
|
887
|
-
const autoBreak = () => {
|
|
888
|
-
ctx.flags.brokeRetry = true;
|
|
889
|
-
};
|
|
890
|
-
outerSignals.addEventListener("abort", autoBreak);
|
|
891
|
-
const mergedSignals = AbortSignal.any([
|
|
892
|
-
innerSignals,
|
|
893
|
-
outerSignals
|
|
894
|
-
]);
|
|
895
|
-
let onAbort;
|
|
896
|
-
let timeoutId;
|
|
897
|
-
try {
|
|
898
|
-
for (const middleware of ctx.policy.middlewares.before) {
|
|
899
|
-
if (middleware._mode === "fluent") {
|
|
900
|
-
await middleware.func(ctx);
|
|
901
|
-
}
|
|
902
|
-
else {
|
|
903
|
-
ctx = await middleware.func(ctx, {
|
|
904
|
-
abort: (reason) => userController.abort(reason),
|
|
905
|
-
throwError,
|
|
906
|
-
breakRetry
|
|
907
|
-
});
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
mergedSignals.throwIfAborted();
|
|
911
|
-
timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
|
|
912
|
-
method: "request",
|
|
913
|
-
data: {
|
|
914
|
-
limit: ctx.policy.settings.timeout
|
|
915
|
-
}
|
|
916
|
-
})), ctx.policy.settings.timeout);
|
|
917
|
-
ctx.result = await Promise.race([
|
|
918
|
-
target(mergedSignals),
|
|
919
|
-
new Promise((_, rej) => {
|
|
920
|
-
onAbort = () => rej(mergedSignals.reason);
|
|
921
|
-
mergedSignals.addEventListener("abort", onAbort);
|
|
922
|
-
})
|
|
923
|
-
]);
|
|
924
|
-
for (const middleware of ctx.policy.middlewares.after) {
|
|
925
|
-
if (middleware._mode === "fluent") {
|
|
926
|
-
await middleware.func(ctx);
|
|
927
|
-
}
|
|
928
|
-
else {
|
|
929
|
-
ctx = await middleware.func(ctx, {
|
|
930
|
-
throwError
|
|
931
|
-
});
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
const setResult = (res) => {
|
|
935
|
-
ctx.result = res;
|
|
936
|
-
};
|
|
937
|
-
for (const middleware of ctx.policy.middlewares.onResult) {
|
|
938
|
-
if (middleware._mode === "fluent") {
|
|
939
|
-
ctx.result = await middleware.func(ctx.result);
|
|
940
|
-
}
|
|
941
|
-
else {
|
|
942
|
-
ctx = await middleware.func(ctx, {
|
|
943
|
-
setResult,
|
|
944
|
-
throwError
|
|
945
|
-
});
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
return {
|
|
949
|
-
success: true,
|
|
950
|
-
data: ctx.result,
|
|
951
|
-
error: null
|
|
952
|
-
};
|
|
953
|
-
}
|
|
954
|
-
finally {
|
|
955
|
-
clearTimeout(timeoutId);
|
|
956
|
-
outerSignals.removeEventListener("abort", autoBreak);
|
|
957
|
-
if (onAbort)
|
|
958
|
-
mergedSignals.removeEventListener("abort", onAbort);
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
catch (error) {
|
|
962
|
-
ctx.error = error;
|
|
963
|
-
if (ctx.flags.brokeRetry)
|
|
964
|
-
throw ctx.error;
|
|
965
|
-
ctx.flags.doRetry = true;
|
|
966
|
-
const proceedRetry = () => ctx.flags.doRetry = true;
|
|
967
|
-
const cancelRetry = () => ctx.flags.doRetry = false;
|
|
968
|
-
for (const middleware of ctx.policy.middlewares.retryIf) {
|
|
969
|
-
if (middleware._mode === "fluent") {
|
|
970
|
-
ctx.flags.doRetry = await middleware.func(ctx.error);
|
|
971
|
-
}
|
|
972
|
-
else {
|
|
973
|
-
ctx = await middleware.func(ctx, {
|
|
974
|
-
proceedRetry,
|
|
975
|
-
cancelRetry
|
|
976
|
-
});
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
if (!ctx.flags.doRetry)
|
|
980
|
-
throw ctx.error;
|
|
981
|
-
ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
|
|
982
|
-
const setDelay = (num) => {
|
|
983
|
-
ctx.system.delay = num;
|
|
984
|
-
};
|
|
985
|
-
for (const middleware of ctx.policy.middlewares.onRetry) {
|
|
986
|
-
if (middleware._mode === "fluent") {
|
|
987
|
-
await middleware.func(ctx.error);
|
|
988
|
-
}
|
|
989
|
-
else {
|
|
990
|
-
ctx = await middleware.func(ctx, {
|
|
991
|
-
throwError,
|
|
992
|
-
setDelay
|
|
993
|
-
});
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
const delay = ctx.system.delay;
|
|
997
|
-
await new Promise(res => setTimeout(res, delay));
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
throw new VigorRetryError("RETRY_EXHAUSTED", {
|
|
1001
|
-
method: "request",
|
|
1002
|
-
data: {
|
|
1003
|
-
maxAttempts: ctx.policy.settings.maxAttempts
|
|
1004
|
-
}
|
|
1005
|
-
});
|
|
1006
|
-
}
|
|
1007
|
-
catch (error) {
|
|
1008
|
-
ctx.error = error;
|
|
1009
|
-
ctx.flags.doRestart = false;
|
|
1010
|
-
ctx.flags.overridden = false;
|
|
1011
|
-
const setResult = (res) => {
|
|
1012
|
-
ctx.flags.overridden = true;
|
|
1013
|
-
ctx.result = res;
|
|
1014
|
-
};
|
|
1015
|
-
const proceedRestart = () => ctx.flags.doRestart = true;
|
|
1016
|
-
const cancelRestart = () => ctx.flags.doRestart = false;
|
|
1017
|
-
for (const middleware of ctx.policy.middlewares.onError) {
|
|
1018
|
-
if (middleware._mode === "fluent") {
|
|
1019
|
-
await middleware.func(ctx.error);
|
|
1020
|
-
}
|
|
1021
|
-
else {
|
|
1022
|
-
ctx = await middleware.func(ctx, {
|
|
1023
|
-
setResult,
|
|
1024
|
-
throwError,
|
|
1025
|
-
proceedRestart,
|
|
1026
|
-
cancelRestart
|
|
1027
|
-
});
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
if (ctx.flags.doRestart) {
|
|
1031
|
-
if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
|
|
1032
|
-
throw new VigorRetryError("RESTART_EXHAUSTED", {
|
|
1033
|
-
method: "request",
|
|
1034
|
-
data: {
|
|
1035
|
-
maxAttempts: ctx.policy.settings.maxRestarts
|
|
1036
|
-
}
|
|
1037
|
-
});
|
|
1038
|
-
return await this.requestRuntime(restartAttempt + 1);
|
|
1039
|
-
}
|
|
1040
|
-
if (ctx.flags.overridden)
|
|
1041
|
-
return {
|
|
1042
|
-
success: true,
|
|
1043
|
-
data: ctx.result,
|
|
1044
|
-
error: null
|
|
1045
|
-
};
|
|
1046
|
-
if (!isVigorEmpty(ctx.policy.settings.default)) {
|
|
1047
|
-
const data = await ctx.policy.settings.default(ctx);
|
|
1048
|
-
return {
|
|
1049
|
-
success: true,
|
|
1050
|
-
data,
|
|
1051
|
-
error: null
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
return {
|
|
1055
|
-
success: false,
|
|
1056
|
-
data: null,
|
|
1057
|
-
error: ctx.error
|
|
1058
|
-
};
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
|
-
|
|
1063
|
-
const VigorParsePolicySettingsBase = {
|
|
1064
|
-
__brand: createBrand("Parse", "Policy<Settings<Schema"),
|
|
1065
|
-
raw: false,
|
|
1066
|
-
default: VigorEmpty,
|
|
1067
|
-
maxRestarts: 3
|
|
1068
|
-
};
|
|
1069
|
-
/** Immutable builder for a parse policy's general settings. */
|
|
1070
|
-
class VigorParsePolicySettings extends VigorStatus {
|
|
1071
|
-
constructor(config = VigorParseBase) {
|
|
1072
|
-
super(VigorParseBase, config);
|
|
1073
|
-
}
|
|
1074
|
-
_create(config) {
|
|
1075
|
-
return new VigorParsePolicySettings(config);
|
|
1076
|
-
}
|
|
1077
|
-
/** When enabled, skips content-type based parsing and returns the raw response. */
|
|
1078
|
-
raw(bool) {
|
|
1079
|
-
return this._next({
|
|
1080
|
-
policy: { settings: { raw: bool } }
|
|
1081
|
-
});
|
|
1082
|
-
}
|
|
1083
|
-
/** Sets the fallback value/factory used when parsing ultimately fails. */
|
|
1084
|
-
default(func) {
|
|
1085
|
-
return this._next({
|
|
1086
|
-
policy: { settings: { default: func } }
|
|
1087
|
-
});
|
|
1088
|
-
}
|
|
1089
|
-
/** Sets the maximum number of full restarts allowed. */
|
|
1090
|
-
maxRestarts(num) {
|
|
1091
|
-
return this._next({
|
|
1092
|
-
policy: { settings: { maxRestarts: num } }
|
|
1093
|
-
});
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
const VigorParsePolicyMiddlewaresBase = {
|
|
1098
|
-
__brand: createBrand("Parse", "Policy<Middlewares<Schema"),
|
|
1099
|
-
before: [],
|
|
1100
|
-
after: [],
|
|
1101
|
-
onResult: [],
|
|
1102
|
-
onError: []
|
|
1103
|
-
};
|
|
1104
|
-
/**
|
|
1105
|
-
* Immutable builder for a parse policy's middleware pipeline (`before`,
|
|
1106
|
-
* `after`, `onResult`, `onError`). Each stage accepts either "fluent"
|
|
1107
|
-
* middleware (returns a plain value merged into the context) or
|
|
1108
|
-
* "intercept" middleware (receives an explicit API to mutate control flow).
|
|
1109
|
-
*/
|
|
1110
|
-
class VigorParsePolicyMiddlewares extends VigorStatus {
|
|
1111
|
-
constructor(config = VigorParseBase) {
|
|
1112
|
-
super(VigorParseBase, config);
|
|
1113
|
-
}
|
|
1114
|
-
_create(config) {
|
|
1115
|
-
return new VigorParsePolicyMiddlewares(config);
|
|
1116
|
-
}
|
|
1117
|
-
before(type, func) {
|
|
1118
|
-
return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
|
|
1119
|
-
}
|
|
1120
|
-
after(type, func) {
|
|
1121
|
-
return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
|
|
1122
|
-
}
|
|
1123
|
-
onResult(type, func) {
|
|
1124
|
-
return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
|
|
1125
|
-
}
|
|
1126
|
-
onError(type, func) {
|
|
1127
|
-
return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
const VigorParseErrorMessageFuncs = {
|
|
1132
|
-
VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
|
|
1133
|
-
INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
|
|
1134
|
-
PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
|
|
1135
|
-
PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
|
|
1136
|
-
RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
|
|
1137
|
-
};
|
|
1138
|
-
/** Error type thrown by the parse module. */
|
|
1139
|
-
class VigorParseError extends VigorError {
|
|
1140
|
-
/**
|
|
1141
|
-
* @param code - One of the parse module's error codes.
|
|
1142
|
-
* @param options - Error metadata, including the `data` payload for `code`.
|
|
1143
|
-
*/
|
|
1144
|
-
constructor(code, options) {
|
|
1145
|
-
const messageFn = VigorParseErrorMessageFuncs[code];
|
|
1146
|
-
super(code, messageFn(options.data), options);
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
const VigorParsePolicyStrategiesBase = {
|
|
1151
|
-
__brand: createBrand("Parse", "Policy<Strategies<Schema"),
|
|
1152
|
-
funcs: []
|
|
1153
|
-
};
|
|
1154
|
-
const ContentTypeParsers = [
|
|
1155
|
-
{ header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
|
|
1156
|
-
{ header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
|
|
1157
|
-
{ header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
|
|
1158
|
-
{ header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
|
|
1159
|
-
{ header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
|
|
1160
|
-
{ header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
|
|
1161
|
-
{ header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
|
|
1162
|
-
{ header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
|
|
1163
|
-
{ header: "text/*", regExp: /^text\/.+/i, method: (res) => res.text() },
|
|
1164
|
-
];
|
|
1165
|
-
const SniffMethods = [
|
|
1166
|
-
{ title: "json", method: (res) => res.json() },
|
|
1167
|
-
{ title: "formData", method: (res) => res.formData() },
|
|
1168
|
-
{ title: "text", method: (res) => res.text() },
|
|
1169
|
-
{ title: "blob", method: (res) => res.blob() },
|
|
1170
|
-
];
|
|
1171
|
-
/** Parses a response by matching its `Content-Type` header against a known parser table. */
|
|
1172
|
-
const VigorParseContentTypeStrategy = async (response) => {
|
|
1173
|
-
const contentTypeHeader = response.headers.get("content-type");
|
|
1174
|
-
if (!contentTypeHeader)
|
|
1175
|
-
throw new VigorParseError("INVALID_CONTENT_TYPE", {
|
|
1176
|
-
method: "VigorParseContentTypeStrategy",
|
|
1177
|
-
data: { received: contentTypeHeader }
|
|
1178
|
-
});
|
|
1179
|
-
const toDo = ContentTypeParsers.find(parser => parser.regExp.test(contentTypeHeader));
|
|
1180
|
-
if (!toDo)
|
|
1181
|
-
throw new VigorParseError("PARSER_NOT_FOUND", {
|
|
1182
|
-
method: "VigorParseContentTypeStrategy",
|
|
1183
|
-
data: {
|
|
1184
|
-
expected: ContentTypeParsers.map(p => p.header),
|
|
1185
|
-
received: contentTypeHeader
|
|
1186
|
-
}
|
|
1187
|
-
});
|
|
1188
|
-
return await toDo.method(response);
|
|
1189
|
-
};
|
|
1190
|
-
/** Parses a response by trying a sequence of body-reading methods until one succeeds. */
|
|
1191
|
-
const VigorParseSniffStrategy = async (response) => {
|
|
1192
|
-
for (const [i, parser] of SniffMethods.entries()) {
|
|
1193
|
-
const cloned = (i === SniffMethods.length - 1) ? response : response.clone();
|
|
1194
|
-
try {
|
|
1195
|
-
return await parser.method(cloned);
|
|
1196
|
-
}
|
|
1197
|
-
catch { }
|
|
1198
|
-
}
|
|
1199
|
-
throw new VigorParseError("PARSER_ALL_FAILED", {
|
|
1200
|
-
method: "VigorParseSniffStrategy",
|
|
1201
|
-
data: { tried: SniffMethods.map(p => p.title) }
|
|
1202
|
-
});
|
|
1203
|
-
};
|
|
1204
|
-
/** Immutable builder for a parse policy's fallback chain of parsing strategies. */
|
|
1205
|
-
class VigorParsePolicyStrategies extends VigorStatus {
|
|
1206
|
-
constructor(config = VigorParseBase) {
|
|
1207
|
-
super(VigorParseBase, config);
|
|
1208
|
-
}
|
|
1209
|
-
_create(config) {
|
|
1210
|
-
return new VigorParsePolicyStrategies(config);
|
|
1211
|
-
}
|
|
1212
|
-
/**
|
|
1213
|
-
* Adds strategy functions to the fallback chain.
|
|
1214
|
-
*
|
|
1215
|
-
* @param replace - When `true`, replaces the existing chain instead of
|
|
1216
|
-
* appending to it (the default is to concat, since strategies are
|
|
1217
|
-
* tried in sequence as a fallback chain).
|
|
1218
|
-
*/
|
|
1219
|
-
_set(funcs, replace) {
|
|
1220
|
-
return this._next({ policy: { strategies: { funcs } } }, replace ? { policy: { strategies: { funcs: "replace" } } } : undefined);
|
|
1221
|
-
}
|
|
1222
|
-
/** Adds the content-type based parsing strategy. */
|
|
1223
|
-
contentType(replace) { return this._set([VigorParseContentTypeStrategy], replace); }
|
|
1224
|
-
/** Adds the sniffing (try-each-method) parsing strategy. */
|
|
1225
|
-
sniff(replace) { return this._set([VigorParseSniffStrategy], replace); }
|
|
1226
|
-
/** Adds a strategy that always parses the response as JSON. */
|
|
1227
|
-
json(replace) { return this._set([(res) => res.json()], replace); }
|
|
1228
|
-
/** Adds a strategy that always parses the response as text. */
|
|
1229
|
-
text(replace) { return this._set([(res) => res.text()], replace); }
|
|
1230
|
-
/** Adds a strategy that always parses the response as an `ArrayBuffer`. */
|
|
1231
|
-
arrayBuffer(replace) { return this._set([(res) => res.arrayBuffer()], replace); }
|
|
1232
|
-
/** Adds a strategy that always parses the response as a `Blob`. */
|
|
1233
|
-
blob(replace) { return this._set([(res) => res.blob()], replace); }
|
|
1234
|
-
/** Adds a strategy that always parses the response as a `Uint8Array`. */
|
|
1235
|
-
bytes(replace) { return this._set([(res) => res.arrayBuffer().then(b => new Uint8Array(b))], replace); }
|
|
1236
|
-
/** Adds a strategy that always parses the response as `FormData`. */
|
|
1237
|
-
formData(replace) { return this._set([(res) => res.formData()], replace); }
|
|
1238
|
-
/** Adds a user-supplied custom parsing strategy. */
|
|
1239
|
-
custom(func, replace) { return this._set([func], replace); }
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
const VigorParsePolicyBase = {
|
|
1243
|
-
__brand: createBrand("Parse", "Policy<Schema"),
|
|
1244
|
-
target: VigorDefault,
|
|
1245
|
-
settings: VigorParsePolicySettingsBase,
|
|
1246
|
-
middlewares: VigorParsePolicyMiddlewaresBase,
|
|
1247
|
-
strategies: VigorParsePolicyStrategiesBase
|
|
1248
|
-
};
|
|
1249
|
-
|
|
1250
|
-
const VigorParseContextBase = {
|
|
1251
|
-
__brand: createBrand("Parse", "Context<Schema"),
|
|
1252
|
-
result: VigorDefault,
|
|
1253
|
-
error: VigorDefault,
|
|
1254
|
-
response: VigorDefault,
|
|
1255
|
-
flags: {
|
|
1256
|
-
overrided: false,
|
|
1257
|
-
restarted: false
|
|
1258
|
-
},
|
|
1259
|
-
record: {},
|
|
1260
|
-
policy: VigorParsePolicyBase
|
|
1261
|
-
};
|
|
1262
|
-
|
|
1263
|
-
const VigorParseBase = {
|
|
1264
|
-
__brand: createBrand("Parse", "Schema"),
|
|
1265
|
-
policy: VigorParsePolicyBase,
|
|
1266
|
-
context: VigorParseContextBase
|
|
1267
|
-
};
|
|
1268
|
-
/**
|
|
1269
|
-
* Immutable builder that parses an HTTP response into a result value,
|
|
1270
|
-
* trying each configured strategy in sequence with an optional middleware
|
|
1271
|
-
* pipeline and restart-on-failure support.
|
|
1272
|
-
*/
|
|
1273
|
-
class VigorParse extends VigorStatus {
|
|
1274
|
-
constructor(config = VigorParseBase) {
|
|
1275
|
-
super(VigorParseBase, config);
|
|
1276
|
-
}
|
|
1277
|
-
_create(config) {
|
|
1278
|
-
return new VigorParse(config);
|
|
1279
|
-
}
|
|
1280
|
-
/** Sets the `Response` object to parse. */
|
|
1281
|
-
target(response) {
|
|
1282
|
-
return this._next({ policy: { target: response } });
|
|
1283
|
-
}
|
|
1284
|
-
/** Configures the parse policy's general settings. */
|
|
1285
|
-
settings(input) {
|
|
1286
|
-
if (typeof input === 'function' || input instanceof VigorParsePolicySettings) {
|
|
1287
|
-
const result = typeof input === 'function'
|
|
1288
|
-
? input(new VigorParsePolicySettings())
|
|
1289
|
-
: input;
|
|
1290
|
-
return this._next({
|
|
1291
|
-
policy: { settings: result.config.policy.settings }
|
|
1292
|
-
});
|
|
1293
|
-
}
|
|
1294
|
-
return this._next({ policy: { settings: input } });
|
|
1295
|
-
}
|
|
1296
|
-
/** Configures the parse policy's middleware pipeline. */
|
|
1297
|
-
middlewares(input) {
|
|
1298
|
-
if (typeof input === 'function' || input instanceof VigorParsePolicyMiddlewares) {
|
|
1299
|
-
const result = typeof input === 'function'
|
|
1300
|
-
? input(new VigorParsePolicyMiddlewares())
|
|
1301
|
-
: input;
|
|
1302
|
-
return this._next({
|
|
1303
|
-
policy: { middlewares: result.config.policy.middlewares }
|
|
1304
|
-
});
|
|
1305
|
-
}
|
|
1306
|
-
return this._next({ policy: { middlewares: input } });
|
|
1307
|
-
}
|
|
1308
|
-
/** Configures the parse policy's fallback chain of parsing strategies. */
|
|
1309
|
-
strategies(input) {
|
|
1310
|
-
if (typeof input === 'function' || input instanceof VigorParsePolicyStrategies) {
|
|
1311
|
-
const result = typeof input === 'function'
|
|
1312
|
-
? input(new VigorParsePolicyStrategies())
|
|
1313
|
-
: input;
|
|
1314
|
-
return this._next({
|
|
1315
|
-
policy: { strategies: result.config.policy.strategies }
|
|
1316
|
-
});
|
|
1317
|
-
}
|
|
1318
|
-
return this._next({ policy: { strategies: input } });
|
|
1319
|
-
}
|
|
1320
|
-
/** Runs parsing and returns the result directly, throwing on final failure. */
|
|
1321
|
-
async request() {
|
|
1322
|
-
const res = await this.requestVerbose();
|
|
1323
|
-
if (res.success)
|
|
1324
|
-
return res.data;
|
|
1325
|
-
throw res.error;
|
|
1326
|
-
}
|
|
1327
|
-
/** Runs parsing and returns a result/error envelope instead of throwing. */
|
|
1328
|
-
async requestVerbose() {
|
|
1329
|
-
return await this.requestRuntime();
|
|
1330
|
-
}
|
|
1331
|
-
/** Internal execution loop implementing the strategy fallback and restart handling. */
|
|
1332
|
-
async requestRuntime(restartAttempt = 1) {
|
|
1333
|
-
const config = this._merge(this.config, {});
|
|
1334
|
-
let ctx = {
|
|
1335
|
-
...config.context,
|
|
1336
|
-
policy: config.policy
|
|
1337
|
-
};
|
|
1338
|
-
if (isVigorDefault(ctx.policy.target))
|
|
1339
|
-
throw new VigorParseError("VALUE_REQUIRED", {
|
|
1340
|
-
method: "request",
|
|
1341
|
-
data: { key: "target" },
|
|
1342
|
-
context: ctx
|
|
1343
|
-
});
|
|
1344
|
-
ctx.response = ctx.policy.target;
|
|
1345
|
-
const throwError = (err) => { throw err; };
|
|
1346
|
-
try {
|
|
1347
|
-
for (const middleware of ctx.policy.middlewares.before) {
|
|
1348
|
-
if (middleware._mode === "fluent") {
|
|
1349
|
-
await middleware.func(ctx);
|
|
1350
|
-
}
|
|
1351
|
-
else {
|
|
1352
|
-
ctx = await middleware.func(ctx, { throwError });
|
|
1353
|
-
}
|
|
1354
|
-
}
|
|
1355
|
-
const response = ctx.response;
|
|
1356
|
-
if (ctx.policy.settings.raw) {
|
|
1357
|
-
ctx.result = response;
|
|
1358
|
-
}
|
|
1359
|
-
else {
|
|
1360
|
-
const funcs = ctx.policy.strategies.funcs.length > 0
|
|
1361
|
-
? ctx.policy.strategies.funcs
|
|
1362
|
-
: [VigorParseContentTypeStrategy];
|
|
1363
|
-
let parsed = false;
|
|
1364
|
-
for (const [i, func] of funcs.entries()) {
|
|
1365
|
-
const cloned = (i === funcs.length - 1) ? response : response.clone();
|
|
1366
|
-
try {
|
|
1367
|
-
ctx.result = await func(cloned);
|
|
1368
|
-
parsed = true;
|
|
1369
|
-
break;
|
|
1370
|
-
}
|
|
1371
|
-
catch { }
|
|
1372
|
-
}
|
|
1373
|
-
if (!parsed)
|
|
1374
|
-
throw new VigorParseError("PARSER_ALL_FAILED", {
|
|
1375
|
-
method: "request",
|
|
1376
|
-
data: { tried: funcs.map((_, i) => `strategy#${i}`) },
|
|
1377
|
-
context: ctx
|
|
1378
|
-
});
|
|
1379
|
-
}
|
|
1380
|
-
const setResult = (res) => { ctx.result = res; };
|
|
1381
|
-
for (const middleware of ctx.policy.middlewares.after) {
|
|
1382
|
-
if (middleware._mode === "fluent") {
|
|
1383
|
-
await middleware.func(ctx);
|
|
1384
|
-
}
|
|
1385
|
-
else {
|
|
1386
|
-
ctx = await middleware.func(ctx, { setResult, throwError });
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
for (const middleware of ctx.policy.middlewares.onResult) {
|
|
1390
|
-
if (middleware._mode === "fluent") {
|
|
1391
|
-
ctx.result = await middleware.func(ctx.result);
|
|
1392
|
-
}
|
|
1393
|
-
else {
|
|
1394
|
-
ctx = await middleware.func(ctx, { setResult, throwError });
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
return {
|
|
1398
|
-
success: true,
|
|
1399
|
-
data: ctx.result,
|
|
1400
|
-
error: null
|
|
1401
|
-
};
|
|
1402
|
-
}
|
|
1403
|
-
catch (error) {
|
|
1404
|
-
ctx.error = error;
|
|
1405
|
-
ctx.flags.overrided = false;
|
|
1406
|
-
ctx.flags.restarted = false;
|
|
1407
|
-
const setResult = (res) => {
|
|
1408
|
-
ctx.flags.overrided = true;
|
|
1409
|
-
ctx.result = res;
|
|
1410
|
-
};
|
|
1411
|
-
const proceedRestart = () => ctx.flags.restarted = true;
|
|
1412
|
-
const cancelRestart = () => ctx.flags.restarted = false;
|
|
1413
|
-
for (const middleware of ctx.policy.middlewares.onError) {
|
|
1414
|
-
if (middleware._mode === "fluent") {
|
|
1415
|
-
await middleware.func(ctx.error);
|
|
1416
|
-
}
|
|
1417
|
-
else {
|
|
1418
|
-
ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
|
|
1419
|
-
}
|
|
1420
|
-
}
|
|
1421
|
-
if (ctx.flags.restarted) {
|
|
1422
|
-
if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
|
|
1423
|
-
throw new VigorParseError("RESTART_EXHAUSTED", {
|
|
1424
|
-
method: "request",
|
|
1425
|
-
data: {
|
|
1426
|
-
maxAttempts: ctx.policy.settings.maxRestarts
|
|
1427
|
-
}
|
|
1428
|
-
});
|
|
1429
|
-
return await this.requestRuntime(restartAttempt + 1);
|
|
1430
|
-
}
|
|
1431
|
-
if (ctx.flags.overrided)
|
|
1432
|
-
return {
|
|
1433
|
-
success: true,
|
|
1434
|
-
data: ctx.result,
|
|
1435
|
-
error: null
|
|
1436
|
-
};
|
|
1437
|
-
if (!isVigorEmpty(ctx.policy.settings.default)) {
|
|
1438
|
-
const data = await ctx.policy.settings.default(ctx);
|
|
1439
|
-
return {
|
|
1440
|
-
success: true,
|
|
1441
|
-
data,
|
|
1442
|
-
error: null
|
|
1443
|
-
};
|
|
1444
|
-
}
|
|
1445
|
-
return {
|
|
1446
|
-
success: false,
|
|
1447
|
-
data: null,
|
|
1448
|
-
error: ctx.error
|
|
1449
|
-
};
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
}
|
|
1453
|
-
|
|
1454
|
-
const VigorFetchPolicyBase = {
|
|
1455
|
-
__brand: createBrand("Fetch", "Policy<Schema"),
|
|
1456
|
-
method: VigorEmpty,
|
|
1457
|
-
origin: VigorEmpty,
|
|
1458
|
-
path: [],
|
|
1459
|
-
query: [],
|
|
1460
|
-
hash: "",
|
|
1461
|
-
headers: {},
|
|
1462
|
-
body: VigorEmpty,
|
|
1463
|
-
extra: {},
|
|
1464
|
-
settings: VigorFetchPolicySettingsBase,
|
|
1465
|
-
middlewares: VigorFetchPolicyMiddlewaresBase,
|
|
1466
|
-
retry: VigorRetryBase,
|
|
1467
|
-
parse: VigorParseBase
|
|
1468
|
-
};
|
|
1469
|
-
|
|
1470
|
-
const VigorFetchContextBase = {
|
|
1471
|
-
__brand: createBrand("Fetch", "Context<Schema"),
|
|
1472
|
-
href: "",
|
|
1473
|
-
response: VigorDefault,
|
|
1474
|
-
result: VigorDefault,
|
|
1475
|
-
error: VigorDefault,
|
|
1476
|
-
options: VigorDefault,
|
|
1477
|
-
flags: {
|
|
1478
|
-
overrided: false,
|
|
1479
|
-
restarted: false
|
|
1480
|
-
},
|
|
1481
|
-
record: {},
|
|
1482
|
-
policy: VigorFetchPolicyBase
|
|
1483
|
-
};
|
|
1484
|
-
|
|
1485
|
-
const VigorFetchErrorMessageFuncs = {
|
|
1486
|
-
VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
|
|
1487
|
-
INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
|
|
1488
|
-
INVALID_PROTOCOL: ({ origin, base }) => base
|
|
1489
|
-
? `Invalid URL: could not resolve "${origin}" against base "${base}"`
|
|
1490
|
-
: `Invalid URL: "${origin}" is not an absolute URL, and no base (window.location) is available to resolve it against — pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,
|
|
1491
|
-
FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
|
|
1492
|
-
RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
|
|
1493
|
-
};
|
|
1494
|
-
/** Error type thrown by the fetch module. */
|
|
1495
|
-
class VigorFetchError extends VigorError {
|
|
1496
|
-
/**
|
|
1497
|
-
* @param code - One of the fetch module's error codes.
|
|
1498
|
-
* @param options - Error metadata, including the `data` payload for `code`.
|
|
1499
|
-
*/
|
|
1500
|
-
constructor(code, options) {
|
|
1501
|
-
const messageFn = VigorFetchErrorMessageFuncs[code];
|
|
1502
|
-
super(code, messageFn(options.data), options);
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
|
|
1506
|
-
const VigorFetchBase = {
|
|
1507
|
-
__brand: createBrand("Fetch", "Schema"),
|
|
1508
|
-
policy: VigorFetchPolicyBase,
|
|
1509
|
-
context: VigorFetchContextBase
|
|
1510
|
-
};
|
|
1511
|
-
/**
|
|
1512
|
-
* Immutable builder that performs an HTTP request, composing an internal
|
|
1513
|
-
* {@link VigorRetry} engine (for retry/timeout/backoff) and a
|
|
1514
|
-
* {@link VigorParse} engine (for response parsing), with a configurable
|
|
1515
|
-
* middleware pipeline around request building and response handling.
|
|
1516
|
-
*/
|
|
1517
|
-
class VigorFetch extends VigorStatus {
|
|
1518
|
-
constructor(config = VigorFetchBase) {
|
|
1519
|
-
super(VigorFetchBase, config);
|
|
1520
|
-
}
|
|
1521
|
-
_create(config) {
|
|
1522
|
-
return new VigorFetch(config);
|
|
1523
|
-
}
|
|
1524
|
-
/** Sets the HTTP method. Defaults to `POST` when a body is set, otherwise `GET`. */
|
|
1525
|
-
method(str) { return this._next({ policy: { method: str } }); }
|
|
1526
|
-
/** Sets the request origin, either an absolute URL or a path relative to the current page. */
|
|
1527
|
-
origin(str) { return this._next({ policy: { origin: str } }); }
|
|
1528
|
-
/** Appends path segments to the request URL. */
|
|
1529
|
-
path(...strs) {
|
|
1530
|
-
return this._next({ policy: { path: this._stringifyList(strs) } });
|
|
1531
|
-
}
|
|
1532
|
-
/** Adds query-string parameter objects to the request URL. */
|
|
1533
|
-
query(...objs) {
|
|
1534
|
-
return this._next({ policy: { query: objs } });
|
|
1535
|
-
}
|
|
1536
|
-
/** Sets the URL fragment ("hash"), replacing any previous value. */
|
|
1537
|
-
hash(str) { return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } }); }
|
|
1538
|
-
/**
|
|
1539
|
-
* Sets request headers.
|
|
1540
|
-
*
|
|
1541
|
-
* @param mode - `"overwrite"` discards all previously configured headers
|
|
1542
|
-
* and keeps only the ones passed here. `"merge"` behaves like
|
|
1543
|
-
* `Object.assign`, overwriting only the keys that overlap and keeping
|
|
1544
|
-
* the rest.
|
|
1545
|
-
*/
|
|
1546
|
-
headers(mode, obj) {
|
|
1547
|
-
if (mode === "overwrite")
|
|
1548
|
-
return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
|
|
1549
|
-
return this._next({ policy: { headers: obj } });
|
|
1550
|
-
}
|
|
1551
|
-
/**
|
|
1552
|
-
* Sets the request body.
|
|
1553
|
-
*
|
|
1554
|
-
* @param mode - `"overwrite"` discards the previous body and fully
|
|
1555
|
-
* replaces it with this value. `"merge"` shallow-merges (via
|
|
1556
|
-
* `Object.assign`) when both the previous and new body are plain
|
|
1557
|
-
* objects; for any other body type (string/Blob/FormData/etc) it is
|
|
1558
|
-
* simply replaced.
|
|
1559
|
-
*/
|
|
1560
|
-
body(mode, obj) {
|
|
1561
|
-
if (mode === "overwrite")
|
|
1562
|
-
return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
|
|
1563
|
-
return this._next({ policy: { body: obj } });
|
|
1564
|
-
}
|
|
1565
|
-
/**
|
|
1566
|
-
* Sets additional `RequestInit` options other than headers/body/method/signal
|
|
1567
|
-
* (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
|
|
1568
|
-
* `referrerPolicy`, `keepalive`, `integrity`).
|
|
1569
|
-
*
|
|
1570
|
-
* @param mode - `"overwrite"` discards all previously configured options
|
|
1571
|
-
* and replaces them with this value. `"merge"` shallow-merges this
|
|
1572
|
-
* value onto the previous options.
|
|
1573
|
-
*/
|
|
1574
|
-
options(mode, obj) {
|
|
1575
|
-
if (mode === "overwrite")
|
|
1576
|
-
return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
|
|
1577
|
-
return this._next({ policy: { extra: obj } });
|
|
1578
|
-
}
|
|
1579
|
-
/** Configures the fetch policy's general settings. */
|
|
1580
|
-
settings(input) {
|
|
1581
|
-
if (typeof input === 'function' || input instanceof VigorFetchPolicySettings) {
|
|
1582
|
-
const result = typeof input === 'function'
|
|
1583
|
-
? input(new VigorFetchPolicySettings())
|
|
1584
|
-
: input;
|
|
1585
|
-
return this._next({ policy: { settings: result.config.policy.settings } });
|
|
1586
|
-
}
|
|
1587
|
-
return this._next({ policy: { settings: input } });
|
|
1588
|
-
}
|
|
1589
|
-
/** Configures the fetch policy's middleware pipeline. */
|
|
1590
|
-
middlewares(input) {
|
|
1591
|
-
if (typeof input === 'function' || input instanceof VigorFetchPolicyMiddlewares) {
|
|
1592
|
-
const result = typeof input === 'function'
|
|
1593
|
-
? input(new VigorFetchPolicyMiddlewares())
|
|
1594
|
-
: input;
|
|
1595
|
-
return this._next({ policy: { middlewares: result.config.policy.middlewares } });
|
|
1596
|
-
}
|
|
1597
|
-
return this._next({ policy: { middlewares: input } });
|
|
1598
|
-
}
|
|
1599
|
-
/** Configures the retry engine used to send the underlying request. */
|
|
1600
|
-
retry(input) {
|
|
1601
|
-
if (typeof input === 'function' || input instanceof VigorRetry) {
|
|
1602
|
-
const result = typeof input === 'function'
|
|
1603
|
-
? input(new VigorRetry())
|
|
1604
|
-
: input;
|
|
1605
|
-
return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
|
|
1606
|
-
}
|
|
1607
|
-
return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
|
|
1608
|
-
}
|
|
1609
|
-
/** Configures the parse engine used to interpret the response. */
|
|
1610
|
-
parse(input) {
|
|
1611
|
-
if (typeof input === 'function' || input instanceof VigorParse) {
|
|
1612
|
-
const result = typeof input === 'function'
|
|
1613
|
-
? input(new VigorParse())
|
|
1614
|
-
: input;
|
|
1615
|
-
return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
|
|
1616
|
-
}
|
|
1617
|
-
return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
|
|
1618
|
-
}
|
|
1619
|
-
/** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
|
|
1620
|
-
_stringifyList(unkList) {
|
|
1621
|
-
return unkList
|
|
1622
|
-
.filter(unk => unk !== null && unk !== undefined)
|
|
1623
|
-
.map(unk => unk instanceof Date ? unk.toISOString() : String(unk));
|
|
1624
|
-
}
|
|
1625
|
-
/**
|
|
1626
|
-
* Resolves the base URL used to interpret a relative `origin`. In a
|
|
1627
|
-
* browser environment this is the current page location; in
|
|
1628
|
-
* environments without `location` (e.g. Node), no base is available and
|
|
1629
|
-
* `origin` must be an absolute URL.
|
|
1630
|
-
*/
|
|
1631
|
-
_resolveBase() {
|
|
1632
|
-
if (typeof globalThis !== 'undefined' && globalThis.location?.href) {
|
|
1633
|
-
return globalThis.location.href;
|
|
1634
|
-
}
|
|
1635
|
-
return undefined;
|
|
1636
|
-
}
|
|
1637
|
-
/**
|
|
1638
|
-
* Builds the final request URL from the configured origin, path
|
|
1639
|
-
* segments, query parameters, and hash. An absolute `origin` ignores
|
|
1640
|
-
* the resolved base (per the `URL` spec); a relative `origin` is
|
|
1641
|
-
* resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
|
|
1642
|
-
*/
|
|
1643
|
-
_buildUrl(origin, path, query, hash) {
|
|
1644
|
-
const base = this._resolveBase();
|
|
1645
|
-
let originObj;
|
|
1646
|
-
try {
|
|
1647
|
-
originObj = new URL(origin, base);
|
|
1648
|
-
}
|
|
1649
|
-
catch {
|
|
1650
|
-
throw new VigorFetchError("INVALID_PROTOCOL", {
|
|
1651
|
-
method: "_buildUrl",
|
|
1652
|
-
data: { origin, base }
|
|
1653
|
-
});
|
|
1654
|
-
}
|
|
1655
|
-
const baseStr = originObj.origin;
|
|
1656
|
-
const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, '')];
|
|
1657
|
-
for (const p of path)
|
|
1658
|
-
pathParts.push(p.replace(/^\/+|\/+$/g, ''));
|
|
1659
|
-
const pathStr = pathParts.filter(Boolean).join('/');
|
|
1660
|
-
const mainObj = new URL(pathStr, baseStr);
|
|
1661
|
-
const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
|
|
1662
|
-
const queryEntries = [...originObj.searchParams.entries(), ...query.flatMap(q => Object.entries(q))];
|
|
1663
|
-
for (const [key, val] of queryEntries) {
|
|
1664
|
-
if (val === undefined || val === null)
|
|
1665
|
-
continue;
|
|
1666
|
-
if (Array.isArray(val)) {
|
|
1667
|
-
for (const e of val)
|
|
1668
|
-
mainObj.searchParams.append(key, parseVal(e));
|
|
1669
|
-
}
|
|
1670
|
-
else {
|
|
1671
|
-
mainObj.searchParams.append(key, parseVal(val));
|
|
1672
|
-
}
|
|
1673
|
-
}
|
|
1674
|
-
mainObj.hash = hash || originObj.hash;
|
|
1675
|
-
return mainObj.href;
|
|
1676
|
-
}
|
|
1677
|
-
/** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
|
|
1678
|
-
_normalizeBody(body) {
|
|
1679
|
-
if (body == null)
|
|
1680
|
-
return { headers: {}, body: body };
|
|
1681
|
-
if (typeof body === "string")
|
|
1682
|
-
return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
|
|
1683
|
-
if (body instanceof Blob)
|
|
1684
|
-
return { headers: body.type ? { "Content-Type": body.type } : {}, body };
|
|
1685
|
-
if (body instanceof ArrayBuffer)
|
|
1686
|
-
return { headers: { "Content-Type": "application/octet-stream" }, body };
|
|
1687
|
-
if (body instanceof URLSearchParams)
|
|
1688
|
-
return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
|
|
1689
|
-
if (body instanceof FormData)
|
|
1690
|
-
return { headers: {}, body };
|
|
1691
|
-
if (typeof body === "object")
|
|
1692
|
-
return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
|
|
1693
|
-
throw new VigorFetchError("INVALID_BODY", {
|
|
1694
|
-
method: "_normalizeBody",
|
|
1695
|
-
data: { received: body }
|
|
1696
|
-
});
|
|
1697
|
-
}
|
|
1698
|
-
/** Runs the request and returns its parsed result directly, throwing on final failure. */
|
|
1699
|
-
async request() {
|
|
1700
|
-
const res = await this.requestVerbose();
|
|
1701
|
-
if (res.success)
|
|
1702
|
-
return res.data;
|
|
1703
|
-
throw res.error;
|
|
1704
|
-
}
|
|
1705
|
-
/** Runs the request and returns a result/error envelope instead of throwing. */
|
|
1706
|
-
async requestVerbose() {
|
|
1707
|
-
return await this.requestRuntime();
|
|
1708
|
-
}
|
|
1709
|
-
/** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
|
|
1710
|
-
async requestRuntime(restartAttempt = 1) {
|
|
1711
|
-
const config = this._merge(this.config, {});
|
|
1712
|
-
let ctx = {
|
|
1713
|
-
...config.context,
|
|
1714
|
-
policy: config.policy
|
|
1715
|
-
};
|
|
1716
|
-
const throwError = (err) => { throw err; };
|
|
1717
|
-
try {
|
|
1718
|
-
if (isVigorEmpty(ctx.policy.origin))
|
|
1719
|
-
throw new VigorFetchError("VALUE_REQUIRED", {
|
|
1720
|
-
method: "request",
|
|
1721
|
-
data: { key: "origin" }
|
|
1722
|
-
});
|
|
1723
|
-
ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
|
|
1724
|
-
const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== undefined;
|
|
1725
|
-
const method = ctx.policy.method || (hasBody ? "POST" : "GET");
|
|
1726
|
-
let options = {
|
|
1727
|
-
...ctx.policy.extra,
|
|
1728
|
-
method: method,
|
|
1729
|
-
headers: {}
|
|
1730
|
-
};
|
|
1731
|
-
if (hasBody) {
|
|
1732
|
-
const normalized = this._normalizeBody(ctx.policy.body);
|
|
1733
|
-
if (normalized.body !== undefined)
|
|
1734
|
-
options.body = normalized.body;
|
|
1735
|
-
Object.assign(options.headers, normalized.headers);
|
|
1736
|
-
}
|
|
1737
|
-
Object.assign(options.headers, ctx.policy.headers);
|
|
1738
|
-
for (const middleware of ctx.policy.middlewares.before) {
|
|
1739
|
-
if (middleware._mode === "fluent") {
|
|
1740
|
-
await middleware.func(ctx);
|
|
1741
|
-
}
|
|
1742
|
-
else {
|
|
1743
|
-
ctx = await middleware.func(ctx, {
|
|
1744
|
-
throwError,
|
|
1745
|
-
setOptions: (o) => { options = o; },
|
|
1746
|
-
setHeaders: (h) => { options.headers = h; },
|
|
1747
|
-
setBody: (b) => { options.body = b; }
|
|
1748
|
-
});
|
|
1749
|
-
}
|
|
1750
|
-
}
|
|
1751
|
-
ctx.options = options;
|
|
1752
|
-
const retryEngine = new VigorRetry(ctx.policy.retry)
|
|
1753
|
-
.target(async (signal) => {
|
|
1754
|
-
return await fetch(ctx.href, { ...options, signal });
|
|
1755
|
-
})
|
|
1756
|
-
.middlewares(m => m
|
|
1757
|
-
.after("intercept", async (rctx, api) => {
|
|
1758
|
-
const response = rctx.result;
|
|
1759
|
-
if (!response.ok) {
|
|
1760
|
-
let parsed = undefined;
|
|
1761
|
-
try {
|
|
1762
|
-
parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
|
|
1763
|
-
}
|
|
1764
|
-
catch {
|
|
1765
|
-
}
|
|
1766
|
-
api.throwError(new VigorFetchError("FETCH_FAILED", {
|
|
1767
|
-
method: "request",
|
|
1768
|
-
data: {
|
|
1769
|
-
status: response.status,
|
|
1770
|
-
statusText: response.statusText,
|
|
1771
|
-
response,
|
|
1772
|
-
url: response.url,
|
|
1773
|
-
parsed
|
|
1774
|
-
}
|
|
1775
|
-
}));
|
|
1776
|
-
}
|
|
1777
|
-
return rctx;
|
|
1778
|
-
})
|
|
1779
|
-
.retryIf("intercept", async (rctx, api) => {
|
|
1780
|
-
const response = rctx.error instanceof VigorFetchError
|
|
1781
|
-
? rctx.error.data?.response
|
|
1782
|
-
: undefined;
|
|
1783
|
-
if (response && ctx.policy.settings.unretryStatus.includes(response.status))
|
|
1784
|
-
api.cancelRetry();
|
|
1785
|
-
else
|
|
1786
|
-
api.proceedRetry();
|
|
1787
|
-
return rctx;
|
|
1788
|
-
})
|
|
1789
|
-
.onRetry("intercept", async (rctx, api) => {
|
|
1790
|
-
const response = rctx.error instanceof VigorFetchError
|
|
1791
|
-
? rctx.error.data?.response
|
|
1792
|
-
: undefined;
|
|
1793
|
-
if (response?.status === 429) {
|
|
1794
|
-
let retryHeader = null;
|
|
1795
|
-
for (const header of ctx.policy.settings.retryHeaders) {
|
|
1796
|
-
retryHeader = response.headers.get(header);
|
|
1797
|
-
if (retryHeader)
|
|
1798
|
-
break;
|
|
1799
|
-
}
|
|
1800
|
-
if (retryHeader) {
|
|
1801
|
-
const toNumber = Number(retryHeader);
|
|
1802
|
-
const delay = !isNaN(toNumber)
|
|
1803
|
-
? toNumber * 1000
|
|
1804
|
-
: (() => {
|
|
1805
|
-
const toDate = new Date(retryHeader).getTime();
|
|
1806
|
-
return !isNaN(toDate) ? toDate - Date.now() : null;
|
|
1807
|
-
})();
|
|
1808
|
-
if (delay !== null && delay > 0)
|
|
1809
|
-
api.setDelay(delay);
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
return rctx;
|
|
1813
|
-
}));
|
|
1814
|
-
ctx.response = await retryEngine.request();
|
|
1815
|
-
const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
|
|
1816
|
-
ctx.result = await parseEngine.request();
|
|
1817
|
-
for (const middleware of ctx.policy.middlewares.after) {
|
|
1818
|
-
if (middleware._mode === "fluent") {
|
|
1819
|
-
await middleware.func(ctx);
|
|
1820
|
-
}
|
|
1821
|
-
else {
|
|
1822
|
-
ctx = await middleware.func(ctx, { throwError, setResult: (r) => { ctx.result = r; } });
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
const setResult = (r) => { ctx.result = r; };
|
|
1826
|
-
for (const middleware of ctx.policy.middlewares.onResult) {
|
|
1827
|
-
if (middleware._mode === "fluent") {
|
|
1828
|
-
ctx.result = await middleware.func(ctx.result);
|
|
1829
|
-
}
|
|
1830
|
-
else {
|
|
1831
|
-
ctx = await middleware.func(ctx, { setResult, throwError });
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
return {
|
|
1835
|
-
success: true,
|
|
1836
|
-
data: ctx.result,
|
|
1837
|
-
error: null
|
|
1838
|
-
};
|
|
1839
|
-
}
|
|
1840
|
-
catch (error) {
|
|
1841
|
-
ctx.error = error;
|
|
1842
|
-
ctx.flags.overrided = false;
|
|
1843
|
-
ctx.flags.restarted = false;
|
|
1844
|
-
const setResult = (r) => {
|
|
1845
|
-
ctx.flags.overrided = true;
|
|
1846
|
-
ctx.result = r;
|
|
1847
|
-
};
|
|
1848
|
-
const proceedRestart = () => ctx.flags.restarted = true;
|
|
1849
|
-
const cancelRestart = () => ctx.flags.restarted = false;
|
|
1850
|
-
for (const middleware of ctx.policy.middlewares.onError) {
|
|
1851
|
-
if (middleware._mode === "fluent") {
|
|
1852
|
-
await middleware.func(ctx.error);
|
|
1853
|
-
}
|
|
1854
|
-
else {
|
|
1855
|
-
ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
|
|
1856
|
-
}
|
|
1857
|
-
}
|
|
1858
|
-
if (ctx.flags.restarted) {
|
|
1859
|
-
if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
|
|
1860
|
-
throw new VigorFetchError("RESTART_EXHAUSTED", {
|
|
1861
|
-
method: "request",
|
|
1862
|
-
data: {
|
|
1863
|
-
maxAttempts: ctx.policy.settings.maxRestarts
|
|
1864
|
-
}
|
|
1865
|
-
});
|
|
1866
|
-
return await this.requestRuntime(restartAttempt + 1);
|
|
1867
|
-
}
|
|
1868
|
-
if (ctx.flags.overrided)
|
|
1869
|
-
return {
|
|
1870
|
-
success: true,
|
|
1871
|
-
data: ctx.result,
|
|
1872
|
-
error: null
|
|
1873
|
-
};
|
|
1874
|
-
if (!isVigorEmpty(ctx.policy.settings.default)) {
|
|
1875
|
-
const data = await ctx.policy.settings.default(ctx);
|
|
1876
|
-
return {
|
|
1877
|
-
success: true,
|
|
1878
|
-
data,
|
|
1879
|
-
error: null
|
|
1880
|
-
};
|
|
1881
|
-
}
|
|
1882
|
-
return {
|
|
1883
|
-
success: false,
|
|
1884
|
-
data: null,
|
|
1885
|
-
error
|
|
1886
|
-
};
|
|
1887
|
-
}
|
|
1888
|
-
}
|
|
1889
|
-
}
|
|
1890
|
-
|
|
1891
|
-
const vigor = {
|
|
1892
|
-
use: (plugin, options) => {
|
|
1893
|
-
plugin.func(vigor, options);
|
|
1894
|
-
},
|
|
1895
|
-
retry: (task) => task ? new VigorRetry().target(task) : new VigorRetry(),
|
|
1896
|
-
parse: (response) => response ? new VigorParse().target(response) : new VigorParse(),
|
|
1897
|
-
fetch: (origin) => origin ? new VigorFetch().origin(origin) : new VigorFetch(),
|
|
1898
|
-
all: (...tasks) => tasks.length > 0 ? new VigorAll().target(...tasks) : new VigorAll(),
|
|
1899
|
-
builders: {
|
|
1900
|
-
fetch: {
|
|
1901
|
-
settings: () => new VigorFetchPolicySettings(),
|
|
1902
|
-
middlewares: () => new VigorFetchPolicyMiddlewares(),
|
|
1903
|
-
},
|
|
1904
|
-
retry: {
|
|
1905
|
-
settings: () => new VigorRetryPolicySettings(),
|
|
1906
|
-
middlewares: () => new VigorRetryPolicyMiddlewares(),
|
|
1907
|
-
algorithms: () => new VigorRetryPolicyAlgorithms(),
|
|
1908
|
-
algorithm: {
|
|
1909
|
-
constant: () => new VigorRetryPolicyAlgorithmsConstant(),
|
|
1910
|
-
linear: () => new VigorRetryPolicyAlgorithmsLinear(),
|
|
1911
|
-
backoff: () => new VigorRetryPolicyAlgorithmsBackoff(),
|
|
1912
|
-
custom: () => new VigorRetryPolicyAlgorithmsCustom(),
|
|
1913
|
-
},
|
|
1914
|
-
},
|
|
1915
|
-
parse: {
|
|
1916
|
-
settings: () => new VigorParsePolicySettings(),
|
|
1917
|
-
middlewares: () => new VigorParsePolicyMiddlewares(),
|
|
1918
|
-
strategies: () => new VigorParsePolicyStrategies(),
|
|
1919
|
-
},
|
|
1920
|
-
all: {
|
|
1921
|
-
settings: () => new VigorAllPolicySettings(),
|
|
1922
|
-
middlewares: () => new VigorAllPolicyMiddlewares(),
|
|
1923
|
-
},
|
|
1924
|
-
}
|
|
1925
|
-
};
|
|
1926
|
-
|
|
1927
|
-
export { VigorAll, VigorAllBase, VigorAllError, VigorAllErrorMessageFuncs, VigorAllPolicyBase, VigorAllPolicyMiddlewares, VigorAllPolicyMiddlewaresBase, VigorAllPolicySettings, VigorAllPolicySettingsBase, VigorError, VigorFetch, VigorFetchBase, VigorFetchError, VigorFetchErrorMessageFuncs, VigorFetchPolicyBase, VigorFetchPolicyMiddlewares, VigorFetchPolicyMiddlewaresBase, VigorFetchPolicySettings, VigorFetchPolicySettingsBase, VigorJitter, VigorParse, VigorParseBase, VigorParseContentTypeStrategy, VigorParseError, VigorParseErrorMessageFuncs, VigorParsePolicyBase, VigorParsePolicyMiddlewares, VigorParsePolicyMiddlewaresBase, VigorParsePolicySettings, VigorParsePolicySettingsBase, VigorParsePolicyStrategies, VigorParsePolicyStrategiesBase, VigorParseSniffStrategy, VigorRetry, VigorRetryBase, VigorRetryError, VigorRetryErrorMessageFuncs, VigorRetryPolicyAlgorithms, VigorRetryPolicyAlgorithmsBackoff, VigorRetryPolicyAlgorithmsBackoffBase, VigorRetryPolicyAlgorithmsBase, VigorRetryPolicyAlgorithmsConstant, VigorRetryPolicyAlgorithmsConstantBase, VigorRetryPolicyAlgorithmsCustom, VigorRetryPolicyAlgorithmsCustomBase, VigorRetryPolicyAlgorithmsLinear, VigorRetryPolicyAlgorithmsLinearBase, VigorRetryPolicyBase, VigorRetryPolicyMiddlewares, VigorRetryPolicyMiddlewaresBase, VigorRetryPolicySettings, VigorRetryPolicySettingsBase, VigorStatus, vigor as default, vigor };
|