vigor-fetch 4.0.11 → 4.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
@@ -74,6 +74,10 @@ __export(index_exports, {
74
74
  VigorRetryPolicySettingsBase: () => VigorRetryPolicySettingsBase,
75
75
  VigorStatus: () => VigorStatus,
76
76
  default: () => index_default,
77
+ isVigorAllError: () => isVigorAllError,
78
+ isVigorFetchError: () => isVigorFetchError,
79
+ isVigorParseError: () => isVigorParseError,
80
+ isVigorRetryError: () => isVigorRetryError,
77
81
  vigor: () => vigor
78
82
  });
79
83
  module.exports = __toCommonJS(index_exports);
@@ -98,7 +102,7 @@ var VigorStatus = class {
98
102
  */
99
103
  constructor(base, config) {
100
104
  this._base = base;
101
- this._config = this._merge(base, config);
105
+ this._config = this._merge(base, config, void 0, "replace");
102
106
  }
103
107
  /**
104
108
  * Derives a new instance by merging `patch` onto the current config.
@@ -116,9 +120,11 @@ var VigorStatus = class {
116
120
  /**
117
121
  * Deep-merges `target` onto `source`, honoring an optional per-path
118
122
  * `strategy` tree. Objects merge key by key, arrays concatenate (unless
119
- * `"replace"` is specified), and any other value is overwritten.
123
+ * `"replace"` is specified, or `arrayMode` is `"replace"`), and any other
124
+ * value — including `null` — is overwritten. Only `undefined` keeps the
125
+ * source value.
120
126
  */
121
- _merge(source, target, strategy) {
127
+ _merge(source, target, strategy, arrayMode = "concat") {
122
128
  const isObj = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
123
129
  const deepClone = (v) => {
124
130
  if (Array.isArray(v)) return v.map(deepClone);
@@ -130,10 +136,10 @@ var VigorStatus = class {
130
136
  return v;
131
137
  };
132
138
  const merge = (a, b, s) => {
133
- if (b === void 0 || b === null) return deepClone(a);
139
+ if (b === void 0) return deepClone(a);
134
140
  if (s === "replace") return b;
135
141
  if (Array.isArray(a) && Array.isArray(b)) {
136
- return s === "replace" ? b : [...a, ...b];
142
+ return arrayMode === "replace" ? deepClone(b) : [...a, ...b];
137
143
  }
138
144
  if (isObj(a) && isObj(b)) {
139
145
  const r = {};
@@ -162,7 +168,9 @@ var VigorStatus = class {
162
168
  var VigorAllPolicySettingsBase = {
163
169
  __brand: createBrand("All", "Policy<Settings<Schema"),
164
170
  concurrency: 5,
165
- onlySuccess: false
171
+ onlySuccess: false,
172
+ timeout: VigorEmpty,
173
+ failFast: false
166
174
  };
167
175
  var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
168
176
  constructor(config = VigorAllBase) {
@@ -179,6 +187,14 @@ var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
179
187
  onlySuccess(bool) {
180
188
  return this._next({ policy: { settings: { onlySuccess: bool } } });
181
189
  }
190
+ /** Sets the per-task timeout, in milliseconds. A task exceeding it fails with `TIMED_OUT`. */
191
+ timeout(num) {
192
+ return this._next({ policy: { settings: { timeout: num } } });
193
+ }
194
+ /** When enabled, the first unrecovered task failure aborts the remaining tasks and fails the batch with that error. */
195
+ failFast(bool) {
196
+ return this._next({ policy: { settings: { failFast: bool } } });
197
+ }
182
198
  };
183
199
 
184
200
  // src/all/middlewares.ts
@@ -225,6 +241,7 @@ var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorSt
225
241
  var VigorAllPolicyBase = {
226
242
  __brand: createBrand("All", "Policy<Schema"),
227
243
  target: [],
244
+ abortSignals: [],
228
245
  settings: VigorAllPolicySettingsBase,
229
246
  middlewares: VigorAllPolicyMiddlewaresBase
230
247
  };
@@ -238,9 +255,10 @@ var VigorAllContextBase = {
238
255
  };
239
256
  var VigorAllEachContextBase = {
240
257
  __brand: createBrand("All", "EachContext<Schema"),
258
+ index: 0,
241
259
  result: VigorDefault,
242
260
  error: VigorDefault,
243
- flags: { overrided: false },
261
+ flags: { overridden: false },
244
262
  record: {}
245
263
  };
246
264
 
@@ -272,7 +290,8 @@ var VigorError = class extends Error {
272
290
 
273
291
  // src/all/error.ts
274
292
  var VigorAllErrorMessageFuncs = {
275
- EMPTY_TARGET: (_) => `Empty target list`
293
+ EMPTY_TARGET: (_) => `Empty target list`,
294
+ TIMED_OUT: ({ limit, index }) => `Task #${index} timeout: exceeded ${limit}ms`
276
295
  };
277
296
  var VigorAllError = class extends VigorError {
278
297
  /**
@@ -284,6 +303,7 @@ var VigorAllError = class extends VigorError {
284
303
  super(code, messageFn(options.data), options);
285
304
  }
286
305
  };
306
+ var isVigorAllError = (error) => error instanceof VigorAllError;
287
307
 
288
308
  // src/all/main.ts
289
309
  var VigorAllBase = {
@@ -302,6 +322,10 @@ var VigorAll = class _VigorAll extends VigorStatus {
302
322
  target(...funcs) {
303
323
  return this._next({ policy: { target: funcs } });
304
324
  }
325
+ /** Sets external abort signals that, when aborted, cancel the remaining tasks and fail the batch. */
326
+ abortSignals(...sig) {
327
+ return this._next({ policy: { abortSignals: sig } });
328
+ }
305
329
  settings(input) {
306
330
  if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
307
331
  const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
@@ -321,22 +345,43 @@ var VigorAll = class _VigorAll extends VigorStatus {
321
345
  return this._next({ policy: { middlewares: input } });
322
346
  }
323
347
  /** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
324
- async _runTask(task, policy) {
325
- let ctx = this._merge(VigorAllEachContextBase, {});
348
+ async _runTask(task, index, policy, batchSignal) {
349
+ let ctx = this._merge(VigorAllEachContextBase, { index });
350
+ const timeoutController = new AbortController();
351
+ const signal = AbortSignal.any([batchSignal, timeoutController.signal]);
352
+ let timeoutId;
353
+ let onAbort;
326
354
  try {
327
355
  for (const beforeEach of policy.middlewares.beforeEach) await beforeEach(ctx);
328
- ctx.result = await task();
356
+ signal.throwIfAborted();
357
+ const limit = policy.settings.timeout;
358
+ if (!isVigorEmpty(limit)) {
359
+ timeoutId = setTimeout(() => timeoutController.abort(new VigorAllError("TIMED_OUT", {
360
+ method: "request",
361
+ data: { limit, index }
362
+ })), limit);
363
+ }
364
+ ctx.result = await Promise.race([
365
+ task(signal),
366
+ new Promise((_, rej) => {
367
+ onAbort = () => rej(signal.reason);
368
+ signal.addEventListener("abort", onAbort);
369
+ })
370
+ ]);
329
371
  for (const afterEach of policy.middlewares.afterEach) await afterEach(ctx);
330
372
  return { success: true, value: ctx.result };
331
373
  } catch (error) {
332
374
  ctx.error = error;
333
375
  const setResult = (r) => {
334
- ctx.flags.overrided = true;
376
+ ctx.flags.overridden = true;
335
377
  ctx.result = r;
336
378
  };
337
379
  for (const onErrorEach of policy.middlewares.onErrorEach) await onErrorEach(ctx, { setResult });
338
- if (ctx.flags.overrided) return { success: true, value: ctx.result };
380
+ if (ctx.flags.overridden) return { success: true, value: ctx.result };
339
381
  return { success: false, value: error };
382
+ } finally {
383
+ clearTimeout(timeoutId);
384
+ if (onAbort) signal.removeEventListener("abort", onAbort);
340
385
  }
341
386
  }
342
387
  /**
@@ -367,9 +412,9 @@ var VigorAll = class _VigorAll extends VigorStatus {
367
412
  const policy = config.policy;
368
413
  let ctx = this._merge(VigorAllContextBase, {
369
414
  policy
370
- });
415
+ }, void 0, "replace");
371
416
  const setResult = (r) => {
372
- ctx = { ...ctx, result: r };
417
+ ctx.result = r;
373
418
  };
374
419
  const throwError = (err) => {
375
420
  throw err;
@@ -384,35 +429,46 @@ var VigorAll = class _VigorAll extends VigorStatus {
384
429
  if (mw._mode === "fluent") {
385
430
  await mw.func(ctx);
386
431
  } else {
387
- ctx = await mw.func(ctx, { throwError });
432
+ ctx = await mw.func(ctx, { throwError }) ?? ctx;
388
433
  }
389
434
  }
390
- const concurrency = Math.max(1, policy.settings.concurrency);
435
+ const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
391
436
  const results = new Array(policy.target.length);
437
+ const batchController = new AbortController();
438
+ const batchSignal = AbortSignal.any([...policy.abortSignals, batchController.signal]);
392
439
  let cursor = 0;
393
440
  const worker = async () => {
394
- while (true) {
441
+ while (!batchSignal.aborted) {
395
442
  const i = cursor++;
396
443
  if (i >= policy.target.length) return;
397
- results[i] = await this._runTask(policy.target[i], policy);
444
+ try {
445
+ results[i] = await this._runTask(policy.target[i], i, policy, batchSignal);
446
+ } catch (error) {
447
+ batchController.abort(error);
448
+ return;
449
+ }
450
+ if (!results[i].success && policy.settings.failFast) {
451
+ batchController.abort(results[i].value);
452
+ }
398
453
  }
399
454
  };
400
455
  await Promise.all(
401
456
  Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
402
457
  );
458
+ batchSignal.throwIfAborted();
403
459
  ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
404
460
  for (const mw of policy.middlewares.after) {
405
461
  if (mw._mode === "fluent") {
406
462
  await mw.func(ctx);
407
463
  } else {
408
- ctx = await mw.func(ctx, { setResult, throwError });
464
+ ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
409
465
  }
410
466
  }
411
467
  for (const mw of policy.middlewares.onResult) {
412
468
  if (mw._mode === "fluent") {
413
469
  ctx.result = await mw.func(ctx.result);
414
470
  } else {
415
- ctx = await mw.func(ctx, { setResult, throwError });
471
+ ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
416
472
  }
417
473
  }
418
474
  return {
@@ -433,8 +489,9 @@ var VigorAll = class _VigorAll extends VigorStatus {
433
489
  // src/fetch/settings.ts
434
490
  var VigorFetchPolicySettingsBase = {
435
491
  __brand: createBrand("Fetch", "Policy<Settings<Schema"),
436
- retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"],
492
+ retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"],
437
493
  unretryStatus: [400, 401, 403, 404, 405, 413, 422],
494
+ redirect: true,
438
495
  maxRestarts: 3,
439
496
  default: VigorEmpty
440
497
  };
@@ -445,13 +502,21 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
445
502
  _create(config) {
446
503
  return new _VigorFetchPolicySettings(config);
447
504
  }
448
- /** Sets response headers consulted to compute a server-suggested retry delay. */
505
+ /** Sets (replaces) the response headers consulted to compute a server-suggested retry delay. */
449
506
  retryHeaders(...strs) {
450
- return this._next({ policy: { settings: { retryHeaders: strs } } });
507
+ return this._next({ policy: { settings: { retryHeaders: strs } } }, { policy: { settings: { retryHeaders: "replace" } } });
451
508
  }
452
- /** Sets HTTP status codes that should never be retried. */
509
+ /** Sets (replaces) the HTTP status codes that should never be retried. */
453
510
  unretryStatus(...nums) {
454
- return this._next({ policy: { settings: { unretryStatus: nums } } });
511
+ return this._next({ policy: { settings: { unretryStatus: nums } } }, { policy: { settings: { unretryStatus: "replace" } } });
512
+ }
513
+ /**
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`.
517
+ */
518
+ redirect(bool) {
519
+ return this._next({ policy: { settings: { redirect: bool } } });
455
520
  }
456
521
  /** Sets the maximum number of full restarts allowed. */
457
522
  maxRestarts(num) {
@@ -599,6 +664,7 @@ var VigorRetryError = class extends VigorError {
599
664
  super(code, messageFn(options.data), options);
600
665
  }
601
666
  };
667
+ var isVigorRetryError = (error) => error instanceof VigorRetryError;
602
668
 
603
669
  // src/retry/algorithms.ts
604
670
  function VigorJitter(jitter) {
@@ -851,6 +917,7 @@ var VigorRetryContextBase = {
851
917
  };
852
918
 
853
919
  // src/retry/main.ts
920
+ var MAX_TIMEOUT = 2 ** 31 - 1;
854
921
  var VigorRetryBase = {
855
922
  __brand: createBrand("Retry", "Schema"),
856
923
  policy: VigorRetryPolicyBase,
@@ -929,14 +996,18 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
929
996
  }
930
997
  /** Runs the target and returns a result/error envelope instead of throwing. */
931
998
  async requestVerbose() {
932
- return await this.requestRuntime();
999
+ try {
1000
+ return await this.requestRuntime();
1001
+ } catch (error) {
1002
+ return { success: false, data: null, error };
1003
+ }
933
1004
  }
934
1005
  /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
935
1006
  async requestRuntime(restartAttempt = 1) {
936
1007
  const config = this._merge(this.config, {});
937
1008
  let ctx = this._merge(VigorRetryContextBase, {
938
1009
  policy: config.policy
939
- });
1010
+ }, void 0, "replace");
940
1011
  if (isVigorEmpty(ctx.policy.target)) throw new VigorRetryError("VALUE_REQUIRED", {
941
1012
  method: "request",
942
1013
  data: {
@@ -948,6 +1019,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
948
1019
  const throwError = (err) => {
949
1020
  throw err;
950
1021
  };
1022
+ const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
951
1023
  try {
952
1024
  while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
953
1025
  ctx.system.attempt++;
@@ -962,11 +1034,6 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
962
1034
  userController.signal,
963
1035
  timeoutController.signal
964
1036
  ]);
965
- const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
966
- const autoBreak = () => {
967
- ctx.flags.brokeRetry = true;
968
- };
969
- outerSignals.addEventListener("abort", autoBreak);
970
1037
  const mergedSignals = AbortSignal.any([
971
1038
  innerSignals,
972
1039
  outerSignals
@@ -982,17 +1049,20 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
982
1049
  abort: (reason) => userController.abort(reason),
983
1050
  throwError,
984
1051
  breakRetry
985
- });
1052
+ }) ?? ctx;
986
1053
  }
987
1054
  }
988
1055
  mergedSignals.throwIfAborted();
989
- timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
990
- method: "request",
991
- data: {
992
- limit: ctx.policy.settings.timeout
993
- },
994
- context: ctx
995
- })), ctx.policy.settings.timeout);
1056
+ const limit = ctx.policy.settings.timeout;
1057
+ 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));
1065
+ }
996
1066
  ctx.result = await Promise.race([
997
1067
  target(mergedSignals),
998
1068
  new Promise((_, rej) => {
@@ -1006,7 +1076,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1006
1076
  } else {
1007
1077
  ctx = await middleware.func(ctx, {
1008
1078
  throwError
1009
- });
1079
+ }) ?? ctx;
1010
1080
  }
1011
1081
  }
1012
1082
  const setResult = (res) => {
@@ -1019,7 +1089,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1019
1089
  ctx = await middleware.func(ctx, {
1020
1090
  setResult,
1021
1091
  throwError
1022
- });
1092
+ }) ?? ctx;
1023
1093
  }
