vigor-fetch 4.1.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -22,6 +22,8 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  VigorAll: () => VigorAll,
24
24
  VigorAllBase: () => VigorAllBase,
25
+ VigorAllContextBase: () => VigorAllContextBase,
26
+ VigorAllEachContextBase: () => VigorAllEachContextBase,
25
27
  VigorAllError: () => VigorAllError,
26
28
  VigorAllErrorMessageFuncs: () => VigorAllErrorMessageFuncs,
27
29
  VigorAllPolicyBase: () => VigorAllPolicyBase,
@@ -29,9 +31,13 @@ __export(index_exports, {
29
31
  VigorAllPolicyMiddlewaresBase: () => VigorAllPolicyMiddlewaresBase,
30
32
  VigorAllPolicySettings: () => VigorAllPolicySettings,
31
33
  VigorAllPolicySettingsBase: () => VigorAllPolicySettingsBase,
34
+ VigorCastPlaceholder: () => VigorCastPlaceholder,
35
+ VigorDefault: () => VigorDefault,
36
+ VigorEmpty: () => VigorEmpty,
32
37
  VigorError: () => VigorError,
33
38
  VigorFetch: () => VigorFetch,
34
39
  VigorFetchBase: () => VigorFetchBase,
40
+ VigorFetchContextBase: () => VigorFetchContextBase,
35
41
  VigorFetchError: () => VigorFetchError,
36
42
  VigorFetchErrorMessageFuncs: () => VigorFetchErrorMessageFuncs,
37
43
  VigorFetchPolicyBase: () => VigorFetchPolicyBase,
@@ -43,6 +49,7 @@ __export(index_exports, {
43
49
  VigorParse: () => VigorParse,
44
50
  VigorParseBase: () => VigorParseBase,
45
51
  VigorParseContentTypeStrategy: () => VigorParseContentTypeStrategy,
52
+ VigorParseContextBase: () => VigorParseContextBase,
46
53
  VigorParseError: () => VigorParseError,
47
54
  VigorParseErrorMessageFuncs: () => VigorParseErrorMessageFuncs,
48
55
  VigorParsePolicyBase: () => VigorParsePolicyBase,
@@ -55,6 +62,7 @@ __export(index_exports, {
55
62
  VigorParseSniffStrategy: () => VigorParseSniffStrategy,
56
63
  VigorRetry: () => VigorRetry,
57
64
  VigorRetryBase: () => VigorRetryBase,
65
+ VigorRetryContextBase: () => VigorRetryContextBase,
58
66
  VigorRetryError: () => VigorRetryError,
59
67
  VigorRetryErrorMessageFuncs: () => VigorRetryErrorMessageFuncs,
60
68
  VigorRetryPolicyAlgorithms: () => VigorRetryPolicyAlgorithms,
@@ -73,11 +81,19 @@ __export(index_exports, {
73
81
  VigorRetryPolicySettings: () => VigorRetryPolicySettings,
74
82
  VigorRetryPolicySettingsBase: () => VigorRetryPolicySettingsBase,
75
83
  VigorStatus: () => VigorStatus,
84
+ adoptVigorFetchError: () => adoptVigorFetchError,
85
+ createBrand: () => createBrand,
86
+ createVigorTimelineRecorder: () => createVigorTimelineRecorder,
76
87
  default: () => index_default,
77
88
  isVigorAllError: () => isVigorAllError,
89
+ isVigorDefault: () => isVigorDefault,
90
+ isVigorEmpty: () => isVigorEmpty,
78
91
  isVigorFetchError: () => isVigorFetchError,
92
+ isVigorInternalMiddleware: () => isVigorInternalMiddleware,
79
93
  isVigorParseError: () => isVigorParseError,
80
94
  isVigorRetryError: () => isVigorRetryError,
95
+ markVigorInternal: () => markVigorInternal,
96
+ readVigorParseBody: () => readVigorParseBody,
81
97
  vigor: () => vigor
82
98
  });
83
99
  module.exports = __toCommonJS(index_exports);
@@ -154,6 +170,14 @@ var VigorStatus = class {
154
170
  };
155
171
  return merge(source, target, strategy);
156
172
  }
173
+ /**
174
+ * Snapshots a runtime context for a timeline entry: a `_merge` deep clone
175
+ * of everything but `timeline`, so later changes to `ctx` don't reach it.
176
+ */
177
+ _snapshot(ctx) {
178
+ const { timeline: _, ...rest } = ctx;
179
+ return this._merge(rest, {});
180
+ }
157
181
  /** The default/base config this builder was constructed with. */
158
182
  get base() {
159
183
  return this._base;
@@ -167,6 +191,7 @@ var VigorStatus = class {
167
191
  // src/all/settings.ts
168
192
  var VigorAllPolicySettingsBase = {
169
193
  __brand: createBrand("All", "Policy<Settings<Schema"),
194
+ debug: false,
170
195
  concurrency: 5,
171
196
  onlySuccess: false,
172
197
  timeout: VigorEmpty,
@@ -195,6 +220,14 @@ var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
195
220
  failFast(bool) {
196
221
  return this._next({ policy: { settings: { failFast: bool } } });
197
222
  }
223
+ /**
224
+ * Turns timeline recording on or off (off by default). Off, the
225
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
226
+ * are taken, so it costs nothing unless you're debugging.
227
+ */
228
+ debug(bool) {
229
+ return this._next({ policy: { settings: { debug: bool } } });
230
+ }
198
231
  };
199
232
 
200
233
  // src/all/middlewares.ts
@@ -251,7 +284,8 @@ var VigorAllContextBase = {
251
284
  __brand: createBrand("All", "Context<Schema"),
252
285
  result: VigorDefault,
253
286
  policy: VigorAllPolicyBase,
254
- record: {}
287
+ record: {},
288
+ timeline: []
255
289
  };
256
290
  var VigorAllEachContextBase = {
257
291
  __brand: createBrand("All", "EachContext<Schema"),
@@ -269,6 +303,7 @@ var VigorError = class extends Error {
269
303
  code;
270
304
  data;
271
305
  method;
306
+ /** The run context when the error was raised; its presence depends on the code (see {@link VigorErrorContext}). */
272
307
  context;
273
308
  /**
274
309
  * @param code - Machine-readable error code.
@@ -303,9 +338,64 @@ var VigorAllError = class extends VigorError {
303
338
  super(code, messageFn(options.data), options);
304
339
  }
305
340
  };
306
- var isVigorAllError = (error) => error instanceof VigorAllError;
341
+ function isVigorAllError(error, ...codes) {
342
+ return error instanceof VigorAllError && (codes.length === 0 || codes.includes(error.code));
343
+ }
344
+
345
+ // src/core/timeline.ts
346
+ var internalMiddlewares = /* @__PURE__ */ new WeakSet();
347
+ function markVigorInternal(func) {
348
+ internalMiddlewares.add(func);
349
+ return func;
350
+ }
351
+ function isVigorInternalMiddleware(middleware) {
352
+ const func = typeof middleware === "function" ? middleware : middleware?.func;
353
+ return typeof func === "function" && internalMiddlewares.has(func);
354
+ }
355
+ function createVigorTimelineRecorder(timeline, snapshot, enabled) {
356
+ const add = (action, content) => {
357
+ if (!enabled) return;
358
+ timeline.push({ action, content, now: Date.now(), ctx: snapshot() });
359
+ };
360
+ const record = add;
361
+ const stage = async (stage2, middlewares, run) => {
362
+ if (middlewares.length === 0) return;
363
+ if (!enabled) {
364
+ for (const middleware of middlewares) await run(middleware, (api) => api);
365
+ return;
366
+ }
367
+ record("MIDDLEWARE_LOOP_STARTED", { stage: stage2, middlewares });
368
+ const started = performance.now();
369
+ try {
370
+ for (const [index, middleware] of middlewares.entries()) {
371
+ const internal = isVigorInternalMiddleware(middleware);
372
+ const ranAt = performance.now();
373
+ try {
374
+ await run(middleware, (api) => {
375
+ const traced = {};
376
+ for (const [method, func] of Object.entries(api)) {
377
+ traced[method] = (...args) => {
378
+ record("MIDDLEWARE_API_CALLED", { stage: stage2, index, middleware, internal, method, args });
379
+ return func(...args);
380
+ };
381
+ }
382
+ return traced;
383
+ });
384
+ } catch (error) {
385
+ record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: true, error });
386
+ throw error;
387
+ }
388
+ record("MIDDLEWARE_RAN", { stage: stage2, index, middleware, internal, took: performance.now() - ranAt, threw: false, error: null });
389
+ }
390
+ } finally {
391
+ record("MIDDLEWARE_LOOP_ENDED", { stage: stage2, middlewares, took: performance.now() - started });
392
+ }
393
+ };
394
+ return { add, stage };
395
+ }
307
396
 
308
397
  // src/all/main.ts
398
+ var MAX_TIMEOUT = 2 ** 31 - 1;
309
399
  var VigorAllBase = {
310
400
  __brand: createBrand("All", "Schema"),
311
401
  policy: VigorAllPolicyBase,
@@ -328,7 +418,7 @@ var VigorAll = class _VigorAll extends VigorStatus {
328
418
  }
329
419
  settings(input) {
330
420
  if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
331
- const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
421
+ const result = typeof input === "function" ? input(new VigorAllPolicySettings(this.config)) : input;
332
422
  return this._next({
333
423
  policy: { settings: result.config.policy.settings }
334
424
  });
@@ -345,21 +435,28 @@ var VigorAll = class _VigorAll extends VigorStatus {
345
435
  return this._next({ policy: { middlewares: input } });
346
436
  }
347
437
  /** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
348
- async _runTask(task, index, policy, batchSignal) {
438
+ async _runTask(task, index, policy, batchSignal, timeline, debug) {
349
439
  let ctx = this._merge(VigorAllEachContextBase, { index });
440
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._merge(ctx, {}), debug);
350
441
  const timeoutController = new AbortController();
351
442
  const signal = AbortSignal.any([batchSignal, timeoutController.signal]);
352
443
  let timeoutId;
353
444
  let onAbort;
445
+ add("TASK_STARTED", { index });
446
+ const started = performance.now();
447
+ const settle = (res) => {
448
+ add("TASK_ENDED", { index, success: res.success, took: performance.now() - started });
449
+ return res;
450
+ };
354
451
  try {
355
- for (const beforeEach of policy.middlewares.beforeEach) await beforeEach(ctx);
452
+ await stage("beforeEach", policy.middlewares.beforeEach, (beforeEach) => beforeEach(ctx));
356
453
  signal.throwIfAborted();
357
454
  const limit = policy.settings.timeout;
358
- if (!isVigorEmpty(limit)) {
455
+ if (!isVigorEmpty(limit) && Number.isFinite(limit) && limit > 0) {
359
456
  timeoutId = setTimeout(() => timeoutController.abort(new VigorAllError("TIMED_OUT", {
360
457
  method: "request",
361
458
  data: { limit, index }
362
- })), limit);
459
+ })), Math.min(limit, MAX_TIMEOUT));
363
460
  }
364
461
  ctx.result = await Promise.race([
365
462
  task(signal),
@@ -368,17 +465,18 @@ var VigorAll = class _VigorAll extends VigorStatus {
368
465
  signal.addEventListener("abort", onAbort);
369
466
  })
370
467
  ]);
371
- for (const afterEach of policy.middlewares.afterEach) await afterEach(ctx);
372
- return { success: true, value: ctx.result };
468
+ await stage("afterEach", policy.middlewares.afterEach, (afterEach) => afterEach(ctx));
469
+ return settle({ success: true, value: ctx.result });
373
470
  } catch (error) {
374
471
  ctx.error = error;
472
+ add("TASK_ERROR", { index, error });
375
473
  const setResult = (r) => {
376
474
  ctx.flags.overridden = true;
377
475
  ctx.result = r;
378
476
  };
379
- for (const onErrorEach of policy.middlewares.onErrorEach) await onErrorEach(ctx, { setResult });
380
- if (ctx.flags.overridden) return { success: true, value: ctx.result };
381
- return { success: false, value: error };
477
+ await stage("onErrorEach", policy.middlewares.onErrorEach, (onErrorEach, trace) => onErrorEach(ctx, trace({ setResult })));
478
+ if (ctx.flags.overridden) return settle({ success: true, value: ctx.result });
479
+ return settle({ success: false, value: error });
382
480
  } finally {
383
481
  clearTimeout(timeoutId);
384
482
  if (onAbort) signal.removeEventListener("abort", onAbort);
@@ -396,43 +494,63 @@ var VigorAll = class _VigorAll extends VigorStatus {
396
494
  { cast: "replace" }
397
495
  );
398
496
  }
399
- /** Runs all tasks and returns the results array directly, throwing on final failure. */
497
+ /**
498
+ * Runs all tasks and returns the results array directly, throwing on final failure.
499
+ *
500
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
501
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
502
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
503
+ */
400
504
  async request() {
401
505
  const res = await this.requestVerbose();
402
506
  if (res.success) return res.data;
403
507
  throw res.error;
404
508
  }
405
- /** Runs all tasks and returns a result/error envelope instead of throwing. */
509
+ /**
510
+ * Runs all tasks and returns a result/error envelope instead of throwing,
511
+ * along with the `timeline` of everything the batch went through.
512
+ */
406
513
  async requestVerbose() {
407
514
  return await this.requestRuntime();
408
515
  }
409
516
  /** Internal execution loop implementing the bounded-concurrency worker pool and the batch-level before/after/onResult pipeline. */
410
- async requestRuntime() {
517
+ async requestRuntime(timeline = []) {
411
518
  const config = this._merge(this.config, {});
412
519
  const policy = config.policy;
413
520
  let ctx = this._merge(VigorAllContextBase, {
414
521
  policy
415
522
  }, void 0, "replace");
523
+ ctx.timeline = timeline;
524
+ const startedAt = performance.now();
525
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
526
+ const end = (success, error) => add("REQUEST_END", {
527
+ success,
528
+ outcome: success ? "result" : "failed",
529
+ error,
530
+ took: performance.now() - startedAt,
531
+ restarts: 0
532
+ });
416
533
  const setResult = (r) => {
417
534
  ctx.result = r;
418
535
  };
419
536
  const throwError = (err) => {
420
537
  throw err;
421
538
  };
539
+ const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
540
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { tasks: policy.target.length, concurrency } });
422
541
  try {
423
542
  if (policy.target.length === 0) throw new VigorAllError("EMPTY_TARGET", {
424
543
  method: "request",
425
544
  data: {},
426
545
  context: ctx
427
546
  });
428
- for (const mw of policy.middlewares.before) {
547
+ await stage("before", policy.middlewares.before, async (mw, trace) => {
429
548
  if (mw._mode === "fluent") {
430
549
  await mw.func(ctx);
431
550
  } else {
432
- ctx = await mw.func(ctx, { throwError }) ?? ctx;
551
+ ctx = await mw.func(ctx, trace({ throwError })) ?? ctx;
433
552
  }
434
- }
435
- const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
553
+ });
436
554
  const results = new Array(policy.target.length);
437
555
  const batchController = new AbortController();
438
556
  const batchSignal = AbortSignal.any([...policy.abortSignals, batchController.signal]);
@@ -442,7 +560,7 @@ var VigorAll = class _VigorAll extends VigorStatus {
442
560
  const i = cursor++;
443
561
  if (i >= policy.target.length) return;
444
562
  try {
445
- results[i] = await this._runTask(policy.target[i], i, policy, batchSignal);
563
+ results[i] = await this._runTask(policy.target[i], i, policy, batchSignal, timeline, policy.settings.debug);
446
564
  } catch (error) {
447
565
  batchController.abort(error);
448
566
  return;
@@ -456,31 +574,36 @@ var VigorAll = class _VigorAll extends VigorStatus {
456
574
  Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
457
575
  );
458
576
  batchSignal.throwIfAborted();
459
- ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
460
- for (const mw of policy.middlewares.after) {
577
+ 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 });
578
+ await stage("after", policy.middlewares.after, async (mw, trace) => {
461
579
  if (mw._mode === "fluent") {
462
580
  await mw.func(ctx);
463
581
  } else {
464
- ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
582
+ ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
465
583
  }
466
- }
467
- for (const mw of policy.middlewares.onResult) {
584
+ });
585
+ await stage("onResult", policy.middlewares.onResult, async (mw, trace) => {
468
586
  if (mw._mode === "fluent") {
469
587
  ctx.result = await mw.func(ctx.result);
470
588
  } else {
471
- ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
589
+ ctx = await mw.func(ctx, trace({ setResult, throwError })) ?? ctx;
472
590
  }
473
- }
591
+ });
592
+ end(true, null);
474
593
  return {
475
594
  success: true,
476
595
  data: ctx.result,
477
- error: null
596
+ error: null,
597
+ timeline
478
598
  };
479
599
  } catch (error) {
600
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
601
+ end(false, error);
480
602
  return {
481
603
  success: false,
482
604
  data: null,
483
- error
605
+ error,
606
+ timeline
484
607
  };
485
608
  }
486
609
  }
@@ -489,9 +612,46 @@ var VigorAll = class _VigorAll extends VigorStatus {
489
612
  // src/fetch/settings.ts
490
613
  var VigorFetchPolicySettingsBase = {
491
614
  __brand: createBrand("Fetch", "Policy<Settings<Schema"),
615
+ debug: false,
492
616
  retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"],
493
- unretryStatus: [400, 401, 403, 404, 405, 413, 422],
494
- redirect: true,
617
+ // Statuses a retry of the same request won't change. Left retryable on
618
+ // purpose: 408 (timeout), 421 (misdirected — another connection may
619
+ // work), 423 (locked), 425 (too early), 429 (rate limit), and 5xx
620
+ // outages (500, 502, 503, 504, 507).
621
+ unretryStatus: [
622
+ 400,
623
+ 401,
624
+ 402,
625
+ 403,
626
+ 404,
627
+ 405,
628
+ 406,
629
+ 407,
630
+ 409,
631
+ 410,
632
+ 411,
633
+ 412,
634
+ 413,
635
+ 414,
636
+ 415,
637
+ 416,
638
+ 417,
639
+ 422,
640
+ 424,
641
+ 426,
642
+ 428,
643
+ 431,
644
+ 451,
645
+ 501,
646
+ 505,
647
+ 506,
648
+ 508,
649
+ 510,
650
+ 511
651
+ ],
652
+ maxRetryAfter: 5 * 60 * 1e3,
653
+ redirect: false,
654
+ confinePath: true,
495
655
  maxRestarts: 3,
496
656
  default: VigorEmpty
497
657
  };
@@ -510,11 +670,24 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
510
670
  unretryStatus(...nums) {
511
671
  return this._next({ policy: { settings: { unretryStatus: nums } } }, { policy: { settings: { unretryStatus: "replace" } } });
512
672
  }
673
+ /** Sets the upper bound, in milliseconds, on a server-suggested retry delay. */
674
+ maxRetryAfter(num) {
675
+ return this._next({ policy: { settings: { maxRetryAfter: num } } });
676
+ }
677
+ /**
678
+ * When enabled, a redirected response (or a readable `3xx` with a
679
+ * `Location` header) navigates the page to its target
680
+ * (`window.location.href`). Without `window.location` — e.g. in Node —
681
+ * this behaves like `false`.
682
+ */
513
683
  /**
514
- * When enabled, a `3xx` response with a `Location` header navigates the
515
- * page to that URL (`window.location.href`). Without `window.location`
516
- * — e.g. in Node — this behaves like `false`.
684
+ * When enabled (the default), a request whose URL would leave its
685
+ * origin's domain or path (e.g. through a `".."` path segment) fails with
686
+ * `PATH_ESCAPED` instead of being sent.
517
687
  */
688
+ confinePath(bool) {
689
+ return this._next({ policy: { settings: { confinePath: bool } } });
690
+ }
518
691
  redirect(bool) {
519
692
  return this._next({ policy: { settings: { redirect: bool } } });
520
693
  }
@@ -526,6 +699,15 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
526
699
  default(func) {
527
700
  return this._next({ policy: { settings: { default: func } } });
528
701
  }
702
+ /**
703
+ * Turns timeline recording on or off (off by default). Off, the
704
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
705
+ * are taken, so it costs nothing unless you're debugging. With it on,
706
+ * the nested retry/parse engines record theirs too.
707
+ */
708
+ debug(bool) {
709
+ return this._next({ policy: { settings: { debug: bool } } });
710
+ }
529
711
  };
530
712
 
531
713
  // src/fetch/middlewares.ts
@@ -560,6 +742,7 @@ var VigorFetchPolicyMiddlewares = class _VigorFetchPolicyMiddlewares extends Vig
560
742
  // src/retry/settings.ts
561
743
  var VigorRetryPolicySettingsBase = {
562
744
  __brand: createBrand("Retry", "Policy<Settings<Schema"),
745
+ debug: false,
563
746
  default: VigorEmpty,
564
747
  maxAttempts: 5,
565
748
  maxRestarts: 3,
@@ -596,6 +779,14 @@ var VigorRetryPolicySettings = class _VigorRetryPolicySettings extends VigorStat
596
779
  policy: { settings: { timeout: num } }
597
780
  });
598
781
  }
782
+ /**
783
+ * Turns timeline recording on or off (off by default). Off, the
784
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
785
+ * are taken, so it costs nothing unless you're debugging.
786
+ */
787
+ debug(bool) {
788
+ return this._next({ policy: { settings: { debug: bool } } });
789
+ }
599
790
  };
600
791
 
601
792
  // src/retry/middlewares.ts
@@ -664,7 +855,9 @@ var VigorRetryError = class extends VigorError {
664
855
  super(code, messageFn(options.data), options);
665
856
  }
666
857
  };
667
- var isVigorRetryError = (error) => error instanceof VigorRetryError;
858
+ function isVigorRetryError(error, ...codes) {
859
+ return error instanceof VigorRetryError && (codes.length === 0 || codes.includes(error.code));
860
+ }
668
861
 
669
862
  // src/retry/algorithms.ts
670
863
  function VigorJitter(jitter) {
@@ -910,14 +1103,17 @@ var VigorRetryContextBase = {
910
1103
  doRetry: true,
911
1104
  doRestart: false,
912
1105
  brokeRetry: false,
1106
+ aborted: false,
1107
+ timedOut: false,
913
1108
  overridden: false
914
1109
  },
915
1110
  record: {},
1111
+ timeline: [],
916
1112
  policy: VigorRetryPolicyBase
917
1113
  };
918
1114
 
919
1115
  // src/retry/main.ts
920
- var MAX_TIMEOUT = 2 ** 31 - 1;
1116
+ var MAX_TIMEOUT2 = 2 ** 31 - 1;
921
1117
  var VigorRetryBase = {
922
1118
  __brand: createBrand("Retry", "Schema"),
923
1119
  policy: VigorRetryPolicyBase,
@@ -944,7 +1140,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
944
1140
  }
945
1141
  settings(input) {
946
1142
  if (typeof input === "function" || input instanceof VigorRetryPolicySettings) {
947
- const result = typeof input === "function" ? input(new VigorRetryPolicySettings()) : input;
1143
+ const result = typeof input === "function" ? input(new VigorRetryPolicySettings(this.config)) : input;
948
1144
  return this._next({
949
1145
  policy: { settings: result.config.policy.settings }
950
1146
  });
@@ -988,33 +1184,63 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
988
1184
  { cast: "replace" }
989
1185
  );
990
1186
  }
991
- /** Runs the target and returns its result directly, throwing on final failure. */
1187
+ /**
1188
+ * Runs the target and returns its result directly, throwing on final failure.
1189
+ *
1190
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
1191
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
1192
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
1193
+ */
992
1194
  async request() {
993
1195
  const res = await this.requestVerbose();
994
1196
  if (res.success) return res.data;
995
1197
  throw res.error;
996
1198
  }
997
- /** Runs the target and returns a result/error envelope instead of throwing. */
1199
+ /**
1200
+ * Runs the target and returns a result/error envelope instead of throwing,
1201
+ * along with the `timeline` of everything the run went through.
1202
+ */
998
1203
  async requestVerbose() {
999
- try {
1000
- return await this.requestRuntime();
1001
- } catch (error) {
1002
- return { success: false, data: null, error };
1003
- }
1204
+ return await this.requestRuntime();
1004
1205
  }
1005
- /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
1006
- async requestRuntime(restartAttempt = 1) {
1206
+ /**
1207
+ * Internal execution loop implementing the attempt/retry/restart lifecycle.
1208
+ * Never throws: every failure, including one from `onError` or `default`,
1209
+ * comes back as an envelope carrying the timeline. A restart passes the
1210
+ * same `timeline` on, so it keeps growing across runs; `startedAt` is the
1211
+ * first run's start, for `REQUEST_END`'s `took`.
1212
+ */
1213
+ async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1007
1214
  const config = this._merge(this.config, {});
1008
1215
  let ctx = this._merge(VigorRetryContextBase, {
1009
1216
  policy: config.policy
1010
1217
  }, void 0, "replace");
1011
- if (isVigorEmpty(ctx.policy.target)) throw new VigorRetryError("VALUE_REQUIRED", {
1218
+ ctx.timeline = timeline;
1219
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
1220
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
1221
+ const end = (success, outcome, error) => add("REQUEST_END", {
1222
+ success,
1223
+ outcome,
1224
+ error,
1225
+ took: performance.now() - startedAt,
1226
+ restarts: restartAttempt - 1
1227
+ });
1228
+ const succeed = (data, outcome) => {
1229
+ end(true, outcome, null);
1230
+ return { success: true, data, error: null, timeline };
1231
+ };
1232
+ const fail = (error) => {
1233
+ end(false, "failed", error);
1234
+ return { success: false, data: null, error, timeline };
1235
+ };
1236
+ const decide = (retry, reason) => add("RETRY_DECISION", { attempt: ctx.system.attempt, retry, reason });
1237
+ if (isVigorEmpty(ctx.policy.target)) return fail(new VigorRetryError("VALUE_REQUIRED", {
1012
1238
  method: "request",
1013
1239
  data: {
1014
1240
  key: "target"
1015
1241
  },
1016
1242
  context: ctx
1017
- });
1243
+ }));
1018
1244
  const target = ctx.policy.target;
1019
1245
  const throwError = (err) => {
1020
1246
  throw err;
@@ -1023,6 +1249,9 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1023
1249
  try {
1024
1250
  while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
1025
1251
  ctx.system.attempt++;
1252
+ add("ATTEMPT_INCREASED", { attempt: ctx.system.attempt });
1253
+ add("PROCESS_HANDLING", { type: "RETRY_START", data: { attempt: ctx.system.attempt } });
1254
+ ctx.flags.timedOut = false;
1026
1255
  try {
1027
1256
  const breakRetry = (err) => {
1028
1257
  ctx.flags.brokeRetry = true;
@@ -1041,28 +1270,34 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1041
1270
  let onAbort;
1042
1271
  let timeoutId;
1043
1272
  try {
1044
- for (const middleware of ctx.policy.middlewares.before) {
1273
+ await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1045
1274
  if (middleware._mode === "fluent") {
1046
1275
  await middleware.func(ctx);
1047
1276
  } else {
1048
- ctx = await middleware.func(ctx, {
1277
+ ctx = await middleware.func(ctx, trace({
1049
1278
  abort: (reason) => userController.abort(reason),
1050
1279
  throwError,
1051
1280
  breakRetry
1052
- }) ?? ctx;
1281
+ })) ?? ctx;
1053
1282
  }
1054
- }
1283
+ });
1055
1284
  mergedSignals.throwIfAborted();
1056
1285
  const limit = ctx.policy.settings.timeout;
1057
1286
  if (Number.isFinite(limit) && limit > 0) {
1058
- timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
1059
- method: "request",
1060
- data: {
1061
- limit
1062
- },
1063
- context: ctx
1064
- })), Math.min(limit, MAX_TIMEOUT));
1287
+ timeoutId = setTimeout(() => {
1288
+ ctx.flags.timedOut = true;
1289
+ timeoutController.abort(new VigorRetryError("TIMED_OUT", {
1290
+ method: "request",
1291
+ data: {
1292
+ limit
1293
+ },
1294
+ context: ctx
1295
+ }));
1296
+ }, Math.min(limit, MAX_TIMEOUT2));
1065
1297
  }
1298
+ const attempt = ctx.system.attempt;
1299
+ add("TARGET_REQUEST_STARTED", { attempt });
1300
+ const started = performance.now();
1066
1301
  ctx.result = await Promise.race([
1067
1302
  target(mergedSignals),
1068
1303
  new Promise((_, rej) => {
@@ -1070,78 +1305,97 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1070
1305
  mergedSignals.addEventListener("abort", onAbort);
1071
1306
  })
1072
1307
  ]);
1073
- for (const middleware of ctx.policy.middlewares.after) {
1308
+ add("TARGET_REQUEST_ENDED", { attempt, took: performance.now() - started });
1309
+ await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
1074
1310
  if (middleware._mode === "fluent") {
1075
1311
  await middleware.func(ctx);
1076
1312
  } else {
1077
- ctx = await middleware.func(ctx, {
1313
+ ctx = await middleware.func(ctx, trace({
1078
1314
  throwError
1079
- }) ?? ctx;
1315
+ })) ?? ctx;
1080
1316
  }
1081
- }
1317
+ });
1082
1318
  const setResult = (res) => {
1083
1319
  ctx.result = res;
1084
1320
  };
1085
- for (const middleware of ctx.policy.middlewares.onResult) {
1321
+ await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1086
1322
  if (middleware._mode === "fluent") {
1087
1323
  ctx.result = await middleware.func(ctx.result);
1088
1324
  } else {
1089
- ctx = await middleware.func(ctx, {
1325
+ ctx = await middleware.func(ctx, trace({
1090
1326
  setResult,
1091
1327
  throwError
1092
- }) ?? ctx;
1328
+ })) ?? ctx;
1093
1329
  }
1094
- }
1095
- return {
1096
- success: true,
1097
- data: ctx.result,
1098
- error: null
1099
- };
1330
+ });
1331
+ return succeed(ctx.result, "result");
1100
1332
  } finally {
1101
1333
  clearTimeout(timeoutId);
1102
1334
  if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
1103
1335
  }
