vigor-fetch 4.0.8 → 4.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,8 +12,9 @@ Vigor gives you an immutable, chainable API for building robust network logic: r
12
12
  - 🔁 **Two-level retry** — per-attempt retry/backoff *and* whole-pipeline restart, each independently configurable
13
13
  - 🌐 **Smart fetch layer** — automatic `429 Retry-After` handling, configurable "never retry" status codes
14
14
  - 🔌 **Content-aware parsing** — auto-detects `Content-Type`, with a sniffing fallback and custom strategies
15
- - ⚡ **Bounded concurrency runner** — run many tasks with a concurrency cap and per-task hooks
15
+ - ⚡ **Bounded concurrency runner** — run many tasks with a concurrency cap, batch-level hooks, and per-task hooks
16
16
  - 🪝 **Two middleware modes** — `"fluent"` (return a value) or `"intercept"` (get an explicit control API)
17
+ - 🧬 **Type-level result override** — `.cast<T>()` on every module, when you know better than inference does
17
18
  - 🧠 **TypeScript-first** — config shape is inferred and carried through the whole chain
18
19
 
19
20
  ---
@@ -89,15 +90,43 @@ const results = await vigor
89
90
  ```ts
90
91
  vigor.fetch(origin?) // -> VigorFetch, origin pre-set if given
91
92
  vigor.retry(task?) // -> VigorRetry, target pre-set if given
92
- vigor.parse(response?) // -> VigorParse, target pre-set if given
93
+ vigor.parse(request|response?) // -> VigorParse, target pre-set if given
93
94
  vigor.all(...tasks) // -> VigorAll, target pre-set if any tasks given
94
95
  vigor.use(plugin, options?)
96
+ vigor.builders // direct access to each module's sub-builders
95
97
  ```
96
98
 
97
- Every module follows the same shape: an **immutable builder** with `.settings()`, `.middlewares()`, and a terminal `.request()` / `.requestVerbose()` pair.
99
+ Every module follows the same shape: an **immutable builder** with `.settings()`, `.middlewares()`, a terminal `.request()` / `.requestVerbose()` pair, and a `.cast<T>()` escape hatch for the result type.
98
100
 
99
101
  - `.request()` returns the result directly and **throws** on final failure.
100
102
  - `.requestVerbose()` never throws — it returns `{ success: true, data, error: null }` or `{ success: false, data: null, error }`.
103
+ - `.cast<T>()` overrides the inferred result type with `T`. It can be called before or after any other configuration method — whichever `.cast<T>()` call happens *last* in the chain wins, and it always takes priority over the naturally-inferred type.
104
+
105
+ ### `vigor.builders`
106
+
107
+ Every sub-builder used internally by `.settings()`/`.middlewares()`/etc. is also reachable directly, if you'd rather construct a reusable config object outside of a chain:
108
+
109
+ ```ts
110
+ vigor.builders.fetch.settings() // -> VigorFetchPolicySettings
111
+ vigor.builders.fetch.middlewares() // -> VigorFetchPolicyMiddlewares
112
+
113
+ vigor.builders.retry.settings() // -> VigorRetryPolicySettings
114
+ vigor.builders.retry.middlewares() // -> VigorRetryPolicyMiddlewares
115
+ vigor.builders.retry.algorithms() // -> VigorRetryPolicyAlgorithms
116
+ vigor.builders.retry.algorithm.constant()
117
+ vigor.builders.retry.algorithm.linear()
118
+ vigor.builders.retry.algorithm.backoff()
119
+ vigor.builders.retry.algorithm.custom()
120
+
121
+ vigor.builders.parse.settings() // -> VigorParsePolicySettings
122
+ vigor.builders.parse.middlewares() // -> VigorParsePolicyMiddlewares
123
+ vigor.builders.parse.strategies() // -> VigorParsePolicyStrategies
124
+
125
+ vigor.builders.all.settings() // -> VigorAllPolicySettings
126
+ vigor.builders.all.middlewares() // -> VigorAllPolicyMiddlewares
127
+ ```
128
+
129
+ This is equivalent to `new VigorFetchPolicySettings()` etc., just namespaced under `vigor` for discoverability.
101
130
 
102
131
  ---
103
132
 
@@ -118,7 +147,8 @@ Every module follows the same shape: an **immutable builder** with `.settings()`
118
147
  | `settings(fn \| config)` | Configures fetch-level settings (below) |
119
148
  | `middlewares(fn \| config)` | Configures the fetch middleware pipeline (below) |
