vigor-fetch 5.4.0 → 6.0.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
@@ -47,8 +47,8 @@ import vigor from "vigor-fetch";
47
47
 
48
48
  const data = await vigor
49
49
  .fetch("https://api.example.com")
50
- .path("v1", "users")
51
- .query({ page: 1, limit: 10 })
50
+ .path("append", "v1", "users")
51
+ .query("append", { page: 1, limit: 10 })
52
52
  .request();
53
53
  // -> GET https://api.example.com/v1/users?page=1&limit=10
54
54
  ```
@@ -115,6 +115,7 @@ Every sub-builder used internally by `.settings()`/`.middlewares()`/etc. is also
115
115
  ```ts
116
116
  vigor.builders.fetch.settings() // -> VigorFetchPolicySettings
117
117
  vigor.builders.fetch.middlewares() // -> VigorFetchPolicyMiddlewares
118
+ vigor.builders.fetch.serializers() // -> VigorFetchPolicySerializers
118
119
 
119
120
  vigor.builders.retry.settings() // -> VigorRetryPolicySettings
120
121
  vigor.builders.retry.middlewares() // -> VigorRetryPolicyMiddlewares
@@ -166,39 +167,44 @@ Without a callback the guard only checks the error you pass, as before: it narro
166
167
  |---|---|
167
168
  | `method(str)` | Forces the HTTP method. Default: `POST` if a body is set, otherwise `GET` |
168
169
  | `origin(str)` | Sets the base URL (absolute) or a path relative to the current page |
169
- | `path(...strs)` | Appends path segments |
170
- | `query(...objs)` | Adds query-parameter objects (each call appends another object to the list) |
171
- | `hash(str)` | Sets the URL fragment, replacing any previous value |
172
- | `headers(mode, obj)` | Sets headers. `mode`: `"overwrite"` (discard previous) or `"merge"` (`Object.assign`-style) |
173
- | `body(mode, obj)` | Sets the body. `"overwrite"` replaces it entirely; `"merge"` shallow-merges when both old and new body are plain objects, otherwise replaces |
170
+ | `path(mode, ...values)` | Sets path values. `mode`: `"append"` (after the ones set so far) or `"replace"` (discard them) |
171
+ | `query(mode, ...objs)` | Sets query-parameter objects. `mode`: `"append"` or `"replace"` |
172
+ | `hash(str)` | Sets the URL fragment (a single value, so it always replaces) |
173
+ | `headers(mode, obj)` | Sets headers. `mode`: `"replace"` (discard previous) or `"merge"` (`Object.assign`-style) |
174
+ | `body(mode, obj)` | Sets the body. `"replace"` replaces it entirely; `"merge"` shallow-merges when both old and new body are plain objects, otherwise replaces |
174
175
  | `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 |
176
+ | `serializers(fn \| config)` | Sets the steps that turn the stored path/query/hash/headers/body into what is sent (see [Serializers](#serializers)) |
175
177
  | `settings(fn \| config)` | Configures fetch-level settings (below) |
176
178
  | `middlewares(fn \| config)` | Configures the fetch middleware pipeline (below) |
177
- | `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 |
178
- | `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 |
179
+ | `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request, starting from its current config (the retry defaults until set). A callback gets a `VigorRetry` holding that config and a config object is merged into it, so each call adds to the previous ones (`algorithms` still replaces the algorithm); a `VigorRetry` instance is a complete engine and replaces it |
180
+ | `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response, merging the same way as `retry()`: a callback or config object adds to the current config, a `VigorParse` instance replaces it. Its result type (`.cast<T>()`, `raw`, middlewares, `default`) becomes the request's result type |
179
181
  | `apiMap<M>()` | Attaches a type-level API map: the matched route's `response` becomes the result type (see [apiMap / route](#apimap--route)) |
180
182
  | `route(key, params?)` | Sets method and path from an API map route, filling its `:name` segments |
181
183
  | `cast<T>()` | Overrides the inferred result type with `T` |
182
184
  | `request()` | Executes and returns the parsed result, throwing on failure |
183
185
  | `requestVerbose()` | Executes and returns `{ success, data, error }` |
184
186
 
185
- > `path()`, `query()`, `headers()` in merge mode, etc. are all additive per call — chain them incrementally rather than passing everything in one call.
187
+ > Every method that sets a list or an object takes its mode first — `"append"`/`"replace"` for lists (`path`, `query`), `"merge"`/`"replace"` for objects (`headers`, `body`, `options`) — so how a call combines with the previous ones is always written at the call. Single values (`origin`, `method`, `hash`) always replace.
186
188
 
187
189
  ### origin / path / query / hash
188
190
 
189
191
  ```ts