1104
1336
  } catch (error) {
1105
1337
  ctx.error = error;
1106
- if (outerSignals.aborted) ctx.flags.brokeRetry = true;
1107
- if (ctx.flags.brokeRetry) throw ctx.error;
1338
+ if (outerSignals.aborted) ctx.flags.aborted = true;
1339
+ add("PROCESS_HANDLING", { type: "RETRY_ERROR", data: {
1340
+ attempt: ctx.system.attempt,
1341
+ error,
1342
+ timedOut: ctx.flags.timedOut,
1343
+ aborted: ctx.flags.aborted
1344
+ } });
1345
+ if (ctx.flags.aborted) {
1346
+ decide(false, "aborted");
1347
+ throw ctx.error;
1348
+ }
1349
+ if (ctx.flags.brokeRetry) {
1350
+ decide(false, "breakRetry");
1351
+ throw ctx.error;
1352
+ }
1108
1353
  ctx.flags.doRetry = true;
1109
1354
  const proceedRetry = () => ctx.flags.doRetry = true;
1110
1355
  const cancelRetry = () => ctx.flags.doRetry = false;
1111
- for (const middleware of ctx.policy.middlewares.retryIf) {
1356
+ await stage("retryIf", ctx.policy.middlewares.retryIf, async (middleware, trace) => {
1112
1357
  if (middleware._mode === "fluent") {
1113
1358
  ctx.flags.doRetry = await middleware.func(ctx.error);
1114
1359
  } else {
1115
- ctx = await middleware.func(ctx, {
1360
+ ctx = await middleware.func(ctx, trace({
1116
1361
  proceedRetry,
1117
1362
  cancelRetry
1118
- }) ?? ctx;
1363
+ })) ?? ctx;
1119
1364
  }
1365
+ });
1366
+ if (!ctx.flags.doRetry) {
1367
+ decide(false, "cancelled");
1368
+ throw ctx.error;
1120
1369
  }
1121
- if (!ctx.flags.doRetry) throw ctx.error;
1370
+ if (ctx.system.attempt >= ctx.policy.settings.maxAttempts) {
1371
+ decide(false, "exhausted");
1372
+ break;
1373
+ }
1374
+ decide(true, "retry");
1122
1375
  ctx.system.delay = ctx.policy.algorithms._calculateDelay(ctx.system.attempt, ctx.policy.algorithms);
1123
1376
  const setDelay = (num) => {
1124
1377
  ctx.system.delay = num;
1125
1378
  };
1126
- for (const middleware of ctx.policy.middlewares.onRetry) {
1379
+ await stage("onRetry", ctx.policy.middlewares.onRetry, async (middleware, trace) => {
1127
1380
  if (middleware._mode === "fluent") {
1128
1381
  await middleware.func(ctx.error);
1129
1382
  } else {
1130
- ctx = await middleware.func(ctx, {
1383
+ ctx = await middleware.func(ctx, trace({
1131
1384
  throwError,
1132
1385
  setDelay
1133
- }) ?? ctx;
1386
+ })) ?? ctx;
1134
1387
  }
1135
- }
1136
- const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT);
1388
+ });
1389
+ const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT2);
1390
+ add("RETRY_DELAY", { attempt: ctx.system.attempt, delay });
1137
1391
  await new Promise((res, rej) => {
1138
1392
  if (outerSignals.aborted) {
1139
- ctx.flags.brokeRetry = true;
1393
+ ctx.flags.aborted = true;
1140
1394
  return rej(outerSignals.reason);
1141
1395
  }
1142
1396
  const onAbort = () => {
1143
1397
  clearTimeout(id);
1144
- ctx.flags.brokeRetry = true;
1398
+ ctx.flags.aborted = true;
1145
1399
  rej(outerSignals.reason);
1146
1400
  };
1147
1401
  const id = setTimeout(() => {
@@ -1163,6 +1417,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1163
1417
  });
1164
1418
  } catch (error) {
1165
1419
  ctx.error = error;
1420
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1166
1421
  ctx.flags.doRestart = false;
1167
1422
  ctx.flags.overridden = false;
1168
1423
  const setResult = (res) => {
@@ -1171,20 +1426,24 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1171
1426
  };
1172
1427
  const proceedRestart = () => ctx.flags.doRestart = true;
1173
1428
  const cancelRestart = () => ctx.flags.doRestart = false;
1174
- for (const middleware of ctx.policy.middlewares.onError) {
1175
- if (middleware._mode === "fluent") {
1176
- await middleware.func(ctx.error);
1177
- } else {
1178
- ctx = await middleware.func(ctx, {
1179
- setResult,
1180
- throwError,
1181
- proceedRestart,
1182
- cancelRestart
1183
- }) ?? ctx;
1184
- }
1429
+ try {
1430
+ await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
1431
+ if (middleware._mode === "fluent") {
1432
+ await middleware.func(ctx.error);
1433
+ } else {
1434
+ ctx = await middleware.func(ctx, trace({
1435
+ setResult,
1436
+ throwError,
1437
+ proceedRestart,
1438
+ cancelRestart
1439
+ })) ?? ctx;
1440
+ }
1441
+ });
1442
+ } catch (err) {
1443
+ return fail(err);
1185
1444
  }
1186
1445
  if (ctx.flags.doRestart) {
1187
- if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
1446
+ if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorRetryError("RESTART_EXHAUSTED", {
1188
1447
  method: "request",
1189
1448
  cause: ctx.error,
1190
1449
  data: {
@@ -1192,27 +1451,19 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1192
1451
  error: ctx.error
1193
1452
  },
1194
1453
  context: ctx
1195
- });
1196
- return await this.requestRuntime(restartAttempt + 1);
1454
+ }));
1455
+ add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
1456
+ return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
1197
1457
  }
