vigor-fetch 4.1.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,6 +14,7 @@ Vigor gives you an immutable, chainable API for building robust network logic: r
14
14
  - 🔌 **Content-aware parsing** — auto-detects `Content-Type`, with a sniffing fallback and custom strategies
15
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
+ - 🕒 **Execution timeline** — with `settings.debug`, `requestVerbose()` returns a typed record of every step a request went through: each attempt's response, every retry decision and why, which middleware ran or threw, and how it ended — nested engines included
17
18
  - 🧬 **Type-level result override** — `.cast<T>()` on every module, when you know better than inference does
18
19
  - 🧠 **TypeScript-first** — config shape is inferred and carried through the whole chain
19
20
 
@@ -81,6 +82,7 @@ const results = await vigor
81
82
  () => fetch("/api/2")
82
83
  )
83
84
  .request();
85
+ // -> [{ success: true, data: Response, error: null }, { success: false, data: null, error: TypeError }]
84
86
  ```
85
87
 
86
88
  ---
@@ -94,13 +96,17 @@ vigor.parse(request|response?) // -> VigorParse, target pre-set if given
94
96
  vigor.all(...tasks) // -> VigorAll, target pre-set if any tasks given
95
97
  vigor.use(plugin, options?)
96
98
  vigor.builders // direct access to each module's sub-builders
99
+ vigor.guards // each module's error type guard
97
100
  ```
98
101
 
99
102
  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.
100
103
 
101
104
  - `.request()` returns the result directly and **throws** on final failure.
