vigor-fetch 4.0.10 → 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.js CHANGED
@@ -18,7 +18,7 @@ var VigorStatus = class {
18
18
  */
19
19
  constructor(base, config) {
20
20
  this._base = base;
21
- this._config = this._merge(base, config);
21
+ this._config = this._merge(base, config, void 0, "replace");
22
22
  }
23
23
  /**
24
24
  * Derives a new instance by merging `patch` onto the current config.
@@ -36,9 +36,11 @@ var VigorStatus = class {
36
36
  /**
37
37
  * Deep-merges `target` onto `source`, honoring an optional per-path
38
38
  * `strategy` tree. Objects merge key by key, arrays concatenate (unless
39
- * `"replace"` is specified), and any other value is overwritten.
39
+ * `"replace"` is specified, or `arrayMode` is `"replace"`), and any other
40
+ * value — including `null` — is overwritten. Only `undefined` keeps the
41
+ * source value.
40
42
  */
41
- _merge(source, target, strategy) {
43
+ _merge(source, target, strategy, arrayMode = "concat") {
42
44
  const isObj = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
43
45
  const deepClone = (v) => {
44
46
  if (Array.isArray(v)) return v.map(deepClone);
@@ -50,10 +52,10 @@ var VigorStatus = class {
50
52
  return v;
51
53
  };
52
54
  const merge = (a, b, s) => {
53
- if (b === void 0 || b === null) return deepClone(a);
55
+ if (b === void 0) return deepClone(a);
54
56
  if (s === "replace") return b;
55
57
  if (Array.isArray(a) && Array.isArray(b)) {
56
- return s === "replace" ? b : [...a, ...b];
58
+ return arrayMode === "replace" ? deepClone(b) : [...a, ...b];
57
59
  }
58
60
  if (isObj(a) && isObj(b)) {
59
61
  const r = {};
@@ -82,7 +84,9 @@ var VigorStatus = class {
82
84
  var VigorAllPolicySettingsBase = {
83
85
  __brand: createBrand("All", "Policy<Settings<Schema"),
84
86
  concurrency: 5,
85
- onlySuccess: false
87
+ onlySuccess: false,
88
+ timeout: VigorEmpty,
89
+ failFast: false
86
90
  };
87
91
  var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
88
92
  constructor(config = VigorAllBase) {
@@ -99,6 +103,14 @@ var VigorAllPolicySettings = class _VigorAllPolicySettings extends VigorStatus {
99
103
  onlySuccess(bool) {
100
104
  return this._next({ policy: { settings: { onlySuccess: bool } } });
101
105
  }
106
+ /** Sets the per-task timeout, in milliseconds. A task exceeding it fails with `TIMED_OUT`. */
107
+ timeout(num) {
108
+ return this._next({ policy: { settings: { timeout: num } } });
109
+ }
110
+ /** When enabled, the first unrecovered task failure aborts the remaining tasks and fails the batch with that error. */
111
+ failFast(bool) {
112
+ return this._next({ policy: { settings: { failFast: bool } } });
113
+ }
102
114
  };
103
115
 
104
116
  // src/all/middlewares.ts
@@ -145,6 +157,7 @@ var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorSt
145
157
  var VigorAllPolicyBase = {
146
158
  __brand: createBrand("All", "Policy<Schema"),
147
159
  target: [],
160
+ abortSignals: [],
148
161
  settings: VigorAllPolicySettingsBase,
149
162
  middlewares: VigorAllPolicyMiddlewaresBase
150
163
  };
@@ -158,9 +171,10 @@ var VigorAllContextBase = {
158
171
  };
159
172
  var VigorAllEachContextBase = {
160
173
  __brand: createBrand("All", "EachContext<Schema"),
174
+ index: 0,
161
175
  result: VigorDefault,
162
176
  error: VigorDefault,
163
- flags: { overrided: false },
177
+ flags: { overridden: false },
164
178
  record: {}
165
179
  };
166
180
 
@@ -192,7 +206,8 @@ var VigorError = class extends Error {
192
206
 
193
207
  // src/all/error.ts
194
208
  var VigorAllErrorMessageFuncs = {
195
- EMPTY_TARGET: (_) => `Empty target list`
209
+ EMPTY_TARGET: (_) => `Empty target list`,
210
+ TIMED_OUT: ({ limit, index }) => `Task #${index} timeout: exceeded ${limit}ms`
196
211
  };
197
212
  var VigorAllError = class extends VigorError {
198
213
  /**
@@ -204,6 +219,7 @@ var VigorAllError = class extends VigorError {
204
219
  super(code, messageFn(options.data), options);
205
220
  }
206
221
  };
222
+ var isVigorAllError = (error) => error instanceof VigorAllError;
207
223
 
208
224
  // src/all/main.ts
209
225
  var VigorAllBase = {
@@ -222,6 +238,10 @@ var VigorAll = class _VigorAll extends VigorStatus {
222
238
  target(...funcs) {
223
239
  return this._next({ policy: { target: funcs } });
224
240
  }
241
+ /** Sets external abort signals that, when aborted, cancel the remaining tasks and fail the batch. */
242
+ abortSignals(...sig) {
243
+ return this._next({ policy: { abortSignals: sig } });
244
+ }
225
245
  settings(input) {
226
246
  if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
227
247
  const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
@@ -241,22 +261,43 @@ var VigorAll = class _VigorAll extends VigorStatus {
241
261
  return this._next({ policy: { middlewares: input } });
242
262
  }
243
263
  /** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
244
- async _runTask(task, policy) {
245
- let ctx = this._merge(VigorAllEachContextBase, {});
264
+ async _runTask(task, index, policy, batchSignal) {
265
+ let ctx = this._merge(VigorAllEachContextBase, { index });
266
+ const timeoutController = new AbortController();
267
+ const signal = AbortSignal.any([batchSignal, timeoutController.signal]);
268
+ let timeoutId;
269
+ let onAbort;
246
270
  try {
247
271
  for (const beforeEach of policy.middlewares.beforeEach) await beforeEach(ctx);
248
- ctx.result = await task();
272
+ signal.throwIfAborted();
273
+ const limit = policy.settings.timeout;
274
+ if (!isVigorEmpty(limit)) {
275
+ timeoutId = setTimeout(() => timeoutController.abort(new VigorAllError("TIMED_OUT", {
276
+ method: "request",
277
+ data: { limit, index }
278
+ })), limit);
279
+ }
280
+ ctx.result = await Promise.race([
281
+ task(signal),
282
+ new Promise((_, rej) => {
283
+ onAbort = () => rej(signal.reason);
284
+ signal.addEventListener("abort", onAbort);
285
+ })
286
+ ]);
249
287
  for (const afterEach of policy.middlewares.afterEach) await afterEach(ctx);
250
288
  return { success: true, value: ctx.result };
251
289
  } catch (error) {
252
290
  ctx.error = error;
253
291
  const setResult = (r) => {
254
- ctx.flags.overrided = true;
292
+ ctx.flags.overridden = true;
255
293
  ctx.result = r;
256
294
  };
257
295
  for (const onErrorEach of policy.middlewares.onErrorEach) await onErrorEach(ctx, { setResult });
258
- if (ctx.flags.overrided) return { success: true, value: ctx.result };
296
+ if (ctx.flags.overridden) return { success: true, value: ctx.result };
259
297
  return { success: false, value: error };
298
+ } finally {
299
+ clearTimeout(timeoutId);
300
+ if (onAbort) signal.removeEventListener("abort", onAbort);
260
301
  }
261
302
  }
262
303
  /**
@@ -287,9 +328,9 @@ var VigorAll = class _VigorAll extends VigorStatus {
287
328
  const policy = config.policy;
288
329
  let ctx = this._merge(VigorAllContextBase, {
289
330
  policy
290
- });
331
+ }, void 0, "replace");
291
332
  const setResult = (r) => {
292
- ctx = { ...ctx, result: r };
333
+ ctx.result = r;
293
334
  };
294
335
  const throwError = (err) => {
295
336
  throw err;
@@ -304,35 +345,46 @@ var VigorAll = class _VigorAll extends VigorStatus {
304
345
  if (mw._mode === "fluent") {
305
346
  await mw.func(ctx);
306
347
  } else {
307
- ctx = await mw.func(ctx, { throwError });
348
+ ctx = await mw.func(ctx, { throwError }) ?? ctx;
308
349
  }
309
350
  }
310
- const concurrency = Math.max(1, policy.settings.concurrency);
351
+ const concurrency = Number.isNaN(policy.settings.concurrency) ? 1 : Math.max(1, Math.floor(policy.settings.concurrency));
311
352
  const results = new Array(policy.target.length);
353
+ const batchController = new AbortController();
354
+ const batchSignal = AbortSignal.any([...policy.abortSignals, batchController.signal]);
312
355
  let cursor = 0;
313
356
  const worker = async () => {
314
- while (true) {
357
+ while (!batchSignal.aborted) {
315
358
  const i = cursor++;
316
359
  if (i >= policy.target.length) return;
317
- results[i] = await this._runTask(policy.target[i], policy);
360
+ try {
361
+ results[i] = await this._runTask(policy.target[i], i, policy, batchSignal);
362
+ } catch (error) {
363
+ batchController.abort(error);
364
+ return;
365
+ }
366
+ if (!results[i].success && policy.settings.failFast) {
367
+ batchController.abort(results[i].value);
368
+ }
318
369
  }
319
370
  };
320
371
  await Promise.all(
321
372
  Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
322
373
  );
374
+ batchSignal.throwIfAborted();
323
375
  ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
324
376
  for (const mw of policy.middlewares.after) {
325
377
  if (mw._mode === "fluent") {
326
378
  await mw.func(ctx);
327
379
  } else {
328
- ctx = await mw.func(ctx, { setResult, throwError });
380
+ ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
329
381
  }
330
382
  }
331
383
  for (const mw of policy.middlewares.onResult) {
332
384
  if (mw._mode === "fluent") {
333
385
  ctx.result = await mw.func(ctx.result);
334
386
  } else {
335
- ctx = await mw.func(ctx, { setResult, throwError });
387
+ ctx = await mw.func(ctx, { setResult, throwError }) ?? ctx;
336
388
  }
337
389
  }
338
390
  return {
@@ -353,8 +405,9 @@ var VigorAll = class _VigorAll extends VigorStatus {
353
405
  // src/fetch/settings.ts
354
406
  var VigorFetchPolicySettingsBase = {
355
407
  __brand: createBrand("Fetch", "Policy<Settings<Schema"),
356
- retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"],
408
+ retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"],
357
409
  unretryStatus: [400, 401, 403, 404, 405, 413, 422],
410
+ redirect: true,
358
411
  maxRestarts: 3,
359
412
  default: VigorEmpty
360
413
  };
@@ -365,13 +418,21 @@ var VigorFetchPolicySettings = class _VigorFetchPolicySettings extends VigorStat
365
418
  _create(config) {
366
419
  return new _VigorFetchPolicySettings(config);
367
420
  }
368
- /** Sets response headers consulted to compute a server-suggested retry delay. */
421
+ /** Sets (replaces) the response headers consulted to compute a server-suggested retry delay. */
369
422
  retryHeaders(...strs) {
370
- return this._next({ policy: { settings: { retryHeaders: strs } } });
423
+ return this._next({ policy: { settings: { retryHeaders: strs } } }, { policy: { settings: { retryHeaders: "replace" } } });
371
424
  }
372
- /** Sets HTTP status codes that should never be retried. */
425
+ /** Sets (replaces) the HTTP status codes that should never be retried. */
373
426
  unretryStatus(...nums) {
374
- return this._next({ policy: { settings: { unretryStatus: nums } } });
427
+ return this._next({ policy: { settings: { unretryStatus: nums } } }, { policy: { settings: { unretryStatus: "replace" } } });
428
+ }
429
+ /**
430
+ * When enabled, a `3xx` response with a `Location` header navigates the
431
+ * page to that URL (`window.location.href`). Without `window.location`
432
+ * — e.g. in Node — this behaves like `false`.
433
+ */
434
+ redirect(bool) {
435
+ return this._next({ policy: { settings: { redirect: bool } } });
375
436
  }
376
437
  /** Sets the maximum number of full restarts allowed. */
377
438
  maxRestarts(num) {
@@ -519,6 +580,7 @@ var VigorRetryError = class extends VigorError {
519
580
  super(code, messageFn(options.data), options);
520
581
  }
521
582
  };
583
+ var isVigorRetryError = (error) => error instanceof VigorRetryError;
522
584
 
523
585
  // src/retry/algorithms.ts
524
586
  function VigorJitter(jitter) {
@@ -771,6 +833,7 @@ var VigorRetryContextBase = {
771
833
  };
772
834
 
773
835
  // src/retry/main.ts
836
+ var MAX_TIMEOUT = 2 ** 31 - 1;
774
837
  var VigorRetryBase = {
775
838
  __brand: createBrand("Retry", "Schema"),
776
839
  policy: VigorRetryPolicyBase,
@@ -849,14 +912,18 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
849
912
  }
850
913
  /** Runs the target and returns a result/error envelope instead of throwing. */
851
914
  async requestVerbose() {
852
- return await this.requestRuntime();
915
+ try {
916
+ return await this.requestRuntime();
917
+ } catch (error) {
918
+ return { success: false, data: null, error };
919
+ }
853
920
  }
854
921
  /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
855
922
  async requestRuntime(restartAttempt = 1) {
856
923
  const config = this._merge(this.config, {});
857
924
  let ctx = this._merge(VigorRetryContextBase, {
858
925
  policy: config.policy
859
- });
926
+ }, void 0, "replace");
860
927
  if (isVigorEmpty(ctx.policy.target)) throw new VigorRetryError("VALUE_REQUIRED", {
861
928
  method: "request",
862
929
  data: {
@@ -868,6 +935,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
868
935
  const throwError = (err) => {
869
936
  throw err;
870
937
  };
938
+ const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
871
939
  try {
872
940
  while (ctx.system.attempt < ctx.policy.settings.maxAttempts) {
873
941
  ctx.system.attempt++;
@@ -882,11 +950,6 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
882
950
  userController.signal,
883
951
  timeoutController.signal
884
952
  ]);
885
- const outerSignals = AbortSignal.any(ctx.policy.abortSignals);
886
- const autoBreak = () => {
887
- ctx.flags.brokeRetry = true;
888
- };
889
- outerSignals.addEventListener("abort", autoBreak);
890
953
  const mergedSignals = AbortSignal.any([
891
954
  innerSignals,
892
955
  outerSignals
@@ -902,17 +965,20 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
902
965
  abort: (reason) => userController.abort(reason),
903
966
  throwError,
904
967
  breakRetry
905
- });
968
+ }) ?? ctx;
906
969
  }
907
970
  }
908
971
  mergedSignals.throwIfAborted();
909
- timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
910
- method: "request",
911
- data: {
912
- limit: ctx.policy.settings.timeout
913
- },
914
- context: ctx
915
- })), ctx.policy.settings.timeout);
972
+ const limit = ctx.policy.settings.timeout;
973
+ if (Number.isFinite(limit) && limit > 0) {
974
+ timeoutId = setTimeout(() => timeoutController.abort(new VigorRetryError("TIMED_OUT", {
975
+ method: "request",
976
+ data: {
977
+ limit
978
+ },
979
+ context: ctx
980
+ })), Math.min(limit, MAX_TIMEOUT));
981
+ }
916
982
  ctx.result = await Promise.race([
917
983
  target(mergedSignals),
918
984
  new Promise((_, rej) => {
@@ -926,7 +992,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
926
992
  } else {
927
993
  ctx = await middleware.func(ctx, {
928
994
  throwError
929
- });
995
+ }) ?? ctx;
930
996
  }
931
997
  }
932
998
  const setResult = (res) => {
@@ -939,7 +1005,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
939
1005
  ctx = await middleware.func(ctx, {
940
1006
  setResult,
941
1007
  throwError
942
- });
1008
+ }) ?? ctx;
943
1009
  }
944
1010
  }
945
1011
  return {
@@ -949,11 +1015,11 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
949
1015
  };
950
1016
  } finally {
951
1017
  clearTimeout(timeoutId);
952
- outerSignals.removeEventListener("abort", autoBreak);
953
1018
  if (onAbort) mergedSignals.removeEventListener("abort", onAbort);
954
1019
  }
955
1020
  } catch (error) {
956
1021
  ctx.error = error;
1022
+ if (outerSignals.aborted) ctx.flags.brokeRetry = true;
957
1023
  if (ctx.flags.brokeRetry) throw ctx.error;
958
1024
  ctx.flags.doRetry = true;
959
1025
  const proceedRetry = () => ctx.flags.doRetry = true;
@@ -965,7 +1031,7 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
965
1031
  ctx = await middleware.func(ctx, {
966
1032
  proceedRetry,
967
1033
  cancelRetry
968
- });
1034
+ }) ?? ctx;
969
1035
  }