190
192
  vigor.fetch("https://api.example.com/", "/api")
191
- .path("v1", "users")
192
- .query({ page: 1 })
193
+ .path("append", "v1", "users")
194
+ .query("append", { page: 1 })
193
195
  .hash("section-2")
194
196
  // -> https://api.example.com/api/v1/users?page=1#section-2
195
197
  ```
196
198
 
197
199
  `origin()` only accepts one argument — pass origin + first path segments as separate calls, or fold extra segments into `path()`.
198
200
 
199
- 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.
201
+ `.path()` and `.query()` store their values as given. Turning them into the URL is done by the `path`, `query` and `url` [serializers](#serializers), and with the default steps:
200
202
 
201
- `.` 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.
203
+ - Path values: `null`/`undefined` are dropped, a `Date` becomes its ISO string, a `/` inside a value separates path levels, and each segment is percent-encoded, so `"a b"` or `"x?y"` can never leak into the query or fragment: `.path("append", "v1/users", "a b")` → `/v1/users/a%20b`. Pass segments **unencoded** — an already-encoded `%20` would be encoded again. The origin's own path goes in front.
204
+ - Query values: the origin's own query goes first, `null`/`undefined` entries are dropped, an array repeats its key (`a=1&a=2`), and a `Date` becomes its ISO string.
205
+ - Without `.hash()`, the origin's fragment is kept.
206
+
207
+ `.` and `..` segments still work as relative steps, but by default (the `url` stage's `confine` step) never out of the origin: with `vigor.fetch("https://api.example.com/api/v1")`, `.path("append", "users", "..", "posts")` goes to `/api/v1/posts`, while `.path("append", "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`). Leaving `confine` out of the `url` stage turns the check off: `.serializers(s => s.url(u => u.hashFromOrigin()))`.
202
208
 
203
209
  ### apiMap / route
204
210
 
@@ -206,64 +212,76 @@ Describe your API once as a type, and every request built from it gets its route
206
212
 
207
213
  ```ts
208
214
  type Api = {
209
- "GET /users": { response: User[] }
210
- "POST /users": { response: User }
211
- "GET /users/me": { response: Me }
212
- "GET /users/:id": { response: User }
213
- "DELETE /users/:id": { response: null }
215
+ "/users": {
216
+ GET: { response: User[] }
217
+ POST: { response: User }
218
+ }
219
+ "/users/me": {
220
+ GET: { response: Me }
221
+ }
222
+ "/users/:id": {
223
+ GET: { response: User }
224
+ DELETE: { response: null }
225
+ }
214
226
  }
215
227
 
216
228
  const api = vigor.fetch("https://api.example.com").apiMap<Api>()
217
229
 
218
- await api.path("users").request() // User[]
219
- await api.path("users", id).request() // User
220
- await api.path("users", "me").request() // Me
221
- await api.path("users").body("overwrite", newUser).request() // User (POST: a body is set)
222
- await api.path("users", id).method("DELETE").request() // null
223
- await api.path("nope").request() // unknown (no route matched)
230
+ await api.path("append", "users").request() // User[]
231
+ await api.path("append", "users", id).request() // User
232
+ await api.path("append", "users", "me").request() // Me
233
+ await api.path("append", "users").body("replace", newUser).request() // User (POST: a body is set)
234
+ await api.path("append", "users", id).method("DELETE").request() // null
235
+ await api.path("append", "nope").request() // unknown (no route matched)
224
236
 
225
237
  await api.route("GET /users/:id", { id: 1 }).request() // User — key autocompletes
226
238
  ```
227
239
 
228
- - 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.
240
+ - Keys are paths, `"/<path>"`; each holds an operation per upper-case method (`GET`, `POST`, …). A `:name` segment matches any one segment; a static segment needs that exact literal. When several paths match, the most specific wins segment by segment from the left (`/users/me` beats `/users/:id`), like a router.
229
241
  - The request's method is the one set with `.method()`, or — as at runtime — `POST` with a body and `GET` without.
230
- - 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.
231
- - 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.
242
+ - Path arguments are matched the way the URL is built: `.path("append", "users/1")` is two segments, `null`/`undefined` are dropped, numbers become their digits. A non-literal argument (`id: string`) only matches a `:name` segment.
243
+ - Routes are relative to the path set before `.apiMap()`, so a shared prefix goes first: `vigor.fetch(origin).path("append", "v1").apiMap<Api>()`. The origin's own pathname isn't part of the match.
232
244
  - 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`.
233
- - `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.
245
+ - `route(key, params)` takes `"<METHOD> /<path>"` keys built from the map, 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.
234
246
  - It's purely a type: `apiMap()` changes nothing at runtime, and responses aren't validated.
235
247
 
236
248
  #### Route descriptions
237
249
 
238
- A route can describe more than its response. Every key is optional:
250
+ A path can hold `params`, shared by all its methods; an operation can hold `request`, `response` and `responses`. Every key is optional:
239
251
 
240
252
  ```ts
241
253
  type Api = {
242
- "GET /users/:id": {
243
- params: { id: number } // .route()'s param types
244
- responses: {
245
- 200: User
246
- 304: null
247
- 404: { error: "not_found" }
248
- "4xx": ApiError // every other 4xx
249
- "5xx": { message: string }
254
+ "/users/:id": {
255
+ params: { id: number } // .route()'s param types
256
+ GET: {
257
+ responses: {
258
+ 200: User
259
+ 304: null
260
+ 404: { error: "not_found" }
261
+ "4xx": ApiError // every other 4xx
262
+ "5xx": { message: string }
263
+ }
250
264
  }
251
265
  }
252
- "POST /users": {
253
- body: { name: string } // the body the request must carry
254
- responses: { 201: User, 422: { fields: Record<string, string> } }
266
+ "/users": {
267
+ POST: {
268
+ request: { body: { name: string } } // the body the request must carry
269
+ responses: { 201: User, 422: { fields: Record<string, string> } }
270
+ }
255
271
  }
256
- "GET /search": {
257
- query: { q: string, page?: number } // what .query() must add up to
258
- response: User[] // shorthand for responses: { "2xx": User[] }
272
+ "/search": {
273
+ GET: {
274
+ request: { query: { q: string, page?: number } } // what .query() must add up to
275
+ response: User[] // shorthand for responses: { "2xx": User[] }
276
+ }
259
277
  }
260
278
  }
261
279
  ```
262
280
 
263
281
  - **`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`.
264
- - **`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.
282
+ - **`response`** is shorthand for `responses: { "2xx": ... }`. Undeclared success statuses aren't modeled, so an operation that declares none falls back to the parse engine's type.
265
283
  - **`params`** types `.route()`'s values: `api.route("GET /users/:id", { id: "1" })` is an error above.
266
- - **`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:
284
+ - **`request.body`** and **`request.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. An operation without `body`/`query` accepts anything there. The compiler error names the route and the problem:
267
285
 
268
286
  ```
269
287
  The 'this' context of type 'VigorFetch<...>' is not assignable to method's 'this' of type
@@ -271,6 +289,32 @@ type Api = {
271
289
  ```
272
290
 
273
291
  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>`.
292
+ - Keys other than these (an old-style `body` next to `response`, a lower-case `get`, `headers` in `request`) are type errors on `.apiMap<Api>()`.
293
+
294
+ #### Overloads
295
+
296
+ When one method answers differently depending on what's sent, give it a tuple of operations:
297
+
298
+ ```ts
299
+ type Api = {
300
+ "/users/:id": {
301
+ params: { id: number }
302
+ GET: [
303
+ { request: { query: { expand: true } }, response: UserWithPosts },
304
+ { request: { query?: { expand?: false } }, response: User },
305
+ ]
306
+ }
307
+ }
308
+
309
+ await api.route("GET /users/:id", { id }).query("append", { expand: true }).request() // UserWithPosts
310
+ await api.route("GET /users/:id", { id }).request() // User
311
+ await api.route("GET /users/:id", { id }).query("append", { expand: flag }).request() // UserWithPosts | User
312
+ ```
313
+
314
+ - The request's `body` and `query`, as set when it's sent, pick the overload: the **first** one they surely match wins (order them from most to least specific).
315
+ - When none surely matches — a value only known as `boolean` or `"csv" | "json"` — it's the union of every overload the request may match. A value may match when its type overlaps the declared one; a missing required key or an unknown key rules an overload out.
316
+ - A request that may match none doesn't compile (`"the request matches none of the route's overloads"`, with every overload's `request` as `expected`).
317
+ - Failures (`FETCH_FAILED`'s `data.parsed`) follow the picked overload too. `params` stay the path's, shared by every overload.
274
318
 
275
319
  #### Status and response
276
320
 
@@ -290,16 +334,44 @@ if (res.success) {
290
334
  - 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`).
291
335
  - `.cast<T>()` and `requestVerbose<R>()` replace every success's `data`, but keep `status` — and the failure types.
292
336
 
337
+ ### Serializers
338
+
339
+ Everything between what you set on the builder and what `fetch` receives is a list of named steps. Nothing outside these steps touches the URL, headers or body.
340
+
341
+ | Stage | Turns | Default steps |
342
+ |---|---|---|
343
+ | `path` | `.path()` values → string segments | `dropNullish`, `stringify`, `split("/")`, `encode`, `prefixOrigin` |
344
+ | `query` | `.query()` entries → `[string, string]` entries | `fromOrigin`, `dropNullish`, `arrays("repeat")`, `stringify` |
345
+ | `url` | the assembled `URL` → the `URL` sent | `hashFromOrigin`, `confine` |
346
+ | `body` | `.body()` value → `BodyInit` and its content type (the first step that handles it wins) | `text`, `blob`, `binary`, `stream`, `urlencoded`, `formData`, `json` |
347
+ | `headers` | `.headers()` object → the headers sent | `caseInsensitive`, `contentType` |
348
+
349
+ The URL is the origin + `/` + the `path` segments joined by `/`, with the `query` entries appended and `.hash()` set; the `url` stage gets it after that.
350
+
351
+ ```ts
352
+ vigor.fetch("https://api.example.com")
353
+ .serializers(s => s
354
+ .query(q => q.dropNullish().arrays("comma").stringify()) // ids=1,2,3
355
+ .headers(h => h.caseInsensitive().custom("trace", headers => ({ ...headers, "X-Trace": id }))))
356
+ ```
357
+
358
+ - **A stage you set replaces that stage's whole list**, and its callback starts from an empty chain: the steps you write are exactly the ones that run. The example above drops `fromOrigin` from `query` and `contentType` from `headers`. Stages you don't set keep their defaults (`VigorFetchSerializersBase`).
359
+ - `custom(name, func)` adds your own step to any stage. Steps get the stage's value and `{ origin, context }` (`headers` steps also get the body's `contentType`); `url` steps may change the `URL` in place and return nothing.
360
+ - `path` and `query` must end in strings: a value left otherwise fails with `SERIALIZE_FAILED`. No `body` step handling the body fails with `INVALID_BODY`.
361
+ - The step factories are also exported on their own (`VigorPathSteps`, `VigorQuerySteps`, `VigorUrlSteps`, `VigorBodySteps`, `VigorHeadersSteps`), and the config-object form takes step lists: `.serializers({ url: [VigorUrlSteps.confine()] })`.
362
+ - With `settings.debug`, the timeline gets a `SERIALIZED` entry per stage with its step names and output.
363
+ - `apiMap` routes match the path as the default `path` steps produce it.
364
+
293
365
  ### headers / body / options
294
366
 
295
367
  ```ts
296
368
  vigor.fetch("/api")
297
369
  .headers("merge", { Authorization: "Bearer token" })
298
- .body("overwrite", { username: "john" })
370
+ .body("replace", { username: "john" })
299
371
  .options("merge", { credentials: "include" })
300
372
  ```
301
373
 
302
- 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")`).
374
+ The body is turned into a `BodyInit` by the `body` [serializer](#serializers): with the default steps, a string, `Blob`, `ArrayBuffer`/typed array/`DataView`, `ReadableStream`, `URLSearchParams` and `FormData` are sent as they are, and any other object as JSON. The `headers` serializer then adds the matching `Content-Type` unless `.headers()` set one, and keeps one key per header name regardless of case. `body("replace", 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")`).
303
375
 
304
376
  > 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.
305
377
 
@@ -320,8 +392,8 @@ Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`/typed array
320
392
  | `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) |
321
393
  | `maxRetryAfter(num)` | Upper bound (ms) on a server-suggested retry delay from `retryHeaders`; longer values are clamped | `300000` (5 min) |
322
394
  | `redirect(bool)` | On a redirected response, navigates the page via `window.location.href` (see below) | `false` |
323
- | `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` |
324
395
  | `maxRestarts(num)` | Max number of full pipeline restarts (see `onError` below) | `3` |
396
+ | `fetcher(fn)` | The function that sends each attempt, in place of the global `fetch` (see [Custom fetch](#custom-fetch)) | global `fetch` |
325
397
  | `default(fn)` | Fallback value/factory used only if the request ultimately fails and no restart/override happened | throws |
326
398
  | `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) (the nested retry/parse engines' too) | `false` |
327
399
 
@@ -333,6 +405,24 @@ On any non-`unretryStatus` failure response, the internal retry engine retries p
333
405
 
334
406
  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.)
335
407
 
408
+ ### Custom fetch
409
+
410
+ By default every attempt goes through the global `fetch`, looked up when the request is sent. `settings.fetcher` swaps in any function with the native signature, `(input: string, init: RequestInit) => Promise<Response>` (exported as `VigorFetcher`):
411
+
412
+ ```ts
413
+ import { fetch as undiciFetch, ProxyAgent } from "undici"
414
+
415
+ const proxied = vigor
416
+ .fetch("https://api.example.com")
417
+ .settings(s => s.fetcher((input, init) => undiciFetch(input, { ...init, dispatcher: new ProxyAgent(proxyUrl) })))
418
+ ```
419
+
420
+ - It receives the fully built URL and the `RequestInit` after the `before` middlewares ran, with the attempt's `signal` (timeout and external aborts) — honor it, or a timed-out attempt keeps running in the background.
421
+ - Everything around it stays the same: retries, `Retry-After`, parsing and middlewares all work on the `Response` it returns, and what it throws is retried like a network error.
422
+ - It's only type-checked: the signature is enforced at compile time, and the `Response` isn't checked at runtime.
423
+ - It's called as a plain function (`this` is `undefined`), so passing `window.fetch` directly is fine.
424
+ - Builders are immutable, so set it once on a base builder and reuse it: `const api = vigor.fetch(origin).settings({ fetcher })`.
425
+
336
426
  ### redirect
337
427
 
338
428
  With `settings.redirect(true)`, a redirected response navigates the browser to its target:
@@ -877,7 +967,7 @@ Every other code always has one, so after `isVigorFetchError(e, "FETCH_FAILED")`
877
967
  On a `requestVerbose()` error, `context` is typed with **that request's own config** — the guards keep it rather than widening to a generic type:
878
968
 
879
969
  ```ts
880
- const res = await vigor.fetch("https://api.example.com").path("users").requestVerbose();
970
+ const res = await vigor.fetch("https://api.example.com").path("append", "users").requestVerbose();
881
971
  if (!res.success && isVigorFetchError(res.error, "FETCH_FAILED")) {
882
972
  res.error.context.policy.origin; // "https://api.example.com"
883
973
  res.error.context.policy.path; // ["users"]
@@ -914,7 +1004,7 @@ if (!res.success) {
914
1004
  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:
915
1005
 
916
1006
  ```ts
917
- const res = await api.route("POST /users").body("overwrite", { name: "a" }).requestVerbose()
1007
+ const res = await api.route("POST /users").body("replace", { name: "a" }).requestVerbose()
918
1008
  if (!res.success) {
919
1009
  isVigorFetchError(res.error, "FETCH_FAILED", err => { // unwraps RETRY_EXHAUSTED if needed
920
1010
  if (err.data.status === 422) {
@@ -932,8 +1022,8 @@ if (!res.success) {
932
1022
 
933
1023
  ## TypeScript notes
934
1024
 
935
- - Every builder is **immutable** — `.settings(...)`, `.path(...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
936
- - 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.
1025
+ - Every builder is **immutable** — `.settings(...)`, `.path("append", ...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
1026
+ - Fetch's request parts take an explicit mode (`path`/`query`: `"append"`/`"replace"`, `headers`/`body`/`options`: `"merge"`/`"replace"`). Elsewhere, array-valued config (parse `strategies`, etc.) **concatenates** across calls by default and object-valued config deep-merges. A handful of methods (`hash`, `serializers(...)` per stage, `retry(VigorRetry)`/`parse(VigorParse)` with an instance, `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.
937
1027
  - Config objects are checked for unknown keys at any depth: `.settings({ maxAttempts: 3, timeot: 5 })` is a type error.
938
1028
  - 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.
939
1029
  - 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.