102
- - `.requestVerbose()` never throws — it returns `{ success: true, data, error: null }` or `{ success: false, data: null, error }`.
105
+ - `.requestVerbose()` never throws — it returns `{ success: true, data, error: null, timeline }` or `{ success: false, data: null, error, timeline }`. `timeline` is recorded only with `settings.debug` on. See [Timeline](#timeline). `vigor.fetch`'s envelope also carries `status` and `response` — see [Status and response](#status-and-response).
103
106
  - `.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.
107
+ - The result type includes what `settings.default` returns, since a fallback can become the result.
108
+ - `.request<R>()` / `.requestVerbose<R>()` take an optional type argument meaning "ignore the inference, it's `R`" — taken as-is, unchecked, for that call only. (`.cast<T>()` does the same on the builder, so it carries through `middlewares` too.)
109
+ - To name the inferred result type itself, use `VigorResultOf<typeof builder>` — `ReturnType<typeof builder.request>` can't see it, since `R` is a free override.
104
110
 
105
111
  ### `vigor.builders`
106
112
 
@@ -128,6 +134,17 @@ vigor.builders.all.middlewares() // -> VigorAllPolicyMiddlewares
128
134
 
129
135
  This is equivalent to `new VigorFetchPolicySettings()` etc., just namespaced under `vigor` for discoverability.
130
136
 
137
+ ### `vigor.guards`
138
+
139
+ Each module's error type guard, namespaced the same way (see [typed errors](#typed-errors)):
140
+
141
+ ```ts
142
+ vigor.guards.retry(err) // same as isVigorRetryError(err)
143
+ vigor.guards.parse(err) // isVigorParseError
144
+ vigor.guards.fetch(err) // isVigorFetchError
145
+ vigor.guards.all(err) // isVigorAllError
146
+ ```
147
+
131
148
  ---
132
149
 
133
150
  ## `vigor.fetch`
@@ -143,11 +160,13 @@ This is equivalent to `new VigorFetchPolicySettings()` etc., just namespaced und
143
160
  | `hash(str)` | Sets the URL fragment, replacing any previous value |
144
161
  | `headers(mode, obj)` | Sets headers. `mode`: `"overwrite"` (discard previous) or `"merge"` (`Object.assign`-style) |
145
162
  | `body(mode, obj)` | Sets the body. `"overwrite"` replaces it entirely; `"merge"` shallow-merges when both old and new body are plain objects, otherwise replaces |
146
- | `options(mode, obj)` | Sets extra native `RequestInit` fields other than `method`/`headers`/`body`/`signal` (e.g. `credentials`, `mode`, `cache`) |
163
+ | `options(mode, obj)` | Sets extra native `RequestInit` fields other than `method`/`headers`/`body`/`signal` (e.g. `credentials`, `mode`, `cache`). `"merge"` shallow-merges onto the previous options |
147
164
  | `settings(fn \| config)` | Configures fetch-level settings (below) |
148
165
  | `middlewares(fn \| config)` | Configures the fetch middleware pipeline (below) |
149
- | `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request |
150
- | `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response |
166
+ | `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request. Replaces the previous engine config; a config object is applied on top of the retry defaults |
167
+ | `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response. Replaces the previous engine config; a config object is applied on top of the parse defaults. Its result type (`.cast<T>()`, `raw`, middlewares, `default`) becomes the request's result type |
168
+ | `apiMap<M>()` | Attaches a type-level API map: the matched route's `response` becomes the result type (see [apiMap / route](#apimap--route)) |
169
+ | `route(key, params?)` | Sets method and path from an API map route, filling its `:name` segments |
151
170
  | `cast<T>()` | Overrides the inferred result type with `T` |
152
171
  | `request()` | Executes and returns the parsed result, throwing on failure |
153
172
  | `requestVerbose()` | Executes and returns `{ success, data, error }` |
@@ -168,6 +187,98 @@ vigor.fetch("https://api.example.com/", "/api")
168
187
 
169
188
  Path segments are percent-encoded, so values like `"a b"` or `"x?y"` can never leak into the query or fragment. A `/` inside a segment still separates path levels: `.path("v1/users", "a b")` → `/v1/users/a%20b`. Pass segments **unencoded** — an already-encoded `%20` would be encoded again.
170
189
 
190
+ `.` and `..` segments still work as relative steps, but by default (`settings.confinePath`) never out of the origin: with `vigor.fetch("https://api.example.com/api/v1")`, `.path("users", "..", "posts")` goes to `/api/v1/posts`, while `.path("users", "../../../internal")` — say, a user-supplied id — fails with `VigorFetchError("PATH_ESCAPED")` without sending anything. The origin's path is the boundary (`/api/v1` allows `/api/v1/...`, not `/api/v1x`). `.settings(s => s.confinePath(false))` turns the check off.
191
+
192
+ ### apiMap / route
193
+
194
+ Describe your API once as a type, and every request built from it gets its route's response type — no `.cast<T>()` per call:
195
+
196
+ ```ts
197
+ type Api = {
198
+ "GET /users": { response: User[] }
199
+ "POST /users": { response: User }
200
+ "GET /users/me": { response: Me }
201
+ "GET /users/:id": { response: User }
202
+ "DELETE /users/:id": { response: null }
203
+ }
204
+
205
+ const api = vigor.fetch("https://api.example.com").apiMap<Api>()
206
+
207
+ await api.path("users").request() // User[]
208
+ await api.path("users", id).request() // User
209
+ await api.path("users", "me").request() // Me
210
+ await api.path("users").body("overwrite", newUser).request() // User (POST: a body is set)
211
+ await api.path("users", id).method("DELETE").request() // null
212
+ await api.path("nope").request() // unknown (no route matched)
213
+
214
+ await api.route("GET /users/:id", { id: 1 }).request() // User — key autocompletes
215
+ ```
216
+
217
+ - Keys are `"<METHOD> /<path>"`. A `:name` segment matches any one segment; a static segment needs that exact literal. When several routes match, the most specific wins segment by segment from the left (`/users/me` beats `/users/:id`), like a router.
218
+ - The request's method is the one set with `.method()`, or — as at runtime — `POST` with a body and `GET` without.
219
+ - Path arguments are matched the way the URL is built: `.path("users/1")` is two segments, `null`/`undefined` are dropped, numbers become their digits. A non-literal argument (`id: string`) only matches a `:name` segment.
220
+ - Routes are relative to the path set before `.apiMap()`, so a shared prefix goes first: `vigor.fetch(origin).path("v1").apiMap<Api>()`. The origin's own pathname isn't part of the match.
221
+ - No match falls back to the parse engine's type (`unknown` by default). `.cast<T>()` still wins over the map, and a `raw` parse still gives the `Response`.
222
+ - `route(key, params)` sets the method and appends the route's path with `:name` segments filled from `params` (encoded like any path segment). Unknown keys, missing or extra params, and a `GET`/`HEAD` route on a request that already has a body are type errors.
223
+ - It's purely a type: `apiMap()` changes nothing at runtime, and responses aren't validated.
224
+
225
+ #### Route descriptions
226
+
227
+ A route can describe more than its response. Every key is optional:
228
+
229
+ ```ts
230
+ type Api = {
231
+ "GET /users/:id": {
232
+ params: { id: number } // .route()'s param types
233
+ responses: {
234
+ 200: User
235
+ 304: null
236
+ 404: { error: "not_found" }
237
+ "4xx": ApiError // every other 4xx
238
+ "5xx": { message: string }
239
+ }
240
+ }
241
+ "POST /users": {
242
+ body: { name: string } // the body the request must carry
243
+ responses: { 201: User, 422: { fields: Record<string, string> } }
244
+ }
245
+ "GET /search": {
246
+ query: { q: string, page?: number } // what .query() must add up to
247
+ response: User[] // shorthand for responses: { "2xx": User[] }
248
+ }
249
+ }
250
+ ```
251
+
252
+ - **`responses`** maps statuses to the parsed body: an exact status (`404`, or `"404"`) or a whole class (`"2xx"`–`"5xx"`) for its statuses not listed on their own. The **success** statuses — `2xx` and `304`, as at runtime — are what the request resolves to: `request()` gives their union (`User | null` above). The others type [`FETCH_FAILED`](#typed-errors)'s `data.parsed`.
253
+ - **`response`** is shorthand for `responses: { "2xx": ... }`. Undeclared success statuses aren't modeled, so a route that declares none falls back to the parse engine's type.
254
+ - **`params`** types `.route()`'s values: `api.route("GET /users/:id", { id: "1" })` is an error above.
255
+ - **`body`** and **`query`** are checked **when the request is sent**, so the order you build it in doesn't matter: `request()`/`requestVerbose()` don't compile when the body doesn't match (or is missing — unless the declared type allows `undefined`), or when the `.query()` objects, added together, miss a key, have an unknown one, or a value of the wrong type. A route without `body`/`query` accepts anything there. The compiler error names the route and the problem:
256
+
257
+ ```
258
+ The 'this' context of type 'VigorFetch<...>' is not assignable to method's 'this' of type
259
+ 'VigorApiRequestIssue<"GET /search", "unknown query key \"pgae\"", { q: string; page?: number }, { readonly q: "x"; readonly pgae: 1 }>'
260
+ ```
261
+
262
+ The check is on `this`, so it's only computed where `request()`/`requestVerbose()` is called. One consequence: calling them on a `VigorFetch<T>` with a still-generic `T` (inside a generic helper) doesn't compile — take a concrete builder, or `VigorFetch<any>`.
263
+
264
+ #### Status and response
265
+
266
+ `vigor.fetch`'s `requestVerbose()` envelope carries the `status` and `response` the result was parsed from:
267
+
268
+ ```ts
269
+ const res = await api.route("GET /users/:id", { id: 1 }).requestVerbose()
270
+ if (res.success) {
271
+ res.status // 200 | 304
272
+ res.response // Response
273
+ if (res.status === 200) res.data // User
274
+ else res.data // null
275
+ }
276
+ ```
277
+
278
+ - With an API map, there's one success member per declared status, each with that status's data run through the middlewares — so narrowing `status` narrows `data`. Without one, `status` is a `number`.
279
+ - A result recovered from a failure — by `onError`'s `setResult` or `settings.default` — has no response: `status` and `response` are `null` (those members only exist when one of the two is set). On a failure they're `null` too; the failed response is on the error (`FETCH_FAILED`'s `data`).
280
+ - `.cast<T>()` and `requestVerbose<R>()` replace every success's `data`, but keep `status` — and the failure types.
281
+
171
282
  ### headers / body / options
172
283
 
173
284
  ```ts
@@ -177,15 +288,15 @@ vigor.fetch("/api")
177
288
  .options("merge", { credentials: "include" })
178
289
  ```
179
290
 
180
- Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`/typed array/`DataView`, `ReadableStream`, `URLSearchParams`, `FormData`, or plain object → JSON), and a matching `Content-Type` header is set automatically unless you've already set one via `.headers()` (header names are compared case-insensitively). `body("overwrite", null)` removes a previously set body.
291
+ Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`/typed array/`DataView`, `ReadableStream`, `URLSearchParams`, `FormData`, or plain object → JSON), and a matching `Content-Type` header is set automatically unless you've already set one via `.headers()` (header names are compared case-insensitively). `body("overwrite", null)` removes a previously set body. A body on a `GET`/`HEAD` request fails immediately with `VigorFetchError("BODY_NOT_ALLOWED")` instead of being sent — and when the method and body are set through the builder, it's already a type error (`.method("GET").body(...)` or `.body(...).method("GET")`).
181
292
 
182
- > A `ReadableStream` body can only be sent once, so a retried or restarted request with a stream body will fail — use a replayable body type if you rely on retries.
293
+ > A `ReadableStream` body can only be sent once, so a request with a stream body is never retried (its first failure is final), and a restarted one will fail — use a replayable body type if you rely on retries.
183
294
 
184
295
  ### settings
185
296
 
186
297
  ```ts