120
149
  | `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request |
121
- | `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the response |
150
+ | `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response |
151
+ | `cast<T>()` | Overrides the inferred result type with `T` |
122
152
  | `request()` | Executes and returns the parsed result, throwing on failure |
123
153
  | `requestVerbose()` | Executes and returns `{ success, data, error }` |
124
154
 
@@ -207,6 +237,19 @@ const data = await vigor
207
237
 
208
238
  Both accept a config object, a builder callback, or an already-built `VigorRetry`/`VigorParse` instance. The target function you'd normally set with `.target()` is ignored here — fetch always supplies its own target (the actual `fetch()` call) and its own `.target()` (`response.clone()` fed through your parse config).
209
239
 
240
+ ### cast
241
+
242
+ ```ts
243
+ const data = await vigor
244
+ .fetch("/api/users")
245
+ .parse(p => p.strategies(s => s.json()))
246
+ .cast<{ id: string; name: string }[]>()
247
+ .request();
248
+ // data: { id: string; name: string }[]
249
+ ```
250
+
251
+ Without `.cast()`, the result type falls back to whatever your `parse()` config naturally infers (`unknown` if unconfigured). `.cast()` overrides that regardless of where in the chain it's called.
252
+
210
253
  ---
211
254
 
212
255
  ## `vigor.retry`
@@ -220,6 +263,7 @@ Both accept a config object, a builder callback, or an already-built `VigorRetry
220
263
  | `settings(fn \| config)` | General retry settings (below) |
221
264
  | `middlewares(fn \| config)` | Middleware pipeline (below) |
222
265
  | `algorithms(fn)` | Selects and configures the delay algorithm (below) |
266
+ | `cast<T>()` | Overrides the inferred result type with `T` |
223
267
  | `request()` / `requestVerbose()` | Executes |
224
268
 
225
269
  ```ts
@@ -303,23 +347,24 @@ There are two independent resilience layers here:
303
347
 
304
348
  | Method | Description |
305
349
  |---|---|
306
- | `target(response)` | Sets the `Response` to parse |
350
+ | `target(request\|response)` | Sets the `Request\|Response` to parse |
307
351
  | `settings(fn \| config)` | General settings (below) |
308
352
  | `middlewares(fn \| config)` | Middleware pipeline (below) |
309
353
  | `strategies(fn \| config)` | Configures the ordered fallback chain of parsing strategies |
354
+ | `cast<T>()` | Overrides the inferred result type with `T` |
310
355
  | `request()` / `requestVerbose()` | Executes |
311
356
 
312
357
  ### settings
313
358
 
314
359
  | Method | Description | Default |
315
360
  |---|---|---|
316
- | `raw(bool)` | When `true`, skips parsing entirely and returns the raw `Response` object | `false` |
361
+ | `raw(bool)` | When `true`, skips parsing entirely and returns the raw `Request\|Response` object | `false` |
317
362
  | `default(fn)` | Fallback value/factory when parsing ultimately fails | throws |
318
363
  | `maxRestarts(num)` | Max full pipeline restarts | `3` |
319
364
 
320
365
  ### strategies
321
366
 
322
- Strategies form an ordered list that's tried in sequence until one succeeds (each attempt but the last clones the response first, so a failed strategy doesn't consume the body). If you never configure any, Vigor defaults to content-type detection.
367
+ Strategies form an ordered list that's tried in sequence until one succeeds (each attempt but the last clones the request|response first, so a failed strategy doesn't consume the body). If you never configure any, Vigor defaults to content-type detection.
323
368
 
324
369
  ```ts
325
370
  .strategies(s => s.sniff())
@@ -327,7 +372,7 @@ Strategies form an ordered list that's tried in sequence until one succeeds (eac
327
372
 
328
373
  | Method | Behavior |
329
374
  |---|---|