1198
- if (ctx.flags.overridden) return {
1199
- success: true,
1200
- data: ctx.result,
1201
- error: null
1202
- };
1458
+ if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
1203
1459
  if (!isVigorEmpty(ctx.policy.settings.default)) {
1204
- const data = await ctx.policy.settings.default(ctx);
1205
- return {
1206
- success: true,
1207
- data,
1208
- error: null
1209
- };
1460
+ try {
1461
+ return succeed(await ctx.policy.settings.default(ctx), "default");
1462
+ } catch (err) {
1463
+ return fail(err);
1464
+ }
1210
1465
  }
1211
- return {
1212
- success: false,
1213
- data: null,
1214
- error: ctx.error
1215
- };
1466
+ return fail(ctx.error);
1216
1467
  }
1217
1468
  }
1218
1469
  };
@@ -1220,6 +1471,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1220
1471
  // src/parse/settings.ts
1221
1472
  var VigorParsePolicySettingsBase = {
1222
1473
  __brand: createBrand("Parse", "Policy<Settings<Schema"),
1474
+ debug: false,
1223
1475
  raw: false,
1224
1476
  default: VigorEmpty,
1225
1477
  maxRestarts: 3
@@ -1249,6 +1501,14 @@ var VigorParsePolicySettings = class _VigorParsePolicySettings extends VigorStat
1249
1501
  policy: { settings: { maxRestarts: num } }
1250
1502
  });