187
298
  .settings(s => s
188
- .unretryStatus(400, 401, 403, 404, 405, 413, 422)
299
+ .unretryStatus(400, 401, 403, 404, 409, 422)
189
300
  .retryHeaders("retry-after", "x-ratelimit-reset")
190
301
  .maxRestarts(3)
191
302
  .default(ctx => ({ fallback: true }))
@@ -195,32 +306,40 @@ Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`/typed array
195
306
  | Method | Description | Default |
196
307
  |---|---|---|
197
308
  | `retryHeaders(...strs)` | Response headers checked for a `429`/`503` retry delay | `["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"]` |
198
- | `unretryStatus(...nums)` | HTTP status codes that are never retried, regardless of the retry engine's attempt budget | `[400, 401, 403, 404, 405, 413, 422]` |
199
- | `redirect(bool)` | On a `3xx` response with a `Location` header, navigates the page via `window.location.href` | `true` |
309
+ | `unretryStatus(...nums)` | HTTP status codes that are never retried, regardless of the retry engine's attempt budget | every `4xx` except `408`, `421`, `423`, `425`, `429`, plus `501`, `505`, `506`, `508`, `510`, `511` (see below) |
310
+ | `maxRetryAfter(num)` | Upper bound (ms) on a server-suggested retry delay from `retryHeaders`; longer values are clamped | `300000` (5 min) |
311
+ | `redirect(bool)` | On a redirected response, navigates the page via `window.location.href` (see below) | `false` |
312
+ | `confinePath(bool)` | Keeps the request URL inside its origin — same domain, within the origin's path; a request that would leave it (e.g. a `".."` segment) fails with `PATH_ESCAPED` before it's sent | `true` |
200
313
  | `maxRestarts(num)` | Max number of full pipeline restarts (see `onError` below) | `3` |
201
314
  | `default(fn)` | Fallback value/factory used only if the request ultimately fails and no restart/override happened | throws |
315
+ | `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) (the nested retry/parse engines' too) | `false` |
316
+
317
+ The default `unretryStatus` covers the statuses a retry of the same request can't change: `400`–`407`, `409`–`417`, `422`, `424`, `426`, `428`, `431`, `451`, `501`, `505`, `506`, `508`, `510`, `511`. These stay retryable: `408 Request Timeout`, `421 Misdirected Request`, `423 Locked`, `425 Too Early`, `429 Too Many Requests`, and transient `5xx` (`500`, `502`, `503`, `504`, `507`).
202
318
 
203
319
  `retryHeaders` and `unretryStatus` **replace** the whole list (in both the builder and the config-object form), so you can also remove defaults — e.g. `.settings({ unretryStatus: [] })` makes every failure status retryable. To extend the defaults instead, spread `VigorFetchPolicySettingsBase.unretryStatus`.
204
320
 
205
- On any non-`unretryStatus` failure response, the internal retry engine retries per its own `settings`/`algorithms` (defaults: 5 attempts, 20s timeout, exponential-ish backoff jitter — see `vigor.retry` below). On a `429` or `503`, Vigor reads `retryHeaders` off the response and uses the first usable value as the next delay automatically. Delta seconds (`Retry-After: 120`), Unix epoch seconds/milliseconds (`X-RateLimit-Reset: 1735689600`), and HTTP dates are all understood.
321
+ On any non-`unretryStatus` failure response, the internal retry engine retries per its own `settings`/`algorithms` (defaults: 5 attempts, 20s timeout, exponential-ish backoff jitter — see `vigor.retry` below). On a `429` or `503`, Vigor reads `retryHeaders` off the response and uses the first usable value as the next delay automatically. Delta seconds (`Retry-After: 120`), Unix epoch seconds/milliseconds (`X-RateLimit-Reset: 1735689600`), and HTTP dates are all understood. The delay is clamped to `maxRetryAfter`.
322
+
323
+ The whole response body is read within the attempt, so the retry engine's per-attempt `timeout` also covers a body that stalls mid-transfer, and a body that fails to arrive is retried. (With the parse engine's `raw` setting, the body is left unread for you to stream.)
206
324
 
207
325
  ### redirect
208
326
 
209
- With `settings.redirect` left `true`, a `3xx` response that carries a `Location` header navigates the browser to it:
327
+ With `settings.redirect(true)`, a redirected response navigates the browser to its target:
210
328
 
211
329
  ```ts
212
330
  await vigor
213
331
  .fetch("/api/session")
214
- .options("merge", { redirect: "manual" }) // otherwise fetch follows 3xx itself
332
+ .settings({ redirect: true })
215
333
  .request();
216
- // 302 Location: /login -> window.location.href = "https://app.example.com/login"
334
+ // 302 Location: /login (followed by fetch) -> window.location.href = "https://app.example.com/login"
217
335
  ```
218
336
 
219
- - A relative `Location` is resolved against the responding URL.
337
+ - With the native default `redirect: "follow"`, the target is the final URL `fetch` landed on (`response.redirected`).
338
+ - With `.options("merge", { redirect: "manual" })` in a runtime where the `3xx` is readable, the target is its `Location` header, resolved against the responding URL.
220
339
  - Navigation isn't instant, so the call still settles: it fails with `VigorFetchError("REDIRECTED")`, whose `data` holds `{ url, status, response }`. That attempt is never retried.