330
- | `contentType(replace?)` | Parses based on the response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text) |
375
+ | `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text) |
331
376
  | `sniff(replace?)` | Tries `json → formData → text → blob` in order until one parses |
332
377
  | `json(replace?)` | Always parses as JSON |
333
378
  | `text(replace?)` | Always parses as text |
@@ -335,7 +380,7 @@ Strategies form an ordered list that's tried in sequence until one succeeds (eac
335
380
  | `blob(replace?)` | Always parses as `Blob` |
336
381
  | `bytes(replace?)` | Always parses as `Uint8Array` |
337
382
  | `formData(replace?)` | Always parses as `FormData` |
338
- | `custom(func, replace?)` | Uses a custom `(response: Response) => Promise<any>` |
383
+ | `custom(func, replace?)` | Uses a custom `(request\|response: Request\|Response) => Promise<any>` |
339
384
 
340
385
  By default each call **appends** to the chain (they concatenate, so you can layer fallbacks: e.g. `contentType()` then `sniff()` as a last resort). Pass `replace: true` as the trailing argument to replace the whole chain instead.
341
386
 
@@ -363,7 +408,7 @@ const data = await vigor
363
408
 
364
409
  ## `vigor.all`
365
410
 
366
- Runs a fixed list of zero-argument tasks with bounded concurrency.
411
+ Runs a fixed list of zero-argument tasks with bounded concurrency, `Promise.allSettled`-style — an individual task failing never makes the whole batch throw by itself.
367
412
 
368
413
  ### Methods
369
414
 
@@ -371,7 +416,8 @@ Runs a fixed list of zero-argument tasks with bounded concurrency.
371
416
  |---|---|
372
417
  | `target(...funcs)` | Sets the task list — each is `() => unknown \| Promise<unknown>` |
373
418
  | `settings(fn \| config)` | Concurrency settings (below) |
374
- | `middlewares(fn \| config)` | Per-task hooks (below) |
419
+ | `middlewares(fn \| config)` | Batch-level and per-task hooks (below) |
420
+ | `cast<T>()` | Overrides the inferred result type with `T` |
375
421
  | `request()` / `requestVerbose()` | Executes |
376
422
 
377
423
  ```ts
@@ -390,43 +436,71 @@ const results = await vigor
390
436
  | Method | Description | Default |
391
437
  |---|---|---|
392
438
  | `concurrency(num)` | Max number of tasks running at once | `5` |
393
- | `onlySuccess(bool)` | When `true`, filters the final array down to only tasks whose middleware chain resolved successfully | `false` |
439
+ | `onlySuccess(bool)` | When `true`, filters the final array down to only tasks whose result wasn't recovered as a failure | `false` |
394
440
 
395
- > Unlike `vigor.retry`/`vigor.fetch`/`vigor.parse`, `vigor.all` has no `default`/fallback setting, and per-task failures don't throw the whole call by themselves — a task that fails (and whose `onError` middleware doesn't call `setResult`) simply contributes its error value into the results array (or is dropped, if `onlySuccess` is on). The only thing that makes `.request()` throw is an **empty** task list.
441
+ > Unlike `vigor.retry`/`vigor.fetch`/`vigor.parse`, `vigor.all` has no `default`/fallback setting and no batch-level `onError` — the only thing that makes `.request()` throw is an **empty** task list (`EMPTY_TARGET`). Per-task failures are handled by `onErrorEach` (below) instead.
442
+
443
+ **Result typing:** when `onlySuccess` is `false` (the default) and `target(...)` is given as literal task functions, the result is inferred as a **tuple** matching each task's own return type — `.target(() => 1 as const, () => "a")` infers `[1, "a"]`, not `unknown[]`. Setting `onlySuccess(true)` filters the array at runtime to an arbitrary length, so the type falls back to a plain array. `.cast<T>()` overrides either case.
396
444
 
397
445
  ### hooks (`middlewares`)
398
446
 
399
- Unlike the other modules, `all`'s per-task hooks are plain functions — there's no `"fluent"`/`"intercept"` mode split.
447
+ `all` has **two tiers** of hooks: batch-level stages (run once for the whole call, support `"fluent"`/`"intercept"` modes like the other modules) and per-task stages (run once per task, plain callbacks with no mode argument).
400
448
 
401
- | Stage | Signature | Runs |
402
- |---|---|---|
403
- | `before(fn)` | `(ctx) => void \| Promise<void>` | Before each task is invoked |
404
- | `after(fn)` | `(ctx) => void \| Promise<void>` | After a task settles successfully |
405
- | `onError(fn)` | `(ctx, { setResult }) => void \| Promise<void>` | When an individual task throws |
449
+ | Stage | Level | Runs | API |
450
+ |---|---|---|---|
451
+ | `before(type, fn)` | Batch | Once, before any task starts | `throwError` (intercept mode) |
452
+ | `after(type, fn)` | Batch | Once, after every task has settled | `setResult`, `throwError` (intercept mode) |
453
+ | `onResult(type, fn)` | Batch | Once, right before returning the final result | `setResult`, `throwError` (intercept mode) |
454
+ | `beforeEach(fn)` | Per-task | Before each individual task is invoked | — |
455
+ | `afterEach(fn)` | Per-task | After a task settles successfully | — |
456
+ | `onErrorEach(fn)` | Per-task | When an individual task throws | `setResult` |
406
457
 