970
1036
  }
971
1037
  if (!ctx.flags.doRetry) throw ctx.error;
@@ -980,11 +1046,26 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
980
1046
  ctx = await middleware.func(ctx, {
981
1047
  throwError,
982
1048
  setDelay
983
- });
1049
+ }) ?? ctx;
984
1050
  }
985
1051
  }
986
- const delay = ctx.system.delay;
987
- await new Promise((res) => setTimeout(res, delay));
1052
+ const delay = Math.min(Math.max(0, Number(ctx.system.delay) || 0), MAX_TIMEOUT);
1053
+ await new Promise((res, rej) => {
1054
+ if (outerSignals.aborted) {
1055
+ ctx.flags.brokeRetry = true;
1056
+ return rej(outerSignals.reason);
1057
+ }
1058
+ const onAbort = () => {
1059
+ clearTimeout(id);
1060
+ ctx.flags.brokeRetry = true;
1061
+ rej(outerSignals.reason);
1062
+ };
1063
+ const id = setTimeout(() => {
1064
+ outerSignals.removeEventListener("abort", onAbort);
1065
+ res();
1066
+ }, delay);
1067
+ outerSignals.addEventListener("abort", onAbort, { once: true });
1068
+ });
988
1069
  }
989
1070
  }
990
1071
  throw new VigorRetryError("RETRY_EXHAUSTED", {
@@ -1015,17 +1096,18 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1015
1096
  throwError,
1016
1097
  proceedRestart,
1017
1098
  cancelRestart
1018
- });
1099
+ }) ?? ctx;
1019
1100
  }
