vigor-fetch 4.0.10 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -13
- package/dist/index.cjs +287 -108
- package/dist/index.d.cts +386 -173
- package/dist/index.d.ts +386 -173
- package/dist/index.js +283 -108
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -166,6 +166,8 @@ vigor.fetch("https://api.example.com/", "/api")
|
|
|
166
166
|
|
|
167
167
|
`origin()` only accepts one argument — pass origin + first path segments as separate calls, or fold extra segments into `path()`.
|
|
168
168
|
|
|
169
|
+
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
|
+
|
|
169
171
|
### headers / body / options
|
|
170
172
|
|
|
171
173
|
```ts
|
|
@@ -175,7 +177,9 @@ vigor.fetch("/api")
|
|
|
175
177
|
.options("merge", { credentials: "include" })
|
|
176
178
|
```
|
|
177
179
|
|
|
178
|
-
Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`, `URLSearchParams`, `FormData`, or plain object → JSON), and a matching `Content-Type` header is set automatically unless you've already set one via `.headers()
|
|
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.
|
|
181
|
+
|
|
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.
|
|
179
183
|
|
|
180
184
|
### settings
|
|
181
185
|
|
|
@@ -190,12 +194,33 @@ Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`, `URLSearch
|
|
|
190
194
|
|
|
191
195
|
| Method | Description | Default |
|
|
192
196
|
|---|---|---|
|
|
193
|
-
| `retryHeaders(...strs)` | Response headers checked for a `429` retry delay | `["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"
|
|
197
|
+
| `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"]` |
|
|
194
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` |
|
|
195
200
|
| `maxRestarts(num)` | Max number of full pipeline restarts (see `onError` below) | `3` |
|
|
196
201
|
| `default(fn)` | Fallback value/factory used only if the request ultimately fails and no restart/override happened | throws |
|
|
197
202
|
|
|
198
|
-
|
|
203
|
+
`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
|
+
|
|
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.
|
|
206
|
+
|
|
207
|
+
### redirect
|
|
208
|
+
|
|
209
|
+
With `settings.redirect` left `true`, a `3xx` response that carries a `Location` header navigates the browser to it:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
await vigor
|
|
213
|
+
.fetch("/api/session")
|
|
214
|
+
.options("merge", { redirect: "manual" }) // otherwise fetch follows 3xx itself
|
|
215
|
+
.request();
|
|
216
|
+
// 302 Location: /login -> window.location.href = "https://app.example.com/login"
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
- A relative `Location` is resolved against the responding URL.
|
|
220
|
+
- 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.
|
|
199
224
|
|
|
200
225
|
### interceptors (`middlewares`)
|
|
201
226
|
|
|
@@ -223,6 +248,10 @@ Every stage takes a mode as the first argument: `"fluent"` (return a plain value
|
|
|
223
248
|
|
|
224
249
|
Fluent-mode signatures: `before`/`after` take `(ctx) => void`, `onResult` takes `(res) => newRes`, `onError` takes `(err) => void`.
|
|
225
250
|
|
|
251
|
+
In `before`, `ctx.options` already holds the built request (`method`, `headers`, `body`, extra options), so a fluent middleware can also edit it directly — e.g. `ctx.options.headers["X-Trace"] = id`.
|
|
252
|
+
|
|
253
|
+
An intercept middleware that returns nothing keeps the current context (this applies to every module).
|
|
254
|
+
|
|
226
255
|
`onError` → `proceedRestart()` re-runs the **entire** fetch pipeline from scratch (up to `settings.maxRestarts` times) — this is separate from, and on top of, the internal retry engine's per-attempt retries.
|
|
227
256
|
|
|
228
257
|
### retry / parse (nested engines)
|
|
@@ -259,7 +288,7 @@ Without `.cast()`, the result type falls back to whatever your `parse()` config
|
|
|
259
288
|
| Method | Description |
|
|
260
289
|
|---|---|
|
|
261
290
|
| `target(fn)` | Sets the function to run: `(signal: AbortSignal) => any \| Promise<any>` |
|
|
262
|
-
| `abortSignals(...sigs)` | Attaches external `AbortSignal`s
|
|
291
|
+
| `abortSignals(...sigs)` | Attaches external `AbortSignal`s. Aborting cancels the current attempt (or the pending retry delay) and stops retrying |
|
|
263
292
|
| `settings(fn \| config)` | General retry settings (below) |
|
|
264
293
|
| `middlewares(fn \| config)` | Middleware pipeline (below) |
|
|
265
294
|
| `algorithms(fn)` | Selects and configures the delay algorithm (below) |
|
|
@@ -283,7 +312,7 @@ await vigor
|
|
|
283
312
|
| `default(fn)` | Fallback value/factory when the target ultimately fails | throws |
|
|
284
313
|
| `maxAttempts(num)` | Max attempts before giving up on this run | `5` |
|
|
285
314
|
| `maxRestarts(num)` | Max full pipeline restarts (see `onError`) | `3` |
|
|
286
|
-
| `timeout(ms)` | Timeout per individual attempt | `20000` |
|
|
315
|
+
| `timeout(ms)` | Timeout per individual attempt. `0` or `Infinity` disables it | `20000` |
|
|
287
316
|
|
|
288
317
|
### algorithms
|
|
289
318
|
|
|
@@ -372,7 +401,7 @@ Strategies form an ordered list that's tried in sequence until one succeeds (eac
|
|
|
372
401
|
|
|
373
402
|
| Method | Behavior |
|
|
374
403
|
|---|---|
|
|
375
|
-
| `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text) |
|
|
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 |
|
|
376
405
|
| `sniff(replace?)` | Tries `json → formData → text → blob` in order until one parses |
|
|
377
406
|
| `json(replace?)` | Always parses as JSON |
|
|
378
407
|
| `text(replace?)` | Always parses as text |
|
|
@@ -408,13 +437,14 @@ const data = await vigor
|
|
|
408
437
|
|
|
409
438
|
## `vigor.all`
|
|
410
439
|
|
|
411
|
-
Runs a fixed list of
|
|
440
|
+
Runs a fixed list of tasks with bounded concurrency, `Promise.allSettled`-style — an individual task failing never makes the whole batch throw by itself.
|
|
412
441
|
|
|
413
442
|
### Methods
|
|
414
443
|
|
|
415
444
|
| Method | Description |
|
|
416
445
|
|---|---|
|
|
417
|
-
| `target(...funcs)` | Sets the task list — each is `() => unknown \| Promise<unknown>` |
|
|
446
|
+
| `target(...funcs)` | Sets the task list — each is `(signal: AbortSignal) => unknown \| Promise<unknown>` |
|
|
447
|
+
| `abortSignals(...signals)` | External signals that cancel the remaining tasks and fail the batch with the signal's reason |
|
|
418
448
|
| `settings(fn \| config)` | Concurrency settings (below) |
|
|
419
449
|
| `middlewares(fn \| config)` | Batch-level and per-task hooks (below) |
|
|
420
450
|
| `cast<T>()` | Overrides the inferred result type with `T` |
|
|
@@ -437,8 +467,23 @@ const results = await vigor
|
|
|
437
467
|
|---|---|---|
|
|
438
468
|
| `concurrency(num)` | Max number of tasks running at once | `5` |
|
|
439
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 |
|
|
471
|
+
| `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` |
|
|
440
472
|
|
|
441
|
-
|
|
473
|
+
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
|
+
|
|
475
|
+
```ts
|
|
476
|
+
const results = await vigor
|
|
477
|
+
.all(
|
|
478
|
+
(signal) => fetch("/api/1", { signal }),
|
|
479
|
+
(signal) => fetch("/api/2", { signal })
|
|
480
|
+
)
|
|
481
|
+
.abortSignals(controller.signal)
|
|
482
|
+
.settings(s => s.timeout(5000).failFast(true))
|
|
483
|
+
.request();
|
|
484
|
+
```
|
|
485
|
+
|
|
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).
|
|
442
487
|
|
|
443
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.
|
|
444
489
|
|
|
@@ -453,7 +498,9 @@ const results = await vigor
|
|
|
453
498
|
| `onResult(type, fn)` | Batch | Once, right before returning the final result | `setResult`, `throwError` (intercept mode) |
|
|
454
499
|
| `beforeEach(fn)` | Per-task | Before each individual task is invoked | — |
|
|
455
500
|
| `afterEach(fn)` | Per-task | After a task settles successfully | — |
|
|
456
|
-
| `onErrorEach(fn)` | Per-task | When an individual task throws | `setResult` |
|
|
501
|
+
| `onErrorEach(fn)` | Per-task | When an individual task throws (including `TIMED_OUT`) | `setResult` |
|
|
502
|
+
|
|
503
|
+
Per-task hooks receive a context with `index` (the task's position in `target`), `result`, `error`, and `flags.overridden`.
|
|
457
504
|
|
|
458
505
|
```ts
|
|
459
506
|
.middlewares(m => m
|
|
@@ -487,7 +534,7 @@ export type VigorPlugin<
|
|
|
487
534
|
vigor.use(plugin, options?)
|
|
488
535
|
```
|
|
489
536
|
|
|
490
|
-
`plugin.func` receives the current `vigor` instance (read-only — plugins never mutate it, e.g. they might read it to wrap an existing method) and returns `Ext`, a set of properties to merge in. `vigor.use()` shallow-clones
|
|
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.
|
|
491
538
|
|
|
492
539
|
```ts
|
|
493
540
|
const loggingPlugin: VigorPlugin<{ prefix?: string }> = {
|
|
@@ -518,6 +565,38 @@ try {
|
|
|
518
565
|
}
|
|
519
566
|
```
|
|
520
567
|
|
|
568
|
+
### typed errors
|
|
569
|
+
|
|
570
|
+
`requestVerbose()`'s `error` is typed per module, as **a union of that module's errors plus `{}`**:
|
|
571
|
+
|
|
572
|
+
| Module | `error` type |
|
|
573
|
+
|---|---|
|
|
574
|
+
| `vigor.retry` | `VigorRetryErrors \| {} \| null \| undefined` |
|
|
575
|
+
| `vigor.parse` | `VigorParseErrors \| {} \| null \| undefined` |
|
|
576
|
+
| `vigor.all` | `VigorAllErrors \| {} \| null \| undefined` |
|
|
577
|
+
| `vigor.fetch` | `VigorFetchErrors \| VigorRetryErrors \| VigorParseErrors \| {} \| null \| undefined` (the nested engines surface their own errors) |
|
|
578
|
+
|
|
579
|
+
`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
|
+
|
|
581
|
+
Narrow with the exported guards — `isVigorRetryError`, `isVigorParseError`, `isVigorFetchError`, `isVigorAllError`:
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
const res = await vigor.retry(task).requestVerbose();
|
|
585
|
+
if (!res.success) {
|
|
586
|
+
if (isVigorRetryError(res.error)) {
|
|
587
|
+
res.error.code; // "VALUE_REQUIRED" | "RETRY_EXHAUSTED" | "RESTART_EXHAUSTED" | "TIMED_OUT"
|
|
588
|
+
if (res.error.code === "TIMED_OUT") res.error.data.limit; // number
|
|
589
|
+
if (res.error.code === "RETRY_EXHAUSTED") res.error.data.error; // the last underlying error
|
|
590
|
+
} else {
|
|
591
|
+
res.error; // whatever your task threw
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
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
|
+
|
|
598
|
+
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.
|
|
599
|
+
|
|
521
600
|
Or avoid try/catch entirely with `requestVerbose()`:
|
|
522
601
|
|
|
523
602
|
```ts
|
|
@@ -529,10 +608,10 @@ if (!res.success) {
|
|
|
529
608
|
|
|
530
609
|
| Module | Error codes |
|
|
531
610
|
|---|---|
|
|
532
|
-
| `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `INVALID_PROTOCOL`, `FETCH_FAILED`, `RESTART_EXHAUSTED` |
|
|
611
|
+
| `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `INVALID_PROTOCOL`, `FETCH_FAILED`, `RESTART_EXHAUSTED`, `REDIRECTED` |
|
|
533
612
|
| `VigorRetryError` | `VALUE_REQUIRED`, `RETRY_EXHAUSTED`, `RESTART_EXHAUSTED`, `TIMED_OUT` |
|
|
534
613
|
| `VigorParseError` | `VALUE_REQUIRED`, `INVALID_CONTENT_TYPE`, `PARSER_NOT_FOUND`, `PARSER_ALL_FAILED`, `RESTART_EXHAUSTED` |
|
|
535
|
-
| `VigorAllError` | `EMPTY_TARGET` |
|
|
614
|
+
| `VigorAllError` | `EMPTY_TARGET`, `TIMED_OUT` |
|
|
536
615
|
|
|
537
616
|
`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`.
|
|
538
617
|
|