221
- - **Without `window.location` (Node, workers, SSR) it does nothing and behaves exactly like `redirect(false)`** — the `3xx` falls through to the normal failure path (`FETCH_FAILED`, retried per your retry config).
222
- - Native `fetch` follows redirects on its own by default, so a `3xx` only reaches Vigor when you pass `redirect: "manual"` (or `"error"`) through `.options()`. Note that in browsers `"manual"` yields an opaque response with no readable `Location`, so same-origin navigation of this kind is mostly useful where the response is readable (e.g. a proxy under your control, or a non-browser runtime with a `window` shim).
223
- - Statuses without a `Location` (e.g. `304 Not Modified`) are left alone.
340
+ - **Without `window.location` (Node, workers, SSR) it does nothing and behaves exactly like `redirect(false)`.**
341
+
342
+ Independently of this setting, a `3xx` (or browser `opaqueredirect`) that reaches Vigor because you chose `redirect: "manual"` fails with `FETCH_FAILED` and is **not retried**, since a retry would get the same redirect. `304 Not Modified` is treated as a result, not a failure (it parses to `null`).
224
343
 
225
344
  ### interceptors (`middlewares`)
226
345
 
@@ -239,6 +358,13 @@ Every stage takes a mode as the first argument: `"fluent"` (return a plain value
239
358
  )
240
359
  ```
241
360
 
361
+ **The returned context replaces `ctx`** — at runtime and in the types. Return values are only checked for being context-shaped; what you change is what carries on:
362
+
363
+ - Returning `ctx` (sync or `async`) changes nothing, so the types stay those of the finished builder — a middleware registered before `.cast()`, `.apiMap()` or `.target()` doesn't freeze the result at that point.
364
+ - Every key you change is overwritten from then on: `({ ...ctx, record: { traceId } })` in `before` types `ctx.record` in every later stage, and `({ ...ctx, result: x })` in `after`/`onResult` makes `x` the result (and what the next `onResult` receives). A fluent `onResult`'s return value — awaited — overwrites `result` the same way.
365
+ - Keys the runtime sets itself are reset where it sets them: `result` (and fetch's `response`) at the start of `after`, so changing `result` in `before` has no effect. A `result` changed in `onError` joins the result type as what a recovered request (`setResult`) resolves to.
366
+ - Each stage's context is its own: `retryIf`/`onRetry`/`onError` see what their stage's earlier middlewares changed, not `before`'s/`after`'s, since those may not have run.
367
+
242
368
  | Stage | Runs | Intercept API |
243
369
  |---|---|---|
244
370
  | `before` | Before the request is sent | `throwError`, `setOptions`, `setHeaders`, `setBody` |
@@ -264,7 +390,7 @@ const data = await vigor
264
390
  .request();
265
391
  ```
266
392
 
267
- 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).
393
+ Both accept a config object, a builder callback, or an already-built `VigorRetry`/`VigorParse` instance. The target you'd normally set with `.target()` is ignored here — fetch always supplies its own: the actual `fetch()` call for the retry engine, and the response for the parse engine (a `response.clone()` for the best-effort parse of a failed response's body, see `FETCH_FAILED`).
268
394
 
269
395
  ### cast
270
396
 
@@ -313,6 +439,7 @@ await vigor
313
439
  | `maxAttempts(num)` | Max attempts before giving up on this run | `5` |
314
440
  | `maxRestarts(num)` | Max full pipeline restarts (see `onError`) | `3` |
315
441
  | `timeout(ms)` | Timeout per individual attempt. `0` or `Infinity` disables it | `20000` |
442
+ | `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
316
443
 
317
444
  ### algorithms
318
445
 
@@ -329,7 +456,7 @@ Delay algorithm is a **replace**, not merge — switching algorithms discards th
329
456
  | `backoff(cfg?)` | `initial` (`0`), `multiplier` (`1.7`), `unit` (`1000`), `minDelay` (`500`), `maxDelay` (`10000`), `jitter` (`800`) |
330
457
  | `custom(cfg?)` | `target: (attempt) => number` (required), `minDelay` (`500`), `maxDelay` (`10000`), `jitter` (`800`) |
331
458
 
332
- Each computed delay is clamped to `[minDelay, maxDelay]` (except `constant`, which has no bounds) and then perturbed by `±jitter` ms.
459
+ Each computed delay is perturbed by `±jitter` ms. For `linear`/`backoff`/`custom`, the jitter fits inside `[minDelay, maxDelay]`: it's capped at half that range, and the delay is clamped to `[minDelay + jitter, maxDelay - jitter]` before jitter is applied, so the final delay never leaves `[minDelay, maxDelay]`. `constant` has no bounds; its interval is only raised to at least `jitter`, so the delay never goes negative.
333
460
 
334
461
  ```ts
