vigor-fetch 4.0.11 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +408 -32
- package/dist/index.cjs +1071 -359
- package/dist/index.d.cts +3578 -1539
- package/dist/index.d.ts +3578 -1539
- package/dist/index.js +1051 -359
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -18,7 +18,7 @@ var VigorStatus = class {
|
|
|
18
18
|
*/
|
|
19
19
|
constructor(base, config) {
|
|
20
20
|
this._base = base;
|
|
21
|
-
this._config = this._merge(base, config);
|
|
21
|
+
this._config = this._merge(base, config, void 0, "replace");
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
24
|
* Derives a new instance by merging `patch` onto the current config.
|
|
@@ -36,9 +36,11 @@ var VigorStatus = class {
|
|
|
36
36
|
/**
|
|
37
37
|
* Deep-merges `target` onto `source`, honoring an optional per-path
|
|
38
38
|
* `strategy` tree. Objects merge key by key, arrays concatenate (unless
|
|
39
|
-
* `"replace"` is specified), and any other
|
|
39
|
+
* `"replace"` is specified, or `arrayMode` is `"replace"`), and any other
|
|
40
|
+
* value — including `null` — is overwritten. Only `undefined` keeps the
|
|
41
|
+
* source value.
|
|
40
42
|
*/
|
|
41
|
-
_merge(source, target, strategy) {
|
|
43
|
+
_merge(source, target, strategy, arrayMode = "concat") {
|
|
42
44
|
const isObj = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
|
|
43
45
|
const deepClone = (v) => {
|
|
44
46
|
if (Array.isArray(v)) return v.map(deepClone);
|
|
@@ -50,10 +52,10 @@ var VigorStatus = class {
|
|
|
50
52
|
return v;
|
|
51
53
|
};
|
|
52
54
|
const merge = (a, b, s) => {
|
|
53
|
-
if (b === void 0
|
|
55
|
+
if (b === void 0) return deepClone(a);
|
|
54
56
|
if (s === "replace") return b;
|
|
55
57
|
if (Array.isArray(a) && Array.isArray(b)) {
|
|
56
|
-
return
|
|
58
|
+
return arrayMode === "replace" ? deepClone(b) : [...a, ...b];
|
|
57
59
|
}
|
|
58
60
|
if (isObj(a) && isObj(b)) {
|
|
59
61
|
const r = {};
|
|
@@ -68,6 +70,14 @@ var VigorStatus = class {
|
|
|
68
70
|
};
|
|
69
71
|
return merge(source, target, strategy);
|
|
70
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Snapshots a runtime context for a timeline entry: a `_merge` deep clone
|
|
75
|
+
* of everything but `timeline`, so later changes to `ctx` don't reach it.
|
|
76
|
+
*/
|
|
77
|
+
_snapshot(ctx) {
|
|
78
|
+
const { timeline: _, ...rest } = ctx;
|
|
79
|
+
return this._merge(rest, {});
|
|
80
|
+
}
|
|
71
81
|
/** The default/base config this builder was constructed with. */
|
|
72
82
|
get base() {
|
|
73
83
|
return this._base;
|
|
@@ -81,8 +91,11 @@ var VigorStatus = class {
|
|
|
81
91
|
// src/all/settings.ts
|
|
82
92
|
var VigorAllPolicySettingsBase = {
|
|
83
93
|
__brand: createBrand("All", "Policy<Settings<Schema"),
|
|
94
|
+
debug: false,
|
|
84
95
|
concurrency: 5,
|
|
85
|
-
onlySuccess: false
|
|
96
|
+
onlySuccess: false,
|
|
97
|
+
timeout: VigorEmpty,
|
|
98
|
+
failFast: false
|
|
86
99
|
};
|
|
87
100
|
var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
|
|
88
101
|
constructor(config = VigorAllBase) {
|
|
@@ -99,6 +112,22 @@ var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
|
|
|
99
112
|
onlySuccess(bool) {
|
|
100
113
|
return this._next({ policy: { settings: { onlySuccess: bool } } });
|
|
101
114
|
}
|
|
115
|
+
/** Sets the per-task timeout, in milliseconds. A task exceeding it fails with `TIMED_OUT`. */
|
|
116
|
+
timeout(num) {
|
|
117
|
+
return this._next({ policy: { settings: { timeout: num } } });
|
|
118
|
+
}
|
|
119
|
+
/** When enabled, the first unrecovered task failure aborts the remaining tasks and fails the batch with that error. */
|
|
120
|
+
failFast(bool) {
|
|
121
|
+
return this._next({ policy: { settings: { failFast: bool } } });
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Turns timeline recording on or off (off by default). Off, the
|
|
125
|
+
* `timeline` of `requestVerbose()` stays empty and no context snapshots
|
|
126
|
+
* are taken, so it costs nothing unless you're debugging.
|
|
127
|
+
*/
|
|
128
|
+
debug(bool) {
|
|
129
|
+
return this._next({ policy: { settings: { debug: bool } } });
|
|
130
|
+
}
|
|
102
131
|
};
|
|
103
132
|
|
|
104
133
|
// src/all/middlewares.ts
|
|
@@ -145,6 +174,7 @@ var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorSt
|
|
|
145
174
|
var VigorAllPolicyBase = {
|
|
146
175
|
__brand: createBrand("All", "Policy<Schema"),
|
|
147
176
|
target: [],
|
|
177
|
+
abortSignals: [],
|
|
148
178
|
settings: VigorAllPolicySettingsBase,
|
|
149
179
|
middlewares: VigorAllPolicyMiddlewaresBase
|
|
150
180
|
};
|
|
@@ -154,13 +184,15 @@ var VigorAllContextBase = {
|
|
|
154
184
|
__brand: createBrand("All", "Context<Schema"),
|
|
155
185
|
result: VigorDefault,
|
|
156
186
|
policy: VigorAllPolicyBase,
|
|
157
|
-
record: {}
|
|
187
|
+
record: {},
|
|
188
|
+
timeline: []
|
|
158
189
|
};
|
|
159
190
|
var VigorAllEachContextBase = {
|
|
160
191
|
__brand: createBrand("All", "EachContext<Schema"),
|
|
192
|
+
index: 0,
|
|
161
193
|
result: VigorDefault,
|
|
162
194
|
error: VigorDefault,
|
|
163
|
-
flags: {
|
|
195
|
+
flags: { overridden: false },
|
|
164
196
|
record: {}
|
|
165
197
|
};
|
|
166
198
|
|
|
@@ -171,6 +203,7 @@ var VigorError = class extends Error {
|
|
|
171
203
|
code;
|
|
172
204
|
data;
|
|
173
205
|
method;
|
|
206
|
+
/** The run context when the error was raised; its presence depends on the code (see {@link VigorErrorContext}). */
|
|
174
207
|
context;
|
|
175
208
|
/**
|
|
176
209
|
* @param code - Machine-readable error code.
|
|
@@ -192,7 +225,8 @@ var VigorError = class extends Error {
|
|
|
192
225
|
|
|
193
226
|
// src/all/error.ts
|
|
194
227
|
var VigorAllErrorMessageFuncs = {
|
|
195
|
-
EMPTY_TARGET: (_) => `Empty target list
|
|
228
|
+
EMPTY_TARGET: (_) => `Empty target list`,
|
|
229
|
+
TIMED_OUT: ({ limit, index }) => `Task #${index} timeout: exceeded ${limit}ms`
|
|
196
230
|
};
|
|
197
231
|
var VigorAllError = class extends VigorError {
|
|
198
232
|
/**
|
|
@@ -204,8 +238,64 @@ var VigorAllError = class extends VigorError {
|
|
|
204
238
|
super(code, messageFn(options.data), options);
|
|
205
239
|
}
|
|
206
240
|
};
|
|
241
|
+
function isVigorAllError(error, ...codes) {
|
|
242
|
+
return error instanceof VigorAllError && (codes.length === 0 || codes.includes(error.code));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// src/core/timeline.ts
|
|
246
|
+
var internalMiddlewares = /* @__PURE__ */ new WeakSet();
|
|
247
|
+
function markVigorInternal(func) {
|
|
248
|
+
internalMiddlewares.add(func);
|
|
249
|
+
return func;
|
|
250
|
+
}
|
|
251
|
+
function isVigorInternalMiddleware(middleware) {
|
|
252
|
+
const func = typeof middleware === "function" ? middleware : middleware?.func;
|
|
253
|
+
return typeof func === "function" && internalMiddlewares.has(func);
|
|
254
|
+
}
|
|
255
|
+
function createVigorTimelineRecorder(timeline, snapshot, enabled) {
|
|
256
|
+
const add = (action, content) => {
|
|
257
|
+
if (!enabled) return;
|
|
258
|
+
timeline.push({ action, content, now: Date.now(), ctx: snapshot() });
|
|
259
|
+
};
|
|
260
|
+
const record = add;
|
|
261
|
+
const stage = async (stage2, middlewares, run) => {
|
|
262
|
+
if (middlewares.length === 0) return;
|
|
263
|
+
if (!enabled) {
|
|
264
|
+
for (const middleware of middlewares) await run(middleware, (api) => api);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
record("MIDDLEWARE_LOOP_STARTED", { stage: stage2, middlewares });
|
|
268
|
+
const started = performance.now();
|
|
269
|
+
try {
|
|
270
|
+
for (const [index, middleware] of middlewares.entries()) {
|
|
271
|
+
const internal = isVigorInternalMiddleware(middleware);
|
|
272
|
+
const ranAt = performance.now();
|
|
273
|
+
try {
|
|
274
|
+
await run(middleware, (api) => {
|
|
275
|
+
const traced = {};
|
|
276
|
+
for (const [method, func] of Object.entries(api)) {
|
|
277
|
+
traced[method] = (...args) => {
|
|
278
|
+
record("MIDDLEWARE_API_CALLED", { stage: stage2, index, middleware, internal, method, args });
|
|
279
|
+
return func(...args);
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
return traced;
|
|
283
|
+
});
|
|
284
|
+
} catch (error) {
|
|
285
|
+
record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: true, error });
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: false, error: null });
|
|
289
|
+
}
|
|
290
|
+
} finally {
|
|
291
|
+
record("MIDDLEWARE_LOOP_ENDED", { stage: stage2, middlewares, took: performance.now() - started });
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
return { add, stage };
|
|
295
|
+
}
|
|
207
296
|
|
|
208
297
|
// src/all/main.ts
|
|
298
|
+
var MAX_TIMEOUT = 2 ** 31 - 1;
|
|
209
299
|
var VigorAllBase = {
|
|
210
300
|
__brand: createBrand("All", "Schema"),
|
|
211
301
|
policy: VigorAllPolicyBase,
|
|
@@ -222,9 +312,13 @@ var VigorAll = class _VigorAll extends VigorStatus {
|
|
|
222
312
|
target(...funcs) {
|
|
223
313
|
return this._next({ policy: { target: funcs } });
|
|
224
314
|
}
|
|
315
|
+
/** Sets external abort signals that, when aborted, cancel the remaining tasks and fail the batch. */
|
|
316
|
+
abortSignals(...sig) {
|
|
317
|
+
return this._next({ policy: { abortSignals: sig } });
|
|
318
|
+
}
|
|
225
319
|
settings(input) {
|
|
226
320
|
if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
|
|
227
|
-
const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
|
|
321
|
+
const result = typeof input === "function" ? input(new VigorAllPolicySettings(this.config)) : input;
|
|
228
322
|
return this._next({
|
|
229
323
|
policy: { settings: result.config.policy.settings }
|
|
230
324
|
});
|
|
@@ -241,22 +335,51 @@ var VigorAll = class _VigorAll extends VigorStatus {
|
|
|
241
335
|
return this._next({ policy: { middlewares: input } });
|
|
242
336
|
}
|
|
243
337
|
/** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
|
|
244
|
-
async _runTask(task, policy) {
|
|
245
|
-
let ctx = this._merge(VigorAllEachContextBase, {});
|
|
338
|
+
async _runTask(task, index, policy, batchSignal, timeline, debug) {
|
|
339
|
+
let ctx = this._merge(VigorAllEachContextBase, { index });
|
|
340
|
+
const { add, stage } = createVigorTimelineRecorder(timeline, () => this._merge(ctx, {}), debug);
|
|
341
|
+
const timeoutController = new AbortController();
|
|
342
|
+
const signal = AbortSignal.any([batchSignal, timeoutController.signal]);
|
|
343
|
+
let timeoutId;
|
|
344
|
+
let onAbort;
|
|
345
|
+
add("TASK_STARTED", { index });
|
|
346
|
+
const started = performance.now();
|
|
347
|
+
const settle = (res) => {
|
|
348
|
+
add("TASK_ENDED", { index, success: res.success, took: performance.now() - started });
|
|
349
|
+
return res;
|
|
350
|
+
};
|
|
246
351
|
try {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
352
|
+
await stage("beforeEach", policy.middlewares.beforeEach, (beforeEach) => beforeEach(ctx));
|
|
353
|
+
signal.throwIfAborted();
|
|
354
|
+
const limit = policy.settings.timeout;
|
|
355
|
+
if (!isVigorEmpty(limit) && Number.isFinite(limit) && limit > 0) {
|
|
356
|
+
timeoutId = setTimeout(() => timeoutController.abort(new VigorAllError("TIMED_OUT", {
|
|
357
|
+
method: "request",
|
|
358
|
+
data: { limit, index }
|
|
359
|
+
})), Math.min(limit, MAX_TIMEOUT));
|
|
360
|
+
}
|
|
361
|
+
ctx.result = await Promise.race([
|
|
362
|
+
task(signal),
|
|
363
|
+
new Promise((_, rej) => {
|
|
364
|
+
onAbort = () => rej(signal.reason);
|
|
365
|
+
signal.addEventListener("abort", onAbort);
|
|
366
|
+
})
|
|
367
|
+
]);
|
|
368
|
+
await stage("afterEach", policy.middlewares.afterEach, (afterEach) => afterEach(ctx));
|
|
369
|
+
return settle({ success: true, value: ctx.result });
|
|
251
370
|
} catch (error) {
|
|
252
371
|
ctx.error = error;
|
|
372
|
+
add("TASK_ERROR", { index, error });
|
|
253
373
|
const setResult = (r) => {
|
|
254
|
-
ctx.flags.
|
|
374
|
+
ctx.flags.overridden = true;
|
|
255
375
|
ctx.result = r;
|
|
256
376
|
};
|
|
257
|
-
|
|
258
|
-
if (ctx.flags.
|
|
259
|
-
return { success: false, value: error };
|
|
377
|
+
await stage("onErrorEach", policy.middlewares.onErrorEach, (onErrorEach, trace) => onErrorEach(ctx, trace({ setResult })));
|
|
378
|
+
if (ctx.flags.overridden) return settle({ success: true, value: ctx.result });
|
|
379
|
+
return settle({ success: false, value: error });
|
|
380
|
+
} finally {
|
|
381
|
+
clearTimeout(timeoutId);
|
|
382
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
260
383
|
}
|
|
261
384
|
}
|
|
262
385
|
/**
|
|
@@ -271,80 +394,116 @@ var VigorAll = class _VigorAll extends VigorStatus {
|
|
|
271
394
|
{ cast: "replace" }
|
|
272
395
|
);
|
|
273
396
|
}
|
|
274
|
-
/**
|
|
397
|
+
/**
|
|
398
|
+
* Runs all tasks and returns the results array directly, throwing on final failure.
|
|
399
|
+
*
|
|
400
|
+
* `R` defaults to the inferred result type. Passing one (`request<User>()`)
|
|
401
|
+
* means "ignore the inference, it's this": it's taken as-is, unchecked.
|
|
402
|
+
* To name the inferred type itself, use `VigorResultOf<typeof builder>`.
|
|
403
|
+
*/
|
|
275
404
|
async request() {
|
|
276
405
|
const res = await this.requestVerbose();
|
|
277
406
|
if (res.success) return res.data;
|
|
278
407
|
throw res.error;
|
|
279
408
|
}
|
|
280
|
-
/**
|
|
409
|
+
/**
|
|
410
|
+
* Runs all tasks and returns a result/error envelope instead of throwing,
|
|
411
|
+
* along with the `timeline` of everything the batch went through.
|
|
412
|
+
*/
|
|
281
413
|
async requestVerbose() {
|
|
282
414
|
return await this.requestRuntime();
|
|
283
415
|
}
|
|
284
416
|
/** Internal execution loop implementing the bounded-concurrency worker pool and the batch-level before/after/onResult pipeline. */
|
|
285
|
-
async requestRuntime() {
|
|
417
|
+
async requestRuntime(timeline = []) {
|
|
286
418
|
const config = this._merge(this.config, {});
|
|
287
419
|
const policy = config.policy;
|
|
288
420
|
let ctx = this._merge(VigorAllContextBase, {
|
|
289
421
|
policy
|
|
422
|
+
}, void 0, "replace");
|
|
423
|
+
ctx.timeline = timeline;
|
|
424
|
+
const startedAt = performance.now();
|
|
425
|
+
const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
|
|
426
|
+
const end = (success, error) => add("REQUEST_END", {
|
|
427
|
+
success,
|
|
428
|
+
outcome: success ? "result" : "failed",
|
|
429
|
+
error,
|
|
430
|
+
took: performance.now() - startedAt,
|
|
431
|
+
restarts: 0
|
|
290
432
|
});
|
|
291
433
|
const setResult = (r) => {
|
|
292
|
-
ctx =
|
|
434
|
+
ctx.result = r;
|
|
293
435
|
};
|
|
294
436
|
const throwError = (err) => {
|
|
295
437
|
throw err;
|
|
296
438
|
};
|
|
439
|
+
const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
|
|
440
|
+
add("PROCESS_HANDLING", { type: "REQUEST_START", data: { tasks: policy.target.length, concurrency } });
|
|
297
441
|
try {
|
|
298
442
|
if (policy.target.length === 0) throw new VigorAllError("EMPTY_TARGET", {
|
|
299
443
|
method: "request",
|
|
300
444
|
data: {},
|
|
301
445
|
context: ctx
|
|
302
446
|
});
|
|
303
|
-
|
|
447
|
+
await stage("before", policy.middlewares.before, async (mw, trace) => {
|
|
304
448
|
if (mw._mode === "fluent") {
|
|
305
449
|
await mw.func(ctx);
|
|
306
450
|
} else {
|
|
307
|
-
ctx = await mw.func(ctx, { throwError });
|
|
451
|
+
ctx = await mw.func(ctx, trace({ throwError })) ?? ctx;
|
|
308
452
|
}
|
|
309
|
-
}
|
|
310
|
-
const concurrency = Math.max(1, policy.settings.concurrency);
|
|
453
|
+
});
|
|
311
454
|
const results = new Array(policy.target.length);
|
|
455
|
+
const batchController = new AbortController();
|
|
456
|
+
const batchSignal = AbortSignal.any([...policy.abortSignals, batchController.signal]);
|
|
312
457
|
let cursor = 0;
|
|
313
458
|
const worker = async () => {
|
|
314
|
-
while (
|
|
459
|
+
while (!batchSignal.aborted) {
|
|
315
460
|
const i = cursor++;
|
|
316
461
|
if (i >= policy.target.length) return;
|
|
317
|
-
|
|
462
|
+
try {
|
|
463
|
+
results[i] = await this._runTask(policy.target[i], i, policy, batchSignal, timeline, policy.settings.debug);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
batchController.abort(error);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (!results[i].success && policy.settings.failFast) {
|
|
469
|
+
batchController.abort(results[i].value);
|
|
470
|
+
}
|
|
318
471
|
}
|
|
319
472
|
};
|
|
320
473
|
await Promise.all(
|
|
321
474
|
Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
|
|
322
475
|
);
|
|
323
|
-
|
|
324
|
-
|
|
476
|
+
batchSignal.throwIfAborted();
|
|
477
|
+
ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.success ? { success: true, data: r.value, error: null } : { success: false, data: null, error: r.value });
|
|
478
|
+
await stage("after", policy.middlewares.after, async (mw, trace) => {
|
|
325
479
|
if (mw._mode === "fluent") {
|
|
326
480
|
await mw.func(ctx);
|
|
327
481
|
} else {
|
|
328
|
-
ctx = await mw.func(ctx, { setResult, throwError });
|
|
482
|
+
ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
|
|
329
483
|
}
|
|
330
|
-
}
|
|
331
|
-
|
|
484
|
+
});
|
|
485
|
+
await stage("onResult", policy.middlewares.onResult, async (mw, trace) => {
|
|
332
486
|
if (mw._mode === "fluent") {
|
|
333
487
|
ctx.result = await mw.func(ctx.result);
|
|
334
488
|
} else {
|
|
335
|
-
ctx = await mw.func(ctx, { setResult, throwError });
|
|
489
|
+
ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
|
|
336
490
|
}
|
|
337
|
-
}
|
|
491
|
+
});
|
|
492
|
+
end(true, null);
|
|
338
493
|
return {
|
|
339
494
|
success: true,
|
|
340
495
|
data: ctx.result,
|
|
341
|
-
error: null
|
|
496
|
+
error: null,
|
|
497
|
+
timeline
|
|
342
498
|
};
|
|
343
499
|
} catch (error) {
|
|
500
|
+
add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
|
|
501
|
+
end(false, error);
|
|
344
502
|
return {
|
|
345
503
|
success: false,
|
|
346
504
|
data: null,
|
|
347
|
-
error
|
|
505
|
+
error,
|
|
506
|
+
timeline
|
|
348
507
|
};
|
|
349
508
|
}
|
|
350
509
|
}
|
|
@@ -353,8 +512,46 @@ var VigorAll = class _VigorAll extends VigorStatus {
|
|
|
353
512
|
// src/fetch/settings.ts
|
|
354
513
|
var VigorFetchPolicySettingsBase = {
|
|
355
514
|
__brand: createBrand("Fetch", "Policy<Settings<Schema"),
|
|
356
|
-
|
|
357
|
-
|
|
515
|
+
debug: false,
|
|
516
|
+
retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"],
|
|
517
|
+
// Statuses a retry of the same request won't change. Left retryable on
|
|
518
|
+
// purpose: 408 (timeout), 421 (misdirected — another connection may
|
|
519
|
+
// work), 423 (locked), 425 (too early), 429 (rate limit), and 5xx
|
|
520
|
+
// outages (500, 502, 503, 504, 507).
|
|
521
|
+
unretryStatus: [
|
|
522
|
+
400,
|
|
523
|
+
401,
|
|
524
|
+
402,
|
|
525
|
+
403,
|
|
526
|
+
404,
|
|
527
|
+
405,
|
|
528
|
+
406,
|
|
529
|
+
407,
|
|
530
|
+
409,
|
|
531
|
+
410,
|
|
532
|
+
411,
|
|
533
|
+
412,
|
|
534
|
+
413,
|
|
535
|
+
414,
|
|
536
|
+
415,
|
|
537
|
+
416,
|
|
538
|
+
417,
|
|
539
|
+
422,
|
|
540
|
+
424,
|
|
541
|
+
426,
|
|
542
|
+
428,
|
|
543
|
+
431,
|
|
544
|
+
451,
|
|
545
|
+
501,
|
|
546
|
+
505,
|
|
547
|
+
506,
|
|
548
|
+
508,
|
|
549
|
+
510,
|
|
550
|
+
511
|
|
551
|
+
],
|
|
552
|
+
maxRetryAfter: 5 * 60 * 1e3,
|
|
553
|
+
redirect: false,
|
|
554
|
+
confinePath: true,
|
|
358
555
|
maxRestarts: 3,
|
|
359
556
|
default: VigorEmpty
|
|
360
557
|
};
|
|
@@ -365,13 +562,34 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
|
|
|
365
562
|
_create(config) {
|
|
366
563
|
return new _VigorFetchPolicySettings(config);
|
|
367
564
|
}
|
|
368
|
-
/** Sets response headers consulted to compute a server-suggested retry delay. */
|
|
565
|
+
/** Sets (replaces) the response headers consulted to compute a server-suggested retry delay. */
|
|
369
566
|
retryHeaders(...strs) {
|
|
370
|
-
return this._next({ policy: { settings: { retryHeaders: strs } } });
|
|
567
|
+
return this._next({ policy: { settings: { retryHeaders: strs } } }, { policy: { settings: { retryHeaders: "replace" } } });
|
|
371
568
|
}
|
|
372
|
-
/** Sets HTTP status codes that should never be retried. */
|
|
569
|
+
/** Sets (replaces) the HTTP status codes that should never be retried. */
|
|
373
570
|
unretryStatus(...nums) {
|
|
374
|
-
return this._next({ policy: { settings: { unretryStatus: nums } } });
|
|
571
|
+
return this._next({ policy: { settings: { unretryStatus: nums } } }, { policy: { settings: { unretryStatus: "replace" } } });
|
|
572
|
+
}
|
|
573
|
+
/** Sets the upper bound, in milliseconds, on a server-suggested retry delay. */
|
|
574
|
+
maxRetryAfter(num) {
|
|
575
|
+
return this._next({ policy: { settings: { maxRetryAfter: num } } });
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* When enabled, a redirected response (or a readable `3xx` with a
|
|
579
|
+
* `Location` header) navigates the page to its target
|
|
580
|
+
* (`window.location.href`). Without `window.location` — e.g. in Node —
|
|
581
|
+
* this behaves like `false`.
|
|
582
|
+
*/
|
|
583
|
+
/**
|
|
584
|
+
* When enabled (the default), a request whose URL would leave its
|
|
585
|
+
* origin's domain or path (e.g. through a `".."` path segment) fails with
|
|
586
|
+
* `PATH_ESCAPED` instead of being sent.
|
|
587
|
+
*/
|
|
588
|
+
confinePath(bool) {
|
|
589
|
+
return this._next({ policy: { settings: { confinePath: bool } } });
|
|
590
|
+
}
|
|
591
|
+
redirect(bool) {
|
|
592
|
+
return this._next({ policy: { settings: { redirect: bool } } });
|
|
375
593
|
}
|
|
376
594
|
/** Sets the maximum number of full restarts allowed. */
|
|
377
595
|
maxRestarts(num) {
|
|
@@ -381,6 +599,15 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
|
|
|
381
599
|
default(func) {
|
|
382
600
|
return this._next({ policy: { settings: { default: func } } });
|
|
383
601
|
}
|
|
602
|
+
/**
|
|
603
|
+
* Turns timeline recording on or off (off by default). Off, the
|
|
604
|
+
* `timeline` of `requestVerbose()` stays empty and no context snapshots
|
|
605
|
+
* are taken, so it costs nothing unless you're debugging. With it on,
|
|
606
|
+
* the nested retry/parse engines record theirs too.
|
|
607
|
+
*/
|
|
608
|
+
debug(bool) {
|
|
609
|
+
return this._next({ policy: { settings: { debug: bool } } });
|
|
610
|
+
}
|
|
384
611
|
};
|
|
385
612
|
|
|
386
613
|
// src/fetch/middlewares.ts
|
|
@@ -415,6 +642,7 @@ var VigorFetchPolicyMiddlewares = class _VigorFetchPolicyMiddlewares extends Vig
|
|
|
415
642
|
// src/retry/settings.ts
|
|
416
643
|
var VigorRetryPolicySettingsBase = {
|
|
417
644
|
__brand: createBrand("Retry", "Policy<Settings<Schema"),
|
|
645
|
+
debug: false,
|
|
418
646
|
default: VigorEmpty,
|
|
419
647
|
maxAttempts: 5,
|
|
420
648
|
maxRestarts: 3,
|
|
@@ -451,6 +679,14 @@ var VigorRetryPolicySettings = class _VigorRetryPolicySettings extends VigorStat
|
|
|
451
679
|
policy: { settings: { timeout: num } }
|
|
452
680
|
});
|
|
453
681
|
}
|
|
682
|
+
/**
|
|
683
|
+
* Turns timeline recording on or off (off by default). Off, the
|
|
684
|
+
* `timeline` of `requestVerbose()` stays empty and no context snapshots
|
|
685
|
+
* are taken, so it costs nothing unless you're debugging.
|
|
686
|
+
*/
|
|
687
|
+
debug(bool) {
|
|
688
|
+
return this._next({ policy: { settings: { debug: bool } } });
|
|
689
|
+
}
|
|
454
690
|
};
|
|
455
691
|
|
|
456
692
|
// src/retry/middlewares.ts
|
|
@@ -519,6 +755,9 @@ var VigorRetryError = class extends VigorError {
|
|
|
519
755
|
super(code, messageFn(options.data), options);
|
|
520
756
|
}
|
|
521
757
|
};
|
|
758
|
+
function isVigorRetryError(error, ...codes) {
|
|
759
|
+
return error instanceof VigorRetryError && (codes.length === 0 || codes.includes(error.code));
|
|
760
|
+
}
|
|
522
761
|
|
|
523
762
|
// src/retry/algorithms.ts
|
|
524
763
|
function VigorJitter(jitter) {
|
|
@@ -764,13 +1003,17 @@ var VigorRetryContextBase = {
|
|
|
764
1003
|
doRetry: true,
|
|
765
1004
|
doRestart: false,
|
|
766
1005
|
brokeRetry: false,
|
|
1006
|
+
aborted: false,
|
|
1007
|
+
timedOut: false,
|
|
767
1008
|
overridden: false
|
|
768
1009
|
},
|
|
769
1010
|
record: {},
|
|
1011
|
+
timeline: [],
|
|
770
1012
|
policy: VigorRetryPolicyBase
|
|
771
1013
|
};
|
|
772
1014
|
|
|
773
1015
|
// src/retry/main.ts
|
|
1016
|
+
var MAX_TIMEOUT2 = 2 ** 31 - 1;
|
|
774
1017
|
var VigorRetryBase = {
|
|
775
1018
|
__brand: createBrand("Retry", "Schema"),
|
|
776
1019
|
policy: VigorRetryPolicyBase,
|
|
@@ -797,7 +1040,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
797
1040
|
}
|
|
798
1041
|
settings(input) {
|
|
799
1042
|
if (typeof input === "function" || input instanceof VigorRetryPolicySettings) {
|
|
800
|
-
const result = typeof input === "function" ? input(new VigorRetryPolicySettings()) : input;
|
|
1043
|
+
const result = typeof input === "function" ? input(new VigorRetryPolicySettings(this.config)) : input;
|
|
801
1044
|
return this._next({
|
|
802
1045
|
policy: { settings: result.config.policy.settings }
|
|
803
1046
|
});
|
|
@@ -841,36 +1084,74 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
841
1084
|
{ cast: "replace" }
|
|
842
1085
|
);
|
|
843
1086
|
}
|
|
844
|
-
/**
|
|
1087
|
+
/**
|
|
1088
|
+
* Runs the target and returns its result directly, throwing on final failure.
|
|
1089
|
+
*
|
|
1090
|
+
* `R` defaults to the inferred result type. Passing one (`request<User>()`)
|
|
1091
|
+
* means "ignore the inference, it's this": it's taken as-is, unchecked.
|
|
1092
|
+
* To name the inferred type itself, use `VigorResultOf<typeof builder>`.
|
|
1093
|
+
*/
|
|
845
1094
|
async request() {
|
|
846
1095
|
const res = await this.requestVerbose();
|
|
847
1096
|
if (res.success) return res.data;
|
|
848
1097
|
throw res.error;
|
|
849
1098
|
}
|
|
850
|
-
/**
|
|
1099
|
+
/**
|
|
1100
|
+
* Runs the target and returns a result/error envelope instead of throwing,
|
|
1101
|
+
* along with the `timeline` of everything the run went through.
|
|
1102
|
+
*/
|
|
851
1103
|
async requestVerbose() {
|
|
852
1104
|
return await this.requestRuntime();
|
|
853
1105
|
}
|
|
854
|
-
/**
|
|
855
|
-
|
|
1106
|
+
/**
|
|
1107
|
+
* Internal execution loop implementing the attempt/retry/restart lifecycle.
|
|
1108
|
+
* Never throws: every failure, including one from `onError` or `default`,
|
|
1109
|
+
* comes back as an envelope carrying the timeline. A restart passes the
|
|
1110
|
+
* same `timeline` on, so it keeps growing across runs; `startedAt` is the
|
|
1111
|
+
* first run's start, for `REQUEST_END`'s `took`.
|
|
1112
|
+
*/
|
|
1113
|
+
async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
|
|
856
1114
|
const config = this._merge(this.config, {});
|
|
857
1115
|
let ctx = this._merge(VigorRetryContextBase, {
|
|
858
1116
|
policy: config.policy
|
|
1117
|
+
}, void 0, "replace");
|
|
1118
|
+
ctx.timeline = timeline;
|
|
1119
|
+
const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
|
|
1120
|
+
add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
|
|
1121
|
+
const end = (success, outcome, error) => add("REQUEST_END", {
|
|
1122
|
+
success,
|
|
1123
|
+
outcome,
|
|
1124
|
+
error,
|
|
1125
|
+
took: performance.now() - startedAt,
|
|
1126
|
+
restarts: restartAttempt - 1
|
|
859
1127
|
});
|
|
860
|
-
|
|
1128
|
+
const succeed = (data, outcome) => {
|
|
1129
|
+
end(true, outcome, null);
|
|
1130
|
+
return { success: true, data, error: null, timeline };
|
|
1131
|
+
};
|
|
1132
|
+
const fail = (error) => {
|
|
1133
|
+
end(false, "failed", error);
|
|
1134
|
+
return { success: false, data: null, error, timeline };
|
|
1135
|
+
};
|
|
1136
|
+
const decide = (retry, reason) => add("RETRY_DECISION", { attempt: ctx.system.attempt, retry, reason });
|
|
1137
|
+
if (isVigorEmpty(ctx.policy.target)) return fail(new VigorRetryError("VALUE_REQUIRED", {
|
|
861
1138
|
method: "request",
|
|
862
1139
|
data: {
|
|
863
1140
|
key: "target"
|
|
864
1141
|
},
|
|
865
1142
|
context: ctx
|
|
866
|
-
});
|
|
1143
|
+
}));
|
|
867
1144
|
const target = ctx.policy.target;
|
|
868
1145
|
const throwError = (err) => {
|
|
869
1146
|
throw err;
|
|
870
1147
|
};
|
|
1148
|
+
const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
|
|
871
1149
|
try {
|
|
872
1150
|
while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
|
|
873
1151
|
ctx.system.attempt++;
|
|
1152
|
+
add("ATTEMPT_INCREASED", { attempt: ctx.system.attempt });
|
|
1153
|
+
add("PROCESS_HANDLING", { type: "RETRY_START", data: { attempt: ctx.system.attempt } });
|
|
1154
|
+
ctx.flags.timedOut = false;
|
|
874
1155
|
try {
|
|
875
1156
|
const breakRetry = (err) => {
|
|
876
1157
|
ctx.flags.brokeRetry = true;
|
|
@@ -882,11 +1163,6 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
882
1163
|
userController.signal,
|
|
883
1164
|
timeoutController.signal
|
|
884
1165
|
]);
|
|
885
|
-
const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
|
|
886
|
-
const autoBreak = () => {
|
|
887
|
-
ctx.flags.brokeRetry = true;
|
|
888
|
-
};
|
|
889
|
-
outerSignals.addEventListener("abort", autoBreak);
|
|
890
1166
|
const mergedSignals = AbortSignal.any([
|
|
891
1167
|
innerSignals,
|
|
892
1168
|
outerSignals
|
|
@@ -894,25 +1170,34 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
894
1170
|
let onAbort;
|
|
895
1171
|
let timeoutId;
|
|
896
1172
|
try {
|
|
897
|
-
|
|
1173
|
+
await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
|
|
898
1174
|
if (middleware._mode === "fluent") {
|
|
899
1175
|
await middleware.func(ctx);
|
|
900
1176
|
} else {
|
|
901
|
-
ctx = await middleware.func(ctx, {
|
|
1177
|
+
ctx = await middleware.func(ctx, trace({
|
|
902
1178
|
abort: (reason) => userController.abort(reason),
|
|
903
1179
|
throwError,
|
|
904
1180
|
breakRetry
|
|
905
|
-
});
|
|
1181
|
+
})) ?? ctx;
|
|
906
1182
|
}
|
|
907
|
-
}
|
|
1183
|
+
});
|
|
908
1184
|
mergedSignals.throwIfAborted();
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
1185
|
+
const limit = ctx.policy.settings.timeout;
|
|
1186
|
+
if (Number.isFinite(limit) && limit > 0) {
|
|
1187
|
+
timeoutId = setTimeout(() => {
|
|
1188
|
+
ctx.flags.timedOut = true;
|
|
1189
|
+
timeoutController.abort(new VigorRetryError("TIMED_OUT", {
|
|
1190
|
+
method: "request",
|
|
1191
|
+
data: {
|
|
1192
|
+
limit
|
|
1193
|
+
},
|
|
1194
|
+
context: ctx
|
|
1195
|
+
}));
|
|
1196
|
+
}, Math.min(limit, MAX_TIMEOUT2));
|
|
1197
|
+
}
|
|
1198
|
+
const attempt = ctx.system.attempt;
|
|
1199
|
+
add("TARGET_REQUEST_STARTED", { attempt });
|
|
1200
|
+
const started = performance.now();
|
|
916
1201
|
ctx.result = await Promise.race([
|
|
917
1202
|
target(mergedSignals),
|
|
918
1203
|
new Promise((_, rej) => {
|
|
@@ -920,71 +1205,105 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
920
1205
|
mergedSignals.addEventListener("abort", onAbort);
|
|
921
1206
|
})
|
|
922
1207
|
]);
|
|
923
|
-
|
|
1208
|
+
add("TARGET_REQUEST_ENDED", { attempt, took: performance.now() - started });
|
|
1209
|
+
await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
|
|
924
1210
|
if (middleware._mode === "fluent") {
|
|
925
1211
|
await middleware.func(ctx);
|
|
926
1212
|
} else {
|
|
927
|
-
ctx = await middleware.func(ctx, {
|
|
1213
|
+
ctx = await middleware.func(ctx, trace({
|
|
928
1214
|
throwError
|
|
929
|
-
});
|
|
1215
|
+
})) ?? ctx;
|
|
930
1216
|
}
|
|
931
|
-
}
|
|
1217
|
+
});
|
|
932
1218
|
const setResult = (res) => {
|
|
933
1219
|
ctx.result = res;
|
|
934
1220
|
};
|
|
935
|
-
|
|
1221
|
+
await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
|
|
936
1222
|
if (middleware._mode === "fluent") {
|
|
937
1223
|
ctx.result = await middleware.func(ctx.result);
|
|
938
1224
|
} else {
|
|
939
|
-
ctx = await middleware.func(ctx, {
|
|
1225
|
+
ctx = await middleware.func(ctx, trace({
|
|
940
1226
|
setResult,
|
|
941
1227
|
throwError
|
|
942
|
-
});
|
|
1228
|
+
})) ?? ctx;
|
|
943
1229
|
}
|
|
944
|
-
}
|
|
945
|
-
return
|
|
946
|
-
success: true,
|
|
947
|
-
data: ctx.result,
|
|
948
|
-
error: null
|
|
949
|
-
};
|
|
1230
|
+
});
|
|
1231
|
+
return succeed(ctx.result, "result");
|
|
950
1232
|
} finally {
|
|
951
1233
|
clearTimeout(timeoutId);
|
|
952
|
-
outerSignals.removeEventListener("abort", autoBreak);
|
|
953
1234
|
if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
|
|
954
1235
|
}
|
|
955
1236
|
} catch (error) {
|
|
956
1237
|
ctx.error = error;
|
|
957
|
-
if (ctx.flags.
|
|
1238
|
+
if (outerSignals.aborted) ctx.flags.aborted = true;
|
|
1239
|
+
add("PROCESS_HANDLING", { type: "RETRY_ERROR", data: {
|
|
1240
|
+
attempt: ctx.system.attempt,
|
|
1241
|
+
error,
|
|
1242
|
+
timedOut: ctx.flags.timedOut,
|
|
1243
|
+
aborted: ctx.flags.aborted
|
|
1244
|
+
} });
|
|
1245
|
+
if (ctx.flags.aborted) {
|
|
1246
|
+
decide(false, "aborted");
|
|
1247
|
+
throw ctx.error;
|
|
1248
|
+
}
|
|
1249
|
+
if (ctx.flags.brokeRetry) {
|
|
1250
|
+
decide(false, "breakRetry");
|
|
1251
|
+
throw ctx.error;
|
|
1252
|
+
}
|
|
958
1253
|
ctx.flags.doRetry = true;
|
|
959
1254
|
const proceedRetry = () => ctx.flags.doRetry = true;
|
|
960
1255
|
const cancelRetry = () => ctx.flags.doRetry = false;
|
|
961
|
-
|
|
1256
|
+
await stage("retryIf", ctx.policy.middlewares.retryIf, async (middleware, trace) => {
|
|
962
1257
|
if (middleware._mode === "fluent") {
|
|
963
1258
|
ctx.flags.doRetry = await middleware.func(ctx.error);
|
|
964
1259
|
} else {
|
|
965
|
-
ctx = await middleware.func(ctx, {
|
|
1260
|
+
ctx = await middleware.func(ctx, trace({
|
|
966
1261
|
proceedRetry,
|
|
967
1262
|
cancelRetry
|
|
968
|
-
});
|
|
1263
|
+
})) ?? ctx;
|
|
969
1264
|
}
|
|
1265
|
+
});
|
|
1266
|
+
if (!ctx.flags.doRetry) {
|
|
1267
|
+
decide(false, "cancelled");
|
|
1268
|
+
throw ctx.error;
|
|
970
1269
|
}
|
|
971
|
-
if (
|
|
1270
|
+
if (ctx.system.attempt >= ctx.policy.settings.maxAttempts) {
|
|
1271
|
+
decide(false, "exhausted");
|
|
1272
|
+
break;
|
|
1273
|
+
}
|
|
1274
|
+
decide(true, "retry");
|
|
972
1275
|
ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
|
|
973
1276
|
const setDelay = (num) => {
|
|
974
1277
|
ctx.system.delay = num;
|
|
975
1278
|
};
|
|
976
|
-
|
|
1279
|
+
await stage("onRetry", ctx.policy.middlewares.onRetry, async (middleware, trace) => {
|
|
977
1280
|
if (middleware._mode === "fluent") {
|
|
978
1281
|
await middleware.func(ctx.error);
|
|
979
1282
|
} else {
|
|
980
|
-
ctx = await middleware.func(ctx, {
|
|
1283
|
+
ctx = await middleware.func(ctx, trace({
|
|
981
1284
|
throwError,
|
|
982
1285
|
setDelay
|
|
983
|
-
});
|
|
1286
|
+
})) ?? ctx;
|
|
984
1287
|
}
|
|
985
|
-
}
|
|
986
|
-
const delay = ctx.system.delay;
|
|
987
|
-
|
|
1288
|
+
});
|
|
1289
|
+
const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT2);
|
|
1290
|
+
add("RETRY_DELAY", { attempt: ctx.system.attempt, delay });
|
|
1291
|
+
await new Promise((res, rej) => {
|
|
1292
|
+
if (outerSignals.aborted) {
|
|
1293
|
+
ctx.flags.aborted = true;
|
|
1294
|
+
return rej(outerSignals.reason);
|
|
1295
|
+
}
|
|
1296
|
+
const onAbort = () => {
|
|
1297
|
+
clearTimeout(id);
|
|
1298
|
+
ctx.flags.aborted = true;
|
|
1299
|
+
rej(outerSignals.reason);
|
|
1300
|
+
};
|
|
1301
|
+
const id = setTimeout(() => {
|
|
1302
|
+
outerSignals.removeEventListener("abort", onAbort);
|
|
1303
|
+
res();
|
|
1304
|
+
}, delay);
|
|
1305
|
+
outerSignals.addEventListener("abort", onAbort, { once: true });
|
|
1306
|
+
});
|
|
988
1307
|
}
|
|
989
1308
|
}
|
|
990
1309
|
throw new VigorRetryError("RETRY_EXHAUSTED", {
|
|
@@ -998,6 +1317,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
998
1317
|
});
|
|
999
1318
|
} catch (error) {
|
|
1000
1319
|
ctx.error = error;
|
|
1320
|
+
add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
|
|
1001
1321
|
ctx.flags.doRestart = false;
|
|
1002
1322
|
ctx.flags.overridden = false;
|
|
1003
1323
|
const setResult = (res) => {
|
|
@@ -1006,47 +1326,44 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
1006
1326
|
};
|
|
1007
1327
|
const proceedRestart = () => ctx.flags.doRestart = true;
|
|
1008
1328
|
const cancelRestart = () => ctx.flags.doRestart = false;
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1329
|
+
try {
|
|
1330
|
+
await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
|
|
1331
|
+
if (middleware._mode === "fluent") {
|
|
1332
|
+
await middleware.func(ctx.error);
|
|
1333
|
+
} else {
|
|
1334
|
+
ctx = await middleware.func(ctx, trace({
|
|
1335
|
+
setResult,
|
|
1336
|
+
throwError,
|
|
1337
|
+
proceedRestart,
|
|
1338
|
+
cancelRestart
|
|
1339
|
+
})) ?? ctx;
|
|
1340
|
+
}
|
|
1341
|
+
});
|
|
1342
|
+
} catch (err) {
|
|
1343
|
+
return fail(err);
|
|
1020
1344
|
}
|
|
1021
1345
|
if (ctx.flags.doRestart) {
|
|
1022
|
-
if (restartAttempt
|
|
1346
|
+
if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorRetryError("RESTART_EXHAUSTED", {
|
|
1023
1347
|
method: "request",
|
|
1024
1348
|
cause: ctx.error,
|
|
1025
1349
|
data: {
|
|
1026
1350
|
maxAttempts: ctx.policy.settings.maxRestarts,
|
|
1027
1351
|
error: ctx.error
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
|
|
1352
|
+
},
|
|
1353
|
+
context: ctx
|
|
1354
|
+
}));
|
|
1355
|
+
add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
|
|
1356
|
+
return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
|
|
1031
1357
|
}
|
|
1032
|
-
if (ctx.flags.overridden) return
|
|
1033
|
-
success: true,
|
|
1034
|
-
data: ctx.result,
|
|
1035
|
-
error: null
|
|
1036
|
-
};
|
|
1358
|
+
if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
|
|
1037
1359
|
if (!isVigorEmpty(ctx.policy.settings.default)) {
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
};
|
|
1360
|
+
try {
|
|
1361
|
+
return succeed(await ctx.policy.settings.default(ctx), "default");
|
|
1362
|
+
} catch (err) {
|
|
1363
|
+
return fail(err);
|
|
1364
|
+
}
|
|
1044
1365
|
}
|
|
1045
|
-
return
|
|
1046
|
-
success: false,
|
|
1047
|
-
data: null,
|
|
1048
|
-
error: ctx.error
|
|
1049
|
-
};
|
|
1366
|
+
return fail(ctx.error);
|
|
1050
1367
|
}
|
|
1051
1368
|
}
|
|
1052
1369
|
};
|
|
@@ -1054,6 +1371,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
|
|
|
1054
1371
|
// src/parse/settings.ts
|
|
1055
1372
|
var VigorParsePolicySettingsBase = {
|
|
1056
1373
|
__brand: createBrand("Parse", "Policy<Settings<Schema"),
|
|
1374
|
+
debug: false,
|
|
1057
1375
|
raw: false,
|
|
1058
1376
|
default: VigorEmpty,
|
|
1059
1377
|
maxRestarts: 3
|
|
@@ -1083,6 +1401,14 @@ var VigorParsePolicySettings = class _VigorParsePolicySettings extends VigorStat
|
|
|
1083
1401
|
policy: { settings: { maxRestarts: num } }
|
|
1084
1402
|
});
|
|
1085
1403
|
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Turns timeline recording on or off (off by default). Off, the
|
|
1406
|
+
* `timeline` of `requestVerbose()` stays empty and no context snapshots
|
|
1407
|
+
* are taken, so it costs nothing unless you're debugging.
|
|
1408
|
+
*/
|
|
1409
|
+
debug(bool) {
|
|
1410
|
+
return this._next({ policy: { settings: { debug: bool } } });
|
|
1411
|
+
}
|
|
1086
1412
|
};
|
|
1087
1413
|
|
|
1088
1414
|
// src/parse/middlewares.ts
|
|
@@ -1115,11 +1441,12 @@ var VigorParsePolicyMiddlewares = class _VigorParsePolicyMiddlewares extends Vig
|
|
|
1115
1441
|
};
|
|
1116
1442
|
|
|
1117
1443
|
// src/parse/error.ts
|
|
1444
|
+
var describeVigorParseFailure = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
1118
1445
|
var VigorParseErrorMessageFuncs = {
|
|
1119
1446
|
VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
|
|
1120
1447
|
INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
|
|
1121
1448
|
PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
|
|
1122
|
-
PARSER_ALL_FAILED: ({ tried }) => `All parsers failed
|
|
1449
|
+
PARSER_ALL_FAILED: ({ tried, errors }) => `All parsers failed: ${tried.map((name, i) => `${name} (${describeVigorParseFailure(errors[i])})`).join(", ")}`,
|
|
1123
1450
|
RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
|
|
1124
1451
|
};
|
|
1125
1452
|
var VigorParseError = class extends VigorError {
|
|
@@ -1132,56 +1459,141 @@ var VigorParseError = class extends VigorError {
|
|
|
1132
1459
|
super(code, messageFn(options.data), options);
|
|
1133
1460
|
}
|
|
1134
1461
|
};
|
|
1462
|
+
function isVigorParseError(error, ...codes) {
|
|
1463
|
+
return error instanceof VigorParseError && (codes.length === 0 || codes.includes(error.code));
|
|
1464
|
+
}
|
|
1135
1465
|
|
|
1136
1466
|
// src/parse/strategies.ts
|
|
1137
1467
|
var VigorParsePolicyStrategiesBase = {
|
|
1138
1468
|
__brand: createBrand("Parse", "Policy<Strategies<Schema"),
|
|
1139
1469
|
funcs: []
|
|
1140
1470
|
};
|
|
1471
|
+
var bodyCache = /* @__PURE__ */ new WeakMap();
|
|
1472
|
+
async function readVigorParseBody(source) {
|
|
1473
|
+
let bytes = bodyCache.get(source);
|
|
1474
|
+
if (!bytes) {
|
|
1475
|
+
bytes = source.body === null ? Promise.resolve(new Uint8Array(0)) : source.arrayBuffer().then((buf) => new Uint8Array(buf));
|
|
1476
|
+
bodyCache.set(source, bytes);
|
|
1477
|
+
}
|
|
1478
|
+
return {
|
|
1479
|
+
bytes: await bytes,
|
|
1480
|
+
contentType: source.headers.get("content-type"),
|
|
1481
|
+
status: source instanceof Response ? source.status : null,
|
|
1482
|
+
headers: source.headers,
|
|
1483
|
+
source
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
var utf8 = new TextDecoder("utf-8");
|
|
1487
|
+
var getCharset = (contentType) => /;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(contentType ?? "")?.[1] ?? "utf-8";
|
|
1488
|
+
var getMimeType = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
1489
|
+
var decodeText = (body, fatal = false) => {
|
|
1490
|
+
let decoder;
|
|
1491
|
+
try {
|
|
1492
|
+
decoder = new TextDecoder(getCharset(body.contentType), { fatal });
|
|
1493
|
+
} catch {
|
|
1494
|
+
decoder = new TextDecoder("utf-8", { fatal });
|
|
1495
|
+
}
|
|
1496
|
+
return decoder.decode(body.bytes);
|
|
1497
|
+
};
|
|
1498
|
+
var parseJson = (body) => JSON.parse(utf8.decode(body.bytes));
|
|
1499
|
+
var parseJsonOrNull = (body) => {
|
|
1500
|
+
const text = utf8.decode(body.bytes);
|
|
1501
|
+
return text.trim() === "" ? null : JSON.parse(text);
|
|
1502
|
+
};
|
|
1503
|
+
var hexValue = (b) => {
|
|
1504
|
+
if (b >= 48 && b <= 57) return b - 48;
|
|
1505
|
+
if (b >= 65 && b <= 70) return b - 65 + 10;
|
|
1506
|
+
if (b >= 97 && b <= 102) return b - 97 + 10;
|
|
1507
|
+
return -1;
|
|
1508
|
+
};
|
|
1509
|
+
var decodeFormComponent = (input) => {
|
|
1510
|
+
const out = new Uint8Array(input.length);
|
|
1511
|
+
let n = 0;
|
|
1512
|
+
for (let i = 0; i < input.length; i++) {
|
|
1513
|
+
const b = input[i];
|
|
1514
|
+
if (b === 43) {
|
|
1515
|
+
out[n++] = 32;
|
|
1516
|
+
continue;
|
|
1517
|
+
}
|
|
1518
|
+
if (b === 37 && i + 2 < input.length) {
|
|
1519
|
+
const hi = hexValue(input[i + 1]);
|
|
1520
|
+
const lo = hexValue(input[i + 2]);
|
|
1521
|
+
if (hi >= 0 && lo >= 0) {
|
|
1522
|
+
out[n++] = hi * 16 + lo;
|
|
1523
|
+
i += 2;
|
|
1524
|
+
continue;
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
out[n++] = b;
|
|
1528
|
+
}
|
|
1529
|
+
return utf8.decode(out.subarray(0, n));
|
|
1530
|
+
};
|
|
1531
|
+
var parseUrlEncoded = (body) => {
|
|
1532
|
+
const form = new FormData();
|
|
1533
|
+
const { bytes } = body;
|
|
1534
|
+
let start = 0;
|
|
1535
|
+
for (let i = 0; i <= bytes.length; i++) {
|
|
1536
|
+
if (i < bytes.length && bytes[i] !== 38) continue;
|
|
1537
|
+
const pair = bytes.subarray(start, i);
|
|
1538
|
+
start = i + 1;
|
|
1539
|
+
if (pair.length === 0) continue;
|
|
1540
|
+
const eq = pair.indexOf(61);
|
|
1541
|
+
const name = eq === -1 ? pair : pair.subarray(0, eq);
|
|
1542
|
+
const value = eq === -1 ? new Uint8Array(0) : pair.subarray(eq + 1);
|
|
1543
|
+
form.append(decodeFormComponent(name), decodeFormComponent(value));
|
|
1544
|
+
}
|
|
1545
|
+
return form;
|
|
1546
|
+
};
|
|
1547
|
+
var parseMultipart = (body) => new Response(body.bytes, { headers: { "content-type": body.contentType ?? "" } }).formData();
|
|
1548
|
+
var parseFormData = (body) => {
|
|
1549
|
+
const mime = getMimeType(body.contentType);
|
|
1550
|
+
if (mime === "application/x-www-form-urlencoded") return parseUrlEncoded(body);
|
|
1551
|
+
if (mime === "multipart/form-data") return parseMultipart(body);
|
|
1552
|
+
throw new VigorParseError("INVALID_CONTENT_TYPE", {
|
|
1553
|
+
method: "parseFormData",
|
|
1554
|
+
data: { received: body.contentType }
|
|
1555
|
+
});
|
|
1556
|
+
};
|
|
1557
|
+
var toArrayBuffer = (body) => body.bytes.slice().buffer;
|
|
1558
|
+
var toBlob = (body) => new Blob([body.bytes], { type: body.contentType ?? "" });
|
|
1559
|
+
var NoBodyStatus = [204, 205, 304];
|
|
1141
1560
|
var ContentTypeParsers = [
|
|
1142
|
-
{ header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method:
|
|
1143
|
-
{ header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (
|
|
1144
|
-
{ header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method:
|
|
1145
|
-
{ header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method:
|
|
1146
|
-
{ header: "image/*", regExp: /^image\/.+/i, method:
|
|
1147
|
-
{ header: "audio/*", regExp: /^audio\/.+/i, method:
|
|
1148
|
-
{ header: "video/*", regExp: /^video\/.+/i, method:
|
|
1149
|
-
{ header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method:
|
|
1150
|
-
{ header: "text/*", regExp: /^text\/.+/i, method: (
|
|
1561
|
+
{ header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: parseJsonOrNull },
|
|
1562
|
+
{ header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (body) => decodeText(body) },
|
|
1563
|
+
{ header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: parseUrlEncoded },
|
|
1564
|
+
{ header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: toArrayBuffer },
|
|
1565
|
+
{ header: "image/*", regExp: /^image\/.+/i, method: toBlob },
|
|
1566
|
+
{ header: "audio/*", regExp: /^audio\/.+/i, method: toBlob },
|
|
1567
|
+
{ header: "video/*", regExp: /^video\/.+/i, method: toBlob },
|
|
1568
|
+
{ header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: parseMultipart },
|
|
1569
|
+
{ header: "text/*", regExp: /^text\/.+/i, method: (body) => decodeText(body) }
|
|
1151
1570
|
];
|
|
1152
1571
|
var SniffMethods = [
|
|
1153
|
-
{ title: "json", method:
|
|
1154
|
-
{ title: "formData", method:
|
|
1155
|
-
{ title: "text", method: (
|
|
1156
|
-
{ title: "blob", method:
|
|
1572
|
+
{ title: "json", method: parseJson },
|
|
1573
|
+
{ title: "formData", method: parseFormData },
|
|
1574
|
+
{ title: "text", method: (body) => decodeText(body, true) },
|
|
1575
|
+
{ title: "blob", method: toBlob }
|
|
1157
1576
|
];
|
|
1158
|
-
var VigorParseContentTypeStrategy = async (
|
|
1159
|
-
|
|
1160
|
-
if (!
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(contentTypeHeader));
|
|
1165
|
-
if (!toDo) throw new VigorParseError("PARSER_NOT_FOUND", {
|
|
1166
|
-
method: "VigorParseContentTypeStrategy",
|
|
1167
|
-
data: {
|
|
1168
|
-
expected: ContentTypeParsers.map((p) => p.header),
|
|
1169
|
-
received: contentTypeHeader
|
|
1170
|
-
}
|
|
1171
|
-
});
|
|
1172
|
-
return await toDo.method(response);
|
|
1577
|
+
var VigorParseContentTypeStrategy = async (body) => {
|
|
1578
|
+
if (body.bytes.length === 0 || body.status !== null && NoBodyStatus.includes(body.status)) return null;
|
|
1579
|
+
if (!body.contentType) return decodeText(body);
|
|
1580
|
+
const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(body.contentType));
|
|
1581
|
+
if (!toDo) return toBlob(body);
|
|
1582
|
+
return await toDo.method(body);
|
|
1173
1583
|
};
|
|
1174
|
-
var VigorParseSniffStrategy = async (
|
|
1175
|
-
|
|
1176
|
-
|
|
1584
|
+
var VigorParseSniffStrategy = async (body) => {
|
|
1585
|
+
const errors = [];
|
|
1586
|
+
for (const parser of SniffMethods) {
|
|
1177
1587
|
try {
|
|
1178
|
-
return await parser.method(
|
|
1179
|
-
} catch {
|
|
1588
|
+
return await parser.method(body);
|
|
1589
|
+
} catch (error) {
|
|
1590
|
+
errors.push(error);
|
|
1180
1591
|
}
|
|
1181
1592
|
}
|
|
1182
1593
|
throw new VigorParseError("PARSER_ALL_FAILED", {
|
|
1183
1594
|
method: "VigorParseSniffStrategy",
|
|
1184
|
-
|
|
1595
|
+
cause: errors.at(-1),
|
|
1596
|
+
data: { tried: SniffMethods.map((p) => p.title), errors }
|
|
1185
1597
|
});
|
|
1186
1598
|
};
|
|
1187
1599
|
var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends VigorStatus {
|
|
@@ -1208,35 +1620,35 @@ var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends Vigor
|
|
|
1208
1620
|
contentType(replace) {
|
|
1209
1621
|
return this._set([VigorParseContentTypeStrategy], replace);
|
|
1210
1622
|
}
|
|
1211
|
-
/** Adds the sniffing (try-each-
|
|
1623
|
+
/** Adds the sniffing (try-each-format) parsing strategy. */
|
|
1212
1624
|
sniff(replace) {
|
|
1213
1625
|
return this._set([VigorParseSniffStrategy], replace);
|
|
1214
1626
|
}
|
|
1215
|
-
/** Adds a strategy that always parses the
|
|
1627
|
+
/** Adds a strategy that always parses the body as JSON. */
|
|
1216
1628
|
json(replace) {
|
|
1217
|
-
return this._set([
|
|
1629
|
+
return this._set([parseJson], replace);
|
|
1218
1630
|
}
|
|
1219
|
-
/** Adds a strategy that always parses the
|
|
1631
|
+
/** Adds a strategy that always parses the body as text, in its declared `charset`. */
|
|
1220
1632
|
text(replace) {
|
|
1221
|
-
return this._set([(
|
|
1633
|
+
return this._set([(body) => decodeText(body)], replace);
|
|
1222
1634
|
}
|
|
1223
|
-
/** Adds a strategy that always parses the
|
|
1635
|
+
/** Adds a strategy that always parses the body as an `ArrayBuffer`. */
|
|
1224
1636
|
arrayBuffer(replace) {
|
|
1225
|
-
return this._set([
|
|
1637
|
+
return this._set([toArrayBuffer], replace);
|
|
1226
1638
|
}
|
|
1227
|
-
/** Adds a strategy that always parses the
|
|
1639
|
+
/** Adds a strategy that always parses the body as a `Blob`. */
|
|
1228
1640
|
blob(replace) {
|
|
1229
|
-
return this._set([
|
|
1641
|
+
return this._set([toBlob], replace);
|
|
1230
1642
|
}
|
|
1231
|
-
/** Adds a strategy that always parses the
|
|
1643
|
+
/** Adds a strategy that always parses the body as a `Uint8Array`. */
|
|
1232
1644
|
bytes(replace) {
|
|
1233
|
-
return this._set([(
|
|
1645
|
+
return this._set([(body) => body.bytes.slice()], replace);
|
|
1234
1646
|
}
|
|
1235
|
-
/** Adds a strategy that always parses the
|
|
1647
|
+
/** Adds a strategy that always parses the body as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`). */
|
|
1236
1648
|
formData(replace) {
|
|
1237
|
-
return this._set([
|
|
1649
|
+
return this._set([parseFormData], replace);
|
|
1238
1650
|
}
|
|
1239
|
-
/** Adds a user-supplied custom parsing strategy. */
|
|
1651
|
+
/** Adds a user-supplied custom parsing strategy. It receives the body already read into bytes. */
|
|
1240
1652
|
custom(func, replace) {
|
|
1241
1653
|
return this._set([func], replace);
|
|
1242
1654
|
}
|
|
@@ -1258,10 +1670,11 @@ var VigorParseContextBase = {
|
|
|
1258
1670
|
error: VigorDefault,
|
|
1259
1671
|
response: VigorDefault,
|
|
1260
1672
|
flags: {
|
|
1261
|
-
|
|
1673
|
+
overridden: false,
|
|
1262
1674
|
restarted: false
|
|
1263
1675
|
},
|
|
1264
1676
|
record: {},
|
|
1677
|
+
timeline: [],
|
|
1265
1678
|
policy: VigorParsePolicyBase
|
|
1266
1679
|
};
|
|
1267
1680
|
|
|
@@ -1284,7 +1697,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
|
|
|
1284
1697
|
}
|
|
1285
1698
|
settings(input) {
|
|
1286
1699
|
if (typeof input === "function" || input instanceof VigorParsePolicySettings) {
|
|
1287
|
-
const result = typeof input === "function" ? input(new VigorParsePolicySettings()) : input;
|
|
1700
|
+
const result = typeof input === "function" ? input(new VigorParsePolicySettings(this.config)) : input;
|
|
1288
1701
|
return this._next({
|
|
1289
1702
|
policy: { settings: result.config.policy.settings }
|
|
1290
1703
|
});
|
|
@@ -1321,101 +1734,142 @@ var VigorParse = class _VigorParse extends VigorStatus {
|
|
|
1321
1734
|
{ cast: "replace" }
|
|
1322
1735
|
);
|
|
1323
1736
|
}
|
|
1324
|
-
/**
|
|
1737
|
+
/**
|
|
1738
|
+
* Runs parsing and returns the result directly, throwing on final failure.
|
|
1739
|
+
*
|
|
1740
|
+
* `R` defaults to the inferred result type. Passing one (`request<User>()`)
|
|
1741
|
+
* means "ignore the inference, it's this": it's taken as-is, unchecked.
|
|
1742
|
+
* To name the inferred type itself, use `VigorResultOf<typeof builder>`.
|
|
1743
|
+
*/
|
|
1325
1744
|
async request() {
|
|
1326
1745
|
const res = await this.requestVerbose();
|
|
1327
1746
|
if (res.success) return res.data;
|
|
1328
1747
|
throw res.error;
|
|
1329
1748
|
}
|
|
1330
|
-
/**
|
|
1749
|
+
/**
|
|
1750
|
+
* Runs parsing and returns a result/error envelope instead of throwing,
|
|
1751
|
+
* along with the `timeline` of everything the run went through.
|
|
1752
|
+
*/
|
|
1331
1753
|
async requestVerbose() {
|
|
1332
1754
|
return await this.requestRuntime();
|
|
1333
1755
|
}
|
|
1334
|
-
/**
|
|
1335
|
-
|
|
1756
|
+
/**
|
|
1757
|
+
* Internal execution loop implementing the strategy fallback and restart
|
|
1758
|
+
* handling. Never throws: every failure, including one from `onError` or
|
|
1759
|
+
* `default`, comes back as an envelope carrying the timeline. A restart
|
|
1760
|
+
* passes the same `timeline` on, so it keeps growing across runs.
|
|
1761
|
+
*/
|
|
1762
|
+
async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
|
|
1336
1763
|
const config = this._merge(this.config, {});
|
|
1337
1764
|
let ctx = this._merge(VigorParseContextBase, {
|
|
1338
1765
|
policy: config.policy
|
|
1766
|
+
}, void 0, "replace");
|
|
1767
|
+
ctx.timeline = timeline;
|
|
1768
|
+
const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
|
|
1769
|
+
add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
|
|
1770
|
+
const end = (success, outcome, error) => add("REQUEST_END", {
|
|
1771
|
+
success,
|
|
1772
|
+
outcome,
|
|
1773
|
+
error,
|
|
1774
|
+
took: performance.now() - startedAt,
|
|
1775
|
+
restarts: restartAttempt - 1
|
|
1339
1776
|
});
|
|
1340
|
-
|
|
1777
|
+
const succeed = (data, outcome) => {
|
|
1778
|
+
end(true, outcome, null);
|
|
1779
|
+
return { success: true, data, error: null, timeline };
|
|
1780
|
+
};
|
|
1781
|
+
const fail = (error) => {
|
|
1782
|
+
end(false, "failed", error);
|
|
1783
|
+
return { success: false, data: null, error, timeline };
|
|
1784
|
+
};
|
|
1785
|
+
if (isVigorDefault(ctx.policy.target)) return fail(new VigorParseError("VALUE_REQUIRED", {
|
|
1341
1786
|
method: "request",
|
|
1342
1787
|
data: { key: "target" },
|
|
1343
1788
|
context: ctx
|
|
1344
|
-
});
|
|
1789
|
+
}));
|
|
1345
1790
|
ctx.response = ctx.policy.target;
|
|
1346
1791
|
const throwError = (err) => {
|
|
1347
1792
|
throw err;
|
|
1348
1793
|
};
|
|
1349
1794
|
try {
|
|
1350
|
-
|
|
1795
|
+
await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
|
|
1351
1796
|
if (middleware._mode === "fluent") {
|
|
1352
1797
|
await middleware.func(ctx);
|
|
1353
1798
|
} else {
|
|
1354
|
-
ctx = await middleware.func(ctx, { throwError });
|
|
1799
|
+
ctx = await middleware.func(ctx, trace({ throwError })) ?? ctx;
|
|
1355
1800
|
}
|
|
1356
|
-
}
|
|
1801
|
+
});
|
|
1357
1802
|
if (ctx.policy.settings.raw) {
|
|
1358
1803
|
ctx.result = ctx.response;
|
|
1359
1804
|
} else {
|
|
1360
|
-
const
|
|
1805
|
+
const readStarted = performance.now();
|
|
1806
|
+
const body = await readVigorParseBody(ctx.response);
|
|
1807
|
+
add("BODY_READ", { size: body.bytes.byteLength, took: performance.now() - readStarted });
|
|
1361
1808
|
const funcs = ctx.policy.strategies.funcs.length > 0 ? ctx.policy.strategies.funcs : [VigorParseContentTypeStrategy];
|
|
1362
1809
|
let parsed = false;
|
|
1363
|
-
|
|
1364
|
-
|
|
1810
|
+
const errors = [];
|
|
1811
|
+
for (const [index, func] of funcs.entries()) {
|
|
1812
|
+
add("STRATEGY_STARTED", { index });
|
|
1813
|
+
const started = performance.now();
|
|
1365
1814
|
try {
|
|
1366
|
-
ctx.result = await func(
|
|
1815
|
+
ctx.result = await func(body);
|
|
1816
|
+
add("STRATEGY_SUCCEEDED", { index, took: performance.now() - started });
|
|
1367
1817
|
parsed = true;
|
|
1368
1818
|
break;
|
|
1369
|
-
} catch {
|
|
1819
|
+
} catch (error) {
|
|
1820
|
+
errors.push(error);
|
|
1821
|
+
add("STRATEGY_FAILED", { index, error, took: performance.now() - started });
|
|
1370
1822
|
}
|
|
1371
1823
|
}
|
|
1372
1824
|
if (!parsed) throw new VigorParseError("PARSER_ALL_FAILED", {
|
|
1373
1825
|
method: "request",
|
|
1374
|
-
|
|
1826
|
+
cause: errors.at(-1),
|
|
1827
|
+
data: { tried: funcs.map((_, i) => `strategy#${i}`), errors },
|
|
1375
1828
|
context: ctx
|
|
1376
1829
|
});
|
|
1377
1830
|
}
|
|
1378
1831
|
const setResult = (res) => {
|
|
1379
1832
|
ctx.result = res;
|
|
1380
1833
|
};
|
|
1381
|
-
|
|
1834
|
+
await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
|
|
1382
1835
|
if (middleware._mode === "fluent") {
|
|
1383
1836
|
await middleware.func(ctx);
|
|
1384
1837
|
} else {
|
|
1385
|
-
ctx = await middleware.func(ctx, { setResult, throwError });
|
|
1838
|
+
ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
|
|
1386
1839
|
}
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1840
|
+
});
|
|
1841
|
+
await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
|
|
1389
1842
|
if (middleware._mode === "fluent") {
|
|
1390
1843
|
ctx.result = await middleware.func(ctx.result);
|
|
1391
1844
|
} else {
|
|
1392
|
-
ctx = await middleware.func(ctx, { setResult, throwError });
|
|
1845
|
+
ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
|
|
1393
1846
|
}
|
|
1394
|
-
}
|
|
1395
|
-
return
|
|
1396
|
-
success: true,
|
|
1397
|
-
data: ctx.result,
|
|
1398
|
-
error: null
|
|
1399
|
-
};
|
|
1847
|
+
});
|
|
1848
|
+
return succeed(ctx.result, "result");
|
|
1400
1849
|
} catch (error) {
|
|
1401
1850
|
ctx.error = error;
|
|
1402
|
-
|
|
1851
|
+
add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
|
|
1852
|
+
ctx.flags.overridden = false;
|
|
1403
1853
|
ctx.flags.restarted = false;
|
|
1404
1854
|
const setResult = (res) => {
|
|
1405
|
-
ctx.flags.
|
|
1855
|
+
ctx.flags.overridden = true;
|
|
1406
1856
|
ctx.result = res;
|
|
1407
1857
|
};
|
|
1408
1858
|
const proceedRestart = () => ctx.flags.restarted = true;
|
|
1409
1859
|
const cancelRestart = () => ctx.flags.restarted = false;
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1860
|
+
try {
|
|
1861
|
+
await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
|
|
1862
|
+
if (middleware._mode === "fluent") {
|
|
1863
|
+
await middleware.func(ctx.error);
|
|
1864
|
+
} else {
|
|
1865
|
+
ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
|
|
1866
|
+
}
|
|
1867
|
+
});
|
|
1868
|
+
} catch (err) {
|
|
1869
|
+
return fail(err);
|
|
1416
1870
|
}
|
|
1417
1871
|
if (ctx.flags.restarted) {
|
|
1418
|
-
if (restartAttempt
|
|
1872
|
+
if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorParseError("RESTART_EXHAUSTED", {
|
|
1419
1873
|
method: "request",
|
|
1420
1874
|
cause: ctx.error,
|
|
1421
1875
|
data: {
|
|
@@ -1423,27 +1877,19 @@ var VigorParse = class _VigorParse extends VigorStatus {
|
|
|
1423
1877
|
error: ctx.error
|
|
1424
1878
|
},
|
|
1425
1879
|
context: ctx
|
|
1426
|
-
});
|
|
1427
|
-
|
|
1880
|
+
}));
|
|
1881
|
+
add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
|
|
1882
|
+
return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
|
|
1428
1883
|
}
|
|
1429
|
-
if (ctx.flags.
|
|
1430
|
-
success: true,
|
|
1431
|
-
data: ctx.result,
|
|
1432
|
-
error: null
|
|
1433
|
-
};
|
|
1884
|
+
if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
|
|
1434
1885
|
if (!isVigorEmpty(ctx.policy.settings.default)) {
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
};
|
|
1886
|
+
try {
|
|
1887
|
+
return succeed(await ctx.policy.settings.default(ctx), "default");
|
|
1888
|
+
} catch (err) {
|
|
1889
|
+
return fail(err);
|
|
1890
|
+
}
|
|
1441
1891
|
}
|
|
1442
|
-
return
|
|
1443
|
-
success: false,
|
|
1444
|
-
data: null,
|
|
1445
|
-
error: ctx.error
|
|
1446
|
-
};
|
|
1892
|
+
return fail(ctx.error);
|
|
1447
1893
|
}
|
|
1448
1894
|
}
|
|
1449
1895
|
};
|
|
@@ -1478,16 +1924,22 @@ var VigorFetchContextBase = {
|
|
|
1478
1924
|
restarted: false
|
|
1479
1925
|
},
|
|
1480
1926
|
record: {},
|
|
1927
|
+
timeline: [],
|
|
1481
1928
|
policy: VigorFetchPolicyBase
|
|
1482
1929
|
};
|
|
1483
1930
|
|
|
1484
1931
|
// src/fetch/error.ts
|
|
1485
1932
|
var VigorFetchErrorMessageFuncs = {
|
|
1933
|
+
...VigorRetryErrorMessageFuncs,
|
|
1934
|
+
...VigorParseErrorMessageFuncs,
|
|
1486
1935
|
VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
|
|
1487
1936
|
INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
|
|
1937
|
+
BODY_NOT_ALLOWED: ({ method }) => `A ${method} request cannot have a body`,
|
|
1488
1938
|
INVALID_PROTOCOL: ({ origin, base }) => base ? `Invalid URL: could not resolve "${origin}" against base "${base}"` : `Invalid URL: "${origin}" is not an absolute URL, and no base (window.location) is available to resolve it against \u2014 pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,
|
|
1489
1939
|
FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
|
|
1490
|
-
RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})
|
|
1940
|
+
RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
|
|
1941
|
+
PATH_ESCAPED: ({ url, base }) => `Path escapes "${base}": the request would go to "${url}" (settings.confinePath)`,
|
|
1942
|
+
REDIRECTED: ({ url, status }) => `Redirected (${status}) to "${url}" \u2014 navigating away`
|
|
1491
1943
|
};
|
|
1492
1944
|
var VigorFetchError = class extends VigorError {
|
|
1493
1945
|
/**
|
|
@@ -1499,12 +1951,27 @@ var VigorFetchError = class extends VigorError {
|
|
|
1499
1951
|
super(code, messageFn(options.data), options);
|
|
1500
1952
|
}
|
|
1501
1953
|
};
|
|
1954
|
+
function isVigorFetchError(error, ...codes) {
|
|
1955
|
+
return error instanceof VigorFetchError && (codes.length === 0 || codes.includes(error.code));
|
|
1956
|
+
}
|
|
1957
|
+
function adoptVigorFetchError(error, context) {
|
|
1958
|
+
if (!(error instanceof VigorRetryError) && !(error instanceof VigorParseError)) return error;
|
|
1959
|
+
const data = error.data;
|
|
1960
|
+
const adopted = data !== null && typeof data === "object" && "error" in data ? { ...data, error: adoptVigorFetchError(data.error, context) } : data;
|
|
1961
|
+
return new VigorFetchError(error.code, {
|
|
1962
|
+
method: error.method,
|
|
1963
|
+
cause: error,
|
|
1964
|
+
data: adopted,
|
|
1965
|
+
context
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1502
1968
|
|
|
1503
1969
|
// src/fetch/main.ts
|
|
1504
1970
|
var VigorFetchBase = {
|
|
1505
1971
|
__brand: createBrand("Fetch", "Schema"),
|
|
1506
1972
|
policy: VigorFetchPolicyBase,
|
|
1507
|
-
cast: VigorEmpty
|
|
1973
|
+
cast: VigorEmpty,
|
|
1974
|
+
apiMap: VigorEmpty
|
|
1508
1975
|
};
|
|
1509
1976
|
var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
1510
1977
|
constructor(config = VigorFetchBase) {
|
|
@@ -1533,52 +2000,29 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1533
2000
|
hash(str) {
|
|
1534
2001
|
return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } });
|
|
1535
2002
|
}
|
|
1536
|
-
/**
|
|
1537
|
-
* Sets request headers.
|
|
1538
|
-
*
|
|
1539
|
-
* @param mode - `"overwrite"` discards all previously configured headers
|
|
1540
|
-
* and keeps only the ones passed here. `"merge"` behaves like
|
|
1541
|
-
* `Object.assign`, overwriting only the keys that overlap and keeping
|
|
1542
|
-
* the rest.
|
|
1543
|
-
*/
|
|
1544
2003
|
headers(mode, obj) {
|
|
1545
2004
|
if (mode === "overwrite") return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
|
|
1546
2005
|
return this._next({ policy: { headers: obj } });
|
|
1547
2006
|
}
|
|
1548
|
-
/**
|
|
1549
|
-
* Sets the request body.
|
|
1550
|
-
*
|
|
1551
|
-
* @param mode - `"overwrite"` discards the previous body and fully
|
|
1552
|
-
* replaces it with this value. `"merge"` shallow-merges (via
|
|
1553
|
-
* `Object.assign`) when both the previous and new body are plain
|
|
1554
|
-
* objects; for any other body type (string/Blob/FormData/etc) it is
|
|
1555
|
-
* simply replaced.
|
|
1556
|
-
*/
|
|
1557
2007
|
body(mode, obj) {
|
|
1558
|
-
|
|
1559
|
-
|
|
2008
|
+
const prev = this.config.policy.body;
|
|
2009
|
+
const body = mode === "merge" && this._isPlainObject(prev) && this._isPlainObject(obj) ? { ...prev, ...obj } : obj;
|
|
2010
|
+
return this._next({ policy: { body } }, { policy: { body: "replace" } });
|
|
1560
2011
|
}
|
|
1561
|
-
/**
|
|
1562
|
-
* Sets additional `RequestInit` options other than headers/body/method/signal
|
|
1563
|
-
* (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
|
|
1564
|
-
* `referrerPolicy`, `keepalive`, `integrity`).
|
|
1565
|
-
*
|
|
1566
|
-
* @param mode - `"overwrite"` discards all previously configured options
|
|
1567
|
-
* and replaces them with this value. `"merge"` shallow-merges this
|
|
1568
|
-
* value onto the previous options.
|
|
1569
|
-
*/
|
|
1570
2012
|
options(mode, obj) {
|
|
1571
|
-
|
|
1572
|
-
return this._next({ policy: { extra:
|
|
2013
|
+
const extra = mode === "merge" ? { ...this.config.policy.extra, ...obj } : obj;
|
|
2014
|
+
return this._next({ policy: { extra } }, { policy: { extra: "replace" } });
|
|
1573
2015
|
}
|
|
1574
2016
|
settings(input) {
|
|
2017
|
+
const strategy = { policy: { settings: { retryHeaders: "replace", unretryStatus: "replace" } } };
|
|
1575
2018
|
if (typeof input === "function" || input instanceof VigorFetchPolicySettings) {
|
|
1576
|
-
const result = typeof input === "function" ? input(new VigorFetchPolicySettings()) : input;
|
|
2019
|
+
const result = typeof input === "function" ? input(new VigorFetchPolicySettings(this.config)) : input;
|
|
1577
2020
|
return this._next(
|
|
1578
|
-
{ policy: { settings: result.config.policy.settings } }
|
|
2021
|
+
{ policy: { settings: result.config.policy.settings } },
|
|
2022
|
+
strategy
|
|
1579
2023
|
);
|
|
1580
2024
|
}
|
|
1581
|
-
return this._next({ policy: { settings: input } });
|
|
2025
|
+
return this._next({ policy: { settings: input } }, strategy);
|
|
1582
2026
|
}
|
|
1583
2027
|
middlewares(input) {
|
|
1584
2028
|
if (typeof input === "function" || input instanceof VigorFetchPolicyMiddlewares) {
|
|
@@ -1594,14 +2038,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1594
2038
|
const result = typeof input === "function" ? input(new VigorRetry()) : input;
|
|
1595
2039
|
return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
|
|
1596
2040
|
}
|
|
1597
|
-
return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
|
|
2041
|
+
return this._next({ policy: { retry: this._merge(VigorRetryBase, input) } }, { policy: { retry: "replace" } });
|
|
1598
2042
|
}
|
|
1599
2043
|
parse(input) {
|
|
1600
2044
|
if (typeof input === "function" || input instanceof VigorParse) {
|
|
1601
2045
|
const result = typeof input === "function" ? input(new VigorParse()) : input;
|
|
1602
2046
|
return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
|
|
1603
2047
|
}
|
|
1604
|
-
return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
|
|
2048
|
+
return this._next({ policy: { parse: this._merge(VigorParseBase, input) } }, { policy: { parse: "replace" } });
|
|
2049
|
+
}
|
|
2050
|
+
/** Whether `v` is a plain object literal (not an array, `FormData`, `Blob`, ...). */
|
|
2051
|
+
_isPlainObject(v) {
|
|
2052
|
+
return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
|
|
1605
2053
|
}
|
|
1606
2054
|
/** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
|
|
1607
2055
|
_stringifyList(unkList) {
|
|
@@ -1623,9 +2071,11 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1623
2071
|
* Builds the final request URL from the configured origin, path
|
|
1624
2072
|
* segments, query parameters, and hash. An absolute `origin` ignores
|
|
1625
2073
|
* the resolved base (per the `URL` spec); a relative `origin` is
|
|
1626
|
-
* resolved against it. Throws `INVALID_PROTOCOL`
|
|
2074
|
+
* resolved against it. Throws `INVALID_PROTOCOL` (with `context`) if
|
|
2075
|
+
* neither is possible, and with `settings.confinePath` on, `PATH_ESCAPED`
|
|
2076
|
+
* if the result leaves the origin's domain or path.
|
|
1627
2077
|
*/
|
|
1628
|
-
_buildUrl(origin, path, query, hash) {
|
|
2078
|
+
_buildUrl(origin, path, query, hash, context) {
|
|
1629
2079
|
const base = this._resolveBase();
|
|
1630
2080
|
let originObj;
|
|
1631
2081
|
try {
|
|
@@ -1633,12 +2083,15 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1633
2083
|
} catch {
|
|
1634
2084
|
throw new VigorFetchError("INVALID_PROTOCOL", {
|
|
1635
2085
|
method: "_buildUrl",
|
|
1636
|
-
data: { origin, base }
|
|
2086
|
+
data: { origin, base },
|
|
2087
|
+
context
|
|
1637
2088
|
});
|
|
1638
2089
|
}
|
|
1639
2090
|
const baseStr = originObj.origin;
|
|
1640
2091
|
const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, "")];
|
|
1641
|
-
for (const p of path)
|
|
2092
|
+
for (const p of path) {
|
|
2093
|
+
for (const part of p.split("/")) pathParts.push(encodeURIComponent(part));
|
|
2094
|
+
}
|
|
1642
2095
|
const pathStr = pathParts.filter(Boolean).join("/");
|
|
1643
2096
|
const mainObj = new URL(pathStr, baseStr);
|
|
1644
2097
|
const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
|
|
@@ -1652,50 +2105,224 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1652
2105
|
}
|
|
1653
2106
|
}
|
|
1654
2107
|
mainObj.hash = hash || originObj.hash;
|
|
2108
|
+
if (context.policy.settings.confinePath) {
|
|
2109
|
+
const basePath = "/" + originObj.pathname.replace(/^\/+|\/+$/g, "");
|
|
2110
|
+
const inside = basePath === "/" || mainObj.pathname === basePath || mainObj.pathname.startsWith(basePath + "/");
|
|
2111
|
+
if (mainObj.origin !== originObj.origin || !inside) throw new VigorFetchError("PATH_ESCAPED", {
|
|
2112
|
+
method: "_buildUrl",
|
|
2113
|
+
data: { url: mainObj.href, base: originObj.origin + (basePath === "/" ? "" : basePath) },
|
|
2114
|
+
context
|
|
2115
|
+
});
|
|
2116
|
+
}
|
|
1655
2117
|
return mainObj.href;
|
|
1656
2118
|
}
|
|
1657
|
-
/** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
|
|
1658
|
-
_normalizeBody(body) {
|
|
2119
|
+
/** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. Throws `INVALID_BODY` (with `context`) for anything else. */
|
|
2120
|
+
_normalizeBody(body, context) {
|
|
1659
2121
|
if (body == null) return { headers: {}, body };
|
|
1660
2122
|
if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
|
|
1661
2123
|
if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
|
|
1662
|
-
if (body instanceof ArrayBuffer) return { headers: { "Content-Type": "application/octet-stream" }, body };
|
|
2124
|
+
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { headers: { "Content-Type": "application/octet-stream" }, body };
|
|
2125
|
+
if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) return { headers: { "Content-Type": "application/octet-stream" }, body };
|
|
1663
2126
|
if (body instanceof URLSearchParams) return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
|
|
1664
2127
|
if (body instanceof FormData) return { headers: {}, body };
|
|
1665
2128
|
if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
|
|
1666
2129
|
throw new VigorFetchError("INVALID_BODY", {
|
|
1667
2130
|
method: "_normalizeBody",
|
|
1668
|
-
data: { received: body }
|
|
2131
|
+
data: { received: body },
|
|
2132
|
+
context
|
|
1669
2133
|
});
|
|
1670
2134
|
}
|
|
2135
|
+
/**
|
|
2136
|
+
* Returns the absolute URL a redirect points at, or `null` when the
|
|
2137
|
+
* response isn't a redirect. A response `fetch` already followed
|
|
2138
|
+
* (`redirect: "follow"`, the default) yields its final URL; a readable
|
|
2139
|
+
* `3xx` (`redirect: "manual"` outside browsers) yields its `Location`,
|
|
2140
|
+
* resolved against the responding URL.
|
|
2141
|
+
*/
|
|
2142
|
+
_resolveRedirect(response, href) {
|
|
2143
|
+
if (response.redirected && response.url) return response.url;
|
|
2144
|
+
if (response.status < 300 || response.status >= 400) return null;
|
|
2145
|
+
const location = response.headers.get("location");
|
|
2146
|
+
if (!location) return null;
|
|
2147
|
+
try {
|
|
2148
|
+
return new URL(location, response.url || href).href;
|
|
2149
|
+
} catch {
|
|
2150
|
+
return null;
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
/** The browser's `location`, or `null` in environments without one (e.g. Node). */
|
|
2154
|
+
_browserLocation() {
|
|
2155
|
+
const win = globalThis.window;
|
|
2156
|
+
return win?.location?.href !== void 0 ? win.location : null;
|
|
2157
|
+
}
|
|
2158
|
+
/** Assigns `source` headers onto `target`, replacing any existing key that differs only in case. */
|
|
2159
|
+
_assignHeaders(target, source) {
|
|
2160
|
+
for (const [key, value] of Object.entries(source)) {
|
|
2161
|
+
const lower = key.toLowerCase();
|
|
2162
|
+
for (const existing of Object.keys(target)) {
|
|
2163
|
+
if (existing.toLowerCase() === lower) delete target[existing];
|
|
2164
|
+
}
|
|
2165
|
+
target[key] = value;
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
/**
|
|
2169
|
+
* Converts a rate-limit header value into a delay in milliseconds, or
|
|
2170
|
+
* `null` if it can't be used. Accepts delta seconds (`Retry-After: 120`),
|
|
2171
|
+
* Unix epoch seconds or milliseconds (`X-RateLimit-Reset: 1735689600`),
|
|
2172
|
+
* and HTTP dates.
|
|
2173
|
+
*/
|
|
2174
|
+
_parseRetryHeader(value) {
|
|
2175
|
+
if (!value) return null;
|
|
2176
|
+
const num = Number(value);
|
|
2177
|
+
let delay;
|
|
2178
|
+
if (value.trim() !== "" && !isNaN(num)) {
|
|
2179
|
+
if (num >= 1e12) delay = num - Date.now();
|
|
2180
|
+
else if (num >= 1e9) delay = num * 1e3 - Date.now();
|
|
2181
|
+
else delay = num * 1e3;
|
|
2182
|
+
} else {
|
|
2183
|
+
const date = new Date(value).getTime();
|
|
2184
|
+
if (isNaN(date)) return null;
|
|
2185
|
+
delay = date - Date.now();
|
|
2186
|
+
}
|
|
2187
|
+
return delay > 0 ? delay : null;
|
|
2188
|
+
}
|
|
1671
2189
|
/**
|
|
1672
2190
|
* Overrides the resolved result type with `T`, taking priority over the
|
|
1673
2191
|
* default `unknown` result. Can be called before or after `parse()` (or
|
|
1674
2192
|
* any other configuration method); whichever `.cast<T>()` call happens
|
|
1675
2193
|
* last wins.
|
|
1676
2194
|
*/
|
|
2195
|
+
/**
|
|
2196
|
+
* Attaches a type-level API map: a request whose method and path match a
|
|
2197
|
+
* route resolves to that route's success `responses` (see `VigorApiRoute`
|
|
2198
|
+
* for `responses`/`params`/`query`/`body`). Keys are
|
|
2199
|
+
* `"<METHOD> /<path>"`, where a `:name` segment matches any one segment.
|
|
2200
|
+
* Routes are relative to the path set so far, so a base path can be set
|
|
2201
|
+
* first: `vigor.fetch(origin).path("v1").apiMap<Api>()`. Purely a type —
|
|
2202
|
+
* nothing changes at runtime. `.cast<T>()` and a `raw` parse still win.
|
|
2203
|
+
*
|
|
2204
|
+
* @example
|
|
2205
|
+
* type Api = {
|
|
2206
|
+
* "GET /users": { response: User[] }
|
|
2207
|
+
* "GET /users/:id": { response: User }
|
|
2208
|
+
* }
|
|
2209
|
+
* const api = vigor.fetch("https://api.example.com").apiMap<Api>()
|
|
2210
|
+
* const user = await api.path("users", id).request() // User
|
|
2211
|
+
*/
|
|
2212
|
+
apiMap() {
|
|
2213
|
+
return this._next(
|
|
2214
|
+
{ apiMap: VigorCastPlaceholder },
|
|
2215
|
+
{ apiMap: "replace" }
|
|
2216
|
+
);
|
|
2217
|
+
}
|
|
2218
|
+
route(key, ...params) {
|
|
2219
|
+
const route = key;
|
|
2220
|
+
const space = route.indexOf(" ");
|
|
2221
|
+
const method = route.slice(0, space);
|
|
2222
|
+
const values = params[0] ?? {};
|
|
2223
|
+
const segments = route.slice(space + 1).split("/").filter(Boolean).map((segment) => {
|
|
2224
|
+
if (!segment.startsWith(":")) return segment;
|
|
2225
|
+
const name = segment.slice(1);
|
|
2226
|
+
const value = values[name];
|
|
2227
|
+
if (value === null || value === void 0) throw new VigorFetchError("VALUE_REQUIRED", {
|
|
2228
|
+
method: "route",
|
|
2229
|
+
data: { key: `params.${name}` }
|
|
2230
|
+
});
|
|
2231
|
+
return value;
|
|
2232
|
+
});
|
|
2233
|
+
return this.method(method).path(...segments);
|
|
2234
|
+
}
|
|
1677
2235
|
cast() {
|
|
1678
2236
|
return this._next(
|
|
1679
2237
|
{ cast: VigorCastPlaceholder },
|
|
1680
2238
|
{ cast: "replace" }
|
|
1681
2239
|
);
|
|
1682
2240
|
}
|
|
1683
|
-
/**
|
|
2241
|
+
/**
|
|
2242
|
+
* Runs the request and returns its parsed result directly, throwing on final failure.
|
|
2243
|
+
*
|
|
2244
|
+
* `R` defaults to the inferred result type. Passing one (`request<User>()`)
|
|
2245
|
+
* means "ignore the inference, it's this": it's taken as-is, unchecked.
|
|
2246
|
+
* To name the inferred type itself, use `VigorResultOf<typeof builder>`.
|
|
2247
|
+
*
|
|
2248
|
+
* With an API map, the request's `body`/`query` must match its route's
|
|
2249
|
+
* (see {@link VigorFetchRequestThis}), or the call doesn't compile.
|
|
2250
|
+
*/
|
|
1684
2251
|
async request() {
|
|
1685
|
-
const res = await this.
|
|
2252
|
+
const res = await this.requestRuntime();
|
|
1686
2253
|
if (res.success) return res.data;
|
|
1687
2254
|
throw res.error;
|
|
1688
2255
|
}
|
|
1689
|
-
/**
|
|
2256
|
+
/**
|
|
2257
|
+
* Runs the request and returns a result/error envelope instead of throwing,
|
|
2258
|
+
* along with the `timeline` of everything the run went through. The
|
|
2259
|
+
* nested retry/parse engines' full timelines are kept inside it, on their
|
|
2260
|
+
* `RETRY_ENDED`/`PARSE_ENDED` entries.
|
|
2261
|
+
*
|
|
2262
|
+
* A success carries the `status` and `response` its result was parsed
|
|
2263
|
+
* from; with an API map, narrowing `status` narrows `data` (see
|
|
2264
|
+
* {@link VigorFetchVerboseResult}). Passing `R` types every success's
|
|
2265
|
+
* `data` as `R`, unchecked.
|
|
2266
|
+
*/
|
|
1690
2267
|
async requestVerbose() {
|
|
1691
2268
|
return await this.requestRuntime();
|
|
1692
2269
|
}
|
|
1693
|
-
/**
|
|
1694
|
-
|
|
2270
|
+
/**
|
|
2271
|
+
* Internal execution loop implementing URL building, retry, parsing, and
|
|
2272
|
+
* restart handling. Never throws: every failure, including one from
|
|
2273
|
+
* `onError` or `default`, comes back as an envelope carrying the timeline.
|
|
2274
|
+
* A restart passes the same `timeline` on, so it keeps growing across runs.
|
|
2275
|
+
*/
|
|
2276
|
+
async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
|
|
1695
2277
|
const config = this._merge(this.config, {});
|
|
1696
2278
|
let ctx = this._merge(VigorFetchContextBase, {
|
|
1697
2279
|
policy: config.policy
|
|
2280
|
+
}, void 0, "replace");
|
|
2281
|
+
ctx.timeline = timeline;
|
|
2282
|
+
const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
|
|
2283
|
+
add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
|
|
2284
|
+
const end = (success, outcome, error) => add("REQUEST_END", {
|
|
2285
|
+
success,
|
|
2286
|
+
outcome,
|
|
2287
|
+
error,
|
|
2288
|
+
took: performance.now() - startedAt,
|
|
2289
|
+
restarts: restartAttempt - 1
|
|
1698
2290
|
});
|
|
2291
|
+
const succeed = (data, outcome, response = null) => {
|
|
2292
|
+
end(true, outcome, null);
|
|
2293
|
+
return { success: true, data, error: null, status: response?.status ?? null, response, timeline };
|
|
2294
|
+
};
|
|
2295
|
+
const fail = (error) => {
|
|
2296
|
+
end(false, "failed", error);
|
|
2297
|
+
return { success: false, data: null, error, status: null, response: null, timeline };
|
|
2298
|
+
};
|
|
2299
|
+
let lastAttempt = 0;
|
|
2300
|
+
const runRetry = async (engine) => {
|
|
2301
|
+
add("RETRY_STARTED", { engine });
|
|
2302
|
+
const started = performance.now();
|
|
2303
|
+
const res = await engine.requestVerbose();
|
|
2304
|
+
add("RETRY_ENDED", {
|
|
2305
|
+
engine,
|
|
2306
|
+
timeline: res.timeline,
|
|
2307
|
+
took: performance.now() - started,
|
|
2308
|
+
response: res.success ? res.data : VigorDefault
|
|
2309
|
+
});
|
|
2310
|
+
return res;
|
|
2311
|
+
};
|
|
2312
|
+
const runParse = async (source, attempt, engine) => {
|
|
2313
|
+
add("PARSE_STARTED", { engine, source, attempt });
|
|
2314
|
+
const started = performance.now();
|
|
2315
|
+
const res = await engine.requestVerbose();
|
|
2316
|
+
add("PARSE_ENDED", {
|
|
2317
|
+
engine,
|
|
2318
|
+
source,
|
|
2319
|
+
attempt,
|
|
2320
|
+
timeline: res.timeline,
|
|
2321
|
+
took: performance.now() - started,
|
|
2322
|
+
result: res.success ? res.data : VigorDefault
|
|
2323
|
+
});
|
|
2324
|
+
return res;
|
|
2325
|
+
};
|
|
1699
2326
|
const throwError = (err) => {
|
|
1700
2327
|
throw err;
|
|
1701
2328
|
};
|
|
@@ -1705,50 +2332,84 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1705
2332
|
data: { key: "origin" },
|
|
1706
2333
|
context: ctx
|
|
1707
2334
|
});
|
|
1708
|
-
ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
|
|
1709
|
-
|
|
2335
|
+
ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash, ctx);
|
|
2336
|
+
add("BUILT_URL", { url: ctx.href });
|
|
2337
|
+
const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body != null;
|
|
1710
2338
|
const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
|
|
1711
|
-
|
|
2339
|
+
const options = {
|
|
1712
2340
|
...ctx.policy.extra,
|
|
1713
2341
|
method,
|
|
1714
2342
|
headers: {}
|
|
1715
2343
|
};
|
|
1716
2344
|
if (hasBody) {
|
|
1717
|
-
const normalized = this._normalizeBody(ctx.policy.body);
|
|
2345
|
+
const normalized = this._normalizeBody(ctx.policy.body, ctx);
|
|
1718
2346
|
if (normalized.body !== void 0) options.body = normalized.body;
|
|
1719
2347
|
Object.assign(options.headers, normalized.headers);
|
|
1720
2348
|
}
|
|
1721
|
-
|
|
1722
|
-
|
|
2349
|
+
this._assignHeaders(options.headers, ctx.policy.headers);
|
|
2350
|
+
ctx.options = options;
|
|
2351
|
+
await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
|
|
1723
2352
|
if (middleware._mode === "fluent") {
|
|
1724
2353
|
await middleware.func(ctx);
|
|
1725
2354
|
} else {
|
|
1726
|
-
ctx = await middleware.func(ctx, {
|
|
2355
|
+
ctx = await middleware.func(ctx, trace({
|
|
1727
2356
|
throwError,
|
|
1728
2357
|
setOptions: (o) => {
|
|
1729
|
-
options = o;
|
|
2358
|
+
ctx.options = o;
|
|
1730
2359
|
},
|
|
1731
2360
|
setHeaders: (h) => {
|
|
1732
|
-
options.headers = h;
|
|
2361
|
+
ctx.options.headers = h;
|
|
1733
2362
|
},
|
|
1734
2363
|
setBody: (b) => {
|
|
1735
|
-
options.body = b;
|
|
2364
|
+
ctx.options.body = b;
|
|
1736
2365
|
}
|
|
1737
|
-
});
|
|
2366
|
+
})) ?? ctx;
|
|
1738
2367
|
}
|
|
2368
|
+
});
|
|
2369
|
+
const finalOptions = isVigorDefault(ctx.options) ? options : ctx.options;
|
|
2370
|
+
ctx.options = finalOptions;
|
|
2371
|
+
add("SET_OPTIONS", { options: finalOptions });
|
|
2372
|
+
const finalMethod = (finalOptions.method ?? "GET").toUpperCase();
|
|
2373
|
+
if (finalOptions.body != null && (finalMethod === "GET" || finalMethod === "HEAD")) throw new VigorFetchError("BODY_NOT_ALLOWED", {
|
|
2374
|
+
method: "request",
|
|
2375
|
+
data: { method: finalMethod },
|
|
2376
|
+
context: ctx
|
|
2377
|
+
});
|
|
2378
|
+
const isStreamBody = typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream;
|
|
2379
|
+
if (isStreamBody) {
|
|
2380
|
+
finalOptions.duplex ??= "half";
|
|
1739
2381
|
}
|
|
1740
|
-
|
|
1741
|
-
const
|
|
1742
|
-
|
|
2382
|
+
const nestedDebug = { policy: { settings: { debug: true } } };
|
|
2383
|
+
const parseEngine = new VigorParse(config.policy.settings.debug ? this._merge(ctx.policy.parse, nestedDebug) : ctx.policy.parse);
|
|
2384
|
+
const retryEngine = new VigorRetry(config.policy.settings.debug ? this._merge(ctx.policy.retry, nestedDebug) : ctx.policy.retry).target(async (signal) => {
|
|
2385
|
+
return await fetch(ctx.href, { ...finalOptions, signal });
|
|
1743
2386
|
}).middlewares(
|
|
1744
2387
|
(m) => m.after("intercept", async (rctx, api) => {
|
|
1745
2388
|
const response = rctx.result;
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
2389
|
+
lastAttempt = rctx.system.attempt;
|
|
2390
|
+
add("RESPONSE_RECEIVED", {
|
|
2391
|
+
attempt: rctx.system.attempt,
|
|
2392
|
+
status: response.status,
|
|
2393
|
+
statusText: response.statusText,
|
|
2394
|
+
ok: response.ok,
|
|
2395
|
+
redirected: response.redirected,
|
|
2396
|
+
url: response.url
|
|
2397
|
+
});
|
|
2398
|
+
if (ctx.policy.settings.redirect) {
|
|
2399
|
+
const target = this._resolveRedirect(response, ctx.href);
|
|
2400
|
+
const location = this._browserLocation();
|
|
2401
|
+
if (target && location) {
|
|
2402
|
+
location.href = target;
|
|
2403
|
+
api.throwError(new VigorFetchError("REDIRECTED", {
|
|
2404
|
+
method: "request",
|
|
2405
|
+
data: { url: target, status: response.status, response },
|
|
2406
|
+
context: ctx
|
|
2407
|
+
}));
|
|
1751
2408
|
}
|
|
2409
|
+
}
|
|
2410
|
+
if (!response.ok && response.status !== 304) {
|
|
2411
|
+
const parseRes2 = await runParse("failedResponse", rctx.system.attempt, parseEngine.target(response.clone()));
|
|
2412
|
+
const parsed = parseRes2.success ? parseRes2.data : void 0;
|
|
1752
2413
|
api.throwError(new VigorFetchError("FETCH_FAILED", {
|
|
1753
2414
|
method: "request",
|
|
1754
2415
|
data: {
|
|
@@ -1757,64 +2418,67 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1757
2418
|
response,
|
|
1758
2419
|
url: response.url,
|
|
1759
2420
|
parsed
|
|
1760
|
-
}
|
|
2421
|
+
},
|
|
2422
|
+
context: ctx
|
|
1761
2423
|
}));
|
|
1762
2424
|
}
|
|
2425
|
+
if (!ctx.policy.parse.policy.settings.raw) await readVigorParseBody(response);
|
|
1763
2426
|
return rctx;
|
|
1764
2427
|
}).retryIf("intercept", async (rctx, api) => {
|
|
1765
2428
|
const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
|
|
1766
|
-
if (
|
|
1767
|
-
else api.
|
|
2429
|
+
if (rctx.error instanceof VigorFetchError && rctx.error.code === "REDIRECTED") api.cancelRetry();
|
|
2430
|
+
else if (isStreamBody) api.cancelRetry();
|
|
2431
|
+
else if (response && (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400)) api.cancelRetry();
|
|
2432
|
+
else if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
|
|
1768
2433
|
return rctx;
|
|
1769
2434
|
}).onRetry("intercept", async (rctx, api) => {
|
|
1770
2435
|
const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
|
|
1771
|
-
if (response?.status === 429) {
|
|
1772
|
-
let retryHeader = null;
|
|
2436
|
+
if (response?.status === 429 || response?.status === 503) {
|
|
1773
2437
|
for (const header of ctx.policy.settings.retryHeaders) {
|
|
1774
|
-
|
|
1775
|
-
if (
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
const delay = !isNaN(toNumber) ? toNumber * 1e3 : (() => {
|
|
1780
|
-
const toDate = new Date(retryHeader).getTime();
|
|
1781
|
-
return !isNaN(toDate) ? toDate - Date.now() : null;
|
|
1782
|
-
})();
|
|
1783
|
-
if (delay !== null && delay > 0) api.setDelay(delay);
|
|
2438
|
+
const delay = this._parseRetryHeader(response.headers.get(header));
|
|
2439
|
+
if (delay !== null) {
|
|
2440
|
+
api.setDelay(Math.min(delay, ctx.policy.settings.maxRetryAfter));
|
|
2441
|
+
break;
|
|
2442
|
+
}
|
|
1784
2443
|
}
|
|
1785
2444
|
}
|
|
1786
2445
|
return rctx;
|
|
1787
2446
|
})
|
|
1788
2447
|
);
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
2448
|
+
for (const name of ["after", "retryIf", "onRetry"]) {
|
|
2449
|
+
const list = retryEngine.config.policy.middlewares[name];
|
|
2450
|
+
markVigorInternal(list[list.length - 1].func);
|
|
2451
|
+
}
|
|
2452
|
+
add("ENGINE_CREATED", { retryEngine, parseEngine });
|
|
2453
|
+
const retryRes = await runRetry(retryEngine);
|
|
2454
|
+
if (!retryRes.success) throw adoptVigorFetchError(retryRes.error, ctx);
|
|
2455
|
+
ctx.response = retryRes.data;
|
|
2456
|
+
const parseRes = await runParse("response", lastAttempt, parseEngine.target(ctx.response));
|
|
2457
|
+
if (!parseRes.success) throw adoptVigorFetchError(parseRes.error, ctx);
|
|
2458
|
+
ctx.result = parseRes.data;
|
|
2459
|
+
await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
|
|
1793
2460
|
if (middleware._mode === "fluent") {
|
|
1794
2461
|
await middleware.func(ctx);
|
|
1795
2462
|
} else {
|
|
1796
|
-
ctx = await middleware.func(ctx, { throwError, setResult: (r) => {
|
|
2463
|
+
ctx = await middleware.func(ctx, trace({ throwError, setResult: (r) => {
|
|
1797
2464
|
ctx.result = r;
|
|
1798
|
-
} });
|
|
2465
|
+
} })) ?? ctx;
|
|
1799
2466
|
}
|
|
1800
|
-
}
|
|
2467
|
+
});
|
|
1801
2468
|
const setResult = (r) => {
|
|
1802
2469
|
ctx.result = r;
|
|
1803
2470
|
};
|
|
1804
|
-
|
|
2471
|
+
await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
|
|
1805
2472
|
if (middleware._mode === "fluent") {
|
|
1806
2473
|
ctx.result = await middleware.func(ctx.result);
|
|
1807
2474
|
} else {
|
|
1808
|
-
ctx = await middleware.func(ctx, { setResult, throwError });
|
|
2475
|
+
ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
|
|
1809
2476
|
}
|
|
1810
|
-
}
|
|
1811
|
-
return
|
|
1812
|
-
success: true,
|
|
1813
|
-
data: ctx.result,
|
|
1814
|
-
error: null
|
|
1815
|
-
};
|
|
2477
|
+
});
|
|
2478
|
+
return succeed(ctx.result, "result", ctx.response);
|
|
1816
2479
|
} catch (error) {
|
|
1817
2480
|
ctx.error = error;
|
|
2481
|
+
add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
|
|
1818
2482
|
ctx.flags.overridden = false;
|
|
1819
2483
|
ctx.flags.restarted = false;
|
|
1820
2484
|
const setResult = (r) => {
|
|
@@ -1823,15 +2487,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1823
2487
|
};
|
|
1824
2488
|
const proceedRestart = () => ctx.flags.restarted = true;
|
|
1825
2489
|
const cancelRestart = () => ctx.flags.restarted = false;
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
2490
|
+
try {
|
|
2491
|
+
await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
|
|
2492
|
+
if (middleware._mode === "fluent") {
|
|
2493
|
+
await middleware.func(ctx.error);
|
|
2494
|
+
} else {
|
|
2495
|
+
ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
|
|
2496
|
+
}
|
|
2497
|
+
});
|
|
2498
|
+
} catch (err) {
|
|
2499
|
+
return fail(err);
|
|
1832
2500
|
}
|
|
1833
2501
|
if (ctx.flags.restarted) {
|
|
1834
|
-
if (restartAttempt
|
|
2502
|
+
if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorFetchError("RESTART_EXHAUSTED", {
|
|
1835
2503
|
method: "request",
|
|
1836
2504
|
cause: ctx.error,
|
|
1837
2505
|
data: {
|
|
@@ -1839,27 +2507,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
|
|
|
1839
2507
|
error: ctx.error
|
|
1840
2508
|
},
|
|
1841
2509
|
context: ctx
|
|
1842
|
-
});
|
|
1843
|
-
|
|
2510
|
+
}));
|
|
2511
|
+
add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
|
|
2512
|
+
return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
|
|
1844
2513
|
}
|
|
1845
|
-
if (ctx.flags.overridden) return
|
|
1846
|
-
success: true,
|
|
1847
|
-
data: ctx.result,
|
|
1848
|
-
error: null
|
|
1849
|
-
};
|
|
2514
|
+
if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
|
|
1850
2515
|
if (!isVigorEmpty(ctx.policy.settings.default)) {
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
};
|
|
2516
|
+
try {
|
|
2517
|
+
return succeed(await ctx.policy.settings.default(ctx), "default");
|
|
2518
|
+
} catch (err) {
|
|
2519
|
+
return fail(err);
|
|
2520
|
+
}
|
|
1857
2521
|
}
|
|
1858
|
-
return
|
|
1859
|
-
success: false,
|
|
1860
|
-
data: null,
|
|
1861
|
-
error
|
|
1862
|
-
};
|
|
2522
|
+
return fail(error);
|
|
1863
2523
|
}
|
|
1864
2524
|
}
|
|
1865
2525
|
};
|
|
@@ -1907,6 +2567,12 @@ var vigorBase = {
|
|
|
1907
2567
|
settings: () => new VigorAllPolicySettings(),
|
|
1908
2568
|
middlewares: () => new VigorAllPolicyMiddlewares()
|
|
1909
2569
|
}
|
|
2570
|
+
},
|
|
2571
|
+
guards: {
|
|
2572
|
+
retry: isVigorRetryError,
|
|
2573
|
+
parse: isVigorParseError,
|
|
2574
|
+
fetch: isVigorFetchError,
|
|
2575
|
+
all: isVigorAllError
|
|
1910
2576
|
}
|
|
1911
2577
|
};
|
|
1912
2578
|
var cloneVigor = (v) => ({
|
|
@@ -1916,21 +2582,29 @@ var cloneVigor = (v) => ({
|
|
|
1916
2582
|
retry: { ...v.builders.retry, algorithm: { ...v.builders.retry.algorithm } },
|
|
1917
2583
|
parse: { ...v.builders.parse },
|
|
1918
2584
|
all: { ...v.builders.all }
|
|
1919
|
-
}
|
|
2585
|
+
},
|
|
2586
|
+
guards: { ...v.guards }
|
|
1920
2587
|
});
|
|
1921
|
-
var
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
2588
|
+
var createVigor = (fields) => {
|
|
2589
|
+
const instance = {
|
|
2590
|
+
...fields,
|
|
2591
|
+
use: (plugin, options) => {
|
|
2592
|
+
const ext = plugin.func(instance, { ...plugin.options, ...options });
|
|
2593
|
+
const { use: _, ...rest } = { ...cloneVigor(instance), ...ext };
|
|
2594
|
+
return createVigor(rest);
|
|
2595
|
+
}
|
|
2596
|
+
};
|
|
2597
|
+
return instance;
|
|
1927
2598
|
};
|
|
2599
|
+
var vigor = createVigor(vigorBase);
|
|
1928
2600
|
|
|
1929
2601
|
// src/index.ts
|
|
1930
2602
|
var index_default = vigor;
|
|
1931
2603
|
export {
|
|
1932
2604
|
VigorAll,
|
|
1933
2605
|
VigorAllBase,
|
|
2606
|
+
VigorAllContextBase,
|
|
2607
|
+
VigorAllEachContextBase,
|
|
1934
2608
|
VigorAllError,
|
|
1935
2609
|
VigorAllErrorMessageFuncs,
|
|
1936
2610
|
VigorAllPolicyBase,
|
|
@@ -1938,9 +2612,13 @@ export {
|
|
|
1938
2612
|
VigorAllPolicyMiddlewaresBase,
|
|
1939
2613
|
VigorAllPolicySettings,
|
|
1940
2614
|
VigorAllPolicySettingsBase,
|
|
2615
|
+
VigorCastPlaceholder,
|
|
2616
|
+
VigorDefault,
|
|
2617
|
+
VigorEmpty,
|
|
1941
2618
|
VigorError,
|
|
1942
2619
|
VigorFetch,
|
|
1943
2620
|
VigorFetchBase,
|
|
2621
|
+
VigorFetchContextBase,
|
|
1944
2622
|
VigorFetchError,
|
|
1945
2623
|
VigorFetchErrorMessageFuncs,
|
|
1946
2624
|
VigorFetchPolicyBase,
|
|
@@ -1952,6 +2630,7 @@ export {
|
|
|
1952
2630
|
VigorParse,
|
|
1953
2631
|
VigorParseBase,
|
|
1954
2632
|
VigorParseContentTypeStrategy,
|
|
2633
|
+
VigorParseContextBase,
|
|
1955
2634
|
VigorParseError,
|
|
1956
2635
|
VigorParseErrorMessageFuncs,
|
|
1957
2636
|
VigorParsePolicyBase,
|
|
@@ -1964,6 +2643,7 @@ export {
|
|
|
1964
2643
|
VigorParseSniffStrategy,
|
|
1965
2644
|
VigorRetry,
|
|
1966
2645
|
VigorRetryBase,
|
|
2646
|
+
VigorRetryContextBase,
|
|
1967
2647
|
VigorRetryError,
|
|
1968
2648
|
VigorRetryErrorMessageFuncs,
|
|
1969
2649
|
VigorRetryPolicyAlgorithms,
|
|
@@ -1982,6 +2662,18 @@ export {
|
|
|
1982
2662
|
VigorRetryPolicySettings,
|
|
1983
2663
|
VigorRetryPolicySettingsBase,
|
|
1984
2664
|
VigorStatus,
|
|
2665
|
+
adoptVigorFetchError,
|
|
2666
|
+
createBrand,
|
|
2667
|
+
createVigorTimelineRecorder,
|
|
1985
2668
|
index_default as default,
|
|
2669
|
+
isVigorAllError,
|
|
2670
|
+
isVigorDefault,
|
|
2671
|
+
isVigorEmpty,
|
|
2672
|
+
isVigorFetchError,
|
|
2673
|
+
isVigorInternalMiddleware,
|
|
2674
|
+
isVigorParseError,
|
|
2675
|
+
isVigorRetryError,
|
|
2676
|
+
markVigorInternal,
|
|
2677
|
+
readVigorParseBody,
|
|
1986
2678
|
vigor
|
|
1987
2679
|
};
|