407
458
  ```ts
408
459
  .middlewares(m => m
409
- .onError(async (ctx, api) => {
460
+ .before("fluent", (ctx) => { console.log("starting batch"); })
461
+ .onResult("intercept", async (ctx, api) => {
462
+ if (ctx.result.length === 0) api.throwError(new Error("nothing succeeded"));
463
+ return ctx;
464
+ })
465
+ .onErrorEach(async (ctx, api) => {
410
466
  console.error(ctx.error);
411
467
  api.setResult(null); // recover instead of letting this task register as failed
412
468
  })
413
469
  )
414
470
  ```
415
471
 
472
+ Batch-level fluent signatures: `before`/`after` take `(ctx) => void`, `onResult` takes `(res) => newRes`. Per-task hooks (`beforeEach`, `afterEach`, `onErrorEach`) are always plain functions — there's no fluent/intercept split for these, since they observe/mutate a single task's context rather than the pipeline's control flow.
473
+
416
474
  ---
417
475
 
418
476
  ## Plugins
419
477
 
420
478
  ```ts
421
- export type VigorPlugin<O> = {
422
- options: O // type-only anchor for inferring O — not used at runtime
423
- func: (v: typeof vigor, options: O) => void
479
+ export type VigorPlugin<
480
+ O extends Record<string, any> = {},
481
+ Ext extends Record<string, any> = Record<string, any>
482
+ > = {
483
+ options: O
484
+ func: (v: VigorInstance, options: O) => Ext
424
485
  }
425
486
 
426
487
  vigor.use(plugin, options?)
427
488
  ```
428
489
 
429
- `vigor.use(plugin, options)` simply invokes `plugin.func(vigor, options)` — a lightweight hook for setup-time side effects (e.g. registering shared config, wiring up logging) rather than a full plugin/extension system.
490
+ `plugin.func` receives the current `vigor` instance (read-only — plugins never mutate it, e.g. they might read it to wrap an existing method) and returns `Ext`, a set of properties to merge in. `vigor.use()` shallow-clones `vigor` (including its nested `builders` groups) and merges `Ext` on top, returning a **new** instance — `VigorInstance & Ext` — leaving the original `vigor` untouched.
491
+
492
+ ```ts
493
+ const loggingPlugin: VigorPlugin<{ prefix?: string }> = {
494
+ options: {},
495
+ func: (v, options) => ({
496
+ fetch: (origin?: string) => v.fetch(origin).middlewares(m => m
497
+ .before("fluent", (ctx) => console.log(options.prefix ?? "[vigor]", ctx.href))
498
+ ),
499
+ }),
500
+ };
501
+
502
+ const myVigor = vigor.use(loggingPlugin, { prefix: "[api]" });
503
+ ```
430
504
 
431
505
  ---
432
506
 