1024
1094
  }
1025
1095
  return {
@@ -1029,11 +1099,11 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1029
1099
  };
1030
1100
  } finally {
1031
1101
  clearTimeout(timeoutId);
1032
- outerSignals.removeEventListener("abort", autoBreak);
1033
1102
  if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
1034
1103
  }
1035
1104
  } catch (error) {
1036
1105
  ctx.error = error;
1106
+ if (outerSignals.aborted) ctx.flags.brokeRetry = true;
1037
1107
  if (ctx.flags.brokeRetry) throw ctx.error;
1038
1108
  ctx.flags.doRetry = true;
1039
1109
  const proceedRetry = () => ctx.flags.doRetry = true;
@@ -1045,7 +1115,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1045
1115
  ctx = await middleware.func(ctx, {
1046
1116
  proceedRetry,
1047
1117
  cancelRetry
1048
- });
1118
+ }) ?? ctx;
1049
1119
  }
1050
1120
  }
1051
1121
  if (!ctx.flags.doRetry) throw ctx.error;
@@ -1060,11 +1130,26 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1060
1130
  ctx = await middleware.func(ctx, {
1061
1131
  throwError,
1062
1132
  setDelay
1063
- });
1133
+ }) ?? ctx;
1064
1134
  }
1065
1135
  }