1251
1503
  }
1504
+ /**
1505
+ * Turns timeline recording on or off (off by default). Off, the
1506
+ * `timeline` of `requestVerbose()` stays empty and no context snapshots
1507
+ * are taken, so it costs nothing unless you're debugging.
1508
+ */
1509
+ debug(bool) {
1510
+ return this._next({ policy: { settings: { debug: bool } } });
1511
+ }
1252
1512
  };
1253
1513
 
1254
1514
  // src/parse/middlewares.ts
@@ -1281,11 +1541,12 @@ var VigorParsePolicyMiddlewares = class _VigorParsePolicyMiddlewares extends Vig
1281
1541
  };
1282
1542
 
1283
1543
  // src/parse/error.ts
1544
+ var describeVigorParseFailure = (error) => error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1284
1545
  var VigorParseErrorMessageFuncs = {
1285
1546
  VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1286
1547
  INVALID_CONTENT_TYPE: ({ received }) => `Invalid Content-Type header: ${String(received)}`,
1287
1548
  PARSER_NOT_FOUND: ({ received, expected }) => `Parser not found for Content-Type "${String(received)}" (known: ${expected.join(", ")})`,
1288
- PARSER_ALL_FAILED: ({ tried }) => `All parsers failed, tried: ${tried.join(", ")}`,
1549
+ PARSER_ALL_FAILED: ({ tried, errors }) => `All parsers failed: ${tried.map((name, i) => `${name} (${describeVigorParseFailure(errors[i])})`).join(", ")}`,
1289
1550
  RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1290
1551
  };
1291
1552
  var VigorParseError = class extends VigorError {
@@ -1298,63 +1559,141 @@ var VigorParseError = class extends VigorError {
1298
1559
  super(code, messageFn(options.data), options);
1299
1560
  }
1300
1561
  };
1301
- var isVigorParseError = (error) => error instanceof VigorParseError;
1562
+ function isVigorParseError(error, ...codes) {
1563
+ return error instanceof VigorParseError && (codes.length === 0 || codes.includes(error.code));
1564
+ }
1302
1565
 
1303
1566
  // src/parse/strategies.ts
1304
1567
  var VigorParsePolicyStrategiesBase = {
1305
1568
  __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1306
1569
  funcs: []
1307
1570
  };