@@ -468,4 +542,5 @@ if (!res.success) {
468
542
 
469
543
  - Every builder is **immutable** — `.settings(...)`, `.path(...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
470
544
  - Array-valued config (`path`, `query`, parse `strategies`, etc.) **concatenates** across calls by default; object-valued config deep-merges. A handful of methods (`hash`, `headers("overwrite", ...)`, `body("overwrite", ...)`, `options("overwrite", ...)`, `retry(...)`, `parse(...)`, `algorithms(...)`) force a full **replace** instead, since merging wouldn't make sense there.
471
- - Config shape is tracked through the whole chain via TypeScript generics, so `.settings()`/`.middlewares()` callbacks and `.request()`'s inferred return type stay accurate as you chain.
545
+ - Config shape is tracked through the whole chain via TypeScript generics, so `.settings()`/`.middlewares()` callbacks and `.request()`'s inferred return type stay accurate as you chain.
546
+ - `.cast<T>()` is available on every module (`fetch`, `retry`, `parse`, `all`) and always wins over the naturally-inferred type, regardless of where in the chain it's called.
package/dist/index.cjs CHANGED
@@ -120,16 +120,26 @@ var VigorStatus = class {
120
120
  */
121
121
  _merge(source, target, strategy) {
122
122
  const isObj = (v) => v !== null && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
123
+ const deepClone = (v) => {
124
+ if (Array.isArray(v)) return v.map(deepClone);
125
+ if (isObj(v)) {
126
+ const r = {};
127
+ for (const k of Object.keys(v)) r[k] = deepClone(v[k]);
128
+ return r;
129
+ }
130
+ return v;
131
+ };
123
132
  const merge = (a, b, s) => {
124
- if (b === void 0 || b === null) return a;
133
+ if (b === void 0 || b === null) return deepClone(a);
125
134
  if (s === "replace") return b;
126
135
  if (Array.isArray(a) && Array.isArray(b)) {
127
136
  return s === "replace" ? b : [...a, ...b];
128
137
  }
129
138
  if (isObj(a) && isObj(b)) {
130
- const r = { ...a };
139
+ const r = {};
131
140
  const sObj = isObj(s) ? s : void 0;
132
- for (const k of Object.keys(b)) {
141
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
142
+ for (const k of keys) {
133
143
  r[k] = merge(a[k], b[k], sObj?.[k]);
134
144
  }
135
145
  return r;
@@ -176,7 +186,10 @@ var VigorAllPolicyMiddlewaresBase = {
176
186
  __brand: createBrand("All", "Policy<Middlewares<Schema"),
177
187
  before: [],
178
188
  after: [],
179
- onError: []
189
+ onResult: [],
190
+ beforeEach: [],
191
+ afterEach: [],
192
+ onErrorEach: []
180
193
  };
181
194
  var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorStatus {
182
195
  constructor(config = VigorAllBase) {
@@ -185,17 +198,26 @@ var VigorAllPolicyMiddlewares = class _VigorAllPolicyMiddlewares extends VigorSt
185
198
  _create(config) {
186
199
  return new _VigorAllPolicyMiddlewares(config);
187
200
  }
201
+ before(type, func) {
202
+ return this._next({ policy: { middlewares: { before: [{ _mode: type, func }] } } });
203
+ }
204
+ after(type, func) {
205
+ return this._next({ policy: { middlewares: { after: [{ _mode: type, func }] } } });
206
+ }
207
+ onResult(type, func) {
208
+ return this._next({ policy: { middlewares: { onResult: [{ _mode: type, func }] } } });
209
+ }
188
210
  /** Registers a middleware that runs before each task is invoked. */
189
- before(func) {
190
- return this._next({ policy: { middlewares: { before: [func] } } });
211
+ beforeEach(func) {
212
+ return this._next({ policy: { middlewares: { beforeEach: [func] } } });
191
213
  }
192
214
  /** Registers a middleware that runs after each task settles successfully. */
193
- after(func) {
194
- return this._next({ policy: { middlewares: { after: [func] } } });
215
+ afterEach(func) {
216
+ return this._next({ policy: { middlewares: { afterEach: [func] } } });
195
217
  }
196
218
  /** Registers a middleware that runs when an individual task fails. */
197
- onError(func) {
198
- return this._next({ policy: { middlewares: { onError: [func] } } });
219
+ onErrorEach(func) {
220
+ return this._next({ policy: { middlewares: { onErrorEach: [func] } } });
199
221
  }
200
222
  };
201
223
 
@@ -280,7 +302,6 @@ var VigorAll = class _VigorAll extends VigorStatus {
280
302
  target(...funcs) {
281
303
  return this._next({ policy: { target: funcs } });
282
304
  }
283
- /** Configures the all-policy's general settings (concurrency, onlySuccess). */
284
305
  settings(input) {
285
306
  if (typeof input === "function" || input instanceof VigorAllPolicySettings) {
286
307
  const result = typeof input === "function" ? input(new VigorAllPolicySettings()) : input;
@@ -290,7 +311,6 @@ var VigorAll = class _VigorAll extends VigorStatus {
290
311
  }
291
312
  return this._next({ policy: { settings: input } });
292
313
  }
293
- /** Configures the all-policy's per-task middleware pipeline. */
294
314
  middlewares(input) {
295
315
  if (typeof input === "function" || input instanceof VigorAllPolicyMiddlewares) {
296
316
  const result = typeof input === "function" ? input(new VigorAllPolicyMiddlewares()) : input;
@@ -300,13 +320,13 @@ var VigorAll = class _VigorAll extends VigorStatus {
300
320
  }
301
321
  return this._next({ policy: { middlewares: input } });
302
322
  }
303
- /** Runs a single task through the before/after/onError middleware pipeline. */
323
+ /** Runs a single task through the beforeEach/afterEach/onErrorEach middleware pipeline. */
304
324
  async _runTask(task, policy) {
305
- let ctx = { ...VigorAllEachContextBase };
325
+ let ctx = this._merge(VigorAllEachContextBase, {});
306
326
  try {
307
- for (const before of policy.middlewares.before) await before(ctx);
327
+ for (const beforeEach of policy.middlewares.beforeEach) await beforeEach(ctx);
308
328
  ctx.result = await task();
309
- for (const after of policy.middlewares.after) await after(ctx);
329
+ for (const afterEach of policy.middlewares.afterEach) await afterEach(ctx);
310
330
  return { success: true, value: ctx.result };
311
331
  } catch (error) {
312
332
  ctx.error = error;
@@ -314,7 +334,7 @@ var VigorAll = class _VigorAll extends VigorStatus {
314
334
  ctx.flags.overrided = true;
315
335
  ctx.result = r;
316
336
  };
317
- for (const onError of policy.middlewares.onError) await onError(ctx, { setResult });
337
+ for (const onErrorEach of policy.middlewares.onErrorEach) await onErrorEach(ctx, { setResult });
318
338
  if (ctx.flags.overrided) return { success: true, value: ctx.result };
319
339
  return { success: false, value: error };
320
340
  }
@@ -341,15 +361,32 @@ var VigorAll = class _VigorAll extends VigorStatus {
341
361
  async requestVerbose() {
342
362
  return await this.requestRuntime();
343
363
  }
344
- /** Internal execution loop implementing the bounded-concurrency worker pool. */
345
- async requestRuntime(restartAttempt = 1) {
364
+ /** Internal execution loop implementing the bounded-concurrency worker pool and the batch-level before/after/onResult pipeline. */
365
+ async requestRuntime() {
346
366
  const config = this._merge(this.config, {});
347
367
  const policy = config.policy;
368
+ let ctx = this._merge(VigorAllContextBase, {
369
+ policy
370
+ });
371
+ const setResult = (r) => {
372
+ ctx = { ...ctx, result: r };
373
+ };
374
+ const throwError = (err) => {
375
+ throw err;
376
+ };
348
377
  try {
349
378
  if (policy.target.length === 0) throw new VigorAllError("EMPTY_TARGET", {
350
379
  method: "request",
351
- data: {}
380
+ data: {},
381
+ context: ctx
352
382
  });
383
+ for (const mw of policy.middlewares.before) {
384
+ if (mw._mode === "fluent") {
385
+ await mw.func(ctx);
386
+ } else {
387
+ ctx = await mw.func(ctx, { throwError });
388
+ }
389
+ }
353
390
  const concurrency = Math.max(1, policy.settings.concurrency);
354
391
  const results = new Array(policy.target.length);
355
392
  let cursor = 0;
@@ -363,10 +400,24 @@ var VigorAll = class _VigorAll extends VigorStatus {
363
400
  await Promise.all(
364
401
  Array.from({ length: Math.min(concurrency, policy.target.length) }, () => worker())
365
402
  );
366
- const result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
403
+ ctx.result = policy.settings.onlySuccess ? results.filter((r) => r.success).map((r) => r.value) : results.map((r) => r.value);
404
+ for (const mw of policy.middlewares.after) {
405
+ if (mw._mode === "fluent") {
406
+ await mw.func(ctx);
407
+ } else {
408
+ ctx = await mw.func(ctx, { setResult, throwError });
409
+ }
410
+ }
411
+ for (const mw of policy.middlewares.onResult) {
412
+ if (mw._mode === "fluent") {
413
+ ctx.result = await mw.func(ctx.result);
414
+ } else {
415
+ ctx = await mw.func(ctx, { setResult, throwError });
416
+ }
417
+ }
367
418
  return {
368
419
  success: true,
369
- data: result,
420
+ data: ctx.result,
370
421
  error: null
371
422
  };
372
423
  } catch (error) {
@@ -824,7 +875,6 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
824
875
  policy: { abortSignals: sig }
825
876
  });
826
877
  }
827
- /** Configures the retry policy's general settings (max attempts, timeout, etc). */
828
878
  settings(input) {
829
879
  if (typeof input === "function" || input instanceof VigorRetryPolicySettings) {
830
880
  const result = typeof input === "function" ? input(new VigorRetryPolicySettings()) : input;
@@ -836,7 +886,6 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
836
886
  policy: { settings: input }
837
887
  });
838
888
  }
839
- /** Configures the retry policy's middleware pipeline. */
840
889
  middlewares(input) {
841
890
  if (typeof input === "function" || input instanceof VigorRetryPolicyMiddlewares) {
842
891
  const result = typeof input === "function" ? input(new VigorRetryPolicyMiddlewares()) : input;
@@ -848,7 +897,6 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
848
897
  policy: { middlewares: input }
849
898
  });
850
899
  }
851
- /** Configures the retry policy's delay algorithm. */
852
900
  algorithms(input) {
853
901
  if (typeof input === "function") {
854
902
  const result = input(new VigorRetryPolicyAlgorithms());
@@ -886,10 +934,9 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
886
934
  /** Internal execution loop implementing the attempt/retry/restart lifecycle. */
887
935
  async requestRuntime(restartAttempt = 1) {
888
936
  const config = this._merge(this.config, {});
889
- let ctx = {
890
- ...VigorRetryContextBase,
937
+ let ctx = this._merge(VigorRetryContextBase, {
891
938
  policy: config.policy
892
- };
939
+ });
893
940
  if (isVigorEmpty(ctx.policy.target)) throw new VigorRetryError("VALUE_REQUIRED", {
894
941
  method: "request",
895
942
  data: {
@@ -943,7 +990,8 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
943
990
  method: "request",
944
991
  data: {
945
992
  limit: ctx.policy.settings.timeout
946
- }
993
+ },
994
+ context: ctx
947
995
  })), ctx.policy.settings.timeout);
948
996
  ctx.result = await Promise.race([
949
997
  target(mergedSignals),
@@ -1025,7 +1073,8 @@ var VigorRetry = class _VigorRetry extends VigorStatus {
1025
1073
  data: {
1026
1074
  maxAttempts: ctx.policy.settings.maxAttempts,
1027
1075
  error: ctx.error
1028
- }
1076
+ },
1077
+ context: ctx
1029
1078
  });
1030
1079
  } catch (error) {
1031
1080
  ctx.error = error;
@@ -1313,7 +1362,6 @@ var VigorParse = class _VigorParse extends VigorStatus {
1313
1362
  target(response) {
1314
1363
  return this._next({ policy: { target: response } });
1315
1364
  }
1316
- /** Configures the parse policy's general settings. */
1317
1365
  settings(input) {
1318
1366
  if (typeof input === "function" || input instanceof VigorParsePolicySettings) {
1319
1367
  const result = typeof input === "function" ? input(new VigorParsePolicySettings()) : input;
@@ -1323,7 +1371,6 @@ var VigorParse = class _VigorParse extends VigorStatus {
1323
1371
  }
1324
1372
  return this._next({ policy: { settings: input } });
1325
1373
  }
1326
- /** Configures the parse policy's middleware pipeline. */
1327
1374
  middlewares(input) {
1328
1375
  if (typeof input === "function" || input instanceof VigorParsePolicyMiddlewares) {
1329
1376
  const result = typeof input === "function" ? input(new VigorParsePolicyMiddlewares()) : input;
@@ -1333,7 +1380,6 @@ var VigorParse = class _VigorParse extends VigorStatus {
1333
1380
  }
1334
1381
  return this._next({ policy: { middlewares: input } });
1335
1382
  }
1336
- /** Configures the parse policy's fallback chain of parsing strategies. */
1337
1383
  strategies(input) {
1338
1384
  if (typeof input === "function" || input instanceof VigorParsePolicyStrategies) {
1339
1385
  const result = typeof input === "function" ? input(new VigorParsePolicyStrategies()) : input;
@@ -1368,10 +1414,9 @@ var VigorParse = class _VigorParse extends VigorStatus {
1368
1414
  /** Internal execution loop implementing the strategy fallback and restart handling. */
1369
1415
  async requestRuntime(restartAttempt = 1) {
1370
1416
  const config = this._merge(this.config, {});
1371
- let ctx = {
1372
- ...VigorParseContextBase,
1417
+ let ctx = this._merge(VigorParseContextBase, {
1373
1418
  policy: config.policy
1374
- };
1419
+ });
1375
1420
  if (isVigorDefault(ctx.policy.target)) throw new VigorParseError("VALUE_REQUIRED", {
1376
1421
  method: "request",
1377
1422
  data: { key: "target" },
@@ -1389,10 +1434,10 @@ var VigorParse = class _VigorParse extends VigorStatus {
1389
1434
  ctx = await middleware.func(ctx, { throwError });
1390
1435
  }
1391
1436
  }
1392
- const response = ctx.response;
1393
1437
  if (ctx.policy.settings.raw) {
1394
- ctx.result = response;
1438
+ ctx.result = ctx.response;
1395
1439
  } else {
1440
+ const response = ctx.response;
1396
1441
  const funcs = ctx.policy.strategies.funcs.length > 0 ? ctx.policy.strategies.funcs : [VigorParseContentTypeStrategy];
1397
1442
  let parsed = false;
1398
1443
  for (const [i, func] of funcs.entries()) {
@@ -1456,7 +1501,8 @@ var VigorParse = class _VigorParse extends VigorStatus {
1456
1501
  data: {
1457
1502
  maxAttempts: ctx.policy.settings.maxRestarts,
1458
1503
  error: ctx.error
1459
- }
1504
+ },
1505
+ context: ctx
1460
1506
  });
1461
1507
  return await this.requestRuntime(restartAttempt + 1);
1462
1508
  }
@@ -1508,7 +1554,7 @@ var VigorFetchContextBase = {
1508
1554
  error: VigorDefault,
1509
1555
  options: VigorDefault,
1510
1556
  flags: {
1511
- overrided: false,
1557
+ overridden: false,
1512
1558
  restarted: false
1513
1559
  },
1514
1560
  record: {},
@@ -1605,7 +1651,6 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1605
1651
  if (mode === "overwrite") return this._next({ policy: { extra: obj } }, { policy: { extra: "replace" } });
1606
1652
  return this._next({ policy: { extra: obj } });
1607
1653
  }
1608
- /** Configures the fetch policy's general settings. */
1609
1654
  settings(input) {
1610
1655
  if (typeof input === "function" || input instanceof VigorFetchPolicySettings) {
1611
1656
  const result = typeof input === "function" ? input(new VigorFetchPolicySettings()) : input;
@@ -1615,7 +1660,6 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1615
1660
  }
1616
1661
  return this._next({ policy: { settings: input } });
1617
1662
  }
1618
- /** Configures the fetch policy's middleware pipeline. */
1619
1663
  middlewares(input) {
1620
1664
  if (typeof input === "function" || input instanceof VigorFetchPolicyMiddlewares) {
1621
1665
  const result = typeof input === "function" ? input(new VigorFetchPolicyMiddlewares()) : input;
@@ -1625,7 +1669,6 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1625
1669
  }
1626
1670
  return this._next({ policy: { middlewares: input } });
1627
1671
  }
1628
- /** Configures the retry engine used to send the underlying request. */
1629
1672
  retry(input) {
1630
1673
  if (typeof input === "function" || input instanceof VigorRetry) {
1631
1674
  const result = typeof input === "function" ? input(new VigorRetry()) : input;
@@ -1633,7 +1676,6 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1633
1676
  }
1634
1677
  return this._next({ policy: { retry: input } }, { policy: { retry: "replace" } });
1635
1678
  }
1636
- /** Configures the parse engine used to interpret the response. */
1637
1679
  parse(input) {
1638
1680
  if (typeof input === "function" || input instanceof VigorParse) {
1639
1681
  const result = typeof input === "function" ? input(new VigorParse()) : input;
@@ -1731,17 +1773,17 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1731
1773
  /** Internal execution loop implementing URL building, retry, parsing, and restart handling. */
1732
1774
  async requestRuntime(restartAttempt = 1) {
1733
1775
  const config = this._merge(this.config, {});
1734
- let ctx = {
1735
- ...VigorFetchContextBase,
1776
+ let ctx = this._merge(VigorFetchContextBase, {
1736
1777
  policy: config.policy
1737
- };
1778
+ });
1738
1779
  const throwError = (err) => {
1739
1780
  throw err;
1740
1781
  };
1741
1782
  try {
1742
1783
  if (isVigorEmpty(ctx.policy.origin)) throw new VigorFetchError("VALUE_REQUIRED", {
1743
1784
  method: "request",
1744
- data: { key: "origin" }
1785
+ data: { key: "origin" },
1786
+ context: ctx
1745
1787
  });
1746
1788
  ctx.href = this._buildUrl(ctx.policy.origin, ctx.policy.path, ctx.policy.query, ctx.policy.hash);
1747
1789
  const hasBody = !isVigorEmpty(ctx.policy.body) && ctx.policy.body !== void 0;
@@ -1853,10 +1895,10 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1853
1895
  };
1854
1896
  } catch (error) {
1855
1897
  ctx.error = error;
1856
- ctx.flags.overrided = false;
1898
+ ctx.flags.overridden = false;
1857
1899
  ctx.flags.restarted = false;
1858
1900
  const setResult = (r) => {
1859
- ctx.flags.overrided = true;
1901
+ ctx.flags.overridden = true;
1860
1902
  ctx.result = r;
1861
1903
  };
1862
1904
  const proceedRestart = () => ctx.flags.restarted = true;
@@ -1875,11 +1917,12 @@ var VigorFetch = class _VigorFetch extends VigorStatus {
1875
1917
  data: {
1876
1918
  maxAttempts: ctx.policy.settings.maxRestarts,
1877
1919
  error: ctx.error
1878
- }
1920
+ },
1921
+ context: ctx
1879
1922
  });
1880
1923
  return await this.requestRuntime(restartAttempt + 1);
1881
1924
  }
1882
- if (ctx.flags.overrided) return {
1925
+ if (ctx.flags.overridden) return {
1883
1926
  success: true,
1884
1927
  data: ctx.result,
1885
1928
  error: null