1066
- const delay = ctx.system.delay;
1067
- await new Promise((res) => setTimeout(res, delay));
1136
+ const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT);
1137
+ await new Promise((res, rej) => {
1138
+ if (outerSignals.aborted) {
1139
+ ctx.flags.brokeRetry = true;
1140
+ return rej(outerSignals.reason);
1141
+ }
1142
+ const onAbort = () => {
1143
+ clearTimeout(id);
1144
+ ctx.flags.brokeRetry = true;
1145
+ rej(outerSignals.reason);
1146
+ };
1147
+ const id = setTimeout(() => {
1148
+ outerSignals.removeEventListener("abort", onAbort);
1149
+ res();
1150
+ }, delay);
1151
+ outerSignals.addEventListener("abort", onAbort, { once: true });
1152
+ });
1068
1153
  }
1069
1154
  }
1070
1155
  throw new VigorRetryError("RETRY_EXHAUSTED", {
@@ -1095,17 +1180,18 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1095
1180
  throwError,
1096
1181
  proceedRestart,
1097
1182
  cancelRestart
1098
- });
1183
+ }) ?? ctx;
1099
1184
  }
1100
1185
  }
1101
1186
  if (ctx.flags.doRestart) {
1102
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
1187
+ if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
1103
1188
  method: "request",
1104
1189
  cause: ctx.error,
1105
1190
  data: {
1106
1191
  maxAttempts: ctx.policy.settings.maxRestarts,
1107
1192
  error: ctx.error
1108
- }
1193
+ },
1194
+ context: ctx
1109
1195
  });