335
462
  .algorithms(a => a.custom({
@@ -356,7 +483,7 @@ Each computed delay is clamped to `[minDelay, maxDelay]` (except `constant`, whi
356
483
  | Stage | Runs | Intercept API |
357
484
  |---|---|---|
358
485
  | `before` | Before each attempt | `throwError`, `abort`, `breakRetry` |
359
- | `after` | After the target settles successfully | `setResult`, `throwError` |
486
+ | `after` | After the target settles successfully | `throwError` |
360
487
  | `onResult` | Right before returning the attempt's result | `setResult`, `throwError` |
361
488
  | `retryIf` | After a failed attempt, decides whether to retry | `proceedRetry`, `cancelRetry` |
362
489
  | `onRetry` | Right before the retry delay is awaited | `throwError`, `setDelay` |
@@ -390,10 +517,13 @@ There are two independent resilience layers here:
390
517
  | `raw(bool)` | When `true`, skips parsing entirely and returns the raw `Request\|Response` object | `false` |
391
518
  | `default(fn)` | Fallback value/factory when parsing ultimately fails | throws |
392
519
  | `maxRestarts(num)` | Max full pipeline restarts | `3` |
520
+ | `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
393
521
 
394
522
  ### strategies
395
523
 
396
- 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.
524
+ Strategies form an ordered list that's tried in sequence until one succeeds. If you never configure any, Vigor defaults to content-type detection.
525
+
526
+ The body is read **once**, into raw bytes, and every strategy parses those same bytes — nothing is cloned, and a failed strategy consumes nothing. Formats are decoded directly from the bytes (`JSON.parse`, `TextDecoder`, a hand-written `x-www-form-urlencoded` parser, ...); only `multipart/form-data` goes through the platform's `formData()`. The bytes are cached per `Request|Response` object, so a restart or a second parse of the same object reuses them.
397
527
 
398
528
  ```ts
399
529
  .strategies(s => s.sniff())
@@ -401,15 +531,31 @@ Strategies form an ordered list that's tried in sequence until one succeeds (eac
401
531
 
402
532
  | Method | Behavior |
403
533
  |---|---|
404
- | `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text). A body-less response (e.g. `204 No Content`) or an empty JSON body resolves to `null`; a response without `Content-Type` is read as text |
405
- | `sniff(replace?)` | Tries `json → formData → text → blob` in order until one parses |
406
- | `json(replace?)` | Always parses as JSON |
407
- | `text(replace?)` | Always parses as text |
534
+ | `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text). An empty body (e.g. `204 No Content`) resolves to `null`; a body without `Content-Type` is read as text; a `Content-Type` it doesn't know (`application/pdf`, `application/zip`, `application/x-ndjson`, ...) becomes a `Blob` of that type, so a response that arrived fine never fails to parse just for its type |
535
+ | `sniff(replace?)` | Tries JSON, then form data (only for a form `Content-Type`), then text (only if the bytes are valid in the declared charset), then falls back to a `Blob` |
536
+ | `json(replace?)` | Always parses as JSON (always UTF-8, per the JSON spec) |
537
+ | `text(replace?)` | Always parses as text, in the `Content-Type`'s `charset` (UTF-8 when absent or unsupported) |
408
538
  | `arrayBuffer(replace?)` | Always parses as `ArrayBuffer` |
409
539
  | `blob(replace?)` | Always parses as `Blob` |
410
540
  | `bytes(replace?)` | Always parses as `Uint8Array` |
411
- | `formData(replace?)` | Always parses as `FormData` |
412
- | `custom(func, replace?)` | Uses a custom `(request\|response: Request\|Response) => Promise<any>` |
541
+ | `formData(replace?)` | Always parses as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`; any other `Content-Type` fails) |
542
+ | `custom(func, replace?)` | Uses a custom `(body: VigorParseBody) => any \| Promise<any>` — see below |
543
+
544
+ A custom strategy receives the already-read body, not the `Request|Response`:
545
+
546
+ ```ts
547
+ type VigorParseBody = {
548
+ bytes: Uint8Array // the raw body, empty when there is none
549
+ contentType: string | null // the Content-Type header
550
+ status: number | null // null when parsing a Request
551
+ headers: Headers
552
+ source: Request | Response // its body is already consumed
553
+ }
554
+
555
+ .strategies(s => s.custom(({ bytes }) => new TextDecoder().decode(bytes).split("\n")))
556
+ ```
557
+
558
+ `readVigorParseBody(requestOrResponse)` is exported too, if you need the same read-once bytes outside a strategy.
413
559
 
414
560
  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.
415
561
 
@@ -433,6 +579,8 @@ const data = await vigor
433
579
  .request();
434
580
  ```
435
581
 
582
+ `proceedRestart()` re-parses the same cached bytes, so a restart never hits an already-consumed body.
583
+
436
584
  ---
437
585
 
438
586
  ## `vigor.all`
@@ -466,9 +614,10 @@ const results = await vigor
466
614
  | Method | Description | Default |
467
615
  |---|---|---|
468
616
  | `concurrency(num)` | Max number of tasks running at once | `5` |
469
- | `onlySuccess(bool)` | When `true`, filters the final array down to only tasks whose result wasn't recovered as a failure | `false` |
470
- | `timeout(ms)` | Per-task timeout. A task exceeding it fails with `VigorAllError("TIMED_OUT")` (recoverable via `onErrorEach`) | disabled |
617
+ | `onlySuccess(bool)` | When `true`, the result is just the successful tasks' values (a failed task not recovered by `onErrorEach` is left out) instead of one outcome per task | `false` |
618
+ | `timeout(ms)` | Per-task timeout. A task exceeding it fails with `VigorAllError("TIMED_OUT")` (recoverable via `onErrorEach`). `0` or `Infinity` disables it | disabled |
471
619
  | `failFast(bool)` | When `true`, the first task failure not recovered by `onErrorEach` aborts the remaining tasks and makes the batch fail with that error | `false` |
620
+ | `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
472
621
 
473
622
  Each task receives an `AbortSignal` that fires on its timeout, on an external `abortSignals` abort, or when `failFast` stops the batch. Pass it along (e.g. to `fetch`) so in-flight work actually stops — a task that ignores it keeps running in the background, but its result is discarded.
474
623
 
@@ -483,9 +632,20 @@ const results = await vigor
483
632
  .request();
484
633
  ```
485
634
 
486
- > Unlike `vigor.retry`/`vigor.fetch`/`vigor.parse`, `vigor.all` has no `default`/fallback setting and no batch-level `onError`. By default the batch only fails on an **empty** task list (`EMPTY_TARGET`), an external abort, a `failFast` stop, or an `onErrorEach` hook throwing. Per-task failures are otherwise handled by `onErrorEach` (below).
635
+ > Unlike `vigor.retry`/`vigor.fetch`/`vigor.parse`, `vigor.all` has no `default`/fallback setting and no batch-level `onError`. By default the batch only fails on an **empty** task list (`EMPTY_TARGET`), an external abort, a `failFast` stop, an `onErrorEach` hook throwing, or a batch-level `before`/`after`/`onResult` middleware throwing. Per-task failures are otherwise handled by `onErrorEach` (below).
636
+
637
+ **Result shape:** with `onlySuccess` off (the default), the result has **one outcome per task**, in order, shaped like `requestVerbose()`'s envelope — `{ success: true, data, error: null }` when the task returned (or `onErrorEach` recovered it), `{ success: false, data: null, error }` when it failed. So a thrown error can never pass for a returned value (and a task that *returns* an `Error` is a success):
638
+
639
+ ```ts
640
+ const [user, posts] = await vigor.all(() => getUser(), () => getPosts()).request();
641
+ if (user.success) user.data; // what getUser returned
642
+ else if (isVigorAllError(user.error, "TIMED_OUT")) user.error.data.index;
643
+ else user.error; // whatever getUser threw
644
+ ```
645
+
646
+ With `onlySuccess(true)`, it's just the successful tasks' values.
487
647
 
488
- **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.
648
+ **Result typing:** given literal task functions, the default result is a **tuple** with each task's own type — `.target(() => 1 as const, () => "a")` infers `[VigorAllSettled<1>, VigorAllSettled<"a">]`, and narrowing a slot by `success` narrows `data`. With `onlySuccess(true)` the length is only known at runtime, so it's an array of the tasks' result types (`(1 | "a")[]`); a non-literal `boolean` gives the union of both shapes. `.cast<T>()` overrides either case.
489
649
 
490
650
  ### hooks (`middlewares`)
491
651
 
@@ -520,6 +680,86 @@ Batch-level fluent signatures: `before`/`after` take `(ctx) => void`, `onResult`
520
680
 
521
681
  ---
522
682
 
683
+ ## Timeline
684
+
685
+ Every `requestVerbose()` result carries a `timeline`: an ordered list of everything the call went through, on success and on failure alike. Recording is **off by default** — turn it on with the `debug` setting, `.settings(s => s.debug(true))` or `.settings({ debug: true })` (every module has it). Without it, `timeline` is an empty array and no context snapshots are taken, so it costs nothing. It's created fresh for each call and can't be passed in; a restart keeps appending to the same list.
686
+
687
+ ```ts
688
+ const res = await vigor.fetch("https://api.example.com/users").settings(s => s.debug(true)).requestVerbose();
689
+
690
+ for (const item of res.timeline) {
691
+ console.log(item.now, item.action, item.content);
692
+ }
693
+ ```
694
+
695
+ Each item is `{ action, content, now, ctx }`. `now` is a `Date.now()` timestamp (a number, not a `Date`). `ctx` is a snapshot of the context at that moment: a deep copy, so later changes don't reach it, without `timeline` itself (`vigor.all`'s per-task actions snapshot that task's context instead). `action` and `content` are typed together, so narrowing by `action` narrows `content`.
696
+
697
+ The same list is also `ctx.timeline`, so middlewares can read what has happened so far. The types are exported as `VigorRetryTimeline`, `VigorParseTimeline`, `VigorFetchTimeline` and `VigorAllTimeline`.
698
+
699
+ ### Shared events
700
+
701
+ | Action | Content |
702
+ |---|---|
703
+ | `PROCESS_HANDLING` | `{ type, data }` — the run's lifecycle steps (below) |
704
+ | `MIDDLEWARE_LOOP_STARTED` | `{ stage, middlewares }` |
705
+ | `MIDDLEWARE_RAN` | `{ stage, index, middleware, internal, took, threw, error }` — one middleware ran; `error` is what it threw when `threw` is `true` |
706
+ | `MIDDLEWARE_LOOP_ENDED` | `{ stage, middlewares, took }` |
707
+ | `MIDDLEWARE_API_CALLED` | `{ stage, index, middleware, internal, method, args }` — an intercept API call, e.g. `setDelay` |
708
+ | `REQUEST_END` | `{ success, outcome, took, restarts, error }` — always the last entry (see below) |
709
+
710
+ A stage with no middlewares records nothing. `took` is in milliseconds. `index` is the middleware's position in its stage, and `internal` is `true` for one Vigor added itself — e.g. the `after`/`retryIf`/`onRetry` middlewares `vigor.fetch` puts on its retry engine to judge responses — so you can tell them from yours.
711
+
712
+ `REQUEST_END` says how the call ended: `outcome` is `"result"` (the pipeline produced it), `"overridden"` (`onError` called `setResult`), `"default"` (`settings.default` produced it), or `"failed"`. `took` spans the whole call, restarts included, and `restarts` counts them; `error` is what it failed with, `null` on success. Nested engines end their own timelines with one too.
713
+
714
+ ### Per module
715
+
716
+ | Module | `PROCESS_HANDLING` types | Other actions |
717
+ |---|---|---|
718
+ | `vigor.retry` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART`, `RETRY_START`, `RETRY_ERROR` | `ATTEMPT_INCREASED`, `TARGET_REQUEST_STARTED`, `TARGET_REQUEST_ENDED`, `RETRY_DECISION`, `RETRY_DELAY` |
719
+ | `vigor.parse` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART` | `BODY_READ`, `STRATEGY_STARTED`, `STRATEGY_SUCCEEDED`, `STRATEGY_FAILED` |
720
+ | `vigor.fetch` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART` | `BUILT_URL`, `SET_OPTIONS`, `ENGINE_CREATED`, `RETRY_STARTED`, `RESPONSE_RECEIVED`, `RETRY_ENDED`, `PARSE_STARTED`, `PARSE_ENDED` |
721
+ | `vigor.all` | `REQUEST_START`, `REQUEST_ERROR` | `TASK_STARTED`, `TASK_ENDED`, `TASK_ERROR` |
722
+
723
+ In `vigor.retry`, `RETRY_START`/`RETRY_ERROR` are per attempt. `RETRY_ERROR`'s data also says whether the attempt `timedOut` (hit `settings.timeout`) or was `aborted` (an external signal fired). After every failed attempt, `RETRY_DECISION` records `{ attempt, retry, reason }`:
724
+
725
+ | `reason` | `retry` | Meaning |
726
+ |---|---|---|
727
+ | `"retry"` | `true` | It will be retried (`RETRY_DELAY` follows) |
728
+ | `"cancelled"` | `false` | `retryIf` decided against it — `cancelRetry()` or a fluent `false`; the matching `MIDDLEWARE_API_CALLED` shows which middleware (e.g. fetch's internal one for an `unretryStatus`) |
729
+ | `"breakRetry"` | `false` | A middleware called `breakRetry()` |
730
+ | `"aborted"` | `false` | An external abort signal fired |
731
+ | `"exhausted"` | `false` | No attempts left |
732
+
733
+ The context's flags mirror this: `ctx.flags.brokeRetry` is set only by `breakRetry()`, `ctx.flags.aborted` by an external abort, and `ctx.flags.timedOut` while the current attempt has timed out.
734
+
735
+ In `vigor.all`, tasks run concurrently, so their entries interleave; each one carries its task's `index`.
736
+
737
+ ### Nested engines in `vigor.fetch`
738
+
739
+ With `debug` on in the fetch's settings, its retry and parse engines record too. `RETRY_ENDED` and `PARSE_ENDED` hold the nested engine's **whole timeline**, alongside the engine, `took`, and its `response`/`result` (`VigorDefault` when it failed):
740
+
741
+ ```ts
742
+ for (const item of res.timeline) {
743
+ if (item.action === "RETRY_ENDED") item.content.timeline; // VigorRetryTimeline
744
+ }
745
+ ```
746
+
747
+ Every response an attempt gets is recorded as `RESPONSE_RECEIVED` — `{ attempt, status, statusText, ok, redirected, url }` — before it's judged, so a failing status still shows up there. `PARSE_STARTED`/`PARSE_ENDED` also carry a `source` — `"response"` for the result, or `"failedResponse"` for the best-effort parse of a failed response's body — and the `attempt` whose response they parsed. Those run inside the retry engine, so they appear between `RETRY_STARTED` and `RETRY_ENDED`, in order:
748
+
749
+ ```text
750
+ RETRY_STARTED
751
+ RESPONSE_RECEIVED attempt=1 status=503
752
+ PARSE_STARTED failedResponse attempt=1
753
+ PARSE_ENDED failedResponse attempt=1
754
+ RESPONSE_RECEIVED attempt=2 status=200
755
+ RETRY_ENDED (the retry engine's own timeline inside)
756
+ PARSE_STARTED response attempt=2
757
+ PARSE_ENDED response attempt=2
758
+ REQUEST_END success outcome="result"
759
+ ```
760
+
761
+ ---
762
+
523
763
  ## Plugins
524
764
 
525
765
  ```ts
@@ -531,10 +771,12 @@ export type VigorPlugin<
531
771
  func: (v: VigorInstance, options: O) => Ext
532
772
  }
533
773
 
534
- vigor.use(plugin, options?)
774
+ vigor.use(plugin, options?) // options: Partial<O>
535
775
  ```
536
776
 
537
- `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 the instance it's called on (including its nested `builders` groups) and merges `Ext` on top, returning a **new** instance, typed `VigorInstance<Ext>`, while the original stays untouched. Calls chain: `vigor.use(a).use(b)` keeps both plugins' extensions, and `b` receives the instance that already includes `a`'s.
777
+ `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 the instance it's called on (including its nested `builders` groups) and merges `Ext` on top, returning a **new** instance, typed `VigorInstance<Ext>`, while the original stays untouched. Calls chain: `vigor.use(a).use(b)` keeps both plugins' extensions, and `b` receives the instance that already includes `a`'s. A property in `Ext` replaces a same-named one (a built-in like `fetch`, or an earlier plugin's), in the type as well as at runtime.
778
+
779
+ `plugin.options` holds the plugin's defaults: `func` receives them with the `options` passed to `use()` shallow-merged on top, so `use(plugin)` alone works and `func` always gets a complete `O`.
538
780
 
539
781
  ```ts
540
782
  const loggingPlugin: VigorPlugin<{ prefix?: string }> = {
@@ -574,11 +816,11 @@ try {
574
816
  | `vigor.retry` | `VigorRetryErrors \| {} \| null \| undefined` |
575
817
  | `vigor.parse` | `VigorParseErrors \| {} \| null \| undefined` |
576
818
  | `vigor.all` | `VigorAllErrors \| {} \| null \| undefined` |
577
- | `vigor.fetch` | `VigorFetchErrors \| VigorRetryErrors \| VigorParseErrors \| {} \| null \| undefined` (the nested engines surface their own errors) |
819
+ | `vigor.fetch` | `VigorFetchErrors \| {} \| null \| undefined` (the nested engines' failures included, see below) |
578
820
 
579
821
  `VigorRetryErrors` & co. are unions with **one member per error code**, so narrowing by `code` also narrows `data` to that code's payload. The `{} | null | undefined` tail is everything Vigor didn't create — an error your own target or middleware threw, an abort reason, a network `TypeError`, or even a bare `throw null`. It's there because those really do reach you: a `cancelRetry()`/`breakRetry()`/abort path returns your error as-is, rather than wrapping it.
580
822
 
581
- Narrow with the exported guards — `isVigorRetryError`, `isVigorParseError`, `isVigorFetchError`, `isVigorAllError`:
823
+ Narrow with the exported guards — `isVigorRetryError`, `isVigorParseError`, `isVigorFetchError`, `isVigorAllError` (or `vigor.guards.*`):
582
824
 
583
825
  ```ts
584
826
  const res = await vigor.retry(task).requestVerbose();
@@ -593,6 +835,46 @@ if (!res.success) {
593
835
  }
594
836
  ```
595
837
 
838
+ Pass one or more codes to check the code too — the error is narrowed to just those codes, so `data` is that code's payload right away (works on a `catch` binding as well):
839
+
840
+ ```ts
841
+ const res = await vigor.fetch("/api/users").requestVerbose();
842
+ if (!res.success) {
843
+ if (isVigorFetchError(res.error, "FETCH_FAILED")) {
844
+ res.error.data.status; // number
845
+ res.error.data.parsed; // the error body, best-effort parsed
846
+ } else if (isVigorFetchError(res.error, "RETRY_EXHAUSTED", "TIMED_OUT")) {
847
+ res.error.code; // "RETRY_EXHAUSTED" | "TIMED_OUT"
848
+ }
849
+ }
850
+
851
+ try { await vigor.fetch("/api/users").request() }
852
+ catch (e) { if (isVigorFetchError(e, "INVALID_PROTOCOL")) e.data.origin }
853
+ ```
854
+
855
+ `error.context` is the run context at the time of the error, and its type depends on the code — some errors are raised where no run exists:
856
+
857
+ | Module | `context` may be `undefined` | `context` is always `undefined` |
858
+ |---|---|---|
859
+ | fetch | `VALUE_REQUIRED` (also raised by `.route()` while building) | — |
860
+ | retry | `VALUE_REQUIRED` (also raised by the `custom` algorithm) | — |
861
+ | parse | `PARSER_ALL_FAILED` (also raised by `VigorParseSniffStrategy`) | `INVALID_CONTENT_TYPE`, `PARSER_NOT_FOUND` (raised inside strategies; the built-in ones no longer raise `PARSER_NOT_FOUND`) |
862
+ | all | — | `TIMED_OUT` (per task — see `data.index`) |
863
+
864
+ Every other code always has one, so after `isVigorFetchError(e, "FETCH_FAILED")`, `e.context.href` needs no check.
865
+
866
+ On a `requestVerbose()` error, `context` is typed with **that request's own config** — the guards keep it rather than widening to a generic type:
867
+
868
+ ```ts
869
+ const res = await vigor.fetch("https://api.example.com").path("users").requestVerbose();
870
+ if (!res.success && isVigorFetchError(res.error, "FETCH_FAILED")) {
871
+ res.error.context.policy.origin; // "https://api.example.com"
872
+ res.error.context.policy.path; // ["users"]
873
+ }
874
+ ```
875
+
876
+ A thrown value (`catch (e)` around `request()`) carries no type, so there the guards give the generic `VigorFetchContextSchema<any>` — use `requestVerbose()` when you want the typed context. The context types (`VigorFetchContextSchema` & co.) are exported.
877
+
596
878
  Prefer the guard over a bare `instanceof`: because of the `{}` member, `instanceof` widens `data` back to every code's payload, while the guard keeps `code` and `data` in sync. And since the tail has no `code`, reading `res.error.code` without narrowing is a compile error — that's the point.
597
879
 
598
880
  All four modules are typed this way. `request()` throws instead of returning an envelope, so its thrown value stays `unknown` — narrow it with the same guards.
@@ -604,22 +886,44 @@ const res = await vigor.fetch("/api/users").requestVerbose();
604
886
  if (!res.success) {
605
887
  // res.error is typed, res.data is null
606
888
  }
889
+ // res.timeline is there either way
607
890
  ```
608
891
 
609
892
  | Module | Error codes |
610
893
  |---|---|
611
- | `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `INVALID_PROTOCOL`, `FETCH_FAILED`, `RESTART_EXHAUSTED`, `REDIRECTED` |
894
+ | `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `BODY_NOT_ALLOWED`, `INVALID_PROTOCOL`, `PATH_ESCAPED`, `FETCH_FAILED`, `RESTART_EXHAUSTED`, `REDIRECTED`, plus every `VigorRetryError` and `VigorParseError` code |
612
895
  | `VigorRetryError` | `VALUE_REQUIRED`, `RETRY_EXHAUSTED`, `RESTART_EXHAUSTED`, `TIMED_OUT` |
613
896
  | `VigorParseError` | `VALUE_REQUIRED`, `INVALID_CONTENT_TYPE`, `PARSER_NOT_FOUND`, `PARSER_ALL_FAILED`, `RESTART_EXHAUSTED` |
614
897
  | `VigorAllError` | `EMPTY_TARGET`, `TIMED_OUT` |
615
898
 
899
+ `vigor.fetch` only ever fails with `VigorFetchError` (or something you threw): when its nested retry or parse engine fails, the error is re-raised as a `VigorFetchError` with the same `code` and `data`, the original kept as `cause`. So a request that ran out of attempts fails with `VigorFetchError("RETRY_EXHAUSTED")` — its `data.error` holding the last attempt's error, e.g. a `FETCH_FAILED` or a `TIMED_OUT` — and a body no strategy could parse with e.g. `VigorFetchError("PARSER_NOT_FOUND")`. `onError` and `settings.default` see the same error.
900
+
616
901
  `FETCH_FAILED`'s `data` includes `parsed`: Vigor best-effort parses the failed response's body (using your configured parse strategies) before throwing, so you can inspect an API's error payload without re-fetching. If parsing that body also fails, `parsed` is simply `undefined`.
617
902
 
903
+ With an [API map](#route-descriptions) route that declares failure `responses`, `FETCH_FAILED`'s `data` has one member per status, so narrowing `data.status` narrows `data.parsed` — to the declared body `| undefined`, or `unknown` for a status the route doesn't cover. `RETRY_EXHAUSTED`/`RESTART_EXHAUSTED`'s `data.error` is typed as the same request's errors, so the last attempt's failure stays typed one level down:
904
+
905
+ ```ts
906
+ const res = await api.route("POST /users").body("overwrite", { name: "a" }).requestVerbose()
907
+ if (!res.success) {
908
+ const err = isVigorFetchError(res.error, "RETRY_EXHAUSTED") ? res.error.data.error : res.error
909
+ if (isVigorFetchError(err, "FETCH_FAILED") && err.data.status === 422) {
910
+ err.data.parsed // { fields: Record<string, string> } | undefined
911
+ }
912
+ }
913
+ ```
914
+
915
+ `.cast<T>()` only replaces the success type — the failure types stay. A `raw` parse makes `parsed` the `Response`, so it keeps the plain `{ status: number, ..., parsed: unknown }` shape.
916
+
917
+ `PARSER_ALL_FAILED` keeps why each strategy failed: `data.tried[i]` names a strategy and `data.errors[i]` is what it threw, the message lists them (`All parsers failed: strategy#0 (SyntaxError: ...)`), and `cause` is the last one — so a malformed JSON body still carries its `SyntaxError`, with or without `settings.debug`.
918
+
618
919
  ---
619
920
 
620
921
  ## TypeScript notes
621
922
 
622
923
  - Every builder is **immutable** — `.settings(...)`, `.path(...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
623
- - 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.
924
+ - 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(...)`, fetch's `retryHeaders`/`unretryStatus`) force a full **replace** instead, since merging wouldn't make sense there. The config's type follows the same rules, so it always matches what's stored at runtime.
925
+ - Config objects are checked for unknown keys at any depth: `.settings({ maxAttempts: 3, timeot: 5 })` is a type error.
926
+ - To store or pass around a configured builder, type it with `any`: `VigorRetry<any>`, `VigorFetch<any>`, etc. The bare `VigorRetry` is the unconfigured instance's type.
927
+ - To narrow `requestVerbose()`'s `error`, use the `isVigor*Error` guards (or `vigor.guards.*`): they narrow `code` and `data` together. The sentinels `VigorDefault`/`VigorEmpty` (and `isVigorDefault`/`isVigorEmpty`) are exported for checking an unset `ctx.result` in middlewares.
624
928
  - 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.
625
929
  - `.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.