1308
- var parseJsonOrNull = async (res) => {
1309
- const text = await res.text();
1571
+ var bodyCache = /* @__PURE__ */ new WeakMap();
1572
+ async function readVigorParseBody(source) {
1573
+ let bytes = bodyCache.get(source);
1574
+ if (!bytes) {
1575
+ bytes = source.body === null ? Promise.resolve(new Uint8Array(0)) : source.arrayBuffer().then((buf) => new Uint8Array(buf));
1576
+ bodyCache.set(source, bytes);
1577
+ }
1578
+ return {
1579
+ bytes: await bytes,
1580
+ contentType: source.headers.get("content-type"),
1581
+ status: source instanceof Response ? source.status : null,
1582
+ headers: source.headers,
1583
+ source
1584
+ };
1585
+ }
1586
+ var utf8 = new TextDecoder("utf-8");
1587
+ var getCharset = (contentType) => /;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(contentType ?? "")?.[1] ?? "utf-8";
1588
+ var getMimeType = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
1589
+ var decodeText = (body, fatal = false) => {
1590
+ let decoder;
1591
+ try {
1592
+ decoder = new TextDecoder(getCharset(body.contentType), { fatal });
1593
+ } catch {
1594
+ decoder = new TextDecoder("utf-8", { fatal });
1595
+ }
1596
+ return decoder.decode(body.bytes);
1597
+ };
1598
+ var parseJson = (body) => JSON.parse(utf8.decode(body.bytes));
1599
+ var parseJsonOrNull = (body) => {
1600
+ const text = utf8.decode(body.bytes);
1310
1601
  return text.trim() === "" ? null : JSON.parse(text);
1311
1602
  };
1603
+ var hexValue = (b) => {
1604
+ if (b >= 48 && b <= 57) return b - 48;
1605
+ if (b >= 65 && b <= 70) return b - 65 + 10;
1606
+ if (b >= 97 && b <= 102) return b - 97 + 10;
1607
+ return -1;
1608
+ };
1609
+ var decodeFormComponent = (input) => {
1610
+ const out = new Uint8Array(input.length);
1611
+ let n = 0;
1612
+ for (let i = 0; i < input.length; i++) {
1613
+ const b = input[i];
1614
+ if (b === 43) {
1615
+ out[n++] = 32;
1616
+ continue;
1617
+ }
1618
+ if (b === 37 && i + 2 < input.length) {
1619
+ const hi = hexValue(input[i + 1]);
1620
+ const lo = hexValue(input[i + 2]);
1621
+ if (hi >= 0 && lo >= 0) {
1622
+ out[n++] = hi * 16 + lo;
1623
+ i += 2;
1624
+ continue;
1625
+ }
1626
+ }
1627
+ out[n++] = b;
1628
+ }
1629
+ return utf8.decode(out.subarray(0, n));
1630
+ };
1631
+ var parseUrlEncoded = (body) => {
1632
+ const form = new FormData();
1633
+ const { bytes } = body;
1634
+ let start = 0;
1635
+ for (let i = 0; i <= bytes.length; i++) {
1636
+ if (i < bytes.length && bytes[i] !== 38) continue;
1637
+ const pair = bytes.subarray(start, i);
1638
+ start = i + 1;
1639
+ if (pair.length === 0) continue;
1640
+ const eq = pair.indexOf(61);
1641
+ const name = eq === -1 ? pair : pair.subarray(0, eq);
1642
+ const value = eq === -1 ? new Uint8Array(0) : pair.subarray(eq + 1);
1643
+ form.append(decodeFormComponent(name), decodeFormComponent(value));
1644
+ }
1645
+ return form;
1646
+ };
1647
+ var parseMultipart = (body) => new Response(body.bytes, { headers: { "content-type": body.contentType ?? "" } }).formData();
1648
+ var parseFormData = (body) => {
1649
+ const mime = getMimeType(body.contentType);
1650
+ if (mime === "application/x-www-form-urlencoded") return parseUrlEncoded(body);
1651
+ if (mime === "multipart/form-data") return parseMultipart(body);
1652
+ throw new VigorParseError("INVALID_CONTENT_TYPE", {
1653
+ method: "parseFormData",
1654
+ data: { received: body.contentType }
1655
+ });
1656
+ };
1657
+ var toArrayBuffer = (body) => body.bytes.slice().buffer;
1658
+ var toBlob = (body) => new Blob([body.bytes], { type: body.contentType ?? "" });
1312
1659
  var NoBodyStatus = [204, 205, 304];
1313
1660
  var ContentTypeParsers = [
1314
1661
  { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: parseJsonOrNull },
1315
- { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1316
- { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1317
- { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
1318
- { header: "image/*", regExp: /^image\/.+/i, method: (res) => res.blob() },
1319
- { header: "audio/*", regExp: /^audio\/.+/i, method: (res) => res.blob() },
1320
- { header: "video/*", regExp: /^video\/.+/i, method: (res) => res.blob() },
1321
- { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: (res) => res.formData() },
1322
- { header: "text/*", regExp: /^text\/.+/i, method: (res) => res.text() }
1662
+ { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (body) => decodeText(body) },
1663
+ { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: parseUrlEncoded },
1664
+ { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: toArrayBuffer },
1665
+ { header: "image/*", regExp: /^image\/.+/i, method: toBlob },
1666
+ { header: "audio/*", regExp: /^audio\/.+/i, method: toBlob },
1667
+ { header: "video/*", regExp: /^video\/.+/i, method: toBlob },
1668
+ { header: "multipart/form-data", regExp: /multipart\/(.+\+)?form-data(.+\+)?/i, method: parseMultipart },
1669
+ { header: "text/*", regExp: /^text\/.+/i, method: (body) => decodeText(body) }
1323
1670
  ];
1324
1671
  var SniffMethods = [
1325
- { title: "json", method: (res) => res.json() },
1326
- { title: "formData", method: (res) => res.formData() },
1327
- { title: "text", method: (res) => res.text() },
1328
- { title: "blob", method: (res) => res.blob() }
1672
+ { title: "json", method: parseJson },
1673
+ { title: "formData", method: parseFormData },
1674
+ { title: "text", method: (body) => decodeText(body, true) },
1675
+ { title: "blob", method: toBlob }
1329
1676
  ];
1330
- var VigorParseContentTypeStrategy = async (response) => {
1331
- if (response.body === null || NoBodyStatus.includes(response.status)) return null;
1332
- const contentTypeHeader = response.headers.get("content-type");
1333
- if (!contentTypeHeader) {
1334
- const text = await response.text();
1335
- return text === "" ? null : text;
1336
- }
1337
- const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(contentTypeHeader));
1338
- if (!toDo) throw new VigorParseError("PARSER_NOT_FOUND", {
1339
- method: "VigorParseContentTypeStrategy",
1340
- data: {
1341
- expected: ContentTypeParsers.map((p) => p.header),
1342
- received: contentTypeHeader
1343
- }
1344
- });
1345
- return await toDo.method(response);
1677
+ var VigorParseContentTypeStrategy = async (body) => {
1678
+ if (body.bytes.length === 0 || body.status !== null && NoBodyStatus.includes(body.status)) return null;
1679
+ if (!body.contentType) return decodeText(body);
1680
+ const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(body.contentType));
1681
+ if (!toDo) return toBlob(body);
1682
+ return await toDo.method(body);
1346
1683
  };
1347
- var VigorParseSniffStrategy = async (response) => {
1348
- for (const [i, parser] of SniffMethods.entries()) {
1349
- const cloned = i === SniffMethods.length - 1 ? response : response.clone();
1684
+ var VigorParseSniffStrategy = async (body) => {
1685
+ const errors = [];
1686
+ for (const parser of SniffMethods) {
1350
1687
  try {
1351
- return await parser.method(cloned);
1352
- } catch {
1688
+ return await parser.method(body);
1689
+ } catch (error) {
1690
+ errors.push(error);
1353
1691
  }
1354
1692
  }
1355
1693
  throw new VigorParseError("PARSER_ALL_FAILED", {
1356
1694
  method: "VigorParseSniffStrategy",
1357
- data: { tried: SniffMethods.map((p) => p.title) }
1695
+ cause: errors.at(-1),
1696
+ data: { tried: SniffMethods.map((p) => p.title), errors }
1358
1697
  });
1359
1698
  };
1360
1699
  var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends VigorStatus {
@@ -1381,35 +1720,35 @@ var VigorParsePolicyStrategies = class _VigorParsePolicyStrategies extends Vigor
1381
1720
  contentType(replace) {
1382
1721
  return this._set([VigorParseContentTypeStrategy], replace);
1383
1722
  }
1384
- /** Adds the sniffing (try-each-method) parsing strategy. */
1723
+ /** Adds the sniffing (try-each-format) parsing strategy. */
1385
1724
  sniff(replace) {
1386
1725
  return this._set([VigorParseSniffStrategy], replace);
1387
1726
  }
1388
- /** Adds a strategy that always parses the response as JSON. */
1727
+ /** Adds a strategy that always parses the body as JSON. */
1389
1728
  json(replace) {
1390
- return this._set([(res) => res.json()], replace);
1729
+ return this._set([parseJson], replace);
1391
1730
  }
1392
- /** Adds a strategy that always parses the response as text. */
1731
+ /** Adds a strategy that always parses the body as text, in its declared `charset`. */
1393
1732
  text(replace) {
1394
- return this._set([(res) => res.text()], replace);
1733
+ return this._set([(body) => decodeText(body)], replace);
1395
1734
  }
1396
- /** Adds a strategy that always parses the response as an `ArrayBuffer`. */
1735
+ /** Adds a strategy that always parses the body as an `ArrayBuffer`. */
1397
1736
  arrayBuffer(replace) {
1398
- return this._set([(res) => res.arrayBuffer()], replace);
1737
+ return this._set([toArrayBuffer], replace);
1399
1738
  }
1400
- /** Adds a strategy that always parses the response as a `Blob`. */
1739
+ /** Adds a strategy that always parses the body as a `Blob`. */
1401
1740
  blob(replace) {
1402
- return this._set([(res) => res.blob()], replace);
1741
+ return this._set([toBlob], replace);
1403
1742
  }
1404
- /** Adds a strategy that always parses the response as a `Uint8Array`. */
1743
+ /** Adds a strategy that always parses the body as a `Uint8Array`. */
1405
1744
  bytes(replace) {
1406
- return this._set([(res) => res.arrayBuffer().then((b) => new Uint8Array(b))], replace);
1745
+ return this._set([(body) => body.bytes.slice()], replace);
1407
1746
  }
1408
- /** Adds a strategy that always parses the response as `FormData`. */
1747
+ /** Adds a strategy that always parses the body as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`). */
1409
1748
  formData(replace) {
1410
- return this._set([(res) => res.formData()], replace);
1749
+ return this._set([parseFormData], replace);
1411
1750
  }
1412
- /** Adds a user-supplied custom parsing strategy. */
1751
+ /** Adds a user-supplied custom parsing strategy. It receives the body already read into bytes. */
1413
1752
  custom(func, replace) {
1414
1753
  return this._set([func], replace);
1415
1754
  }
@@ -1435,6 +1774,7 @@ var VigorParseContextBase = {
1435
1774
  restarted: false
1436
1775
  },
1437
1776
  record: {},
1777
+ timeline: [],
1438
1778
  policy: VigorParsePolicyBase
1439
1779
  };
1440
1780
 
@@ -1457,7 +1797,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
1457
1797
  }
1458
1798
  settings(input) {
1459
1799
  if (typeof input === "function" || input instanceof VigorParsePolicySettings) {
1460
- const result = typeof input === "function" ? input(new VigorParsePolicySettings()) : input;
1800
+ const result = typeof input === "function" ? input(new VigorParsePolicySettings(this.config)) : input;
1461
1801
  return this._next({
1462
1802
  policy: { settings: result.config.policy.settings }
1463
1803
  });
@@ -1494,88 +1834,121 @@ var VigorParse = class _VigorParse extends VigorStatus {
1494
1834
  { cast: "replace" }
1495
1835
  );
1496
1836
  }
1497
- /** Runs parsing and returns the result directly, throwing on final failure. */
1837
+ /**
1838
+ * Runs parsing and returns the result directly, throwing on final failure.
1839
+ *
1840
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
1841
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
1842
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
1843
+ */
1498
1844
  async request() {
1499
1845
  const res = await this.requestVerbose();
1500
1846
  if (res.success) return res.data;
1501
1847
  throw res.error;
1502
1848
  }
1503
- /** Runs parsing and returns a result/error envelope instead of throwing. */
1849
+ /**
1850
+ * Runs parsing and returns a result/error envelope instead of throwing,
1851
+ * along with the `timeline` of everything the run went through.
1852
+ */
1504
1853
  async requestVerbose() {
1505
- try {
1506
- return await this.requestRuntime();
1507
- } catch (error) {
1508
- return { success: false, data: null, error };
1509
- }
1854
+ return await this.requestRuntime();
1510
1855
  }
1511
- /** Internal execution loop implementing the strategy fallback and restart handling. */
1512
- async requestRuntime(restartAttempt = 1) {
1856
+ /**
1857
+ * Internal execution loop implementing the strategy fallback and restart
1858
+ * handling. Never throws: every failure, including one from `onError` or
1859
+ * `default`, comes back as an envelope carrying the timeline. A restart
1860
+ * passes the same `timeline` on, so it keeps growing across runs.
1861
+ */
1862
+ async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1513
1863
  const config = this._merge(this.config, {});
1514
1864
  let ctx = this._merge(VigorParseContextBase, {
1515
1865
  policy: config.policy
1516
1866
  }, void 0, "replace");
1517
- if (isVigorDefault(ctx.policy.target)) throw new VigorParseError("VALUE_REQUIRED", {
1867
+ ctx.timeline = timeline;
1868
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
1869
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
1870
+ const end = (success, outcome, error) => add("REQUEST_END", {
1871
+ success,
1872
+ outcome,
1873
+ error,
1874
+ took: performance.now() - startedAt,
1875
+ restarts: restartAttempt - 1
1876
+ });
1877
+ const succeed = (data, outcome) => {
1878
+ end(true, outcome, null);
1879
+ return { success: true, data, error: null, timeline };
1880
+ };
1881
+ const fail = (error) => {
1882
+ end(false, "failed", error);
1883
+ return { success: false, data: null, error, timeline };
1884
+ };
1885
+ if (isVigorDefault(ctx.policy.target)) return fail(new VigorParseError("VALUE_REQUIRED", {
1518
1886
  method: "request",
1519
1887
  data: { key: "target" },
1520
1888
  context: ctx
1521
- });
1889
+ }));
1522
1890
  ctx.response = ctx.policy.target;
1523
1891
  const throwError = (err) => {
1524
1892
  throw err;
1525
1893
  };
1526
1894
  try {
1527
- for (const middleware of ctx.policy.middlewares.before) {
1895
+ await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1528
1896
  if (middleware._mode === "fluent") {
1529
1897
  await middleware.func(ctx);
1530
1898
  } else {
1531
- ctx = await middleware.func(ctx, { throwError }) ?? ctx;
1899
+ ctx = await middleware.func(ctx, trace({ throwError })) ?? ctx;
1532
1900
  }
1533
- }
1901
+ });
1534
1902
  if (ctx.policy.settings.raw) {
1535
1903
  ctx.result = ctx.response;
1536
1904
  } else {
1537
- const response = ctx.response;
1905
+ const readStarted = performance.now();
1906
+ const body = await readVigorParseBody(ctx.response);
1907
+ add("BODY_READ", { size: body.bytes.byteLength, took: performance.now() - readStarted });
1538
1908
  const funcs = ctx.policy.strategies.funcs.length > 0 ? ctx.policy.strategies.funcs : [VigorParseContentTypeStrategy];
1539
1909
  let parsed = false;
1540
- for (const [i, func] of funcs.entries()) {
1541
- const cloned = i === funcs.length - 1 ? response : response.clone();
1910
+ const errors = [];
1911
+ for (const [index, func] of funcs.entries()) {
1912
+ add("STRATEGY_STARTED", { index });
1913
+ const started = performance.now();
1542
1914
  try {
1543
- ctx.result = await func(cloned);
1915
+ ctx.result = await func(body);
1916
+ add("STRATEGY_SUCCEEDED", { index, took: performance.now() - started });
1544
1917
  parsed = true;
1545
1918
  break;
1546
- } catch {
1919
+ } catch (error) {
1920
+ errors.push(error);
1921
+ add("STRATEGY_FAILED", { index, error, took: performance.now() - started });
1547
1922
  }
1548
1923
  }
1549
1924
  if (!parsed) throw new VigorParseError("PARSER_ALL_FAILED", {
1550
1925
  method: "request",
1551
- data: { tried: funcs.map((_, i) => `strategy#${i}`) },
1926
+ cause: errors.at(-1),
1927
+ data: { tried: funcs.map((_, i) => `strategy#${i}`), errors },
1552
1928
  context: ctx
1553
1929
  });
1554
1930
  }
1555
1931
  const setResult = (res) => {
1556
1932
  ctx.result = res;
1557
1933
  };
1558
- for (const middleware of ctx.policy.middlewares.after) {
1934
+ await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
1559
1935
  if (middleware._mode === "fluent") {
1560
1936
  await middleware.func(ctx);
1561
1937
  } else {
1562
- ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1938
+ ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1563
1939
  }
1564
- }
1565
- for (const middleware of ctx.policy.middlewares.onResult) {
1940
+ });
1941
+ await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
1566
1942
  if (middleware._mode === "fluent") {
1567
1943
  ctx.result = await middleware.func(ctx.result);
1568
1944
  } else {
1569
- ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1945
+ ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
1570
1946
  }
1571
- }
1572
- return {
1573
- success: true,
1574
- data: ctx.result,
1575
- error: null
1576
- };
1947
+ });
1948
+ return succeed(ctx.result, "result");
1577
1949
  } catch (error) {
1578
1950
  ctx.error = error;
1951
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
1579
1952
  ctx.flags.overridden = false;
1580
1953
  ctx.flags.restarted = false;
1581
1954
  const setResult = (res) => {
@@ -1584,15 +1957,19 @@ var VigorParse = class _VigorParse extends VigorStatus {
1584
1957
  };
1585
1958
  const proceedRestart = () => ctx.flags.restarted = true;
1586
1959
  const cancelRestart = () => ctx.flags.restarted = false;
1587
- for (const middleware of ctx.policy.middlewares.onError) {
1588
- if (middleware._mode === "fluent") {
1589
- await middleware.func(ctx.error);
1590
- } else {
1591
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1592
- }
1960
+ try {
1961
+ await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
1962
+ if (middleware._mode === "fluent") {
1963
+ await middleware.func(ctx.error);
1964
+ } else {
1965
+ ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
1966
+ }
1967
+ });
1968
+ } catch (err) {
1969
+ return fail(err);
1593
1970
  }
1594
1971
  if (ctx.flags.restarted) {
1595
- if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1972
+ if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorParseError("RESTART_EXHAUSTED", {
1596
1973
  method: "request",
1597
1974
  cause: ctx.error,
1598
1975
  data: {
@@ -1600,27 +1977,19 @@ var VigorParse = class _VigorParse extends VigorStatus {
1600
1977
  error: ctx.error
1601
1978
  },
1602
1979
  context: ctx
1603
- });
1604
- return await this.requestRuntime(restartAttempt + 1);
1980
+ }));
1981
+ add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
1982
+ return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
1605
1983
  }
