vigor-fetch 4.1.0 → 5.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 +334 -37
- package/dist/index.cjs +868 -335
- package/dist/index.d.cts +3684 -1850
- package/dist/index.d.ts +3684 -1850
- package/dist/index.js +852 -335
- package/package.json +3 -2
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
|
|
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,
|
|
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 | `
|
|
199
|
-
| `
|
|
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
|
|
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
|
-
.
|
|
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
|
-
-
|
|
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)
|
|
222
|
-
|
|
223
|
-
|
|
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
|
|
|
@@ -264,7 +383,7 @@ const data = await vigor
|
|
|
264
383
|
.request();
|
|
265
384
|
```
|
|
266
385
|
|
|
267
|
-
Both accept a config object, a builder callback, or an already-built `VigorRetry`/`VigorParse` instance. The target
|
|
386
|
+
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
387
|
|
|
269
388
|
### cast
|
|
270
389
|
|
|
@@ -313,6 +432,7 @@ await vigor
|
|
|
313
432
|
| `maxAttempts(num)` | Max attempts before giving up on this run | `5` |
|
|
314
433
|
| `maxRestarts(num)` | Max full pipeline restarts (see `onError`) | `3` |
|
|
315
434
|
| `timeout(ms)` | Timeout per individual attempt. `0` or `Infinity` disables it | `20000` |
|
|
435
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
|
|
316
436
|
|
|
317
437
|
### algorithms
|
|
318
438
|
|
|
@@ -329,7 +449,7 @@ Delay algorithm is a **replace**, not merge — switching algorithms discards th
|
|
|
329
449
|
| `backoff(cfg?)` | `initial` (`0`), `multiplier` (`1.7`), `unit` (`1000`), `minDelay` (`500`), `maxDelay` (`10000`), `jitter` (`800`) |
|
|
330
450
|
| `custom(cfg?)` | `target: (attempt) => number` (required), `minDelay` (`500`), `maxDelay` (`10000`), `jitter` (`800`) |
|
|
331
451
|
|
|
332
|
-
Each computed delay is clamped to `[minDelay, maxDelay]`
|
|
452
|
+
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
453
|
|
|
334
454
|
```ts
|
|
335
455
|
.algorithms(a => a.custom({
|
|
@@ -356,7 +476,7 @@ Each computed delay is clamped to `[minDelay, maxDelay]` (except `constant`, whi
|
|
|
356
476
|
| Stage | Runs | Intercept API |
|
|
357
477
|
|---|---|---|
|
|
358
478
|
| `before` | Before each attempt | `throwError`, `abort`, `breakRetry` |
|
|
359
|
-
| `after` | After the target settles successfully | `
|
|
479
|
+
| `after` | After the target settles successfully | `throwError` |
|
|
360
480
|
| `onResult` | Right before returning the attempt's result | `setResult`, `throwError` |
|
|
361
481
|
| `retryIf` | After a failed attempt, decides whether to retry | `proceedRetry`, `cancelRetry` |
|
|
362
482
|
| `onRetry` | Right before the retry delay is awaited | `throwError`, `setDelay` |
|
|
@@ -390,10 +510,13 @@ There are two independent resilience layers here:
|
|
|
390
510
|
| `raw(bool)` | When `true`, skips parsing entirely and returns the raw `Request\|Response` object | `false` |
|
|
391
511
|
| `default(fn)` | Fallback value/factory when parsing ultimately fails | throws |
|
|
392
512
|
| `maxRestarts(num)` | Max full pipeline restarts | `3` |
|
|
513
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
|
|
393
514
|
|
|
394
515
|
### strategies
|
|
395
516
|
|
|
396
|
-
Strategies form an ordered list that's tried in sequence until one succeeds
|
|
517
|
+
Strategies form an ordered list that's tried in sequence until one succeeds. If you never configure any, Vigor defaults to content-type detection.
|
|
518
|
+
|
|
519
|
+
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
520
|
|
|
398
521
|
```ts
|
|
399
522
|
.strategies(s => s.sniff())
|
|
@@ -401,15 +524,31 @@ Strategies form an ordered list that's tried in sequence until one succeeds (eac
|
|
|
401
524
|
|
|
402
525
|
| Method | Behavior |
|
|
403
526
|
|---|---|
|
|
404
|
-
| `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text).
|
|
405
|
-
| `sniff(replace?)` | Tries
|
|
406
|
-
| `json(replace?)` | Always parses as JSON |
|
|
407
|
-
| `text(replace?)` | Always parses as text |
|
|
527
|
+
| `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 |
|
|
528
|
+
| `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` |
|
|
529
|
+
| `json(replace?)` | Always parses as JSON (always UTF-8, per the JSON spec) |
|
|
530
|
+
| `text(replace?)` | Always parses as text, in the `Content-Type`'s `charset` (UTF-8 when absent or unsupported) |
|
|
408
531
|
| `arrayBuffer(replace?)` | Always parses as `ArrayBuffer` |
|
|
409
532
|
| `blob(replace?)` | Always parses as `Blob` |
|
|
410
533
|
| `bytes(replace?)` | Always parses as `Uint8Array` |
|
|
411
|
-
| `formData(replace?)` | Always parses as `FormData` |
|
|
412
|
-
| `custom(func, replace?)` | Uses a custom `(
|
|
534
|
+
| `formData(replace?)` | Always parses as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`; any other `Content-Type` fails) |
|
|
535
|
+
| `custom(func, replace?)` | Uses a custom `(body: VigorParseBody) => any \| Promise<any>` — see below |
|
|
536
|
+
|
|
537
|
+
A custom strategy receives the already-read body, not the `Request|Response`:
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
type VigorParseBody = {
|
|
541
|
+
bytes: Uint8Array // the raw body, empty when there is none
|
|
542
|
+
contentType: string | null // the Content-Type header
|
|
543
|
+
status: number | null // null when parsing a Request
|
|
544
|
+
headers: Headers
|
|
545
|
+
source: Request | Response // its body is already consumed
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
.strategies(s => s.custom(({ bytes }) => new TextDecoder().decode(bytes).split("\n")))
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
`readVigorParseBody(requestOrResponse)` is exported too, if you need the same read-once bytes outside a strategy.
|
|
413
552
|
|
|
414
553
|
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
554
|
|
|
@@ -433,6 +572,8 @@ const data = await vigor
|
|
|
433
572
|
.request();
|
|
434
573
|
```
|
|
435
574
|
|
|
575
|
+
`proceedRestart()` re-parses the same cached bytes, so a restart never hits an already-consumed body.
|
|
576
|
+
|
|
436
577
|
---
|
|
437
578
|
|
|
438
579
|
## `vigor.all`
|
|
@@ -466,9 +607,10 @@ const results = await vigor
|
|
|
466
607
|
| Method | Description | Default |
|
|
467
608
|
|---|---|---|
|
|
468
609
|
| `concurrency(num)` | Max number of tasks running at once | `5` |
|
|
469
|
-
| `onlySuccess(bool)` | When `true`,
|
|
470
|
-
| `timeout(ms)` | Per-task timeout. A task exceeding it fails with `VigorAllError("TIMED_OUT")` (recoverable via `onErrorEach`) | disabled |
|
|
610
|
+
| `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` |
|
|
611
|
+
| `timeout(ms)` | Per-task timeout. A task exceeding it fails with `VigorAllError("TIMED_OUT")` (recoverable via `onErrorEach`). `0` or `Infinity` disables it | disabled |
|
|
471
612
|
| `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` |
|
|
613
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
|
|
472
614
|
|
|
473
615
|
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
616
|
|
|
@@ -483,9 +625,20 @@ const results = await vigor
|
|
|
483
625
|
.request();
|
|
484
626
|
```
|
|
485
627
|
|
|
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,
|
|
628
|
+
> 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).
|
|
629
|
+
|
|
630
|
+
**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):
|
|
631
|
+
|
|
632
|
+
```ts
|
|
633
|
+
const [user, posts] = await vigor.all(() => getUser(), () => getPosts()).request();
|
|
634
|
+
if (user.success) user.data; // what getUser returned
|
|
635
|
+
else if (isVigorAllError(user.error, "TIMED_OUT")) user.error.data.index;
|
|
636
|
+
else user.error; // whatever getUser threw
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
With `onlySuccess(true)`, it's just the successful tasks' values.
|
|
487
640
|
|
|
488
|
-
**Result typing:**
|
|
641
|
+
**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
642
|
|
|
490
643
|
### hooks (`middlewares`)
|
|
491
644
|
|
|
@@ -520,6 +673,86 @@ Batch-level fluent signatures: `before`/`after` take `(ctx) => void`, `onResult`
|
|
|
520
673
|
|
|
521
674
|
---
|
|
522
675
|
|
|
676
|
+
## Timeline
|
|
677
|
+
|
|
678
|
+
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.
|
|
679
|
+
|
|
680
|
+
```ts
|
|
681
|
+
const res = await vigor.fetch("https://api.example.com/users").settings(s => s.debug(true)).requestVerbose();
|
|
682
|
+
|
|
683
|
+
for (const item of res.timeline) {
|
|
684
|
+
console.log(item.now, item.action, item.content);
|
|
685
|
+
}
|
|
686
|
+
```
|
|
687
|
+
|
|
688
|
+
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`.
|
|
689
|
+
|
|
690
|
+
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`.
|
|
691
|
+
|
|
692
|
+
### Shared events
|
|
693
|
+
|
|
694
|
+
| Action | Content |
|
|
695
|
+
|---|---|
|
|
696
|
+
| `PROCESS_HANDLING` | `{ type, data }` — the run's lifecycle steps (below) |
|
|
697
|
+
| `MIDDLEWARE_LOOP_STARTED` | `{ stage, middlewares }` |
|
|
698
|
+
| `MIDDLEWARE_RAN` | `{ stage, index, middleware, internal, took, threw, error }` — one middleware ran; `error` is what it threw when `threw` is `true` |
|
|
699
|
+
| `MIDDLEWARE_LOOP_ENDED` | `{ stage, middlewares, took }` |
|
|
700
|
+
| `MIDDLEWARE_API_CALLED` | `{ stage, index, middleware, internal, method, args }` — an intercept API call, e.g. `setDelay` |
|
|
701
|
+
| `REQUEST_END` | `{ success, outcome, took, restarts, error }` — always the last entry (see below) |
|
|
702
|
+
|
|
703
|
+
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.
|
|
704
|
+
|
|
705
|
+
`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.
|
|
706
|
+
|
|
707
|
+
### Per module
|
|
708
|
+
|
|
709
|
+
| Module | `PROCESS_HANDLING` types | Other actions |
|
|
710
|
+
|---|---|---|
|
|
711
|
+
| `vigor.retry` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART`, `RETRY_START`, `RETRY_ERROR` | `ATTEMPT_INCREASED`, `TARGET_REQUEST_STARTED`, `TARGET_REQUEST_ENDED`, `RETRY_DECISION`, `RETRY_DELAY` |
|
|
712
|
+
| `vigor.parse` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART` | `BODY_READ`, `STRATEGY_STARTED`, `STRATEGY_SUCCEEDED`, `STRATEGY_FAILED` |
|
|
713
|
+
| `vigor.fetch` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART` | `BUILT_URL`, `SET_OPTIONS`, `ENGINE_CREATED`, `RETRY_STARTED`, `RESPONSE_RECEIVED`, `RETRY_ENDED`, `PARSE_STARTED`, `PARSE_ENDED` |
|
|
714
|
+
| `vigor.all` | `REQUEST_START`, `REQUEST_ERROR` | `TASK_STARTED`, `TASK_ENDED`, `TASK_ERROR` |
|
|
715
|
+
|
|
716
|
+
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 }`:
|
|
717
|
+
|
|
718
|
+
| `reason` | `retry` | Meaning |
|
|
719
|
+
|---|---|---|
|
|
720
|
+
| `"retry"` | `true` | It will be retried (`RETRY_DELAY` follows) |
|
|
721
|
+
| `"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`) |
|
|
722
|
+
| `"breakRetry"` | `false` | A middleware called `breakRetry()` |
|
|
723
|
+
| `"aborted"` | `false` | An external abort signal fired |
|
|
724
|
+
| `"exhausted"` | `false` | No attempts left |
|
|
725
|
+
|
|
726
|
+
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.
|
|
727
|
+
|
|
728
|
+
In `vigor.all`, tasks run concurrently, so their entries interleave; each one carries its task's `index`.
|
|
729
|
+
|
|
730
|
+
### Nested engines in `vigor.fetch`
|
|
731
|
+
|
|
732
|
+
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):
|
|
733
|
+
|
|
734
|
+
```ts
|
|
735
|
+
for (const item of res.timeline) {
|
|
736
|
+
if (item.action === "RETRY_ENDED") item.content.timeline; // VigorRetryTimeline
|
|
737
|
+
}
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
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:
|
|
741
|
+
|
|
742
|
+
```text
|
|
743
|
+
RETRY_STARTED
|
|
744
|
+
RESPONSE_RECEIVED attempt=1 status=503
|
|
745
|
+
PARSE_STARTED failedResponse attempt=1
|
|
746
|
+
PARSE_ENDED failedResponse attempt=1
|
|
747
|
+
RESPONSE_RECEIVED attempt=2 status=200
|
|
748
|
+
RETRY_ENDED (the retry engine's own timeline inside)
|
|
749
|
+
PARSE_STARTED response attempt=2
|
|
750
|
+
PARSE_ENDED response attempt=2
|
|
751
|
+
REQUEST_END success outcome="result"
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
---
|
|
755
|
+
|
|
523
756
|
## Plugins
|
|
524
757
|
|
|
525
758
|
```ts
|
|
@@ -531,10 +764,12 @@ export type VigorPlugin<
|
|
|
531
764
|
func: (v: VigorInstance, options: O) => Ext
|
|
532
765
|
}
|
|
533
766
|
|
|
534
|
-
vigor.use(plugin, options?)
|
|
767
|
+
vigor.use(plugin, options?) // options: Partial<O>
|
|
535
768
|
```
|
|
536
769
|
|
|
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.
|
|
770
|
+
`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.
|
|
771
|
+
|
|
772
|
+
`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
773
|
|
|
539
774
|
```ts
|
|
540
775
|
const loggingPlugin: VigorPlugin<{ prefix?: string }> = {
|
|
@@ -574,11 +809,11 @@ try {
|
|
|
574
809
|
| `vigor.retry` | `VigorRetryErrors \| {} \| null \| undefined` |
|
|
575
810
|
| `vigor.parse` | `VigorParseErrors \| {} \| null \| undefined` |
|
|
576
811
|
| `vigor.all` | `VigorAllErrors \| {} \| null \| undefined` |
|
|
577
|
-
| `vigor.fetch` | `VigorFetchErrors \|
|
|
812
|
+
| `vigor.fetch` | `VigorFetchErrors \| {} \| null \| undefined` (the nested engines' failures included, see below) |
|
|
578
813
|
|
|
579
814
|
`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
815
|
|
|
581
|
-
Narrow with the exported guards — `isVigorRetryError`, `isVigorParseError`, `isVigorFetchError`, `isVigorAllError
|
|
816
|
+
Narrow with the exported guards — `isVigorRetryError`, `isVigorParseError`, `isVigorFetchError`, `isVigorAllError` (or `vigor.guards.*`):
|
|
582
817
|
|
|
583
818
|
```ts
|
|
584
819
|
const res = await vigor.retry(task).requestVerbose();
|
|
@@ -593,6 +828,46 @@ if (!res.success) {
|
|
|
593
828
|
}
|
|
594
829
|
```
|
|
595
830
|
|
|
831
|
+
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):
|
|
832
|
+
|
|
833
|
+
```ts
|
|
834
|
+
const res = await vigor.fetch("/api/users").requestVerbose();
|
|
835
|
+
if (!res.success) {
|
|
836
|
+
if (isVigorFetchError(res.error, "FETCH_FAILED")) {
|
|
837
|
+
res.error.data.status; // number
|
|
838
|
+
res.error.data.parsed; // the error body, best-effort parsed
|
|
839
|
+
} else if (isVigorFetchError(res.error, "RETRY_EXHAUSTED", "TIMED_OUT")) {
|
|
840
|
+
res.error.code; // "RETRY_EXHAUSTED" | "TIMED_OUT"
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
try { await vigor.fetch("/api/users").request() }
|
|
845
|
+
catch (e) { if (isVigorFetchError(e, "INVALID_PROTOCOL")) e.data.origin }
|
|
846
|
+
```
|
|
847
|
+
|
|
848
|
+
`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:
|
|
849
|
+
|
|
850
|
+
| Module | `context` may be `undefined` | `context` is always `undefined` |
|
|
851
|
+
|---|---|---|
|
|
852
|
+
| fetch | `VALUE_REQUIRED` (also raised by `.route()` while building) | — |
|
|
853
|
+
| retry | `VALUE_REQUIRED` (also raised by the `custom` algorithm) | — |
|
|
854
|
+
| 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`) |
|
|
855
|
+
| all | — | `TIMED_OUT` (per task — see `data.index`) |
|
|
856
|
+
|
|
857
|
+
Every other code always has one, so after `isVigorFetchError(e, "FETCH_FAILED")`, `e.context.href` needs no check.
|
|
858
|
+
|
|
859
|
+
On a `requestVerbose()` error, `context` is typed with **that request's own config** — the guards keep it rather than widening to a generic type:
|
|
860
|
+
|
|
861
|
+
```ts
|
|
862
|
+
const res = await vigor.fetch("https://api.example.com").path("users").requestVerbose();
|
|
863
|
+
if (!res.success && isVigorFetchError(res.error, "FETCH_FAILED")) {
|
|
864
|
+
res.error.context.policy.origin; // "https://api.example.com"
|
|
865
|
+
res.error.context.policy.path; // ["users"]
|
|
866
|
+
}
|
|
867
|
+
```
|
|
868
|
+
|
|
869
|
+
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.
|
|
870
|
+
|
|
596
871
|
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
872
|
|
|
598
873
|
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 +879,44 @@ const res = await vigor.fetch("/api/users").requestVerbose();
|
|
|
604
879
|
if (!res.success) {
|
|
605
880
|
// res.error is typed, res.data is null
|
|
606
881
|
}
|
|
882
|
+
// res.timeline is there either way
|
|
607
883
|
```
|
|
608
884
|
|
|
609
885
|
| Module | Error codes |
|
|
610
886
|
|---|---|
|
|
611
|
-
| `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `INVALID_PROTOCOL`, `FETCH_FAILED`, `RESTART_EXHAUSTED`, `REDIRECTED` |
|
|
887
|
+
| `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `BODY_NOT_ALLOWED`, `INVALID_PROTOCOL`, `PATH_ESCAPED`, `FETCH_FAILED`, `RESTART_EXHAUSTED`, `REDIRECTED`, plus every `VigorRetryError` and `VigorParseError` code |
|
|
612
888
|
| `VigorRetryError` | `VALUE_REQUIRED`, `RETRY_EXHAUSTED`, `RESTART_EXHAUSTED`, `TIMED_OUT` |
|
|
613
889
|
| `VigorParseError` | `VALUE_REQUIRED`, `INVALID_CONTENT_TYPE`, `PARSER_NOT_FOUND`, `PARSER_ALL_FAILED`, `RESTART_EXHAUSTED` |
|
|
614
890
|
| `VigorAllError` | `EMPTY_TARGET`, `TIMED_OUT` |
|
|
615
891
|
|
|
892
|
+
`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.
|
|
893
|
+
|
|
616
894
|
`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
895
|
|
|
896
|
+
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:
|
|
897
|
+
|
|
898
|
+
```ts
|
|
899
|
+
const res = await api.route("POST /users").body("overwrite", { name: "a" }).requestVerbose()
|
|
900
|
+
if (!res.success) {
|
|
901
|
+
const err = isVigorFetchError(res.error, "RETRY_EXHAUSTED") ? res.error.data.error : res.error
|
|
902
|
+
if (isVigorFetchError(err, "FETCH_FAILED") && err.data.status === 422) {
|
|
903
|
+
err.data.parsed // { fields: Record<string, string> } | undefined
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
```
|
|
907
|
+
|
|
908
|
+
`.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.
|
|
909
|
+
|
|
910
|
+
`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`.
|
|
911
|
+
|
|
618
912
|
---
|
|
619
913
|
|
|
620
914
|
## TypeScript notes
|
|
621
915
|
|
|
622
916
|
- 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.
|
|
917
|
+
- 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.
|
|
918
|
+
- Config objects are checked for unknown keys at any depth: `.settings({ maxAttempts: 3, timeot: 5 })` is a type error.
|
|
919
|
+
- 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.
|
|
920
|
+
- 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
921
|
- 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
922
|
- `.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.
|