1110
1196
  return await this.requestRuntime(restartAttempt + 1);
1111
1197
  }
@@ -1212,14 +1298,20 @@ var VigorParseError = class extends VigorError {
1212
1298
  super(code, messageFn(options.data), options);
1213
1299
  }
1214
1300
  };
1301
+ var isVigorParseError = (error) => error instanceof VigorParseError;
1215
1302
 
1216
1303
  // src/parse/strategies.ts
1217
1304
  var VigorParsePolicyStrategiesBase = {
1218
1305
  __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1219
1306
  funcs: []
1220
1307
  };
1308
+ var parseJsonOrNull = async (res) => {
1309
+ const text = await res.text();
1310
+ return text.trim() === "" ? null : JSON.parse(text);
1311
+ };
1312
+ var NoBodyStatus = [204, 205, 304];
1221
1313
  var ContentTypeParsers = [
1222
- { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
1314
+ { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: parseJsonOrNull },
1223
1315
  { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1224
1316
  { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1225
1317
  { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
@@ -1236,11 +1328,12 @@ var SniffMethods = [
1236
1328
  { title: "blob", method: (res) => res.blob() }
1237
1329
  ];
1238
1330
  var VigorParseContentTypeStrategy = async (response) => {
1331
+ if (response.body === null || NoBodyStatus.includes(response.status)) return null;
1239
1332
  const contentTypeHeader = response.headers.get("content-type");
1240
- if (!contentTypeHeader) throw new VigorParseError("INVALID_CONTENT_TYPE", {
1241
- method: "VigorParseContentTypeStrategy",
1242
- data: { received: contentTypeHeader }
1243
- });
1333
+ if (!contentTypeHeader) {
1334
+ const text = await response.text();
1335
+ return text === "" ? null : text;
1336
+ }
1244
1337
  const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(contentTypeHeader));
1245
1338
  if (!toDo) throw new VigorParseError("PARSER_NOT_FOUND", {
1246
1339
  method: "VigorParseContentTypeStrategy",
@@ -1338,7 +1431,7 @@ var VigorParseContextBase = {
1338
1431
  error: VigorDefault,
1339
1432
  response: VigorDefault,
1340
1433
  flags: {
1341
- overrided: false,
1434
+ overridden: false,
1342
1435
  restarted: false
1343
1436
  },
1344
1437
  record: {},
@@ -1409,14 +1502,18 @@ var VigorParse = class _VigorParse extends VigorStatus {
1409
1502
  }
1410
1503
  /** Runs parsing and returns a result/error envelope instead of throwing. */
1411
1504
  async requestVerbose() {
1412
- return await this.requestRuntime();
1505
+ try {
1506
+ return await this.requestRuntime();
1507
+ } catch (error) {
1508
+ return { success: false, data: null, error };
1509
+ }
1413
1510
  }
1414
1511
  /** Internal execution loop implementing the strategy fallback and restart handling. */
1415
1512
  async requestRuntime(restartAttempt = 1) {
1416
1513
  const config = this._merge(this.config, {});
1417
1514
  let ctx = this._merge(VigorParseContextBase, {
1418
1515
  policy: config.policy
1419
- });
1516
+ }, void 0, "replace");
1420
1517
  if (isVigorDefault(ctx.policy.target)) throw new VigorParseError("VALUE_REQUIRED", {
1421
1518
  method: "request",
1422
1519
  data: { key: "target" },
@@ -1431,7 +1528,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
1431
1528
  if (middleware._mode === "fluent") {
1432
1529
  await middleware.func(ctx);
1433
1530
  } else {
1434
- ctx = await middleware.func(ctx, { throwError });
1531
+ ctx = await middleware.func(ctx, { throwError }) ?? ctx;
1435
1532
  }
1436
1533
  }
1437
1534
  if (ctx.policy.settings.raw) {
@@ -1462,14 +1559,14 @@ var VigorParse = class _VigorParse extends VigorStatus {
1462
1559
  if (middleware._mode === "fluent") {
1463
1560
  await middleware.func(ctx);
1464
1561
  } else {
1465
- ctx = await middleware.func(ctx, { setResult, throwError });
1562
+ ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1466
1563
  }
1467
1564
  }
1468
1565
  for (const middleware of ctx.policy.middlewares.onResult) {
1469
1566
  if (middleware._mode === "fluent") {
1470
1567
  ctx.result = await middleware.func(ctx.result);
1471
1568
  } else {
1472
- ctx = await middleware.func(ctx, { setResult, throwError });
1569
+ ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1473
1570
  }
1474
1571
  }
1475
1572
  return {
@@ -1479,10 +1576,10 @@ var VigorParse = class _VigorParse extends VigorStatus {
1479
1576
  };
1480
1577
  } catch (error) {
1481
1578
  ctx.error = error;
1482
- ctx.flags.overrided = false;
1579
+ ctx.flags.overridden = false;
1483
1580
  ctx.flags.restarted = false;
1484
1581
  const setResult = (res) => {
1485
- ctx.flags.overrided = true;
1582
+ ctx.flags.overridden = true;
1486
1583
  ctx.result = res;
1487
1584
  };
1488
1585
  const proceedRestart = () => ctx.flags.restarted = true;
@@ -1491,11 +1588,11 @@ var VigorParse = class _VigorParse extends VigorStatus {
1491
1588
  if (middleware._mode === "fluent") {
1492
1589
  await middleware.func(ctx.error);
1493
1590
  } else {
1494
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1591
+ ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1495
1592
  }
1496
1593
  }
1497
1594
  if (ctx.flags.restarted) {
1498
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1595
+ if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1499
1596
  method: "request",
1500
1597
  cause: ctx.error,
1501
1598
  data: {
@@ -1506,7 +1603,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
1506
1603
  });
1507
1604
  return await this.requestRuntime(restartAttempt + 1);
1508
1605
  }
1509
- if (ctx.flags.overrided) return {
1606
+ if (ctx.flags.overridden) return {
1510
1607
  success: true,
1511
1608
  data: ctx.result,
1512
1609
  error: null
@@ -1567,7 +1664,8 @@ var VigorFetchErrorMessageFuncs = {
1567
1664
  INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1568
1665
  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`,
1569
1666
  FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1570
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1667
+ RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1668
+ REDIRECTED: ({ url, status }) => `Redirected (${status}) to "${url}" \u2014 navigating away`
1571
1669
  };
1572
1670
  var VigorFetchError = class extends VigorError {
1573
1671
  /**
@@ -1579,6 +1677,7 @@ var VigorFetchError = class extends VigorError {
1579
1677
  super(code, messageFn(options.data), options);
1580
1678
  }
1581
1679
  };
1680
+ var isVigorFetchError = (error) => error instanceof VigorFetchError;
1582
1681
 
1583
1682
  // src/fetch/main.ts
1584
1683
  var VigorFetchBase = {
@@ -1652,13 +1751,15 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1652
1751
  return this._next({ policy: { extra: obj } });
1653
1752
  }
1654
1753
  settings(input) {
1754
+ const strategy = { policy: { settings: { retryHeaders: "replace", unretryStatus: "replace" } } };
1655
1755
  if (typeof input === "function" || input instanceof VigorFetchPolicySettings) {
1656
- const result = typeof input === "function" ? input(new VigorFetchPolicySettings()) : input;
1756
+ const result = typeof input === "function" ? input(new VigorFetchPolicySettings(this.config)) : input;
1657
1757
  return this._next(
1658
- { policy: { settings: result.config.policy.settings } }
1758
+ { policy: { settings: result.config.policy.settings } },
1759
+ strategy
1659
1760
  );
1660
1761
  }
1661
- return this._next({ policy: { settings: input } });
1762
+ return this._next({ policy: { settings: input } }, strategy);
1662
1763
  }
1663
1764
  middlewares(input) {
1664
1765
  if (typeof input === "function" || input instanceof VigorFetchPolicyMiddlewares) {
@@ -1718,7 +1819,9 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1718
1819
  }
1719
1820
  const baseStr = originObj.origin;
1720
1821
  const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, "")];
1721
- for (const p of path) pathParts.push(p.replace(/^\/+|\/+$/g, ""));
1822
+ for (const p of path) {
1823
+ for (const part of p.split("/")) pathParts.push(encodeURIComponent(part));
1824
+ }
1722
1825
  const pathStr = pathParts.filter(Boolean).join("/");
1723
1826
  const mainObj = new URL(pathStr, baseStr);
1724
1827
  const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
@@ -1739,7 +1842,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1739
1842
  if (body == null) return { headers: {}, body };
1740
1843
  if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1741
1844
  if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
1742
- if (body instanceof ArrayBuffer) return { headers: { "Content-Type": "application/octet-stream" }, body };
1845
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { headers: { "Content-Type": "application/octet-stream" }, body };
1846
+ if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) return { headers: { "Content-Type": "application/octet-stream" }, body };
1743
1847
  if (body instanceof URLSearchParams) return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
1744
1848
  if (body instanceof FormData) return { headers: {}, body };
1745
1849
  if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
@@ -1748,6 +1852,57 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1748
1852
  data: { received: body }
1749
1853
  });
1750
1854
  }
1855
+ /**
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.
1859
+ */
1860
+ _resolveRedirect(response, href) {
1861
+ if (response.status < 300 || response.status >= 400) return null;
1862
+ const location = response.headers.get("location");
1863
+ if (!location) return null;
1864
+ try {
1865
+ return new URL(location, response.url || href).href;
1866
+ } catch {
1867
+ return null;
1868
+ }
1869
+ }
1870
+ /** The browser's `location`, or `null` in environments without one (e.g. Node). */
1871
+ _browserLocation() {
1872
+ const win = globalThis.window;
1873
+ return win?.location?.href !== void 0 ? win.location : null;
1874
+ }
1875
+ /** Assigns `source` headers onto `target`, replacing any existing key that differs only in case. */
1876
+ _assignHeaders(target, source) {
1877
+ for (const [key, value] of Object.entries(source)) {
1878
+ const lower = key.toLowerCase();
1879
+ for (const existing of Object.keys(target)) {
1880
+ if (existing.toLowerCase() === lower) delete target[existing];
1881
+ }
1882
+ target[key] = value;
1883
+ }
1884
+ }
1885
+ /**
1886
+ * Converts a rate-limit header value into a delay in milliseconds, or
1887
+ * `null` if it can't be used. Accepts delta seconds (`Retry-After: 120`),
1888
+ * Unix epoch seconds or milliseconds (`X-RateLimit-Reset: 1735689600`),
1889
+ * and HTTP dates.
1890
+ */
1891
+ _parseRetryHeader(value) {
1892
+ if (!value) return null;
1893
+ const num = Number(value);
1894
+ let delay;
1895
+ if (value.trim() !== "" && !isNaN(num)) {
1896
+ if (num >= 1e12) delay = num - Date.now();
1897
+ else if (num >= 1e9) delay = num * 1e3 - Date.now();
1898
+ else delay = num * 1e3;
1899
+ } else {
1900
+ const date = new Date(value).getTime();
1901
+ if (isNaN(date)) return null;
1902
+ delay = date - Date.now();
1903
+ }
1904
+ return delay > 0 ? delay : null;
1905
+ }
1751
1906
  /**
1752
1907
  * Overrides the resolved result type with `T`, taking priority over the
1753
1908
  * default `unknown` result. Can be called before or after `parse()` (or
@@ -1768,14 +1923,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1768
1923
  }
1769
1924
  /** Runs the request and returns a result/error envelope instead of throwing. */
1770
1925
  async requestVerbose() {
1771
- return await this.requestRuntime();
1926
+ try {
1927
+ return await this.requestRuntime();
1928
+ } catch (error) {
1929
+ return { success: false, data: null, error };
1930
+ }
1772
1931
  }
1773
1932
  /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1774
1933
  async requestRuntime(restartAttempt = 1) {
1775
1934
  const config = this._merge(this.config, {});
1776
1935
  let ctx = this._merge(VigorFetchContextBase, {
1777
1936
  policy: config.policy
1778
- });
1937
+ }, void 0, "replace");
1779
1938
  const throwError = (err) => {
1780
1939
  throw err;
1781
1940
  };
@@ -1786,9 +1945,9 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1786
1945
  context: ctx
1787
1946
  });
1788
1947
  ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1789
- const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== void 0;
1948
+ const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body != null;
1790
1949
  const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
1791
- let options = {
1950
+ const options = {
1792
1951
  ...ctx.policy.extra,
1793
1952
  method,
1794
1953
  headers: {}
@@ -1798,7 +1957,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1798
1957
  if (normalized.body !== void 0) options.body = normalized.body;
1799
1958
  Object.assign(options.headers, normalized.headers);
1800
1959
  }
1801
- Object.assign(options.headers, ctx.policy.headers);
1960
+ this._assignHeaders(options.headers, ctx.policy.headers);
1961
+ ctx.options = options;
1802
1962
  for (const middleware of ctx.policy.middlewares.before) {
1803
1963
  if (middleware._mode === "fluent") {
1804
1964
  await middleware.func(ctx);
@@ -1806,23 +1966,39 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1806
1966
  ctx = await middleware.func(ctx, {
1807
1967
  throwError,
1808
1968
  setOptions: (o) => {
1809
- options = o;
1969
+ ctx.options = o;
1810
1970
  },
1811
1971
  setHeaders: (h) => {
1812
- options.headers = h;
1972
+ ctx.options.headers = h;
1813
1973
  },
1814
1974
  setBody: (b) => {
1815
- options.body = b;
1975
+ ctx.options.body = b;
1816
1976
  }
1817
- });
1977
+ }) ?? ctx;
1818
1978
  }
1819
1979
  }
1820
- ctx.options = options;
1980
+ const finalOptions = isVigorDefault(ctx.options) ? options : ctx.options;
1981
+ ctx.options = finalOptions;
1982
+ if (typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream) {
1983
+ finalOptions.duplex ??= "half";
1984
+ }
1821
1985
  const retryEngine = new VigorRetry(ctx.policy.retry).target(async (signal) => {
1822
- return await fetch(ctx.href, { ...options, signal });
1986
+ return await fetch(ctx.href, { ...finalOptions, signal });
1823
1987
  }).middlewares(
1824
1988
  (m) => m.after("intercept", async (rctx, api) => {
1825
1989
  const response = rctx.result;
1990
+ if (ctx.policy.settings.redirect) {
1991
+ const target = this._resolveRedirect(response, ctx.href);
1992
+ const location = this._browserLocation();
1993
+ if (target && location) {
1994
+ location.href = target;
1995
+ api.throwError(new VigorFetchError("REDIRECTED", {
1996
+ method: "request",
1997
+ data: { url: target, status: response.status, response },
1998
+ context: ctx
1999
+ }));
2000
+ }
2001
+ }
1826
2002
  if (!response.ok) {
1827
2003
  let parsed = void 0;
1828
2004
  try {
@@ -1843,24 +2019,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1843
2019
  return rctx;
1844
2020
  }).retryIf("intercept", async (rctx, api) => {
1845
2021
  const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1846
- if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
1847
- else api.proceedRetry();
2022
+ if (rctx.error instanceof VigorFetchError && rctx.error.code === "REDIRECTED") api.cancelRetry();
2023
+ else if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
1848
2024
  return rctx;
1849
2025
  }).onRetry("intercept", async (rctx, api) => {
1850
2026
  const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1851
- if (response?.status === 429) {
1852
- let retryHeader = null;
2027
+ if (response?.status === 429 || response?.status === 503) {
1853
2028
  for (const header of ctx.policy.settings.retryHeaders) {
1854
- retryHeader = response.headers.get(header);
1855
- if (retryHeader) break;
1856
- }
1857
- if (retryHeader) {
1858
- const toNumber = Number(retryHeader);
1859
- const delay = !isNaN(toNumber) ? toNumber * 1e3 : (() => {
1860
- const toDate = new Date(retryHeader).getTime();
1861
- return !isNaN(toDate) ? toDate - Date.now() : null;
1862
- })();
1863
- if (delay !== null && delay > 0) api.setDelay(delay);
2029
+ const delay = this._parseRetryHeader(response.headers.get(header));
2030
+ if (delay !== null) {
2031
+ api.setDelay(delay);
2032
+ break;
2033
+ }
1864
2034
  }
1865
2035
  }
1866
2036
  return rctx;
@@ -1875,7 +2045,7 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1875
2045
  } else {
1876
2046
  ctx = await middleware.func(ctx, { throwError, setResult: (r) => {
1877
2047
  ctx.result = r;
1878
- } });
2048
+ } }) ?? ctx;
1879
2049
  }
1880
2050
  }
1881
2051
  const setResult = (r) => {
@@ -1885,7 +2055,7 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1885
2055
  if (middleware._mode === "fluent") {
1886
2056
  ctx.result = await middleware.func(ctx.result);
1887
2057
  } else {
1888
- ctx = await middleware.func(ctx, { setResult, throwError });
2058
+ ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1889
2059
  }
1890
2060
  }
1891
2061
  return {
@@ -1907,11 +2077,11 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1907
2077
  if (middleware._mode === "fluent") {
1908
2078
  await middleware.func(ctx.error);
1909
2079
  } else {
1910
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
2080
+ ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1911
2081
  }
1912
2082
  }
1913
2083
  if (ctx.flags.restarted) {
1914
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
2084
+ if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
1915
2085
  method: "request",
1916
2086
  cause: ctx.error,
1917
2087
  data: {
@@ -1998,13 +2168,18 @@ var cloneVigor = (v) => ({
1998
2168
  all: { ...v.builders.all }
1999
2169
  }
2000
2170
  });
2001
- var vigor = {
2002
- ...vigorBase,
2003
- use: (plugin, options) => {
2004
- const ext = plugin.func(vigor, options);
2005
- return { ...cloneVigor(vigor), ...ext };
2006
- }
2171
+ var createVigor = (fields) => {
2172
+ const instance = {
2173
+ ...fields,
2174
+ use: (plugin, options) => {
2175
+ const ext = plugin.func(instance, options);
2176
+ const { use: _, ...rest } = { ...cloneVigor(instance), ...ext };
2177
+ return createVigor(rest);
2178
+ }
2179
+ };
2180
+ return instance;
2007
2181
  };
2182
+ var vigor = createVigor(vigorBase);
2008
2183
 
2009
2184
  // src/index.ts
2010
2185
  var index_default = vigor;
@@ -2063,5 +2238,9 @@ var index_default = vigor;
2063
2238
  VigorRetryPolicySettings,
2064
2239
  VigorRetryPolicySettingsBase,
2065
2240
  VigorStatus,
2241
+ isVigorAllError,
2242
+ isVigorFetchError,
2243
+ isVigorParseError,
2244
+ isVigorRetryError,
2066
2245
  vigor
2067
2246
  });