1020
1101
  }
1021
1102
  if (ctx.flags.doRestart) {
1022
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
1103
+ if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorRetryError("RESTART_EXHAUSTED", {
1023
1104
  method: "request",
1024
1105
  cause: ctx.error,
1025
1106
  data: {
1026
1107
  maxAttempts: ctx.policy.settings.maxRestarts,
1027
1108
  error: ctx.error
1028
- }
1109
+ },
1110
+ context: ctx
1029
1111
  });
1030
1112
  return await this.requestRuntime(restartAttempt + 1);
1031
1113
  }
@@ -1132,14 +1214,20 @@ var VigorParseError = class extends VigorError {
1132
1214
  super(code, messageFn(options.data), options);
1133
1215
  }
1134
1216
  };
1217
+ var isVigorParseError = (error) => error instanceof VigorParseError;
1135
1218
 
1136
1219
  // src/parse/strategies.ts
1137
1220
  var VigorParsePolicyStrategiesBase = {
1138
1221
  __brand: createBrand("Parse", "Policy<Strategies<Schema"),
1139
1222
  funcs: []
1140
1223
  };
1224
+ var parseJsonOrNull = async (res) => {
1225
+ const text = await res.text();
1226
+ return text.trim() === "" ? null : JSON.parse(text);
1227
+ };
1228
+ var NoBodyStatus = [204, 205, 304];
1141
1229
  var ContentTypeParsers = [
1142
- { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: (res) => res.json() },
1230
+ { header: "application/json", regExp: /application\/(.+\+)?json(.+\+)?/i, method: parseJsonOrNull },
1143
1231
  { header: "application/xml", regExp: /application\/(.+\+)?xml(.+\+)?/i, method: (res) => res.text() },
1144
1232
  { header: "application/x-www-form-urlencoded", regExp: /application\/(.+\+)?x-www-form-urlencoded(.+\+)?/i, method: (res) => res.formData() },
1145
1233
  { header: "application/octet-stream", regExp: /application\/(.+\+)?octet-stream(.+\+)?/i, method: (res) => res.arrayBuffer() },
@@ -1156,11 +1244,12 @@ var SniffMethods = [
1156
1244
  { title: "blob", method: (res) => res.blob() }
1157
1245
  ];
1158
1246
  var VigorParseContentTypeStrategy = async (response) => {
1247
+ if (response.body === null || NoBodyStatus.includes(response.status)) return null;
1159
1248
  const contentTypeHeader = response.headers.get("content-type");
1160
- if (!contentTypeHeader) throw new VigorParseError("INVALID_CONTENT_TYPE", {
1161
- method: "VigorParseContentTypeStrategy",
1162
- data: { received: contentTypeHeader }
1163
- });
1249
+ if (!contentTypeHeader) {
1250
+ const text = await response.text();
1251
+ return text === "" ? null : text;
1252
+ }
1164
1253
  const toDo = ContentTypeParsers.find((parser) => parser.regExp.test(contentTypeHeader));
1165
1254
  if (!toDo) throw new VigorParseError("PARSER_NOT_FOUND", {
1166
1255
  method: "VigorParseContentTypeStrategy",
@@ -1258,7 +1347,7 @@ var VigorParseContextBase = {
1258
1347
  error: VigorDefault,
1259
1348
  response: VigorDefault,
1260
1349
  flags: {
1261
- overrided: false,
1350
+ overridden: false,
1262
1351
  restarted: false
1263
1352
  },
1264
1353
  record: {},
@@ -1329,14 +1418,18 @@ var VigorParse = class _VigorParse extends VigorStatus {
1329
1418
  }
1330
1419
  /** Runs parsing and returns a result/error envelope instead of throwing. */
1331
1420
  async requestVerbose() {
1332
- return await this.requestRuntime();
1421
+ try {
1422
+ return await this.requestRuntime();
1423
+ } catch (error) {
1424
+ return { success: false, data: null, error };
1425
+ }
1333
1426
  }
1334
1427
  /** Internal execution loop implementing the strategy fallback and restart handling. */
1335
1428
  async requestRuntime(restartAttempt = 1) {
1336
1429
  const config = this._merge(this.config, {});
1337
1430
  let ctx = this._merge(VigorParseContextBase, {
1338
1431
  policy: config.policy
1339
- });
1432
+ }, void 0, "replace");
1340
1433
  if (isVigorDefault(ctx.policy.target)) throw new VigorParseError("VALUE_REQUIRED", {
1341
1434
  method: "request",
1342
1435
  data: { key: "target" },
@@ -1351,7 +1444,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
1351
1444
  if (middleware._mode === "fluent") {
1352
1445
  await middleware.func(ctx);
1353
1446
  } else {
1354
- ctx = await middleware.func(ctx, { throwError });
1447
+ ctx = await middleware.func(ctx, { throwError }) ?? ctx;
1355
1448
  }
1356
1449
  }
1357
1450
  if (ctx.policy.settings.raw) {
@@ -1382,14 +1475,14 @@ var VigorParse = class _VigorParse extends VigorStatus {
1382
1475
  if (middleware._mode === "fluent") {
1383
1476
  await middleware.func(ctx);
1384
1477
  } else {
1385
- ctx = await middleware.func(ctx, { setResult, throwError });
1478
+ ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1386
1479
  }
1387
1480
  }
1388
1481
  for (const middleware of ctx.policy.middlewares.onResult) {
1389
1482
  if (middleware._mode === "fluent") {
1390
1483
  ctx.result = await middleware.func(ctx.result);
1391
1484
  } else {
1392
- ctx = await middleware.func(ctx, { setResult, throwError });
1485
+ ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1393
1486
  }
1394
1487
  }
1395
1488
  return {
@@ -1399,10 +1492,10 @@ var VigorParse = class _VigorParse extends VigorStatus {
1399
1492
  };
1400
1493
  } catch (error) {
1401
1494
  ctx.error = error;
1402
- ctx.flags.overrided = false;
1495
+ ctx.flags.overridden = false;
1403
1496
  ctx.flags.restarted = false;
1404
1497
  const setResult = (res) => {
1405
- ctx.flags.overrided = true;
1498
+ ctx.flags.overridden = true;
1406
1499
  ctx.result = res;
1407
1500
  };
1408
1501
  const proceedRestart = () => ctx.flags.restarted = true;
@@ -1411,11 +1504,11 @@ var VigorParse = class _VigorParse extends VigorStatus {
1411
1504
  if (middleware._mode === "fluent") {
1412
1505
  await middleware.func(ctx.error);
1413
1506
  } else {
1414
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1507
+ ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1415
1508
  }
1416
1509
  }
1417
1510
  if (ctx.flags.restarted) {
1418
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1511
+ if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorParseError("RESTART_EXHAUSTED", {
1419
1512
  method: "request",
1420
1513
  cause: ctx.error,
1421
1514
  data: {
@@ -1426,7 +1519,7 @@ var VigorParse = class _VigorParse extends VigorStatus {
1426
1519
  });
1427
1520
  return await this.requestRuntime(restartAttempt + 1);
1428
1521
  }
1429
- if (ctx.flags.overrided) return {
1522
+ if (ctx.flags.overridden) return {
1430
1523
  success: true,
1431
1524
  data: ctx.result,
1432
1525
  error: null
@@ -1487,7 +1580,8 @@ var VigorFetchErrorMessageFuncs = {
1487
1580
  INVALID_BODY: ({ received }) => `Invalid Body type: ${typeof received}`,
1488
1581
  INVALID_PROTOCOL: ({ origin, base }) => base ? `Invalid URL: could not resolve "${origin}" against base "${base}"` : `Invalid URL: "${origin}" is not an absolute URL, and no base (window.location) is available to resolve it against \u2014 pass an absolute origin (e.g. "https://api.example.com") when running outside a browser`,
1489
1582
  FETCH_FAILED: ({ status, statusText }) => `Fetch Failed: ${status} ${statusText}`,
1490
- RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`
1583
+ RESTART_EXHAUSTED: ({ maxAttempts }) => `Restart exhausted, (max ${maxAttempts})`,
1584
+ REDIRECTED: ({ url, status }) => `Redirected (${status}) to "${url}" \u2014 navigating away`
1491
1585
  };
1492
1586
  var VigorFetchError = class extends VigorError {
1493
1587
  /**
@@ -1499,6 +1593,7 @@ var VigorFetchError = class extends VigorError {
1499
1593
  super(code, messageFn(options.data), options);
1500
1594
  }
1501
1595
  };
1596
+ var isVigorFetchError = (error) => error instanceof VigorFetchError;
1502
1597
 
1503
1598
  // src/fetch/main.ts
1504
1599
  var VigorFetchBase = {
@@ -1572,13 +1667,15 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1572
1667
  return this._next({ policy: { extra: obj } });
1573
1668
  }
1574
1669
  settings(input) {
1670
+ const strategy = { policy: { settings: { retryHeaders: "replace", unretryStatus: "replace" } } };
1575
1671
  if (typeof input === "function" || input instanceof VigorFetchPolicySettings) {
1576
- const result = typeof input === "function" ? input(new VigorFetchPolicySettings()) : input;
1672
+ const result = typeof input === "function" ? input(new VigorFetchPolicySettings(this.config)) : input;
1577
1673
  return this._next(
1578
- { policy: { settings: result.config.policy.settings } }
1674
+ { policy: { settings: result.config.policy.settings } },
1675
+ strategy
1579
1676
  );
1580
1677
  }
1581
- return this._next({ policy: { settings: input } });
1678
+ return this._next({ policy: { settings: input } }, strategy);
1582
1679
  }
1583
1680
  middlewares(input) {
1584
1681
  if (typeof input === "function" || input instanceof VigorFetchPolicyMiddlewares) {
@@ -1638,7 +1735,9 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1638
1735
  }
1639
1736
  const baseStr = originObj.origin;
1640
1737
  const pathParts = [originObj.pathname.replace(/^\/+|\/+$/g, "")];
1641
- for (const p of path) pathParts.push(p.replace(/^\/+|\/+$/g, ""));
1738
+ for (const p of path) {
1739
+ for (const part of p.split("/")) pathParts.push(encodeURIComponent(part));
1740
+ }
1642
1741
  const pathStr = pathParts.filter(Boolean).join("/");
1643
1742
  const mainObj = new URL(pathStr, baseStr);
1644
1743
  const parseVal = (val) => val instanceof Date ? val.toISOString() : String(val);
@@ -1659,7 +1758,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1659
1758
  if (body == null) return { headers: {}, body };
1660
1759
  if (typeof body === "string") return { headers: { "Content-Type": "text/plain;charset=UTF-8" }, body };
1661
1760
  if (body instanceof Blob) return { headers: body.type ? { "Content-Type": body.type } : {}, body };
1662
- if (body instanceof ArrayBuffer) return { headers: { "Content-Type": "application/octet-stream" }, body };
1761
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { headers: { "Content-Type": "application/octet-stream" }, body };
1762
+ if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) return { headers: { "Content-Type": "application/octet-stream" }, body };
1663
1763
  if (body instanceof URLSearchParams) return { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" }, body };
1664
1764
  if (body instanceof FormData) return { headers: {}, body };
1665
1765
  if (typeof body === "object") return { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
@@ -1668,6 +1768,57 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1668
1768
  data: { received: body }
1669
1769
  });
1670
1770
  }
1771
+ /**
1772
+ * Returns the absolute URL a `3xx` response points at, or `null` when the
1773
+ * response isn't a redirect or carries no usable `Location` header. A
1774
+ * relative `Location` is resolved against the responding URL.
1775
+ */
1776
+ _resolveRedirect(response, href) {
1777
+ if (response.status < 300 || response.status >= 400) return null;
1778
+ const location = response.headers.get("location");
1779
+ if (!location) return null;
1780
+ try {
1781
+ return new URL(location, response.url || href).href;
1782
+ } catch {
1783
+ return null;
1784
+ }
1785
+ }
1786
+ /** The browser's `location`, or `null` in environments without one (e.g. Node). */
1787
+ _browserLocation() {
1788
+ const win = globalThis.window;
1789
+ return win?.location?.href !== void 0 ? win.location : null;
1790
+ }
1791
+ /** Assigns `source` headers onto `target`, replacing any existing key that differs only in case. */
1792
+ _assignHeaders(target, source) {
1793
+ for (const [key, value] of Object.entries(source)) {
1794
+ const lower = key.toLowerCase();
1795
+ for (const existing of Object.keys(target)) {
1796
+ if (existing.toLowerCase() === lower) delete target[existing];
1797
+ }
1798
+ target[key] = value;
1799
+ }
1800
+ }
1801
+ /**
1802
+ * Converts a rate-limit header value into a delay in milliseconds, or
1803
+ * `null` if it can't be used. Accepts delta seconds (`Retry-After: 120`),
1804
+ * Unix epoch seconds or milliseconds (`X-RateLimit-Reset: 1735689600`),
1805
+ * and HTTP dates.
1806
+ */
1807
+ _parseRetryHeader(value) {
1808
+ if (!value) return null;
1809
+ const num = Number(value);
1810
+ let delay;
1811
+ if (value.trim() !== "" && !isNaN(num)) {
1812
+ if (num >= 1e12) delay = num - Date.now();
1813
+ else if (num >= 1e9) delay = num * 1e3 - Date.now();
1814
+ else delay = num * 1e3;
1815
+ } else {
1816
+ const date = new Date(value).getTime();
1817
+ if (isNaN(date)) return null;
1818
+ delay = date - Date.now();
1819
+ }
1820
+ return delay > 0 ? delay : null;
1821
+ }
1671
1822
  /**
1672
1823
  * Overrides the resolved result type with `T`, taking priority over the
1673
1824
  * default `unknown` result. Can be called before or after `parse()` (or
@@ -1688,14 +1839,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1688
1839
  }
1689
1840
  /** Runs the request and returns a result/error envelope instead of throwing. */
1690
1841
  async requestVerbose() {
1691
- return await this.requestRuntime();
1842
+ try {
1843
+ return await this.requestRuntime();
1844
+ } catch (error) {
1845
+ return { success: false, data: null, error };
1846
+ }
1692
1847
  }
1693
1848
  /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1694
1849
  async requestRuntime(restartAttempt = 1) {
1695
1850
  const config = this._merge(this.config, {});
1696
1851
  let ctx = this._merge(VigorFetchContextBase, {
1697
1852
  policy: config.policy
1698
- });
1853
+ }, void 0, "replace");
1699
1854
  const throwError = (err) => {
1700
1855
  throw err;
1701
1856
  };
@@ -1706,9 +1861,9 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1706
1861
  context: ctx
1707
1862
  });
1708
1863
  ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1709
- const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== void 0;
1864
+ const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body != null;
1710
1865
  const method = isVigorEmpty(ctx.policy.method) ? hasBody ? "POST" : "GET" : ctx.policy.method;
1711
- let options = {
1866
+ const options = {
1712
1867
  ...ctx.policy.extra,
1713
1868
  method,
1714
1869
  headers: {}
@@ -1718,7 +1873,8 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1718
1873
  if (normalized.body !== void 0) options.body = normalized.body;
1719
1874
  Object.assign(options.headers, normalized.headers);
1720
1875
  }
1721
- Object.assign(options.headers, ctx.policy.headers);
1876
+ this._assignHeaders(options.headers, ctx.policy.headers);
1877
+ ctx.options = options;
1722
1878
  for (const middleware of ctx.policy.middlewares.before) {
1723
1879
  if (middleware._mode === "fluent") {
1724
1880
  await middleware.func(ctx);
@@ -1726,23 +1882,39 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1726
1882
  ctx = await middleware.func(ctx, {
1727
1883
  throwError,
1728
1884
  setOptions: (o) => {
1729
- options = o;
1885
+ ctx.options = o;
1730
1886
  },
1731
1887
  setHeaders: (h) => {
1732
- options.headers = h;
1888
+ ctx.options.headers = h;
1733
1889
  },
1734
1890
  setBody: (b) => {
1735
- options.body = b;
1891
+ ctx.options.body = b;
1736
1892
  }
1737
- });
1893
+ }) ?? ctx;
1738
1894
  }
1739
1895
  }
1740
- ctx.options = options;
1896
+ const finalOptions = isVigorDefault(ctx.options) ? options : ctx.options;
1897
+ ctx.options = finalOptions;
1898
+ if (typeof ReadableStream !== "undefined" && finalOptions.body instanceof ReadableStream) {
1899
+ finalOptions.duplex ??= "half";
1900
+ }
1741
1901
  const retryEngine = new VigorRetry(ctx.policy.retry).target(async (signal) => {
1742
- return await fetch(ctx.href, { ...options, signal });
1902
+ return await fetch(ctx.href, { ...finalOptions, signal });
1743
1903
  }).middlewares(
1744
1904
  (m) => m.after("intercept", async (rctx, api) => {
1745
1905
  const response = rctx.result;
1906
+ if (ctx.policy.settings.redirect) {
1907
+ const target = this._resolveRedirect(response, ctx.href);
1908
+ const location = this._browserLocation();
1909
+ if (target && location) {
1910
+ location.href = target;
1911
+ api.throwError(new VigorFetchError("REDIRECTED", {
1912
+ method: "request",
1913
+ data: { url: target, status: response.status, response },
1914
+ context: ctx
1915
+ }));
1916
+ }
1917
+ }
1746
1918
  if (!response.ok) {
1747
1919
  let parsed = void 0;
1748
1920
  try {
@@ -1763,24 +1935,18 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1763
1935
  return rctx;
1764
1936
  }).retryIf("intercept", async (rctx, api) => {
1765
1937
  const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1766
- if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
1767
- else api.proceedRetry();
1938
+ if (rctx.error instanceof VigorFetchError && rctx.error.code === "REDIRECTED") api.cancelRetry();
1939
+ else if (response && ctx.policy.settings.unretryStatus.includes(response.status)) api.cancelRetry();
1768
1940
  return rctx;
1769
1941
  }).onRetry("intercept", async (rctx, api) => {
1770
1942
  const response = rctx.error instanceof VigorFetchError ? rctx.error.data?.response : void 0;
1771
- if (response?.status === 429) {
1772
- let retryHeader = null;
1943
+ if (response?.status === 429 || response?.status === 503) {
1773
1944
  for (const header of ctx.policy.settings.retryHeaders) {
1774
- retryHeader = response.headers.get(header);
1775
- if (retryHeader) break;
1776
- }
1777
- if (retryHeader) {
1778
- const toNumber = Number(retryHeader);
1779
- const delay = !isNaN(toNumber) ? toNumber * 1e3 : (() => {
1780
- const toDate = new Date(retryHeader).getTime();
1781
- return !isNaN(toDate) ? toDate - Date.now() : null;
1782
- })();
1783
- if (delay !== null && delay > 0) api.setDelay(delay);
1945
+ const delay = this._parseRetryHeader(response.headers.get(header));
1946
+ if (delay !== null) {
1947
+ api.setDelay(delay);
1948
+ break;
1949
+ }
1784
1950
  }
1785
1951
  }
1786
1952
  return rctx;
@@ -1795,7 +1961,7 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1795
1961
  } else {
1796
1962
  ctx = await middleware.func(ctx, { throwError, setResult: (r) => {
1797
1963
  ctx.result = r;
1798
- } });
1964
+ } }) ?? ctx;
1799
1965
  }
1800
1966
  }
1801
1967
  const setResult = (r) => {
@@ -1805,7 +1971,7 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1805
1971
  if (middleware._mode === "fluent") {
1806
1972
  ctx.result = await middleware.func(ctx.result);
1807
1973
  } else {
1808
- ctx = await middleware.func(ctx, { setResult, throwError });
1974
+ ctx = await middleware.func(ctx, { setResult, throwError }) ?? ctx;
1809
1975
  }
1810
1976
  }
1811
1977
  return {
@@ -1827,11 +1993,11 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1827
1993
  if (middleware._mode === "fluent") {
1828
1994
  await middleware.func(ctx.error);
1829
1995
  } else {
1830
- ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart });
1996
+ ctx = await middleware.func(ctx, { setResult, throwError, proceedRestart, cancelRestart }) ?? ctx;
1831
1997
  }
1832
1998
  }
1833
1999
  if (ctx.flags.restarted) {
1834
- if (restartAttempt + 1 > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
2000
+ if (restartAttempt > ctx.policy.settings.maxRestarts) throw new VigorFetchError("RESTART_EXHAUSTED", {
1835
2001
  method: "request",
1836
2002
  cause: ctx.error,
1837
2003
  data: {
@@ -1918,13 +2084,18 @@ var cloneVigor = (v) => ({
1918
2084
  all: { ...v.builders.all }
1919
2085
  }
1920
2086
  });
1921
- var vigor = {
1922
- ...vigorBase,
1923
- use: (plugin, options) => {
1924
- const ext = plugin.func(vigor, options);
1925
- return { ...cloneVigor(vigor), ...ext };
1926
- }
2087
+ var createVigor = (fields) => {
2088
+ const instance = {
2089
+ ...fields,
2090
+ use: (plugin, options) => {
2091
+ const ext = plugin.func(instance, options);
2092
+ const { use: _, ...rest } = { ...cloneVigor(instance), ...ext };
2093
+ return createVigor(rest);
2094
+ }
2095
+ };
2096
+ return instance;
1927
2097
  };
2098
+ var vigor = createVigor(vigorBase);
1928
2099
 
1929
2100
  // src/index.ts
1930
2101
  var index_default = vigor;
@@ -1983,5 +2154,9 @@ export {
1983
2154
  VigorRetryPolicySettingsBase,
1984
2155
  VigorStatus,
1985
2156
  index_default as default,
2157
+ isVigorAllError,
2158
+ isVigorFetchError,
2159
+ isVigorParseError,
2160
+ isVigorRetryError,
1986
2161
  vigor
1987
2162
  };