@indra211/exios 2.0.1 → 3.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 +89 -0
- package/dist/index.cjs +237 -11
- package/dist/index.d.cts +13 -0
- package/dist/index.d.ts +113 -8
- package/dist/index.js +237 -11
- package/dist/index.node.cjs +237 -11
- package/dist/index.node.js +237 -11
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -97,6 +97,12 @@ await exios.get(url, {
|
|
|
97
97
|
- `response.request` / `error.request` are the adapter's request object (typed `any`), not always a `Request`.
|
|
98
98
|
- `responseEncoding` is now honoured (it was ignored).
|
|
99
99
|
|
|
100
|
+
## Breaking changes in 3.0.0
|
|
101
|
+
|
|
102
|
+
- `error.toJSON()` now redacts credentials, sensitive header values and the request body (see [Error diagnostics](#error-diagnostics)). The shape is unchanged; code that read a secret back out of serialized errors will now see `"[REDACTED]"`.
|
|
103
|
+
- `response.meta` and `error.meta` gain optional fields (`requestId`, `correlationId`, `durationMs`, …). Tests that compare `meta` with an exact `toEqual({ attempts: 1 })` need `toMatchObject`.
|
|
104
|
+
- Retry, breaker, error codes and error messages are unchanged.
|
|
105
|
+
|
|
100
106
|
## Migrating from axios
|
|
101
107
|
|
|
102
108
|
1. Swap the import: `import axios from 'axios'` becomes `import exios from '@indra211/exios'`. Named helpers: `isExiosError` (was `isAxiosError`), `isCancel`, `ExiosError`, `CanceledError`, `toFormData`, `mergeConfig`.
|
|
@@ -156,6 +162,73 @@ The open to half-open move is lazy: it happens when the next request arrives, so
|
|
|
156
162
|
|
|
157
163
|
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.
|
|
158
164
|
|
|
165
|
+
## Observability and diagnostics
|
|
166
|
+
|
|
167
|
+
### Request and correlation IDs
|
|
168
|
+
|
|
169
|
+
Every logical request gets a `requestId`: a UUID from `crypto.randomUUID()` where that exists, otherwise a unique fallback. Retries share it. You can pass your own, and request interceptors can read or replace it. `correlationId` is yours to set, usually on an instance, to tie requests to a wider operation.
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
const api = exios.create({
|
|
173
|
+
baseURL: "https://api.example.com",
|
|
174
|
+
correlationId: "checkout-7f3a",
|
|
175
|
+
correlationIdHeader: "x-correlation-id", // opt-in: off by default
|
|
176
|
+
});
|
|
177
|
+
const res = await api.get("/cart");
|
|
178
|
+
res.meta; // { attempts, requestId, correlationId, durationMs, responseTimeMs }
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
IDs are **not** sent to the server unless you set `correlationIdHeader`. An extra header can trigger a CORS preflight in browsers. The header carries `correlationId`, or `requestId` when there is none. A header you set yourself always wins.
|
|
182
|
+
|
|
183
|
+
`durationMs` covers the whole logical request: breaker gate, every attempt and the backoff sleeps. `responseTimeMs` covers the final attempt only. Neither includes request or response interceptors. For `responseType: 'stream'`, timing stops when the headers arrive.
|
|
184
|
+
|
|
185
|
+
### Error diagnostics
|
|
186
|
+
|
|
187
|
+
Error messages and codes are unchanged from axios. Errors that reach your code carry context in `error.meta`:
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
try {
|
|
191
|
+
await api.get("/users/1");
|
|
192
|
+
} catch (err) {
|
|
193
|
+
err.code; // 'ERR_BAD_REQUEST', 'ERR_NETWORK', 'ECONNABORTED', 'ERR_CIRCUIT_OPEN', ...
|
|
194
|
+
err.meta; // { attempts, requestId, correlationId, method, url, durationMs }
|
|
195
|
+
err.cause; // the original error (e.g. the ECONNREFUSED system error) for network failures
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`meta.url` is `baseURL + url` without the serialized `params`. A query string you wrote into `url` yourself is kept.
|
|
200
|
+
|
|
201
|
+
`error.toJSON()` (and so `JSON.stringify(error)`) is **log-safe**: the values of `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Auth-Token`, `X-XSRF-Token` and `X-CSRF-Token`, `auth.password`, proxy credentials and the request body are replaced with `"[REDACTED]"`. The error object itself (`error.config`) is not modified.
|
|
202
|
+
|
|
203
|
+
### Lifecycle events
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const off = api.on("retry", (e) => {
|
|
207
|
+
console.log(e.requestId, `attempt ${e.attempt} failed (${e.status ?? e.error?.code}), retrying in ${e.delayMs}ms`);
|
|
208
|
+
});
|
|
209
|
+
api.once("circuitOpen", (e) => alert(`${e.key} is down`));
|
|
210
|
+
off(); // unsubscribe one listener
|
|
211
|
+
api.off("retry"); // or remove every listener of an event
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
| Event | When | Payload (besides `requestId`, `correlationId`, `method`, `url`, `config`, `timestamp`) |
|
|
215
|
+
| ----------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
|
216
|
+
| `request` | Once per logical request, after request interceptors, before the breaker | none |
|
|
217
|
+
| `retry` | Before each backoff sleep | `attempt` (the one that failed), `delayMs`, `error?`, `status?` |
|
|
218
|
+
| `timeout` | Every time an attempt times out (it may then be retried) | `attempt`, `timeoutMs`, `error` |
|
|
219
|
+
| `response` | Final success, before response interceptors | `response`, `status`, `attempts`, `durationMs`, `responseTimeMs` |
|
|
220
|
+
| `error` | Final failure, cancellations excluded | `error`, `code?`, `status?`, `attempts`, `durationMs` |
|
|
221
|
+
| `canceled` | The request was canceled (`signal` or `CancelToken`) | `error`, `attempts`, `durationMs` |
|
|
222
|
+
| `circuitOpen` | A breaker opened | `key`, `from`, `to`, `timestamp` only |
|
|
223
|
+
| `circuitHalfOpen` | A breaker moved to half-open (lazily, when the next request arrives) | same |
|
|
224
|
+
| `circuitClose` | A breaker closed | same |
|
|
225
|
+
|
|
226
|
+
- Payloads are typed (`ExiosEventMap`) and are built only when the event has a listener, so unused events cost nothing.
|
|
227
|
+
- Listeners run synchronously. A listener that throws is reported with `console.error` and never affects the request or other listeners.
|
|
228
|
+
- Listeners belong to one instance. `create()` does not copy them, just as it does not copy interceptors.
|
|
229
|
+
- A request rejected by a request interceptor never dispatches, so it emits no events.
|
|
230
|
+
- `retry.onRetry` and `breaker.onStateChange` keep working as before, and run before the events.
|
|
231
|
+
|
|
159
232
|
## Behavior rules
|
|
160
233
|
|
|
161
234
|
These are deliberate and tested.
|
|
@@ -183,6 +256,22 @@ Also:
|
|
|
183
256
|
- `redirect: 'manual' | 'error'` and `fetchOptions` on the `xhr` adapter (browsers' XHR always follows redirects); use `adapter: 'fetch'` when you need them.
|
|
184
257
|
- Distributed or persisted breaker state.
|
|
185
258
|
|
|
259
|
+
## Development: browser tests
|
|
260
|
+
|
|
261
|
+
| Script | Browsers |
|
|
262
|
+
| --- | --- |
|
|
263
|
+
| `npm run test:browser` | Chromium, WebKit (Playwright engines, headless) |
|
|
264
|
+
| `npm run test:browser:all` | Chromium, Firefox, WebKit (used in CI) |
|
|
265
|
+
| `npm run test:browser:edge` | the real Microsoft Edge app installed on your machine |
|
|
266
|
+
| `npm run test:browser:safari` | the real Safari app: **experimental, not working yet** (see below) |
|
|
267
|
+
| `npm run test:browser:mac` | Chromium, WebKit, Firefox and real Edge |
|
|
268
|
+
|
|
269
|
+
Real Safari is driven by macOS's built-in `safaridriver`. It does not work yet: Safari opens, but the test page never connects back to Vitest. WebKit (Safari's engine) is covered by the other scripts. One-time setup if you want to work on it:
|
|
270
|
+
|
|
271
|
+
1. In Safari: Settings > Advanced > tick "Show features for web developers".
|
|
272
|
+
2. Settings > Developer > tick "Allow remote automation".
|
|
273
|
+
3. In a terminal: `safaridriver --enable` (asks for your password).
|
|
274
|
+
|
|
186
275
|
## Author
|
|
187
276
|
|
|
188
277
|
Questions, bugs or ideas: [work.indrasena@outlook.com](mailto:work.indrasena@outlook.com)
|
package/dist/index.cjs
CHANGED
|
@@ -24,6 +24,36 @@ __export(cjs_exports, {
|
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(cjs_exports);
|
|
26
26
|
|
|
27
|
+
// src/core/redact.ts
|
|
28
|
+
var REDACTED = "[REDACTED]";
|
|
29
|
+
var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
|
|
30
|
+
"authorization",
|
|
31
|
+
"proxy-authorization",
|
|
32
|
+
"cookie",
|
|
33
|
+
"set-cookie",
|
|
34
|
+
"x-api-key",
|
|
35
|
+
"x-auth-token",
|
|
36
|
+
"x-xsrf-token",
|
|
37
|
+
"x-csrf-token"
|
|
38
|
+
]);
|
|
39
|
+
function redactHeaders(headers) {
|
|
40
|
+
if (!headers || typeof headers !== "object") return headers;
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [k, v] of Object.entries(headers))
|
|
43
|
+
out[k] = SENSITIVE_HEADERS.has(k.toLowerCase()) ? REDACTED : v;
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
function redactConfig(config) {
|
|
47
|
+
if (!config || typeof config !== "object") return config;
|
|
48
|
+
const c = { ...config };
|
|
49
|
+
if (c.headers && typeof c.headers === "object") c.headers = redactHeaders(c.headers);
|
|
50
|
+
if (c.auth) c.auth = { username: c.auth.username, password: REDACTED };
|
|
51
|
+
if (c.proxy && typeof c.proxy === "object" && c.proxy.auth)
|
|
52
|
+
c.proxy = { ...c.proxy, auth: { username: c.proxy.auth.username, password: REDACTED } };
|
|
53
|
+
if (c.data !== void 0) c.data = REDACTED;
|
|
54
|
+
return c;
|
|
55
|
+
}
|
|
56
|
+
|
|
27
57
|
// src/errors/ExiosError.ts
|
|
28
58
|
var ExiosError = class _ExiosError extends Error {
|
|
29
59
|
static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
|
|
@@ -53,13 +83,14 @@ var ExiosError = class _ExiosError extends Error {
|
|
|
53
83
|
this.response = response;
|
|
54
84
|
this.status = response?.status;
|
|
55
85
|
}
|
|
86
|
+
/** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
|
|
56
87
|
toJSON() {
|
|
57
88
|
return {
|
|
58
89
|
message: this.message,
|
|
59
90
|
name: this.name,
|
|
60
91
|
code: this.code,
|
|
61
92
|
status: this.status,
|
|
62
|
-
config: this.config,
|
|
93
|
+
config: redactConfig(this.config),
|
|
63
94
|
meta: this.meta,
|
|
64
95
|
stack: this.stack
|
|
65
96
|
};
|
|
@@ -1209,14 +1240,16 @@ function defaultIsFailure(o) {
|
|
|
1209
1240
|
return status >= 500 || status === 408 || status === 429;
|
|
1210
1241
|
}
|
|
1211
1242
|
var CircuitBreaker = class {
|
|
1212
|
-
constructor(key, cfg, now = Date.now) {
|
|
1243
|
+
constructor(key, cfg, now = Date.now, onTransition) {
|
|
1213
1244
|
this.key = key;
|
|
1214
1245
|
this.cfg = cfg;
|
|
1215
1246
|
this.now = now;
|
|
1247
|
+
this.onTransition = onTransition;
|
|
1216
1248
|
}
|
|
1217
1249
|
key;
|
|
1218
1250
|
cfg;
|
|
1219
1251
|
now;
|
|
1252
|
+
onTransition;
|
|
1220
1253
|
_state = "closed";
|
|
1221
1254
|
epoch = 0;
|
|
1222
1255
|
openedAt = 0;
|
|
@@ -1320,22 +1353,25 @@ var CircuitBreaker = class {
|
|
|
1320
1353
|
this.cfg.onStateChange?.(this.key, from, to);
|
|
1321
1354
|
} catch {
|
|
1322
1355
|
}
|
|
1356
|
+
this.onTransition?.(this.key, from, to);
|
|
1323
1357
|
}
|
|
1324
1358
|
};
|
|
1325
1359
|
var BreakerRegistry = class {
|
|
1326
|
-
constructor(getConfig, now = Date.now) {
|
|
1360
|
+
constructor(getConfig, now = Date.now, onTransition) {
|
|
1327
1361
|
this.getConfig = getConfig;
|
|
1328
1362
|
this.now = now;
|
|
1363
|
+
this.onTransition = onTransition;
|
|
1329
1364
|
}
|
|
1330
1365
|
getConfig;
|
|
1331
1366
|
now;
|
|
1367
|
+
onTransition;
|
|
1332
1368
|
breakers = /* @__PURE__ */ new Map();
|
|
1333
1369
|
get(key) {
|
|
1334
1370
|
const cfg = this.getConfig();
|
|
1335
1371
|
if (cfg === false) return null;
|
|
1336
1372
|
let b = this.breakers.get(key);
|
|
1337
1373
|
if (!b) {
|
|
1338
|
-
b = new CircuitBreaker(key, cfg, this.now);
|
|
1374
|
+
b = new CircuitBreaker(key, cfg, this.now, this.onTransition);
|
|
1339
1375
|
this.breakers.set(key, b);
|
|
1340
1376
|
}
|
|
1341
1377
|
return b;
|
|
@@ -1440,6 +1476,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
|
|
|
1440
1476
|
cancelBody(outcome.response?.data);
|
|
1441
1477
|
if (hooks.signal?.aborted) throw abortError(hooks.signal);
|
|
1442
1478
|
cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
|
|
1479
|
+
hooks.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
|
|
1443
1480
|
await sleep(delay, hooks.signal);
|
|
1444
1481
|
hooks.beforeRetry?.();
|
|
1445
1482
|
}
|
|
@@ -1461,7 +1498,7 @@ function defaultBreakerKey(config) {
|
|
|
1461
1498
|
return full;
|
|
1462
1499
|
}
|
|
1463
1500
|
}
|
|
1464
|
-
async function dispatchRequest(config, registry2) {
|
|
1501
|
+
async function dispatchRequest(config, registry2, observer) {
|
|
1465
1502
|
const token = config.cancelToken;
|
|
1466
1503
|
if (token) {
|
|
1467
1504
|
if (token.reason) {
|
|
@@ -1478,7 +1515,8 @@ async function dispatchRequest(config, registry2) {
|
|
|
1478
1515
|
try {
|
|
1479
1516
|
const response = await dispatchRequest(
|
|
1480
1517
|
{ ...config, signal: joined.signal, cancelToken: void 0 },
|
|
1481
|
-
registry2
|
|
1518
|
+
registry2,
|
|
1519
|
+
observer
|
|
1482
1520
|
);
|
|
1483
1521
|
if (isOneShotBody(response.data)) {
|
|
1484
1522
|
response.data = whenBodyDone(response.data, release);
|
|
@@ -1497,6 +1535,7 @@ async function dispatchRequest(config, registry2) {
|
|
|
1497
1535
|
const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
|
|
1498
1536
|
const ticket = breaker?.acquire(config);
|
|
1499
1537
|
let attempts = 0;
|
|
1538
|
+
let responseTimeMs;
|
|
1500
1539
|
try {
|
|
1501
1540
|
let adapter;
|
|
1502
1541
|
try {
|
|
@@ -1509,15 +1548,31 @@ async function dispatchRequest(config, registry2) {
|
|
|
1509
1548
|
try {
|
|
1510
1549
|
result = await runWithRetry(
|
|
1511
1550
|
() => {
|
|
1512
|
-
attempts
|
|
1513
|
-
|
|
1551
|
+
const n = ++attempts;
|
|
1552
|
+
const t0 = Date.now();
|
|
1553
|
+
const failed = (e) => {
|
|
1554
|
+
responseTimeMs = Date.now() - t0;
|
|
1555
|
+
if (isExiosError(e)) observer?.onAttemptError?.(n, e);
|
|
1556
|
+
throw e;
|
|
1557
|
+
};
|
|
1558
|
+
let result2;
|
|
1559
|
+
try {
|
|
1560
|
+
result2 = Promise.resolve(adapter(config));
|
|
1561
|
+
} catch (e) {
|
|
1562
|
+
return failed(e);
|
|
1563
|
+
}
|
|
1564
|
+
return result2.then((r) => {
|
|
1565
|
+
responseTimeMs = Date.now() - t0;
|
|
1566
|
+
return r;
|
|
1567
|
+
}, failed);
|
|
1514
1568
|
},
|
|
1515
1569
|
ticket?.probe ? false : config.retry,
|
|
1516
1570
|
// half-open probes get exactly one attempt
|
|
1517
1571
|
config,
|
|
1518
1572
|
{
|
|
1519
1573
|
signal: config.signal,
|
|
1520
|
-
beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
|
|
1574
|
+
beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0,
|
|
1575
|
+
onRetry: observer?.onRetry
|
|
1521
1576
|
}
|
|
1522
1577
|
);
|
|
1523
1578
|
} catch (e) {
|
|
@@ -1536,6 +1591,7 @@ async function dispatchRequest(config, registry2) {
|
|
|
1536
1591
|
if (outcome.error) throw outcome.error;
|
|
1537
1592
|
const response = outcome.response;
|
|
1538
1593
|
response.meta.attempts = attempts;
|
|
1594
|
+
if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
|
|
1539
1595
|
const { status } = response;
|
|
1540
1596
|
if (config.validateStatus && !config.validateStatus(status)) {
|
|
1541
1597
|
const err = new ExiosError(
|
|
@@ -1554,6 +1610,53 @@ async function dispatchRequest(config, registry2) {
|
|
|
1554
1610
|
}
|
|
1555
1611
|
}
|
|
1556
1612
|
|
|
1613
|
+
// src/core/events.ts
|
|
1614
|
+
var EventHub = class {
|
|
1615
|
+
listeners = /* @__PURE__ */ new Map();
|
|
1616
|
+
on(name, listener) {
|
|
1617
|
+
if (typeof listener !== "function")
|
|
1618
|
+
throw new TypeError(`exios: listener for "${name}" must be a function`);
|
|
1619
|
+
let set = this.listeners.get(name);
|
|
1620
|
+
if (!set) this.listeners.set(name, set = /* @__PURE__ */ new Set());
|
|
1621
|
+
set.add(listener);
|
|
1622
|
+
return () => this.off(name, listener);
|
|
1623
|
+
}
|
|
1624
|
+
once(name, listener) {
|
|
1625
|
+
const off = this.on(name, (e) => {
|
|
1626
|
+
off();
|
|
1627
|
+
listener(e);
|
|
1628
|
+
});
|
|
1629
|
+
return off;
|
|
1630
|
+
}
|
|
1631
|
+
off(name, listener) {
|
|
1632
|
+
const set = this.listeners.get(name);
|
|
1633
|
+
if (!set) return;
|
|
1634
|
+
if (listener === void 0) set.clear();
|
|
1635
|
+
else set.delete(listener);
|
|
1636
|
+
if (set.size === 0) this.listeners.delete(name);
|
|
1637
|
+
}
|
|
1638
|
+
has(name) {
|
|
1639
|
+
return this.listeners.has(name);
|
|
1640
|
+
}
|
|
1641
|
+
listenerCount(name) {
|
|
1642
|
+
return this.listeners.get(name)?.size ?? 0;
|
|
1643
|
+
}
|
|
1644
|
+
/** Build the payload only when someone listens: `emit('x', () => ({ ... }))`. */
|
|
1645
|
+
emit(name, payload) {
|
|
1646
|
+
const set = this.listeners.get(name);
|
|
1647
|
+
if (!set) return;
|
|
1648
|
+
const event = payload();
|
|
1649
|
+
for (const l of [...set]) {
|
|
1650
|
+
try {
|
|
1651
|
+
l(event);
|
|
1652
|
+
} catch (err) {
|
|
1653
|
+
if (typeof console !== "undefined")
|
|
1654
|
+
console.error(`[exios] "${name}" listener threw:`, err);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
|
|
1557
1660
|
// src/core/InterceptorManager.ts
|
|
1558
1661
|
var InterceptorManager = class {
|
|
1559
1662
|
handlers = [];
|
|
@@ -1790,7 +1893,27 @@ function assertRequestBreaker(b) {
|
|
|
1790
1893
|
}
|
|
1791
1894
|
}
|
|
1792
1895
|
|
|
1896
|
+
// src/core/requestId.ts
|
|
1897
|
+
var seq = 0;
|
|
1898
|
+
function createRequestId() {
|
|
1899
|
+
const c = globalThis.crypto;
|
|
1900
|
+
if (typeof c?.randomUUID === "function") {
|
|
1901
|
+
try {
|
|
1902
|
+
return c.randomUUID();
|
|
1903
|
+
} catch {
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
seq = (seq + 1) % Number.MAX_SAFE_INTEGER;
|
|
1907
|
+
return `${Date.now().toString(36)}-${seq.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1793
1910
|
// src/core/Exios.ts
|
|
1911
|
+
var CIRCUIT_EVENTS = {
|
|
1912
|
+
open: "circuitOpen",
|
|
1913
|
+
"half-open": "circuitHalfOpen",
|
|
1914
|
+
closed: "circuitClose"
|
|
1915
|
+
};
|
|
1916
|
+
var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ECONNABORTED", "ETIMEDOUT"]);
|
|
1794
1917
|
var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
|
|
1795
1918
|
var Exios = class {
|
|
1796
1919
|
defaults;
|
|
@@ -1800,10 +1923,18 @@ var Exios = class {
|
|
|
1800
1923
|
};
|
|
1801
1924
|
breaker;
|
|
1802
1925
|
registry;
|
|
1926
|
+
events = new EventHub();
|
|
1803
1927
|
constructor(defaults) {
|
|
1804
1928
|
this.defaults = defaults;
|
|
1805
1929
|
this.registry = new BreakerRegistry(
|
|
1806
|
-
() => resolveBreaker(this.defaults.breaker)
|
|
1930
|
+
() => resolveBreaker(this.defaults.breaker),
|
|
1931
|
+
Date.now,
|
|
1932
|
+
(key, from, to) => this.events.emit(CIRCUIT_EVENTS[to], () => ({
|
|
1933
|
+
key,
|
|
1934
|
+
from,
|
|
1935
|
+
to,
|
|
1936
|
+
timestamp: Date.now()
|
|
1937
|
+
}))
|
|
1807
1938
|
);
|
|
1808
1939
|
this.breaker = {
|
|
1809
1940
|
state: (key) => this.registry.state(key),
|
|
@@ -1821,7 +1952,7 @@ var Exios = class {
|
|
|
1821
1952
|
synchronous = synchronous && h.synchronous;
|
|
1822
1953
|
requestChain.unshift(h);
|
|
1823
1954
|
});
|
|
1824
|
-
const dispatch = (c) =>
|
|
1955
|
+
const dispatch = (c) => this.dispatch(finalizeConfig(c));
|
|
1825
1956
|
let promise;
|
|
1826
1957
|
if (synchronous) {
|
|
1827
1958
|
promise = this.runSync(requestChain, resolved, dispatch);
|
|
@@ -1839,6 +1970,98 @@ var Exios = class {
|
|
|
1839
1970
|
});
|
|
1840
1971
|
return promise;
|
|
1841
1972
|
}
|
|
1973
|
+
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
1974
|
+
on(name, listener) {
|
|
1975
|
+
return this.events.on(name, listener);
|
|
1976
|
+
}
|
|
1977
|
+
/** Like `on`, but the listener runs at most once. */
|
|
1978
|
+
once(name, listener) {
|
|
1979
|
+
return this.events.once(name, listener);
|
|
1980
|
+
}
|
|
1981
|
+
/** Remove one listener, or every listener of `name` when `listener` is omitted. */
|
|
1982
|
+
off(name, listener) {
|
|
1983
|
+
this.events.off(name, listener);
|
|
1984
|
+
}
|
|
1985
|
+
/** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
|
|
1986
|
+
async dispatch(config) {
|
|
1987
|
+
const requestId = config.requestId ??= createRequestId();
|
|
1988
|
+
const { correlationId } = config;
|
|
1989
|
+
const header = config.correlationIdHeader?.toLowerCase();
|
|
1990
|
+
if (header && config.headers[header] === void 0)
|
|
1991
|
+
config.headers = { ...config.headers, [header]: correlationId ?? requestId };
|
|
1992
|
+
const hub = this.events;
|
|
1993
|
+
const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
|
|
1994
|
+
const base = () => ({
|
|
1995
|
+
requestId,
|
|
1996
|
+
correlationId,
|
|
1997
|
+
method: config.method,
|
|
1998
|
+
url,
|
|
1999
|
+
config,
|
|
2000
|
+
timestamp: Date.now()
|
|
2001
|
+
});
|
|
2002
|
+
const start = Date.now();
|
|
2003
|
+
const observer = {
|
|
2004
|
+
onRetry: (o) => hub.emit("retry", () => ({
|
|
2005
|
+
...base(),
|
|
2006
|
+
attempt: o.attempt,
|
|
2007
|
+
delayMs: o.delayMs,
|
|
2008
|
+
error: o.error,
|
|
2009
|
+
status: o.response?.status ?? o.error?.response?.status
|
|
2010
|
+
})),
|
|
2011
|
+
onAttemptError: (attempt, error) => {
|
|
2012
|
+
if (TIMEOUT_CODES.has(error.code ?? ""))
|
|
2013
|
+
hub.emit("timeout", () => ({
|
|
2014
|
+
...base(),
|
|
2015
|
+
attempt,
|
|
2016
|
+
timeoutMs: config.timeout ?? 0,
|
|
2017
|
+
error
|
|
2018
|
+
}));
|
|
2019
|
+
}
|
|
2020
|
+
};
|
|
2021
|
+
hub.emit("request", base);
|
|
2022
|
+
try {
|
|
2023
|
+
const response = await dispatchRequest(config, this.registry, observer);
|
|
2024
|
+
const durationMs = Date.now() - start;
|
|
2025
|
+
const meta = response.meta;
|
|
2026
|
+
meta.requestId = requestId;
|
|
2027
|
+
if (correlationId !== void 0) meta.correlationId = correlationId;
|
|
2028
|
+
meta.durationMs = durationMs;
|
|
2029
|
+
hub.emit("response", () => ({
|
|
2030
|
+
...base(),
|
|
2031
|
+
response,
|
|
2032
|
+
status: response.status,
|
|
2033
|
+
attempts: meta.attempts,
|
|
2034
|
+
durationMs,
|
|
2035
|
+
responseTimeMs: meta.responseTimeMs ?? durationMs
|
|
2036
|
+
}));
|
|
2037
|
+
return response;
|
|
2038
|
+
} catch (e) {
|
|
2039
|
+
const durationMs = Date.now() - start;
|
|
2040
|
+
let attempts = 0;
|
|
2041
|
+
if (isExiosError(e)) {
|
|
2042
|
+
const meta = e.meta;
|
|
2043
|
+
meta.requestId ??= requestId;
|
|
2044
|
+
if (correlationId !== void 0) meta.correlationId ??= correlationId;
|
|
2045
|
+
meta.method ??= config.method;
|
|
2046
|
+
meta.url ??= url;
|
|
2047
|
+
meta.durationMs ??= durationMs;
|
|
2048
|
+
attempts = meta.attempts;
|
|
2049
|
+
}
|
|
2050
|
+
if (isCancel(e)) {
|
|
2051
|
+
hub.emit("canceled", () => ({ ...base(), error: e, attempts, durationMs }));
|
|
2052
|
+
} else {
|
|
2053
|
+
hub.emit("error", () => ({
|
|
2054
|
+
...base(),
|
|
2055
|
+
error: e,
|
|
2056
|
+
code: isExiosError(e) ? e.code : void 0,
|
|
2057
|
+
status: isExiosError(e) ? e.status ?? e.response?.status : void 0,
|
|
2058
|
+
attempts,
|
|
2059
|
+
durationMs
|
|
2060
|
+
}));
|
|
2061
|
+
}
|
|
2062
|
+
throw e;
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
1842
2065
|
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
1843
2066
|
runSync(chain, config, dispatch) {
|
|
1844
2067
|
let value = config;
|
|
@@ -1916,6 +2139,9 @@ var Exios = class {
|
|
|
1916
2139
|
};
|
|
1917
2140
|
var METHODS = [
|
|
1918
2141
|
"request",
|
|
2142
|
+
"on",
|
|
2143
|
+
"once",
|
|
2144
|
+
"off",
|
|
1919
2145
|
"getUri",
|
|
1920
2146
|
"get",
|
|
1921
2147
|
"delete",
|
package/dist/index.d.cts
CHANGED
|
@@ -34,5 +34,18 @@ declare namespace exios {
|
|
|
34
34
|
type ResponseType = Pkg.ResponseType;
|
|
35
35
|
type RetryConfig = Pkg.RetryConfig;
|
|
36
36
|
type Transformer = Pkg.Transformer;
|
|
37
|
+
type CanceledEvent = Pkg.CanceledEvent;
|
|
38
|
+
type CircuitEvent = Pkg.CircuitEvent;
|
|
39
|
+
type ErrorEvent = Pkg.ErrorEvent;
|
|
40
|
+
type ErrorMeta = Pkg.ErrorMeta;
|
|
41
|
+
type ExiosEventListener<K extends Pkg.ExiosEventName> = Pkg.ExiosEventListener<K>;
|
|
42
|
+
type ExiosEventMap = Pkg.ExiosEventMap;
|
|
43
|
+
type ExiosEventName = Pkg.ExiosEventName;
|
|
44
|
+
type RequestEvent = Pkg.RequestEvent;
|
|
45
|
+
type RequestEventBase = Pkg.RequestEventBase;
|
|
46
|
+
type ResponseEvent = Pkg.ResponseEvent;
|
|
47
|
+
type ResponseMeta = Pkg.ResponseMeta;
|
|
48
|
+
type RetryEvent = Pkg.RetryEvent;
|
|
49
|
+
type TimeoutEvent = Pkg.TimeoutEvent;
|
|
37
50
|
}
|
|
38
51
|
export = exios;
|
package/dist/index.d.ts
CHANGED
|
@@ -15,10 +15,9 @@ declare class ExiosError<T = any, D = any> extends Error {
|
|
|
15
15
|
response?: ExiosResponse<T, D>;
|
|
16
16
|
status?: number;
|
|
17
17
|
readonly isExiosError: true;
|
|
18
|
-
meta:
|
|
19
|
-
attempts: number;
|
|
20
|
-
};
|
|
18
|
+
meta: ErrorMeta;
|
|
21
19
|
constructor(message: string, code?: string, config?: InternalConfig<D>, request?: any, response?: ExiosResponse<T, D>);
|
|
20
|
+
/** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
|
|
22
21
|
toJSON(): Record<string, unknown>;
|
|
23
22
|
static from<T = any, D = any>(err: unknown, code: string | undefined, config?: InternalConfig<D>, request?: any, response?: ExiosResponse<T, D>): ExiosError<T, D>;
|
|
24
23
|
}
|
|
@@ -191,6 +190,15 @@ interface ExiosRequestConfig<D = any> {
|
|
|
191
190
|
redirect?: RequestRedirect;
|
|
192
191
|
retry?: false | Partial<RetryConfig>;
|
|
193
192
|
breaker?: false | Partial<BreakerConfig>;
|
|
193
|
+
/** Id of this logical request (retries share it). Generated when not set. */
|
|
194
|
+
requestId?: string;
|
|
195
|
+
/** Id that ties this request to a wider operation; often set on an instance. */
|
|
196
|
+
correlationId?: string;
|
|
197
|
+
/**
|
|
198
|
+
* Send `correlationId` (or `requestId` when there is none) in this header, e.g. "x-correlation-id".
|
|
199
|
+
* Off by default: an extra header can trigger a CORS preflight. A header the caller already set wins.
|
|
200
|
+
*/
|
|
201
|
+
correlationIdHeader?: string;
|
|
194
202
|
}
|
|
195
203
|
/**
|
|
196
204
|
* Type of `instance.defaults`: like a request config, but every header bucket, `retry` and `breaker`
|
|
@@ -204,6 +212,8 @@ interface ExiosDefaults<D = any> extends Omit<ExiosRequestConfig<D>, "headers" |
|
|
|
204
212
|
interface InternalConfig<D = any> extends Omit<ExiosRequestConfig<D>, "headers" | "retry" | "breaker"> {
|
|
205
213
|
method: Lowercase<Method>;
|
|
206
214
|
headers: Record<string, string>;
|
|
215
|
+
/** Always set by the time a request reaches an adapter. */
|
|
216
|
+
requestId?: string;
|
|
207
217
|
retry: false | RetryConfig;
|
|
208
218
|
breaker: false | BreakerConfig;
|
|
209
219
|
}
|
|
@@ -215,10 +225,96 @@ interface ExiosResponse<T = any, D = any> {
|
|
|
215
225
|
config: InternalConfig<D>;
|
|
216
226
|
/** XMLHttpRequest (xhr), ClientRequest (http) or Request (fetch). */
|
|
217
227
|
request: any;
|
|
218
|
-
meta:
|
|
219
|
-
|
|
220
|
-
|
|
228
|
+
meta: ResponseMeta;
|
|
229
|
+
}
|
|
230
|
+
/** Diagnostics attached to a response. Fields other than `attempts` are set by exios ≥ 3. */
|
|
231
|
+
interface ResponseMeta {
|
|
232
|
+
/** Attempts made, retries included. */
|
|
233
|
+
attempts: number;
|
|
234
|
+
requestId?: string;
|
|
235
|
+
correlationId?: string;
|
|
236
|
+
/** Whole logical request, retries and backoff included (ms). */
|
|
237
|
+
durationMs?: number;
|
|
238
|
+
/** The final attempt only (ms). */
|
|
239
|
+
responseTimeMs?: number;
|
|
240
|
+
}
|
|
241
|
+
/** Diagnostics attached to an ExiosError. Fields other than `attempts` are set by exios ≥ 3. */
|
|
242
|
+
interface ErrorMeta {
|
|
243
|
+
attempts: number;
|
|
244
|
+
requestId?: string;
|
|
245
|
+
correlationId?: string;
|
|
246
|
+
method?: Lowercase<Method>;
|
|
247
|
+
/** baseURL + url, without the serialized `params`. */
|
|
248
|
+
url?: string;
|
|
249
|
+
durationMs?: number;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Fields every request lifecycle event carries. */
|
|
253
|
+
interface RequestEventBase {
|
|
254
|
+
requestId: string;
|
|
255
|
+
correlationId?: string;
|
|
256
|
+
method: Lowercase<Method>;
|
|
257
|
+
/** baseURL + url, without the serialized `params`. */
|
|
258
|
+
url: string;
|
|
259
|
+
config: InternalConfig;
|
|
260
|
+
/** `Date.now()` when the event was emitted. */
|
|
261
|
+
timestamp: number;
|
|
262
|
+
}
|
|
263
|
+
type RequestEvent = RequestEventBase;
|
|
264
|
+
interface ResponseEvent extends RequestEventBase {
|
|
265
|
+
response: ExiosResponse;
|
|
266
|
+
status: number;
|
|
267
|
+
attempts: number;
|
|
268
|
+
/** Whole logical request, retries and backoff included. */
|
|
269
|
+
durationMs: number;
|
|
270
|
+
/** The final attempt only. */
|
|
271
|
+
responseTimeMs: number;
|
|
272
|
+
}
|
|
273
|
+
interface ErrorEvent extends RequestEventBase {
|
|
274
|
+
/** Usually an ExiosError; a value thrown by user code (e.g. `retry.shouldRetry`) is passed as is. */
|
|
275
|
+
error: unknown;
|
|
276
|
+
code?: string;
|
|
277
|
+
status?: number;
|
|
278
|
+
attempts: number;
|
|
279
|
+
durationMs: number;
|
|
280
|
+
}
|
|
281
|
+
interface RetryEvent extends RequestEventBase {
|
|
282
|
+
/** The attempt that failed (1 = the first try). */
|
|
283
|
+
attempt: number;
|
|
284
|
+
delayMs: number;
|
|
285
|
+
error?: ExiosError;
|
|
286
|
+
status?: number;
|
|
287
|
+
}
|
|
288
|
+
interface TimeoutEvent extends RequestEventBase {
|
|
289
|
+
attempt: number;
|
|
290
|
+
timeoutMs: number;
|
|
291
|
+
error: ExiosError;
|
|
292
|
+
}
|
|
293
|
+
interface CanceledEvent extends RequestEventBase {
|
|
294
|
+
error: ExiosError;
|
|
295
|
+
attempts: number;
|
|
296
|
+
durationMs: number;
|
|
297
|
+
}
|
|
298
|
+
interface CircuitEvent {
|
|
299
|
+
/** Breaker key (by default the request origin). */
|
|
300
|
+
key: string;
|
|
301
|
+
from: BreakerState;
|
|
302
|
+
to: BreakerState;
|
|
303
|
+
timestamp: number;
|
|
304
|
+
}
|
|
305
|
+
interface ExiosEventMap {
|
|
306
|
+
request: RequestEvent;
|
|
307
|
+
response: ResponseEvent;
|
|
308
|
+
error: ErrorEvent;
|
|
309
|
+
retry: RetryEvent;
|
|
310
|
+
timeout: TimeoutEvent;
|
|
311
|
+
canceled: CanceledEvent;
|
|
312
|
+
circuitOpen: CircuitEvent;
|
|
313
|
+
circuitHalfOpen: CircuitEvent;
|
|
314
|
+
circuitClose: CircuitEvent;
|
|
221
315
|
}
|
|
316
|
+
type ExiosEventName = keyof ExiosEventMap;
|
|
317
|
+
type ExiosEventListener<K extends ExiosEventName> = (event: ExiosEventMap[K]) => void;
|
|
222
318
|
|
|
223
319
|
interface InterceptorOptions {
|
|
224
320
|
synchronous?: boolean;
|
|
@@ -251,8 +347,17 @@ declare class Exios {
|
|
|
251
347
|
reset(key?: string): void;
|
|
252
348
|
};
|
|
253
349
|
private readonly registry;
|
|
350
|
+
private readonly events;
|
|
254
351
|
constructor(defaults: ExiosDefaults);
|
|
255
352
|
request<T = any, R = ExiosResponse<T>, D = any>(configOrUrl: string | Cfg<D>, config?: Cfg<D>): Promise<R>;
|
|
353
|
+
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
354
|
+
on<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
|
|
355
|
+
/** Like `on`, but the listener runs at most once. */
|
|
356
|
+
once<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
|
|
357
|
+
/** Remove one listener, or every listener of `name` when `listener` is omitted. */
|
|
358
|
+
off<K extends ExiosEventName>(name: K, listener?: ExiosEventListener<K>): void;
|
|
359
|
+
/** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
|
|
360
|
+
private dispatch;
|
|
256
361
|
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
257
362
|
private runSync;
|
|
258
363
|
getUri(config?: ExiosRequestConfig): string;
|
|
@@ -269,7 +374,7 @@ declare class Exios {
|
|
|
269
374
|
putForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
|
|
270
375
|
patchForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
|
|
271
376
|
}
|
|
272
|
-
declare const METHODS: readonly ["request", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
|
|
377
|
+
declare const METHODS: readonly ["request", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
|
|
273
378
|
interface ExiosStatic extends Pick<Exios, (typeof METHODS)[number] | "defaults" | "interceptors" | "breaker"> {
|
|
274
379
|
<T = any, R = ExiosResponse<T>, D = any>(config: ExiosRequestConfig<D>): Promise<R>;
|
|
275
380
|
<T = any, R = ExiosResponse<T>, D = any>(url: string, config?: ExiosRequestConfig<D>): Promise<R>;
|
|
@@ -296,4 +401,4 @@ declare const exios: ExiosDefault;
|
|
|
296
401
|
declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
|
|
297
402
|
|
|
298
403
|
export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, create, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
|
|
299
|
-
export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CancelTokenSource, Canceler, ExiosDefault, ExiosDefaults, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, ResponseType, RetryConfig, Transformer };
|
|
404
|
+
export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, ErrorEvent, ErrorMeta, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };
|