1606
- if (ctx.flags.overridden) return {
1607
- success: true,
1608
- data: ctx.result,
1609
- error: null
1610
- };
1984
+ if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
1611
1985
  if (!isVigorEmpty(ctx.policy.settings.default)) {
1612
- const data = await ctx.policy.settings.default(ctx);
1613
- return {
1614
- success: true,
1615
- data,
1616
- error: null
1617
- };
1986
+ try {
1987
+ return succeed(await ctx.policy.settings.default(ctx), "default");
1988
+ } catch (err) {
1989
+ return fail(err);
1990
+ }
1618
1991
  }
1619
- return {
1620
- success: false,
1621
- data: null,
1622
- error: ctx.error
1623
- };
1992
+ return fail(ctx.error);
1624
1993
  }
1625
1994
  }
1626
1995
  };
@@ -1655,16 +2024,21 @@ var VigorFetchContextBase = {
1655
2024
  restarted: false
1656
2025
  },
1657
2026
  record: {},
2027
+ timeline: [],
1658
2028
  policy: VigorFetchPolicyBase
1659
2029
  };
1660
2030
 
1661
2031
  // src/fetch/error.ts
1662
2032
  var VigorFetchErrorMessageFuncs = {
2033
+ ...VigorRetryErrorMessageFuncs,
2034
+ ...VigorParseErrorMessageFuncs,
1663
2035
  VALUE_REQUIRED: ({ key }) => `Value Required (missing ${key})`,
1664
2036
  INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
2037
+ BODY_NOT_ALLOWED: ({ method }) => `A ${method} request cannot have a body`,
1665
2038
  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`,
1666
2039
  FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1667
2040
  RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
2041
+ PATH_ESCAPED: ({ url, base }) => `Path escapes "${base}": the request would go to "${url}" (settings.confinePath)`,
1668
2042
  REDIRECTED: ({ url, status }) => `Redirected (${status}) to "${url}" \u2014 navigating away`
1669
2043
  };
1670
2044
  var VigorFetchError = class extends VigorError {
@@ -1677,13 +2051,27 @@ var VigorFetchError = class extends VigorError {
1677
2051
  super(code, messageFn(options.data), options);
1678
2052
  }
1679
2053
  };
1680
- var isVigorFetchError = (error) => error instanceof VigorFetchError;
2054
+ function isVigorFetchError(error, ...codes) {
2055
+ return error instanceof VigorFetchError && (codes.length === 0 || codes.includes(error.code));
2056
+ }
2057
+ function adoptVigorFetchError(error, context) {
2058
+ if (!(error instanceof VigorRetryError) && !(error instanceof VigorParseError)) return error;
2059
+ const data = error.data;
2060
+ const adopted = data !== null && typeof data === "object" && "error" in data ? { ...data, error: adoptVigorFetchError(data.error, context) } : data;
2061
+ return new VigorFetchError(error.code, {
2062
+ method: error.method,
2063
+ cause: error,
2064
+ data: adopted,
2065
+ context
2066
+ });
2067
+ }
1681
2068
 
1682
2069
  // src/fetch/main.ts
1683
2070
  var VigorFetchBase = {
1684
2071
  __brand: createBrand("Fetch", "Schema"),
1685
2072
  policy: VigorFetchPolicyBase,
1686
- cast: VigorEmpty
2073
+ cast: VigorEmpty,
2074
+ apiMap: VigorEmpty
1687
2075
  };
1688
2076
  var VigorFetch = class _VigorFetch extends VigorStatus {
1689
2077
  constructor(config = VigorFetchBase) {
@@ -1712,43 +2100,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1712
2100
  hash(str) {
1713
2101
  return this._next({ policy: { hash: str } }, { policy: { hash: "replace" } });
1714
2102
  }
1715
- /**
1716
- * Sets request headers.
1717
- *
1718
- * @param mode - `"overwrite"` discards all previously configured headers
1719
- * and keeps only the ones passed here. `"merge"` behaves like
1720
- * `Object.assign`, overwriting only the keys that overlap and keeping
1721
- * the rest.
1722
- */
1723
2103
  headers(mode, obj) {
1724
2104
  if (mode === "overwrite") return this._next({ policy: { headers: obj } }, { policy: { headers: "replace" } });
1725
2105
  return this._next({ policy: { headers: obj } });
1726
2106
  }
1727
- /**
1728
- * Sets the request body.
1729
- *
1730
- * @param mode - `"overwrite"` discards the previous body and fully
1731
- * replaces it with this value. `"merge"` shallow-merges (via
1732
- * `Object.assign`) when both the previous and new body are plain
1733
- * objects; for any other body type (string/Blob/FormData/etc) it is
1734
- * simply replaced.
1735
- */
1736
2107
  body(mode, obj) {
1737
- if (mode === "overwrite") return this._next({ policy: { body: obj } }, { policy: { body: "replace" } });
1738
- return this._next({ policy: { body: obj } });
2108
+ const prev = this.config.policy.body;
2109
+ const body = mode === "merge" && this._isPlainObject(prev) && this._isPlainObject(obj) ? { ...prev, ...obj } : obj;
2110
+ return this._next({ policy: { body } }, { policy: { body: "replace" } });
1739
2111
  }
1740
- /**
1741
- * Sets additional `RequestInit` options other than headers/body/method/signal
1742
- * (e.g. `credentials`, `mode`, `cache`, `redirect`, `referrer`,
1743
- * `referrerPolicy`, `keepalive`, `integrity`).
1744
- *
1745
- * @param mode - `"overwrite"` discards all previously configured options
1746
- * and replaces them with this value. `"merge"` shallow-merges this
1747
- * value onto the previous options.
1748
- */
1749
2112
  options(mode, obj) {
1750
- if (mode === "overwrite") return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1751
- return this._next({ policy: { extra: obj } });
2113
+ const extra = mode === "merge" ? { ...this.config.policy.extra, ...obj } : obj;
2114
+ return this._next({ policy: { extra } }, { policy: { extra: "replace" } });
1752
2115
  }
1753
2116
  settings(input) {
1754
2117
  const strategy = { policy: { settings: { retryHeaders: "replace", unretryStatus: "replace" } } };
@@ -1775,14 +2138,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1775
2138
  const result = typeof input === "function" ? input(new VigorRetry()) : input;
1776
2139
  return this._next({ policy: { retry: result.config } }, { policy: { retry: "replace" } });
1777
2140
  }
1778
- return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
2141
+ return this._next({ policy: { retry: this._merge(VigorRetryBase, input) } }, { policy: { retry: "replace" } });
1779
2142
  }
1780
2143
  parse(input) {
1781
2144
  if (typeof input === "function" || input instanceof VigorParse) {
1782
2145
  const result = typeof input === "function" ? input(new VigorParse()) : input;
1783
2146
  return this._next({ policy: { parse: result.config } }, { policy: { parse: "replace" } });
1784
2147
  }
1785
- return this._next({ policy: { parse: input } }, { policy: { parse: "replace" } });
2148
+ return this._next({ policy: { parse: this._merge(VigorParseBase, input) } }, { policy: { parse: "replace" } });
2149
+ }
2150
+ /** Whether `v` is a plain object literal (not an array, `FormData`, `Blob`, ...). */
2151
+ _isPlainObject(v) {
2152
+ return v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
1786
2153
  }
1787
2154
  /** Converts a list of stringable values into strings, dropping `null`/`undefined` entries. */
1788
2155
  _stringifyList(unkList) {
@@ -1804,9 +2171,11 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1804
2171
  * Builds the final request URL from the configured origin, path
1805
2172
  * segments, query parameters, and hash. An absolute `origin` ignores
1806
2173
  * the resolved base (per the `URL` spec); a relative `origin` is
1807
- * resolved against it. Throws `INVALID_PROTOCOL` if neither is possible.
2174
+ * resolved against it. Throws `INVALID_PROTOCOL` (with `context`) if
2175
+ * neither is possible, and with `settings.confinePath` on, `PATH_ESCAPED`
2176
+ * if the result leaves the origin's domain or path.
1808
2177
  */
1809
- _buildUrl(origin, path, query, hash) {
2178
+ _buildUrl(origin, path, query, hash, context) {
1810
2179
  const base = this._resolveBase();
1811
2180
  let originObj;
1812
2181
  try {
@@ -1814,7 +2183,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1814
2183
  } catch {
1815
2184
  throw new VigorFetchError("INVALID_PROTOCOL", {
1816
2185
  method: "_buildUrl",
1817
- data: { origin, base }
2186
+ data: { origin, base },
2187
+ context
1818
2188
  });
1819
2189
  }
1820
2190
  const baseStr = originObj.origin;
@@ -1835,10 +2205,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1835
2205
  }
1836
2206
  }
1837
2207
  mainObj.hash = hash || originObj.hash;
2208
+ if (context.policy.settings.confinePath) {
2209
+ const basePath = "/" + originObj.pathname.replace(/^\/+|\/+$/g, "");
2210
+ const inside = basePath === "/" || mainObj.pathname === basePath || mainObj.pathname.startsWith(basePath + "/");
2211
+ if (mainObj.origin !== originObj.origin || !inside) throw new VigorFetchError("PATH_ESCAPED", {
2212
+ method: "_buildUrl",
2213
+ data: { url: mainObj.href, base: originObj.origin + (basePath === "/" ? "" : basePath) },
2214
+ context
2215
+ });
2216
+ }
1838
2217
  return mainObj.href;
1839
2218
  }
1840
- /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. */
1841
- _normalizeBody(body) {
2219
+ /** Infers the `Content-Type` header and serializes `body` into a `BodyInit`. Throws `INVALID_BODY` (with `context`) for anything else. */
2220
+ _normalizeBody(body, context) {
1842
2221
  if (body == null) return { headers: {}, body };
1843
2222
  if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1844
2223
  if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
@@ -1849,15 +2228,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1849
2228
  if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
1850
2229
  throw new VigorFetchError("INVALID_BODY", {
1851
2230
  method: "_normalizeBody",
1852
- data: { received: body }
2231
+ data: { received: body },
2232
+ context
1853
2233
  });
1854
2234
  }
1855
2235
  /**
1856
- * Returns the absolute URL a `3xx` response points at, or `null` when the
1857
- * response isn't a redirect or carries no usable `Location` header. A
1858
- * relative `Location` is resolved against the responding URL.
2236
+ * Returns the absolute URL a redirect points at, or `null` when the
2237
+ * response isn't a redirect. A response `fetch` already followed
2238
+ * (`redirect: "follow"`, the default) yields its final URL; a readable
2239
+ * `3xx` (`redirect: "manual"` outside browsers) yields its `Location`,
2240
+ * resolved against the responding URL.
1859
2241
  */
1860
2242
  _resolveRedirect(response, href) {
2243
+ if (response.redirected && response.url) return response.url;
1861
2244
  if (response.status < 300 || response.status >= 400) return null;
1862
2245
  const location = response.headers.get("location");
1863
2246
  if (!location) return null;
@@ -1909,32 +2292,137 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1909
2292
  * any other configuration method); whichever `.cast<T>()` call happens
1910
2293
  * last wins.
1911
2294
  */
2295
+ /**
2296
+ * Attaches a type-level API map: a request whose method and path match a
2297
+ * route resolves to that route's success `responses` (see `VigorApiRoute`
2298
+ * for `responses`/`params`/`query`/`body`). Keys are
2299
+ * `"<METHOD> /<path>"`, where a `:name` segment matches any one segment.
2300
+ * Routes are relative to the path set so far, so a base path can be set
2301
+ * first: `vigor.fetch(origin).path("v1").apiMap<Api>()`. Purely a type —
2302
+ * nothing changes at runtime. `.cast<T>()` and a `raw` parse still win.
2303
+ *
2304
+ * @example
2305
+ * type Api = {
2306
+ * "GET /users": { response: User[] }
2307
+ * "GET /users/:id": { response: User }
2308
+ * }
2309
+ * const api = vigor.fetch("https://api.example.com").apiMap<Api>()
2310
+ * const user = await api.path("users", id).request() // User
2311
+ */
2312
+ apiMap() {
2313
+ return this._next(
2314
+ { apiMap: VigorCastPlaceholder },
2315
+ { apiMap: "replace" }
2316
+ );
2317
+ }
2318
+ route(key, ...params) {
2319
+ const route = key;
2320
+ const space = route.indexOf(" ");
2321
+ const method = route.slice(0, space);
2322
+ const values = params[0] ?? {};
2323
+ const segments = route.slice(space + 1).split("/").filter(Boolean).map((segment) => {
2324
+ if (!segment.startsWith(":")) return segment;
2325
+ const name = segment.slice(1);
2326
+ const value = values[name];
2327
+ if (value === null || value === void 0) throw new VigorFetchError("VALUE_REQUIRED", {
2328
+ method: "route",
2329
+ data: { key: `params.${name}` }
2330
+ });
2331
+ return value;
2332
+ });
2333
+ return this.method(method).path(...segments);
2334
+ }
1912
2335
  cast() {
1913
2336
  return this._next(
1914
2337
  { cast: VigorCastPlaceholder },
1915
2338
  { cast: "replace" }
1916
2339
  );
1917
2340
  }
1918
- /** Runs the request and returns its parsed result directly, throwing on final failure. */
2341
+ /**
2342
+ * Runs the request and returns its parsed result directly, throwing on final failure.
2343
+ *
2344
+ * `R` defaults to the inferred result type. Passing one (`request<User>()`)
2345
+ * means "ignore the inference, it's this": it's taken as-is, unchecked.
2346
+ * To name the inferred type itself, use `VigorResultOf<typeof builder>`.
2347
+ *
2348
+ * With an API map, the request's `body`/`query` must match its route's
2349
+ * (see {@link VigorFetchRequestThis}), or the call doesn't compile.
2350
+ */
1919
2351
  async request() {
1920
- const res = await this.requestVerbose();
2352
+ const res = await this.requestRuntime();
1921
2353
  if (res.success) return res.data;
1922
2354
  throw res.error;
1923
2355
  }
1924
- /** Runs the request and returns a result/error envelope instead of throwing. */
2356
+ /**
2357
+ * Runs the request and returns a result/error envelope instead of throwing,
2358
+ * along with the `timeline` of everything the run went through. The
2359
+ * nested retry/parse engines' full timelines are kept inside it, on their
2360
+ * `RETRY_ENDED`/`PARSE_ENDED` entries.
2361
+ *
2362
+ * A success carries the `status` and `response` its result was parsed
2363
+ * from; with an API map, narrowing `status` narrows `data` (see
2364
+ * {@link VigorFetchVerboseResult}). Passing `R` types every success's
2365
+ * `data` as `R`, unchecked.
2366
+ */
1925
2367
  async requestVerbose() {
1926
- try {
1927
- return await this.requestRuntime();
1928
- } catch (error) {
1929
- return { success: false, data: null, error };
1930
- }
2368
+ return await this.requestRuntime();
1931
2369
  }
1932
- /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1933
- async requestRuntime(restartAttempt = 1) {
2370
+ /**
2371
+ * Internal execution loop implementing URL building, retry, parsing, and
2372
+ * restart handling. Never throws: every failure, including one from
2373
+ * `onError` or `default`, comes back as an envelope carrying the timeline.
2374
+ * A restart passes the same `timeline` on, so it keeps growing across runs.
2375
+ */
2376
+ async requestRuntime(restartAttempt = 1, timeline = [], startedAt = performance.now()) {
1934
2377
  const config = this._merge(this.config, {});
1935
2378
  let ctx = this._merge(VigorFetchContextBase, {
1936
2379
  policy: config.policy
1937
2380
  }, void 0, "replace");
2381
+ ctx.timeline = timeline;
2382
+ const { add, stage } = createVigorTimelineRecorder(timeline, () => this._snapshot(ctx), config.policy.settings.debug);
2383
+ add("PROCESS_HANDLING", { type: "REQUEST_START", data: { restartAttempt } });
2384
+ const end = (success, outcome, error) => add("REQUEST_END", {
2385
+ success,
2386
+ outcome,
2387
+ error,
2388
+ took: performance.now() - startedAt,
2389
+ restarts: restartAttempt - 1
2390
+ });
2391
+ const succeed = (data, outcome, response = null) => {
2392
+ end(true, outcome, null);
2393
+ return { success: true, data, error: null, status: response?.status ?? null, response, timeline };
2394
+ };
2395
+ const fail = (error) => {
2396
+ end(false, "failed", error);
2397
+ return { success: false, data: null, error, status: null, response: null, timeline };
2398
+ };
2399
+ let lastAttempt = 0;
2400
+ const runRetry = async (engine) => {
2401
+ add("RETRY_STARTED", { engine });
2402
+ const started = performance.now();
2403
+ const res = await engine.requestVerbose();
2404
+ add("RETRY_ENDED", {
2405
+ engine,
2406
+ timeline: res.timeline,
2407
+ took: performance.now() - started,
2408
+ response: res.success ? res.data : VigorDefault
2409
+ });
2410
+ return res;
2411
+ };
2412
+ const runParse = async (source, attempt, engine) => {
2413
+ add("PARSE_STARTED", { engine, source, attempt });
2414
+ const started = performance.now();
2415
+ const res = await engine.requestVerbose();
2416
+ add("PARSE_ENDED", {
2417
+ engine,
2418
+ source,
2419
+ attempt,
2420
+ timeline: res.timeline,
2421
+ took: performance.now() - started,
2422
+ result: res.success ? res.data : VigorDefault
2423
+ });
2424
+ return res;
2425
+ };
1938
2426
  const throwError = (err) => {
1939
2427
  throw err;
1940
2428
  };
@@ -1944,7 +2432,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1944
2432
  data: { key: "origin" },
1945
2433
  context: ctx
1946
2434
  });
1947
- ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
2435
+ ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash, ctx);
2436
+ add("BUILT_URL", { url: ctx.href });
1948
2437
  const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body != null;
1949
2438
  const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
1950
2439
  const options = {
@@ -1953,17 +2442,17 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1953
2442
  headers: {}
1954
2443
  };
1955
2444
  if (hasBody) {
1956
- const normalized = this._normalizeBody(ctx.policy.body);
2445
+ const normalized = this._normalizeBody(ctx.policy.body, ctx);
1957
2446
  if (normalized.body !== void 0) options.body = normalized.body;
1958
2447
  Object.assign(options.headers, normalized.headers);
1959
2448
  }
1960
2449
  this._assignHeaders(options.headers, ctx.policy.headers);
1961
2450
  ctx.options = options;
1962
- for (const middleware of ctx.policy.middlewares.before) {
2451
+ await stage("before", ctx.policy.middlewares.before, async (middleware, trace) => {
1963
2452
  if (middleware._mode === "fluent") {
1964
2453
  await middleware.func(ctx);
1965
2454
  } else {
1966
- ctx = await middleware.func(ctx, {
2455
+ ctx = await middleware.func(ctx, trace({
1967
2456
  throwError,
1968
2457
  setOptions: (o) => {
1969
2458
  ctx.options = o;
@@ -1974,19 +2463,38 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1974
2463
  setBody: (b) => {
1975
2464
  ctx.options.body = b;
1976
2465
  }
1977
- }) ?? ctx;
2466
+ })) ?? ctx;
1978
2467
  }
1979
- }
2468
+ });
1980
2469
  const finalOptions = isVigorDefault(ctx.options) ? options : ctx.options;
1981
2470
  ctx.options = finalOptions;
1982
- if (typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream) {
2471
+ add("SET_OPTIONS", { options: finalOptions });
2472
+ const finalMethod = (finalOptions.method ?? "GET").toUpperCase();
2473
+ if (finalOptions.body != null && (finalMethod === "GET" || finalMethod === "HEAD")) throw new VigorFetchError("BODY_NOT_ALLOWED", {
2474
+ method: "request",
2475
+ data: { method: finalMethod },
2476
+ context: ctx
2477
+ });
2478
+ const isStreamBody = typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream;
2479
+ if (isStreamBody) {
1983
2480
  finalOptions.duplex ??= "half";
1984
2481
  }
1985
- const retryEngine = new VigorRetry(ctx.policy.retry).target(async (signal) => {
2482
+ const nestedDebug = { policy: { settings: { debug: true } } };
2483
+ const parseEngine = new VigorParse(config.policy.settings.debug ? this._merge(ctx.policy.parse, nestedDebug) : ctx.policy.parse);
2484
+ const retryEngine = new VigorRetry(config.policy.settings.debug ? this._merge(ctx.policy.retry, nestedDebug) : ctx.policy.retry).target(async (signal) => {
1986
2485
  return await fetch(ctx.href, { ...finalOptions, signal });
1987
2486
  }).middlewares(
1988
2487
  (m) => m.after("intercept", async (rctx, api) => {
1989
2488
  const response = rctx.result;
2489
+ lastAttempt = rctx.system.attempt;
2490
+ add("RESPONSE_RECEIVED", {
2491
+ attempt: rctx.system.attempt,
2492
+ status: response.status,
2493
+ statusText: response.statusText,
2494
+ ok: response.ok,
2495
+ redirected: response.redirected,
2496
+ url: response.url
2497
+ });
1990
2498
  if (ctx.policy.settings.redirect) {
1991
2499
  const target = this._resolveRedirect(response, ctx.href);
1992
2500
  const location = this._browserLocation();
@@ -1999,12 +2507,9 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1999
2507
  }));
2000
2508
  }
2001
2509
  }
2002
- if (!response.ok) {
2003
- let parsed = void 0;
2004
- try {
2005
- parsed = await new VigorParse(ctx.policy.parse).target(response.clone()).request();
2006
- } catch {
2007
- }
2510
+ if (!response.ok && response.status !== 304) {
2511
+ const parseRes2 = await runParse("failedResponse", rctx.system.attempt, parseEngine.target(response.clone()));
2512
+ const parsed = parseRes2.success ? parseRes2.data : void 0;
2008
2513
  api.throwError(new VigorFetchError("FETCH_FAILED", {
2009
2514
  method: "request",
2010
2515
  data: {
@@ -2013,13 +2518,17 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
2013
2518
  response,
2014
2519
  url: response.url,
2015
2520
  parsed
2016
- }
2521
+ },
2522
+ context: ctx
2017
2523
  }));
2018
2524
  }
2525
+ if (!ctx.policy.parse.policy.settings.raw) await readVigorParseBody(response);
2019
2526
  return rctx;
2020
2527
  }).retryIf("intercept", async (rctx, api) => {
2021
2528
  const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
2022
2529
  if (rctx.error instanceof VigorFetchError && rctx.error.code === "REDIRECTED") api.cancelRetry();
2530
+ else if (isStreamBody) api.cancelRetry();
2531
+ else if (response && (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400)) api.cancelRetry();
2023
2532
  else if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
2024
2533
  return rctx;
2025
2534
  }).onRetry("intercept", async (rctx, api) => {
@@ -2028,7 +2537,7 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
2028
2537
  for (const header of ctx.policy.settings.retryHeaders) {
2029
2538
  const delay = this._parseRetryHeader(response.headers.get(header));
2030
2539
  if (delay !== null) {
2031
- api.setDelay(delay);
2540
+ api.setDelay(Math.min(delay, ctx.policy.settings.maxRetryAfter));
2032
2541
  break;
2033
2542
  }
2034
2543
  }
@@ -2036,35 +2545,40 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
2036
2545
  return rctx;
2037
2546
  })
2038
2547
  );
2039
- ctx.response = await retryEngine.request();
2040
- const parseEngine = new VigorParse(ctx.policy.parse).target(ctx.response);
2041
- ctx.result = await parseEngine.request();
2042
- for (const middleware of ctx.policy.middlewares.after) {
2548
+ for (const name of ["after", "retryIf", "onRetry"]) {
2549
+ const list = retryEngine.config.policy.middlewares[name];
2550
+ markVigorInternal(list[list.length - 1].func);
2551
+ }
2552
+ add("ENGINE_CREATED", { retryEngine, parseEngine });
2553
+ const retryRes = await runRetry(retryEngine);
2554
+ if (!retryRes.success) throw adoptVigorFetchError(retryRes.error, ctx);
2555
+ ctx.response = retryRes.data;
2556
+ const parseRes = await runParse("response", lastAttempt, parseEngine.target(ctx.response));
2557
+ if (!parseRes.success) throw adoptVigorFetchError(parseRes.error, ctx);
2558
+ ctx.result = parseRes.data;
2559
+ await stage("after", ctx.policy.middlewares.after, async (middleware, trace) => {
2043
2560
  if (middleware._mode === "fluent") {
2044
2561
  await middleware.func(ctx);
2045
2562
  } else {
2046
- ctx = await middleware.func(ctx, { throwError, setResult: (r) => {
2563
+ ctx = await middleware.func(ctx, trace({ throwError, setResult: (r) => {
2047
2564
  ctx.result = r;
2048
- } }) ?? ctx;
2565
+ } })) ?? ctx;
2049
2566
  }
2050
- }
2567
+ });
2051
2568
  const setResult = (r) => {
2052
2569
  ctx.result = r;
2053
2570
  };
2054
- for (const middleware of ctx.policy.middlewares.onResult) {
2571
+ await stage("onResult", ctx.policy.middlewares.onResult, async (middleware, trace) => {
2055
2572
  if (middleware._mode === "fluent") {
2056
2573
  ctx.result = await middleware.func(ctx.result);
2057
2574
  } else {
2058
- ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
2575
+ ctx = await middleware.func(ctx, trace({ setResult, throwError })) ?? ctx;
2059
2576
  }
2060
- }
2061
- return {
2062
- success: true,
2063
- data: ctx.result,
2064
- error: null
2065
- };
2577
+ });
2578
+ return succeed(ctx.result, "result", ctx.response);
2066
2579
  } catch (error) {
2067
2580
  ctx.error = error;
2581
+ add("PROCESS_HANDLING", { type: "REQUEST_ERROR", data: { error } });
2068
2582
  ctx.flags.overridden = false;
2069
2583
  ctx.flags.restarted = false;
2070
2584
  const setResult = (r) => {
@@ -2073,15 +2587,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
2073
2587
  };
2074
2588
  const proceedRestart = () => ctx.flags.restarted = true;
2075
2589
  const cancelRestart = () => ctx.flags.restarted = false;
2076
- for (const middleware of ctx.policy.middlewares.onError) {
2077
- if (middleware._mode === "fluent") {
2078
- await middleware.func(ctx.error);
2079
- } else {
2080
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
2081
- }
2590
+ try {
2591
+ await stage("onError", ctx.policy.middlewares.onError, async (middleware, trace) => {
2592
+ if (middleware._mode === "fluent") {
2593
+ await middleware.func(ctx.error);
2594
+ } else {
2595
+ ctx = await middleware.func(ctx, trace({ setResult, throwError, proceedRestart, cancelRestart })) ?? ctx;
2596
+ }
2597
+ });
2598
+ } catch (err) {
2599
+ return fail(err);
2082
2600
  }
2083
2601
  if (ctx.flags.restarted) {
2084
- if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
2602
+ if (restartAttempt > ctx.policy.settings.maxRestarts) return fail(new VigorFetchError("RESTART_EXHAUSTED", {
2085
2603
  method: "request",
2086
2604
  cause: ctx.error,
2087
2605
  data: {
@@ -2089,27 +2607,19 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
2089
2607
  error: ctx.error
2090
2608
  },
2091
2609
  context: ctx
2092
- });
2093
- return await this.requestRuntime(restartAttempt + 1);
2610
+ }));
2611
+ add("PROCESS_HANDLING", { type: "REQUEST_RESTART", data: { restartAttempt: restartAttempt + 1 } });
2612
+ return await this.requestRuntime(restartAttempt + 1, timeline, startedAt);
2094
2613
  }
2095
- if (ctx.flags.overridden) return {
2096
- success: true,
2097
- data: ctx.result,
2098
- error: null
2099
- };
2614
+ if (ctx.flags.overridden) return succeed(ctx.result, "overridden");
2100
2615
  if (!isVigorEmpty(ctx.policy.settings.default)) {
2101
- const data = await ctx.policy.settings.default(ctx);
2102
- return {
2103
- success: true,
2104
- data,
2105
- error: null
2106
- };
2616
+ try {
2617
+ return succeed(await ctx.policy.settings.default(ctx), "default");
2618
+ } catch (err) {
2619
+ return fail(err);
2620
+ }
2107
2621
  }
2108
- return {
2109
- success: false,
2110
- data: null,
2111
- error
2112
- };
2622
+ return fail(error);
2113
2623
  }
2114
2624
  }
2115
2625
  };
@@ -2157,6 +2667,12 @@ var vigorBase = {
2157
2667
  settings: () => new VigorAllPolicySettings(),
2158
2668
  middlewares: () => new VigorAllPolicyMiddlewares()
2159
2669
  }
2670
+ },
2671
+ guards: {
2672
+ retry: isVigorRetryError,
2673
+ parse: isVigorParseError,
2674
+ fetch: isVigorFetchError,
2675
+ all: isVigorAllError
2160
2676
  }
2161
2677
  };
2162
2678
  var cloneVigor = (v) => ({
@@ -2166,13 +2682,14 @@ var cloneVigor = (v) => ({
2166
2682
  retry: { ...v.builders.retry, algorithm: { ...v.builders.retry.algorithm } },
2167
2683
  parse: { ...v.builders.parse },
2168
2684
  all: { ...v.builders.all }
2169
- }
2685
+ },
2686
+ guards: { ...v.guards }
2170
2687
  });
2171
2688
  var createVigor = (fields) => {
2172
2689
  const instance = {
2173
2690
  ...fields,
2174
2691
  use: (plugin, options) => {
2175
- const ext = plugin.func(instance, options);
2692
+ const ext = plugin.func(instance, { ...plugin.options, ...options });
2176
2693
  const { use: _, ...rest } = { ...cloneVigor(instance), ...ext };
2177
2694
  return createVigor(rest);
2178
2695
  }
@@ -2187,6 +2704,8 @@ var index_default = vigor;
2187
2704
  0 && (module.exports = {
2188
2705
  VigorAll,
2189
2706
  VigorAllBase,
2707
+ VigorAllContextBase,
2708
+ VigorAllEachContextBase,
2190
2709
  VigorAllError,
2191
2710
  VigorAllErrorMessageFuncs,
2192
2711
  VigorAllPolicyBase,
@@ -2194,9 +2713,13 @@ var index_default = vigor;
2194
2713
  VigorAllPolicyMiddlewaresBase,
2195
2714
  VigorAllPolicySettings,
2196
2715
  VigorAllPolicySettingsBase,
2716
+ VigorCastPlaceholder,
2717
+ VigorDefault,
2718
+ VigorEmpty,
2197
2719
  VigorError,
2198
2720
  VigorFetch,
2199
2721
  VigorFetchBase,
2722
+ VigorFetchContextBase,
2200
2723
  VigorFetchError,
2201
2724
  VigorFetchErrorMessageFuncs,
2202
2725
  VigorFetchPolicyBase,
@@ -2208,6 +2731,7 @@ var index_default = vigor;
2208
2731
  VigorParse,
2209
2732
  VigorParseBase,
2210
2733
  VigorParseContentTypeStrategy,
2734
+ VigorParseContextBase,
2211
2735
  VigorParseError,
2212
2736
  VigorParseErrorMessageFuncs,
2213
2737
  VigorParsePolicyBase,
@@ -2220,6 +2744,7 @@ var index_default = vigor;
2220
2744
  VigorParseSniffStrategy,
2221
2745
  VigorRetry,
2222
2746
  VigorRetryBase,
2747
+ VigorRetryContextBase,
2223
2748
  VigorRetryError,
2224
2749
  VigorRetryErrorMessageFuncs,
2225
2750
  VigorRetryPolicyAlgorithms,
@@ -2238,9 +2763,17 @@ var index_default = vigor;
2238
2763
  VigorRetryPolicySettings,
2239
2764
  VigorRetryPolicySettingsBase,
2240
2765
  VigorStatus,
2766
+ adoptVigorFetchError,
2767
+ createBrand,
2768
+ createVigorTimelineRecorder,
2241
2769
  isVigorAllError,
2770
+ isVigorDefault,
2771
+ isVigorEmpty,
2242
2772
  isVigorFetchError,
2773
+ isVigorInternalMiddleware,
2243
2774
  isVigorParseError,
2244
2775
  isVigorRetryError,
2776
+ markVigorInternal,
2777
+ readVigorParseBody,
2245
2778
  vigor
2246
2779
  });