@indra211/exios 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +147 -2
- package/dist/index.cjs +1463 -0
- package/dist/index.d.cts +31 -0
- package/dist/index.d.ts +233 -0
- package/dist/index.js +1442 -0
- package/package.json +51 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 exios contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# exios
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An axios-compatible HTTP client built on native `fetch`, with **exponential-backoff retry** and a **circuit breaker** built in. Zero runtime dependencies, fully typed, ESM + CJS, runs in Node >= 20 and modern browsers (and Deno/Bun, since it only uses web-standard APIs).
|
|
4
|
+
|
|
5
|
+
Retry and the breaker are **on by default** for the default instance and for every `create()` instance, with safe defaults (idempotent methods only, `Retry-After` honoured, breaker outside the retry loop).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @indra211/exios
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
CommonJS works too: `require('@indra211/exios')` returns the default instance itself, so `const exios = require('@indra211/exios'); exios.get(...)` works, and named exports are available as properties (`require('@indra211/exios').create`, `.CircuitOpenError`, ...). `require('@indra211/exios').default` is the same instance.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import exios, { create, isExiosError, isCancel, CircuitOpenError } from "@indra211/exios";
|
|
19
|
+
|
|
20
|
+
const { data } = await exios.get<{ id: number }>(
|
|
21
|
+
"https://api.example.com/users/1",
|
|
22
|
+
{
|
|
23
|
+
params: { expand: "team" },
|
|
24
|
+
},
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
const api = exios.create({
|
|
28
|
+
baseURL: "https://api.example.com",
|
|
29
|
+
timeout: 5000,
|
|
30
|
+
retry: { retries: 2, baseDelayMs: 200 },
|
|
31
|
+
breaker: { failureThreshold: 5, resetTimeoutMs: 10_000 },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
api.interceptors.request.use((config) => {
|
|
35
|
+
config.headers.authorization = "Bearer ...";
|
|
36
|
+
return config;
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
const res = await api.post("/orders", { sku: "a1" });
|
|
41
|
+
console.log(res.status, res.meta.attempts);
|
|
42
|
+
} catch (err) {
|
|
43
|
+
if (err instanceof CircuitOpenError)
|
|
44
|
+
console.log("circuit open for", err.origin, "until", err.retryAt);
|
|
45
|
+
else if (isCancel(err)) console.log("canceled");
|
|
46
|
+
else if (isExiosError(err))
|
|
47
|
+
console.log(err.code, err.status, err.meta?.attempts);
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`api.defaults` is mutable, axios-style: `api.defaults.headers.common.Authorization = 'Bearer ...'` and per-method buckets such as `api.defaults.headers.post['Content-Type'] = '...'` work (every bucket always exists). Headers set by request interceptors are normalised before sending: keys are case-insensitive, the last write wins, and `null` removes a header.
|
|
52
|
+
|
|
53
|
+
The API surface matches axios: `exios(config)`, `exios(url, config)`, `exios.request`, `get/delete/head/options`, `post/put/patch`, `postForm/putForm/patchForm`, `create`, `defaults`, `interceptors`, `getUri`. Responses are `{ data, status, statusText, headers, config, request, meta }`.
|
|
54
|
+
|
|
55
|
+
## Migrating from axios
|
|
56
|
+
|
|
57
|
+
1. Swap the import: `import axios from 'axios'` becomes `import exios from '@indra211/exios'`. Named helpers: `isExiosError` (was `isAxiosError`), `isCancel`, `ExiosError`, `CanceledError`, `toFormData`, `mergeConfig`.
|
|
58
|
+
2. Replace `CancelToken` with `AbortSignal`: pass `signal: controller.signal`. `CancelToken` is not implemented.
|
|
59
|
+
3. Error codes are the axios strings (`ERR_BAD_REQUEST`, `ERR_BAD_RESPONSE`, `ERR_NETWORK`, `ECONNABORTED`, `ETIMEDOUT`, `ERR_CANCELED`, `ERR_BAD_OPTION_VALUE`) plus the new `ERR_CIRCUIT_OPEN`.
|
|
60
|
+
4. The number of attempts made is `response.meta.attempts` (and `error.meta.attempts`). A request rejected by an open circuit has `attempts: 0`.
|
|
61
|
+
5. `response.headers` is a plain lowercase-keyed object; `response.request` is the `Request` that was sent.
|
|
62
|
+
6. Fetch-specific options replace Node transport options: `fetch` (custom implementation), `fetchOptions` (`cache`, `credentials`, `mode`, `redirect`, `referrer`, `referrerPolicy`, `integrity`, `keepalive`, `priority`) and `redirect`. `fetchOptions.credentials` is used as given; `withCredentials: true` forces `'include'`, and the default is `'same-origin'`.
|
|
63
|
+
7. Any object body that is not `FormData`, `Blob`, `ArrayBuffer`/typed array, `ReadableStream` or `URLSearchParams` (including class instances and `Date`) is sent as JSON, like axios. Only plain objects and arrays are converted for `multipart/form-data` or `application/x-www-form-urlencoded`.
|
|
64
|
+
8. If you used `axios-retry` or `opossum`, remove them: use the `retry` and `breaker` options below.
|
|
65
|
+
|
|
66
|
+
## Retry
|
|
67
|
+
|
|
68
|
+
`retry` is `false` or an options object. Defaults:
|
|
69
|
+
|
|
70
|
+
| Option | Default | Meaning |
|
|
71
|
+
| --------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
72
|
+
| `retries` | `3` | Retries after the first attempt (up to 4 attempts) |
|
|
73
|
+
| `methods` | `['get','head','options','put','delete']` | Methods that may be retried (also gates retries after network errors) |
|
|
74
|
+
| `statusCodes` | `[408, 429, 500, 502, 503, 504]` | Response statuses that trigger a retry |
|
|
75
|
+
| `retryOnNetworkError` | `true` | Retry `ERR_NETWORK` and timeouts |
|
|
76
|
+
| `baseDelayMs` | `300` | Delay before the first retry |
|
|
77
|
+
| `maxDelayMs` | `30000` | Cap on any delay (including `Retry-After`) |
|
|
78
|
+
| `factor` | `2` | Backoff multiplier: delay n = `min(maxDelayMs, baseDelayMs * factor^(n-1))` |
|
|
79
|
+
| `jitter` | `'full'` | `'full'` picks `random(0, delay)`; `'none'` uses the exact delay |
|
|
80
|
+
| `respectRetryAfter` | `true` | `Retry-After` (seconds or HTTP date) replaces the computed delay, capped at `maxDelayMs` |
|
|
81
|
+
| `maxElapsedMs` | none | Optional time budget for the retry sequence: no new attempt starts if its delay would exceed the budget (an attempt already in flight is not cut short; use `timeout` for that) |
|
|
82
|
+
| `shouldRetry` | none | `({ error?, response?, attempt, config }) => boolean \| Promise<boolean>` |
|
|
83
|
+
| `onRetry` | none | `({ error?, response?, attempt, delayMs }) => void`, called before each backoff sleep |
|
|
84
|
+
|
|
85
|
+
`timeout` applies per attempt. Aborting `signal` cancels the whole sequence immediately, including a pending backoff sleep.
|
|
86
|
+
|
|
87
|
+
A `shouldRetry` or `onRetry` hook that throws rejects the request with that error as-is (not wrapped in an `ExiosError`), and nothing is recorded on the breaker for that request.
|
|
88
|
+
|
|
89
|
+
All numeric options are validated when a request is made: `retries`, `baseDelayMs`, `maxDelayMs` and `maxElapsedMs` must be non-negative finite numbers and `factor` must be `>= 1`; anything else rejects with `ERR_BAD_OPTION_VALUE`. An option set to `undefined` counts as not set and keeps its default.
|
|
90
|
+
|
|
91
|
+
## Circuit breaker
|
|
92
|
+
|
|
93
|
+
There is one breaker per origin (`protocol//host:port`) per instance, kept in memory. States: closed, then open after the failure threshold, then half-open after `resetTimeoutMs`; probe success closes it, probe failure re-opens it. Requests rejected while open fail immediately with `CircuitOpenError` (`code: 'ERR_CIRCUIT_OPEN'`, with `origin` and `retryAt`).
|
|
94
|
+
|
|
95
|
+
| Option | Default | Meaning |
|
|
96
|
+
| ---------------------- | -------------------------------- | ----------------------------------------------------------------------------------------- |
|
|
97
|
+
| `failureThreshold` | `5` | Consecutive failures that open the circuit |
|
|
98
|
+
| `windowMs` | none | If set, rolling-window mode: the failure _rate_ is used and `failureThreshold` is ignored |
|
|
99
|
+
| `minRequests` | `10` | Minimum samples in the window before the rate applies |
|
|
100
|
+
| `failureRateThreshold` | `0.5` | Failure rate that opens the circuit (window mode) |
|
|
101
|
+
| `resetTimeoutMs` | `30000` | Time open before moving to half-open |
|
|
102
|
+
| `halfOpenMaxRequests` | `1` | Concurrent probes allowed in half-open |
|
|
103
|
+
| `successThreshold` | `1` | Probe successes needed to close |
|
|
104
|
+
| `isFailure` | network error, timeout, 5xx, 429 | `({ error?, response? }) => boolean` (also settable per request) |
|
|
105
|
+
| `key` | origin of the final URL | `(config) => string` (also settable per request) |
|
|
106
|
+
| `onStateChange` | none | `(key, from, to) => void` |
|
|
107
|
+
|
|
108
|
+
Introspect with `api.breaker.state(origin)` and reset with `api.breaker.reset(origin?)`. 4xx responses other than 408/429 are not failures, and cancellations never count.
|
|
109
|
+
|
|
110
|
+
The open to half-open move is lazy: it happens when the next request arrives, so `breaker.state(origin)` keeps reporting `'open'` after `resetTimeoutMs` has passed until a request is made.
|
|
111
|
+
|
|
112
|
+
Breaker options are validated like retry options: `failureThreshold`, `resetTimeoutMs`, `minRequests` and `windowMs` must be `> 0`, `failureRateThreshold` must be in `(0, 1]`, and `halfOpenMaxRequests` and `successThreshold` must be `>= 1`. Invalid values reject with `ERR_BAD_OPTION_VALUE`; `undefined` keeps the default. Relative and protocol-relative URLs are keyed by their origin resolved against `location` in browsers.
|
|
113
|
+
|
|
114
|
+
## Behavior rules
|
|
115
|
+
|
|
116
|
+
These are deliberate and tested.
|
|
117
|
+
|
|
118
|
+
1. **Per-request `breaker` config.** Thresholds (`failureThreshold`, window settings, `resetTimeoutMs`, `halfOpenMaxRequests`, `successThreshold`, `onStateChange`) are per instance only. Per request you may set only `breaker: false` (skip the gate and report nothing), `breaker.key` and `breaker.isFailure`. A breaker reads the instance config when it is first created for a key; changing `defaults.breaker` later affects new keys only, and `api.breaker.reset()` discards existing breakers so they pick up the new config.
|
|
119
|
+
2. **`create()` inherits resilience.** Instances from `create()` get retry and breaker enabled with the default settings. Pass `retry: false` / `breaker: false` to opt out.
|
|
120
|
+
3. **`validateStatus` does not affect resilience.** Retry and breaker judge the raw attempt outcome (network error/timeout, or the HTTP status). A 503 accepted by a custom `validateStatus` is still retried and still counts as a breaker failure, unless `shouldRetry` / `isFailure` say otherwise. `validateStatus` only decides whether the final result resolves or rejects.
|
|
121
|
+
4. **Half-open probes get no retries.** A request admitted as a half-open probe makes exactly one attempt; its outcome closes or re-opens the circuit immediately.
|
|
122
|
+
5. **Node floor is 20.** `engines.node` is `>=20`. The full test suite needs Node 22+ (Vitest), so Node 20 is covered by a smoke test against the built package, not the full suite.
|
|
123
|
+
6. **`shouldRetry` scope.** It replaces the `methods`, `statusCodes` and `retryOnNetworkError` checks, so an explicit hook can retry a POST. It can never override the never-retry list (canceled, circuit open, bad option, one-shot stream body); `retries` and `maxElapsedMs` still cap.
|
|
124
|
+
7. **Rolling-window mode.** When `windowMs` is set, `failureThreshold` is ignored. Closing from half-open clears the window / consecutive counter.
|
|
125
|
+
8. **Network errors and `methods`.** The `methods` filter gates every retry, including after network errors: a POST that failed at the network level may have reached the server, so it is not retried by default.
|
|
126
|
+
|
|
127
|
+
Also:
|
|
128
|
+
|
|
129
|
+
- **Breaker outside retry.** The breaker sees one outcome per logical request, not one per attempt. Between attempts it is re-checked; if other requests opened it, the loop stops with `CircuitOpenError`.
|
|
130
|
+
- **2xx responses are never retried**, even if `shouldRetry` returns true.
|
|
131
|
+
- **Throwing request interceptors.** A synchronous request interceptor that throws routes to the next interceptor's `onRejected` (this differs from axios).
|
|
132
|
+
- **Hung half-open probes.** A half-open probe that hangs longer than `resetTimeoutMs` counts as a failure.
|
|
133
|
+
- **Never retried:** cancellations, `ERR_CIRCUIT_OPEN`, `ERR_BAD_OPTION_VALUE`, and requests whose body is a one-shot `ReadableStream`.
|
|
134
|
+
|
|
135
|
+
## Not supported
|
|
136
|
+
|
|
137
|
+
- **Upload progress** (`onUploadProgress`): `fetch` cannot report it. Download progress (`onDownloadProgress`) is supported.
|
|
138
|
+
- **Node transport options:** `httpAgent`, `httpsAgent`, `proxy`, `socketPath`, `maxRedirects`, `decompress`, `insecureHTTPParser`. Use `redirect: 'follow' | 'manual' | 'error'` instead.
|
|
139
|
+
- **Node streams:** `responseType: 'stream'` returns a web `ReadableStream`, not a Node `Readable`. Aborting `signal` after the response resolved still stops the stream (reads reject with `CanceledError`); `timeout` covers only getting the response, not reading the stream. A stream body from an attempt that is retried is cancelled.
|
|
140
|
+
- **`responseEncoding`:** ignored; text responses are always decoded as UTF-8.
|
|
141
|
+
- **XSRF** cookie/header handling.
|
|
142
|
+
- **Adapters:** there is a single transport, `fetch`. Inject a custom implementation with the `fetch` option.
|
|
143
|
+
- **`CancelToken`:** use `AbortSignal`.
|
|
144
|
+
- **Distributed or persisted breaker state.**
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT
|