vigor-fetch 4.0.4 → 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.mjs DELETED
@@ -1,1935 +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
- cause: ctx.error,
1003
- data: {
1004
- maxAttempts: ctx.policy.settings.maxAttempts,
1005
- error: ctx.error
1006
- }
1007
- });
1008
- }
1009
- catch (error) {
1010
- ctx.error = error;
1011
- ctx.flags.doRestart = false;
1012
- ctx.flags.overridden = false;
1013
- const setResult = (res) => {
1014
- ctx.flags.overridden = true;
1015
- ctx.result = res;
1016
- };
1017
- const proceedRestart = () => ctx.flags.doRestart = true;
1018
- const cancelRestart = () => ctx.flags.doRestart = false;
1019
- for (const middleware of ctx.policy.middlewares.onError) {
1020
- if (middleware._mode === "fluent") {
1021
- await middleware.func(ctx.error);
1022
- }
1023
- else {
1024
- ctx = await middleware.func(ctx, {
1025
- setResult,
1026
- throwError,
1027
- proceedRestart,
1028
- cancelRestart
1029
- });
1030
- }
1031
- }
1032
- if (ctx.flags.doRestart) {
1033
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1034
- throw new VigorRetryError("RESTART_EXHAUSTED", {
1035
- method: "request",
1036
- cause: ctx.error,
1037
- data: {
1038
- maxAttempts: ctx.policy.settings.maxRestarts,
1039
- error: ctx.error
1040
- }
1041
- });
1042
- return await this.requestRuntime(restartAttempt + 1);
1043
- }
1044
- if (ctx.flags.overridden)
1045
- return {
1046
- success: true,
1047
- data: ctx.result,
1048
- error: null
1049
- };
1050
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1051
- const data = await ctx.policy.settings.default(ctx);
1052
- return {
1053
- success: true,
1054
- data,
1055
- error: null
1056
- };
1057
- }
1058
- return {
1059
- success: false,
1060
- data: null,
1061
- error: ctx.error
1062
- };
1063
- }
1064
- }
1065
- }
1066
-
1067
- const VigorParsePolicySettingsBase = {
1068
- __brand: createBrand("Parse", "Policy<Settings<Schema"),
1069
- raw: false,
1070
- default: VigorEmpty,
1071
- maxRestarts: 3
1072
- };
1073
- /** Immutable builder for a parse policy's general settings. */
1074
- class VigorParsePolicySettings extends VigorStatus {
1075
- constructor(config = VigorParseBase) {
1076
- super(VigorParseBase, config);
1077
- }
1078
- _create(config) {
1079
- return new VigorParsePolicySettings(config);
1080
- }
1081
- /** When enabled, skips content-type based parsing and returns the raw response. */
1082
- raw(bool) {
1083
- return this._next({
1084
- policy: { settings: { raw: bool } }
1085
- });
1086
- }
1087
- /** Sets the fallback value/factory used when parsing ultimately fails. */
1088
- default(func) {
1089
- return this._next({
1090
- policy: { settings: { default: func } }
1091
- });
1092
- }
1093
- /** Sets the maximum number of full restarts allowed. */
1094
- maxRestarts(num) {
1095
- return this._next({
1096
- policy: { settings: { maxRestarts: num } }
1097
- });
1098
- }
1099
- }
1100
-
1101
- const VigorParsePolicyMiddlewaresBase = {
1102
- __brand: createBrand("Parse", "Policy<Middlewares<Schema"),
1103
- before: [],
1104
- after: [],
1105
- onResult: [],
1106
- onError: []
1107
- };
1108
- /**
1109
- * Immutable builder for a parse policy's middleware pipeline (`before`,
1110
- * `after`, `onResult`, `onError`). Each stage accepts either "fluent"
1111
- * middleware (returns a plain value merged into the context) or
1112
- * "intercept" middleware (receives an explicit API to mutate control flow).
1113
- */
1114
- class VigorParsePolicyMiddlewares extends VigorStatus {
1115
- constructor(config = VigorParseBase) {
1116
- super(VigorParseBase, config);
1117
- }
1118
- _create(config) {
1119
- return new VigorParsePolicyMiddlewares(config);
1120
- }
1121
- before(type, func) {
1122
- return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
1123
- }
1124
- after(type, func) {
1125
- return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
1126
- }
1127
- onResult(type, func) {
1128
- return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
1129
- }
1130
- onError(type, func) {
1131
- return this._next({ policy: { middlewares: { onError: [{ _mode: type, func }] } } });
1132
- }
1133
- }
1134
-
1135
- const VigorParseErrorMessageFuncs = {
1136
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1137
- INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1138
- PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1139
- PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
1140
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1141
- };
1142
- /** Error type thrown by the parse module. */
1143
- class VigorParseError extends VigorError {
1144
- /**
1145
- * @param code - One of the parse module's error codes.
1146
- * @param options - Error metadata, including the `data` payload for `code`.
1147
- */
1148
- constructor(code, options) {
1149
- const messageFn = VigorParseErrorMessageFuncs[code];
1150
- super(code, messageFn(options.data), options);
1151
- }
1152
- }
1153
-
1154
- const VigorParsePolicyStrategiesBase = {
1155
- __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1156
- funcs: []
1157
- };
1158
- const ContentTypeParsers = [
1159
- { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
1160
- { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1161
- { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1162
- { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
1163
- { header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
1164
- { header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
1165
- { header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
1166
- { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
1167
- { header: "text/*", regExp: /^text\/.+/i, method: (res) => res.text() },
1168
- ];
1169
- const SniffMethods = [
1170
- { title: "json", method: (res) => res.json() },
1171
- { title: "formData", method: (res) => res.formData() },
1172
- { title: "text", method: (res) => res.text() },
1173
- { title: "blob", method: (res) => res.blob() },
1174
- ];
1175
- /** Parses a response by matching its `Content-Type` header against a known parser table. */
1176
- const VigorParseContentTypeStrategy = async (response) => {
1177
- const contentTypeHeader = response.headers.get("content-type");
1178
- if (!contentTypeHeader)
1179
- throw new VigorParseError("INVALID_CONTENT_TYPE", {
1180
- method: "VigorParseContentTypeStrategy",
1181
- data: { received: contentTypeHeader }
1182
- });
1183
- const toDo = ContentTypeParsers.find(parser => parser.regExp.test(contentTypeHeader));
1184
- if (!toDo)
1185
- throw new VigorParseError("PARSER_NOT_FOUND", {
1186
- method: "VigorParseContentTypeStrategy",
1187
- data: {
1188
- expected: ContentTypeParsers.map(p => p.header),
1189
- received: contentTypeHeader
1190
- }
1191
- });
1192
- return await toDo.method(response);
1193
- };
1194
- /** Parses a response by trying a sequence of body-reading methods until one succeeds. */
1195
- const VigorParseSniffStrategy = async (response) => {
1196
- for (const [i, parser] of SniffMethods.entries()) {
1197
- const cloned = (i === SniffMethods.length - 1) ? response : response.clone();
1198
- try {
1199
- return await parser.method(cloned);
1200
- }
1201
- catch { }
1202
- }
1203
- throw new VigorParseError("PARSER_ALL_FAILED", {
1204
- method: "VigorParseSniffStrategy",
1205
- data: { tried: SniffMethods.map(p => p.title) }
1206
- });
1207
- };
1208
- /** Immutable builder for a parse policy's fallback chain of parsing strategies. */
1209
- class VigorParsePolicyStrategies extends VigorStatus {
1210
- constructor(config = VigorParseBase) {
1211
- super(VigorParseBase, config);
1212
- }
1213
- _create(config) {
1214
- return new VigorParsePolicyStrategies(config);
1215
- }
1216
- /**
1217
- * Adds strategy functions to the fallback chain.
1218
- *
1219
- * @param replace - When `true`, replaces the existing chain instead of
1220
- * appending to it (the default is to concat, since strategies are
1221
- * tried in sequence as a fallback chain).
1222
- */
1223
- _set(funcs, replace) {
1224
- return this._next({ policy: { strategies: { funcs } } }, replace ? { policy: { strategies: { funcs: "replace" } } } : undefined);
1225
- }
1226
- /** Adds the content-type based parsing strategy. */
1227
- contentType(replace) { return this._set([VigorParseContentTypeStrategy], replace); }
1228
- /** Adds the sniffing (try-each-method) parsing strategy. */
1229
- sniff(replace) { return this._set([VigorParseSniffStrategy], replace); }
1230
- /** Adds a strategy that always parses the response as JSON. */
1231
- json(replace) { return this._set([(res) => res.json()], replace); }
1232
- /** Adds a strategy that always parses the response as text. */
1233
- text(replace) { return this._set([(res) => res.text()], replace); }
1234
- /** Adds a strategy that always parses the response as an `ArrayBuffer`. */
1235
- arrayBuffer(replace) { return this._set([(res) => res.arrayBuffer()], replace); }
1236
- /** Adds a strategy that always parses the response as a `Blob`. */
1237
- blob(replace) { return this._set([(res) => res.blob()], replace); }
1238
- /** Adds a strategy that always parses the response as a `Uint8Array`. */
1239
- bytes(replace) { return this._set([(res) => res.arrayBuffer().then(b => new Uint8Array(b))], replace); }
1240
- /** Adds a strategy that always parses the response as `FormData`. */
1241
- formData(replace) { return this._set([(res) => res.formData()], replace); }
1242
- /** Adds a user-supplied custom parsing strategy. */
1243
- custom(func, replace) { return this._set([func], replace); }
1244
- }
1245
-
1246
- const VigorParsePolicyBase = {
1247
- __brand: createBrand("Parse", "Policy<Schema"),
1248
- target: VigorDefault,
1249
- settings: VigorParsePolicySettingsBase,
1250
- middlewares: VigorParsePolicyMiddlewaresBase,
1251
- strategies: VigorParsePolicyStrategiesBase
1252
- };
1253
-
1254
- const VigorParseContextBase = {
1255
- __brand: createBrand("Parse", "Context<Schema"),
1256
- result: VigorDefault,
1257
- error: VigorDefault,
1258
- response: VigorDefault,
1259
- flags: {
1260
- overrided: false,
1261
- restarted: false
1262
- },
1263
- record: {},
1264
- policy: VigorParsePolicyBase
1265
- };
1266
-
1267
- const VigorParseBase = {
1268
- __brand: createBrand("Parse", "Schema"),
1269
- policy: VigorParsePolicyBase,
1270
- context: VigorParseContextBase
1271
- };
1272
- /**
1273
- * Immutable builder that parses an HTTP response into a result value,
1274
- * trying each configured strategy in sequence with an optional middleware
1275
- * pipeline and restart-on-failure support.
1276
- */
1277
- class VigorParse extends VigorStatus {
1278
- constructor(config = VigorParseBase) {
1279
- super(VigorParseBase, config);
1280
- }
1281
- _create(config) {
1282
- return new VigorParse(config);
1283
- }
1284
- /** Sets the `Response` object to parse. */
1285
- target(response) {
1286
- return this._next({ policy: { target: response } });
1287
- }
1288
- /** Configures the parse policy's general settings. */
1289
- settings(input) {
1290
- if (typeof input === 'function' || input instanceof VigorParsePolicySettings) {
1291
- const result = typeof input === 'function'
1292
- ? input(new VigorParsePolicySettings())
1293
- : input;
1294
- return this._next({
1295
- policy: { settings: result.config.policy.settings }
1296
- });
1297
- }
1298
- return this._next({ policy: { settings: input } });
1299
- }
1300
- /** Configures the parse policy's middleware pipeline. */
1301
- middlewares(input) {
1302
- if (typeof input === 'function' || input instanceof VigorParsePolicyMiddlewares) {
1303
- const result = typeof input === 'function'
1304
- ? input(new VigorParsePolicyMiddlewares())
1305
- : input;
1306
- return this._next({
1307
- policy: { middlewares: result.config.policy.middlewares }
1308
- });
1309
- }
1310
- return this._next({ policy: { middlewares: input } });
1311
- }
1312
- /** Configures the parse policy's fallback chain of parsing strategies. */
1313
- strategies(input) {
1314
- if (typeof input === 'function' || input instanceof VigorParsePolicyStrategies) {
1315
- const result = typeof input === 'function'
1316
- ? input(new VigorParsePolicyStrategies())
1317
- : input;
1318
- return this._next({
1319
- policy: { strategies: result.config.policy.strategies }
1320
- });
1321
- }
1322
- return this._next({ policy: { strategies: input } });
1323
- }
1324
- /** Runs parsing and returns the result directly, throwing on final failure. */
1325
- async request() {
1326
- const res = await this.requestVerbose();
1327
- if (res.success)
1328
- return res.data;
1329
- throw res.error;
1330
- }
1331
- /** Runs parsing and returns a result/error envelope instead of throwing. */
1332
- async requestVerbose() {
1333
- return await this.requestRuntime();
1334
- }
1335
- /** Internal execution loop implementing the strategy fallback and restart handling. */
1336
- async requestRuntime(restartAttempt = 1) {
1337
- const config = this._merge(this.config, {});
1338
- let ctx = {
1339
- ...config.context,
1340
- policy: config.policy
1341
- };
1342
- if (isVigorDefault(ctx.policy.target))
1343
- throw new VigorParseError("VALUE_REQUIRED", {
1344
- method: "request",
1345
- data: { key: "target" },
1346
- context: ctx
1347
- });
1348
- ctx.response = ctx.policy.target;
1349
- const throwError = (err) => { throw err; };
1350
- try {
1351
- for (const middleware of ctx.policy.middlewares.before) {
1352
- if (middleware._mode === "fluent") {
1353
- await middleware.func(ctx);
1354
- }
1355
- else {
1356
- ctx = await middleware.func(ctx, { throwError });
1357
- }
1358
- }
1359
- const response = ctx.response;
1360
- if (ctx.policy.settings.raw) {
1361
- ctx.result = response;
1362
- }
1363
- else {
1364
- const funcs = ctx.policy.strategies.funcs.length > 0
1365
- ? ctx.policy.strategies.funcs
1366
- : [VigorParseContentTypeStrategy];
1367
- let parsed = false;
1368
- for (const [i, func] of funcs.entries()) {
1369
- const cloned = (i === funcs.length - 1) ? response : response.clone();
1370
- try {
1371
- ctx.result = await func(cloned);
1372
- parsed = true;
1373
- break;
1374
- }
1375
- catch { }
1376
- }
1377
- if (!parsed)
1378
- throw new VigorParseError("PARSER_ALL_FAILED", {
1379
- method: "request",
1380
- data: { tried: funcs.map((_, i) => `strategy#${i}`) },
1381
- context: ctx
1382
- });
1383
- }
1384
- const setResult = (res) => { ctx.result = res; };
1385
- for (const middleware of ctx.policy.middlewares.after) {
1386
- if (middleware._mode === "fluent") {
1387
- await middleware.func(ctx);
1388
- }
1389
- else {
1390
- ctx = await middleware.func(ctx, { setResult, throwError });
1391
- }
1392
- }
1393
- for (const middleware of ctx.policy.middlewares.onResult) {
1394
- if (middleware._mode === "fluent") {
1395
- ctx.result = await middleware.func(ctx.result);
1396
- }
1397
- else {
1398
- ctx = await middleware.func(ctx, { setResult, throwError });
1399
- }
1400
- }
1401
- return {
1402
- success: true,
1403
- data: ctx.result,
1404
- error: null
1405
- };
1406
- }
1407
- catch (error) {
1408
- ctx.error = error;
1409
- ctx.flags.overrided = false;
1410
- ctx.flags.restarted = false;
1411
- const setResult = (res) => {
1412
- ctx.flags.overrided = true;
1413
- ctx.result = res;
1414
- };
1415
- const proceedRestart = () => ctx.flags.restarted = true;
1416
- const cancelRestart = () => ctx.flags.restarted = false;
1417
- for (const middleware of ctx.policy.middlewares.onError) {
1418
- if (middleware._mode === "fluent") {
1419
- await middleware.func(ctx.error);
1420
- }
1421
- else {
1422
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1423
- }
1424
- }
1425
- if (ctx.flags.restarted) {
1426
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1427
- throw new VigorParseError("RESTART_EXHAUSTED", {
1428
- method: "request",
1429
- cause: ctx.error,
1430
- data: {
1431
- maxAttempts: ctx.policy.settings.maxRestarts,
1432
- error: ctx.error
1433
- }
1434
- });
1435
- return await this.requestRuntime(restartAttempt + 1);
1436
- }
1437
- if (ctx.flags.overrided)
1438
- return {
1439
- success: true,
1440
- data: ctx.result,
1441
- error: null
1442
- };
1443
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1444
- const data = await ctx.policy.settings.default(ctx);
1445
- return {
1446
- success: true,
1447
- data,
1448
- error: null
1449
- };
1450
- }
1451
- return {
1452
- success: false,
1453
- data: null,
1454
- error: ctx.error
1455
- };
1456
- }
1457
- }
1458
- }
1459
-
1460
- const VigorFetchPolicyBase = {
1461
- __brand: createBrand("Fetch", "Policy<Schema"),
1462
- method: VigorEmpty,
1463
- origin: VigorEmpty,
1464
- path: [],
1465
- query: [],
1466
- hash: "",
1467
- headers: {},
1468
- body: VigorEmpty,
1469
- extra: {},
1470
- settings: VigorFetchPolicySettingsBase,
1471
- middlewares: VigorFetchPolicyMiddlewaresBase,
1472
- retry: VigorRetryBase,
1473
- parse: VigorParseBase
1474
- };
1475
-
1476
- const VigorFetchContextBase = {
1477
- __brand: createBrand("Fetch", "Context<Schema"),
1478
- href: "",
1479
- response: VigorDefault,
1480
- result: VigorDefault,
1481
- error: VigorDefault,
1482
- options: VigorDefault,
1483
- flags: {
1484
- overrided: false,
1485
- restarted: false
1486
- },
1487
- record: {},
1488
- policy: VigorFetchPolicyBase
1489
- };
1490
-
1491
- const VigorFetchErrorMessageFuncs = {
1492
- VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1493
- INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1494
- INVALID_PROTOCOL: ({ origin, base }) => base
1495
- ? `Invalid URL: could not resolve "${origin}" against base "${base}"`
1496
- : `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`,
1497
- FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1498
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1499
- };
1500
- /** Error type thrown by the fetch module. */
1501
- class VigorFetchError extends VigorError {
1502
- /**
1503
- * @param code - One of the fetch module's error codes.
1504
- * @param options - Error metadata, including the `data` payload for `code`.
1505
- */
1506
- constructor(code, options) {
1507
- const messageFn = VigorFetchErrorMessageFuncs[code];
1508
- super(code, messageFn(options.data), options);
1509
- }
1510
- }
1511
-
1512
- const VigorFetchBase = {
1513
- __brand: createBrand("Fetch", "Schema"),
1514
- policy: VigorFetchPolicyBase,
1515
- context: VigorFetchContextBase
1516
- };
1517
- /**
1518
- * Immutable builder that performs an HTTP request, composing an internal
1519
- * {@link VigorRetry} engine (for retry/timeout/backoff) and a
1520
- * {@link VigorParse} engine (for response parsing), with a configurable
1521
- * middleware pipeline around request building and response handling.
1522
- */
1523
- class VigorFetch extends VigorStatus {
1524
- constructor(config = VigorFetchBase) {
1525
- super(VigorFetchBase, config);
1526
- }
1527
- _create(config) {
1528
- return new VigorFetch(config);
1529
- }
1530
- /** Sets the HTTP method. Defaults to `POST` when a body is set, otherwise `GET`. */
1531
- method(str) { return this._next({ policy: { method: str } }); }
1532
- /** Sets the request origin, either an absolute URL or a path relative to the current page. */
1533
- origin(str) { return this._next({ policy: { origin: str } }); }
1534
- /** Appends path segments to the request URL. */
1535
- path(...strs) {
1536
- return this._next({ policy: { path: this._stringifyList(strs) } });
1537
- }
1538
- /** Adds query-string parameter objects to the request URL. */
1539
- query(...objs) {
1540
- return this._next({ policy: { query: objs } });
1541
- }
1542
- /** Sets the URL fragment ("hash"), replacing any previous value. */
1543
- hash(str) { return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } }); }
1544
- /**
1545
- * Sets request headers.
1546
- *
1547
- * @param mode - `"overwrite"` discards all previously configured headers
1548
- * and keeps only the ones passed here. `"merge"` behaves like
1549
- * `Object.assign`, overwriting only the keys that overlap and keeping
1550
- * the rest.
1551
- */
1552
- headers(mode, obj) {
1553
- if (mode === "overwrite")
1554
- return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
1555
- return this._next({ policy: { headers: obj } });
1556
- }
1557
- /**
1558
- * Sets the request body.
1559
- *
1560
- * @param mode - `"overwrite"` discards the previous body and fully
1561
- * replaces it with this value. `"merge"` shallow-merges (via
1562
- * `Object.assign`) when both the previous and new body are plain
1563
- * objects; for any other body type (string/Blob/FormData/etc) it is
1564
- * simply replaced.
1565
- */
1566
- body(mode, obj) {
1567
- if (mode === "overwrite")
1568
- return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
1569
- return this._next({ policy: { body: obj } });
1570
- }
1571
- /**
1572
- * Sets additional `RequestInit` options other than headers/body/method/signal
1573
- * (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
1574
- * `referrerPolicy`, `keepalive`, `integrity`).
1575
- *
1576
- * @param mode - `"overwrite"` discards all previously configured options
1577
- * and replaces them with this value. `"merge"` shallow-merges this
1578
- * value onto the previous options.
1579
- */
1580
- options(mode, obj) {
1581
- if (mode === "overwrite")
1582
- return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1583
- return this._next({ policy: { extra: obj } });
1584
- }
1585
- /** Configures the fetch policy's general settings. */
1586
- settings(input) {
1587
- if (typeof input === 'function' || input instanceof VigorFetchPolicySettings) {
1588
- const result = typeof input === 'function'
1589
- ? input(new VigorFetchPolicySettings())
1590
- : input;
1591
- return this._next({ policy: { settings: result.config.policy.settings } });
1592
- }
1593
- return this._next({ policy: { settings: input } });
1594
- }
1595
- /** Configures the fetch policy's middleware pipeline. */
1596
- middlewares(input) {
1597
- if (typeof input === 'function' || input instanceof VigorFetchPolicyMiddlewares) {
1598
- const result = typeof input === 'function'
1599
- ? input(new VigorFetchPolicyMiddlewares())
1600
- : input;
1601
- return this._next({ policy: { middlewares: result.config.policy.middlewares } });
1602
- }
1603
- return this._next({ policy: { middlewares: input } });
1604
- }
1605
- /** Configures the retry engine used to send the underlying request. */
1606
- retry(input) {
1607
- if (typeof input === 'function' || input instanceof VigorRetry) {
1608
- const result = typeof input === 'function'
1609
- ? input(new VigorRetry())
1610
- : input;
1611
- return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
1612
- }
1613
- return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
1614
- }
1615
- /** Configures the parse engine used to interpret the response. */
1616
- parse(input) {
1617
- if (typeof input === 'function' || input instanceof VigorParse) {
1618
- const result = typeof input === 'function'
1619
- ? input(new VigorParse())
1620
- : input;
1621
- return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
1622
- }
1623
- return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
1624
- }
1625
- /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
1626
- _stringifyList(unkList) {
1627
- return unkList
1628
- .filter(unk => unk !== null && unk !== undefined)
1629
- .map(unk => unk instanceof Date ? unk.toISOString() : String(unk));
1630
- }
1631
- /**
1632
- * Resolves the base URL used to interpret a relative `origin`. In a
1633
- * browser environment this is the current page location; in
1634
- * environments without `location` (e.g. Node), no base is available and
1635
- * `origin` must be an absolute URL.
1636
- */
1637
- _resolveBase() {
1638
- if (typeof globalThis !== 'undefined' && globalThis.location?.href) {
1639
- return globalThis.location.href;
1640
- }
1641
- return undefined;
1642
- }
1643
- /**
1644
- * Builds the final request URL from the configured origin, path
1645
- * segments, query parameters, and hash. An absolute `origin` ignores
1646
- * the resolved base (per the `URL` spec); a relative `origin` is
1647
- * resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
1648
- */
1649
- _buildUrl(origin, path, query, hash) {
1650
- const base = this._resolveBase();
1651
- let originObj;
1652
- try {
1653
- originObj = new URL(origin, base);
1654
- }
1655
- catch {
1656
- throw new VigorFetchError("INVALID_PROTOCOL", {
1657
- method: "_buildUrl",
1658
- data: { origin, base }
1659
- });
1660
- }
1661
- const baseStr = originObj.origin;
1662
- const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, '')];
1663
- for (const p of path)
1664
- pathParts.push(p.replace(/^\/+|\/+$/g, ''));
1665
- const pathStr = pathParts.filter(Boolean).join('/');
1666
- const mainObj = new URL(pathStr, baseStr);
1667
- const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
1668
- const queryEntries = [...originObj.searchParams.entries(), ...query.flatMap(q => Object.entries(q))];
1669
- for (const [key, val] of queryEntries) {
1670
- if (val === undefined || val === null)
1671
- continue;
1672
- if (Array.isArray(val)) {
1673
- for (const e of val)
1674
- mainObj.searchParams.append(key, parseVal(e));
1675
- }
1676
- else {
1677
- mainObj.searchParams.append(key, parseVal(val));
1678
- }
1679
- }
1680
- mainObj.hash = hash || originObj.hash;
1681
- return mainObj.href;
1682
- }
1683
- /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
1684
- _normalizeBody(body) {
1685
- if (body == null)
1686
- return { headers: {}, body: body };
1687
- if (typeof body === "string")
1688
- return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1689
- if (body instanceof Blob)
1690
- return { headers: body.type ? { "Content-Type": body.type } : {}, body };
1691
- if (body instanceof ArrayBuffer)
1692
- return { headers: { "Content-Type": "application/octet-stream" }, body };
1693
- if (body instanceof URLSearchParams)
1694
- return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
1695
- if (body instanceof FormData)
1696
- return { headers: {}, body };
1697
- if (typeof body === "object")
1698
- return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
1699
- throw new VigorFetchError("INVALID_BODY", {
1700
- method: "_normalizeBody",
1701
- data: { received: body }
1702
- });
1703
- }
1704
- /** Runs the request and returns its parsed result directly, throwing on final failure. */
1705
- async request() {
1706
- const res = await this.requestVerbose();
1707
- if (res.success)
1708
- return res.data;
1709
- throw res.error;
1710
- }
1711
- /** Runs the request and returns a result/error envelope instead of throwing. */
1712
- async requestVerbose() {
1713
- return await this.requestRuntime();
1714
- }
1715
- /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1716
- async requestRuntime(restartAttempt = 1) {
1717
- const config = this._merge(this.config, {});
1718
- let ctx = {
1719
- ...config.context,
1720
- policy: config.policy
1721
- };
1722
- const throwError = (err) => { throw err; };
1723
- try {
1724
- if (isVigorEmpty(ctx.policy.origin))
1725
- throw new VigorFetchError("VALUE_REQUIRED", {
1726
- method: "request",
1727
- data: { key: "origin" }
1728
- });
1729
- ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1730
- const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== undefined;
1731
- const method = isVigorEmpty(ctx.policy.method) ? (hasBody ? "POST" : "GET") : ctx.policy.method;
1732
- let options = {
1733
- ...ctx.policy.extra,
1734
- method: method,
1735
- headers: {}
1736
- };
1737
- if (hasBody) {
1738
- const normalized = this._normalizeBody(ctx.policy.body);
1739
- if (normalized.body !== undefined)
1740
- options.body = normalized.body;
1741
- Object.assign(options.headers, normalized.headers);
1742
- }
1743
- Object.assign(options.headers, ctx.policy.headers);
1744
- for (const middleware of ctx.policy.middlewares.before) {
1745
- if (middleware._mode === "fluent") {
1746
- await middleware.func(ctx);
1747
- }
1748
- else {
1749
- ctx = await middleware.func(ctx, {
1750
- throwError,
1751
- setOptions: (o) => { options = o; },
1752
- setHeaders: (h) => { options.headers = h; },
1753
- setBody: (b) => { options.body = b; }
1754
- });
1755
- }
1756
- }
1757
- ctx.options = options;
1758
- const retryEngine = new VigorRetry(ctx.policy.retry)
1759
- .target(async (signal) => {
1760
- return await fetch(ctx.href, { ...options, signal });
1761
- })
1762
- .middlewares(m => m
1763
- .after("intercept", async (rctx, api) => {
1764
- const response = rctx.result;
1765
- if (!response.ok) {
1766
- let parsed = undefined;
1767
- try {
1768
- parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
1769
- }
1770
- catch {
1771
- }
1772
- api.throwError(new VigorFetchError("FETCH_FAILED", {
1773
- method: "request",
1774
- data: {
1775
- status: response.status,
1776
- statusText: response.statusText,
1777
- response,
1778
- url: response.url,
1779
- parsed
1780
- }
1781
- }));
1782
- }
1783
- return rctx;
1784
- })
1785
- .retryIf("intercept", async (rctx, api) => {
1786
- const response = rctx.error instanceof VigorFetchError
1787
- ? rctx.error.data?.response
1788
- : undefined;
1789
- if (response && ctx.policy.settings.unretryStatus.includes(response.status))
1790
- api.cancelRetry();
1791
- else
1792
- api.proceedRetry();
1793
- return rctx;
1794
- })
1795
- .onRetry("intercept", async (rctx, api) => {
1796
- const response = rctx.error instanceof VigorFetchError
1797
- ? rctx.error.data?.response
1798
- : undefined;
1799
- if (response?.status === 429) {
1800
- let retryHeader = null;
1801
- for (const header of ctx.policy.settings.retryHeaders) {
1802
- retryHeader = response.headers.get(header);
1803
- if (retryHeader)
1804
- break;
1805
- }
1806
- if (retryHeader) {
1807
- const toNumber = Number(retryHeader);
1808
- const delay = !isNaN(toNumber)
1809
- ? toNumber * 1000
1810
- : (() => {
1811
- const toDate = new Date(retryHeader).getTime();
1812
- return !isNaN(toDate) ? toDate - Date.now() : null;
1813
- })();
1814
- if (delay !== null && delay > 0)
1815
- api.setDelay(delay);
1816
- }
1817
- }
1818
- return rctx;
1819
- }));
1820
- ctx.response = await retryEngine.request();
1821
- const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
1822
- ctx.result = await parseEngine.request();
1823
- for (const middleware of ctx.policy.middlewares.after) {
1824
- if (middleware._mode === "fluent") {
1825
- await middleware.func(ctx);
1826
- }
1827
- else {
1828
- ctx = await middleware.func(ctx, { throwError, setResult: (r) => { ctx.result = r; } });
1829
- }
1830
- }
1831
- const setResult = (r) => { ctx.result = r; };
1832
- for (const middleware of ctx.policy.middlewares.onResult) {
1833
- if (middleware._mode === "fluent") {
1834
- ctx.result = await middleware.func(ctx.result);
1835
- }
1836
- else {
1837
- ctx = await middleware.func(ctx, { setResult, throwError });
1838
- }
1839
- }
1840
- return {
1841
- success: true,
1842
- data: ctx.result,
1843
- error: null
1844
- };
1845
- }
1846
- catch (error) {
1847
- ctx.error = error;
1848
- ctx.flags.overrided = false;
1849
- ctx.flags.restarted = false;
1850
- const setResult = (r) => {
1851
- ctx.flags.overrided = true;
1852
- ctx.result = r;
1853
- };
1854
- const proceedRestart = () => ctx.flags.restarted = true;
1855
- const cancelRestart = () => ctx.flags.restarted = false;
1856
- for (const middleware of ctx.policy.middlewares.onError) {
1857
- if (middleware._mode === "fluent") {
1858
- await middleware.func(ctx.error);
1859
- }
1860
- else {
1861
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1862
- }
1863
- }
1864
- if (ctx.flags.restarted) {
1865
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts)
1866
- throw new VigorFetchError("RESTART_EXHAUSTED", {
1867
- method: "request",
1868
- cause: ctx.error,
1869
- data: {
1870
- maxAttempts: ctx.policy.settings.maxRestarts,
1871
- error: ctx.error
1872
- }
1873
- });
1874
- return await this.requestRuntime(restartAttempt + 1);
1875
- }
1876
- if (ctx.flags.overrided)
1877
- return {
1878
- success: true,
1879
- data: ctx.result,
1880
- error: null
1881
- };
1882
- if (!isVigorEmpty(ctx.policy.settings.default)) {
1883
- const data = await ctx.policy.settings.default(ctx);
1884
- return {
1885
- success: true,
1886
- data,
1887
- error: null
1888
- };
1889
- }
1890
- return {
1891
- success: false,
1892
- data: null,
1893
- error
1894
- };
1895
- }
1896
- }
1897
- }
1898
-
1899
- const vigor = {
1900
- use: (plugin, options) => {
1901
- plugin.func(vigor, options);
1902
- },
1903
- retry: (task) => task ? new VigorRetry().target(task) : new VigorRetry(),
1904
- parse: (response) => response ? new VigorParse().target(response) : new VigorParse(),
1905
- fetch: (origin) => origin ? new VigorFetch().origin(origin) : new VigorFetch(),
1906
- all: (...tasks) => tasks.length > 0 ? new VigorAll().target(...tasks) : new VigorAll(),
1907
- builders: {
1908
- fetch: {
1909
- settings: () => new VigorFetchPolicySettings(),
1910
- middlewares: () => new VigorFetchPolicyMiddlewares(),
1911
- },
1912
- retry: {
1913
- settings: () => new VigorRetryPolicySettings(),
1914
- middlewares: () => new VigorRetryPolicyMiddlewares(),
1915
- algorithms: () => new VigorRetryPolicyAlgorithms(),
1916
- algorithm: {
1917
- constant: () => new VigorRetryPolicyAlgorithmsConstant(),
1918
- linear: () => new VigorRetryPolicyAlgorithmsLinear(),
1919
- backoff: () => new VigorRetryPolicyAlgorithmsBackoff(),
1920
- custom: () => new VigorRetryPolicyAlgorithmsCustom(),
1921
- },
1922
- },
1923
- parse: {
1924
- settings: () => new VigorParsePolicySettings(),
1925
- middlewares: () => new VigorParsePolicyMiddlewares(),
1926
- strategies: () => new VigorParsePolicyStrategies(),
1927
- },
1928
- all: {
1929
- settings: () => new VigorAllPolicySettings(),
1930
- middlewares: () => new VigorAllPolicyMiddlewares(),
1931
- },
1932
- }
1933
- };
1934
-
1935
- 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 };