@indra211/exios 3.1.1 → 3.2.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 +99 -0
- package/dist/index.cjs +92 -2
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +33 -2
- package/dist/index.js +92 -2
- package/dist/index.node.cjs +117 -3
- package/dist/index.node.js +117 -3
- package/dist/testing.cjs +275 -0
- package/dist/testing.d.cts +87 -0
- package/dist/testing.d.ts +87 -0
- package/dist/testing.js +244 -0
- package/package.json +18 -1
package/README.md
CHANGED
|
@@ -81,6 +81,7 @@ await exios.get(url, {
|
|
|
81
81
|
|
|
82
82
|
- **Proxy:** `proxy` wins; `proxy: false` disables proxying; otherwise `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` (and lowercase variants) are used, like axios. HTTPS targets go through a `CONNECT` tunnel, using the TLS options (`ca`, `rejectUnauthorized`, ...) of your `httpsAgent`. An `https:` proxy (`protocol: 'https'` or `HTTPS_PROXY=https://...`) is reached over TLS. Aborts and timeouts also tear down a `CONNECT` still in progress.
|
|
83
83
|
- **Redirects:** 303, and 301/302 after a POST, become GET without a body; 307/308 resend the method and body (a one-shot stream body cannot be resent, so the 307/308 is returned). A redirect to another host or port, or from `https:` to `http:`, drops `Authorization`, `Cookie` and `Proxy-Authorization`. A redirect that would have to resend a one-shot stream body is returned instead of followed. Too many redirects reject with `ERR_FR_TOO_MANY_REDIRECTS` (never retried).
|
|
84
|
+
- **Protocols:** only `http:` and `https:`. Any other URL (`file:`, `ftp:`, `data:`, ...), whether requested or reached through a redirect, rejects with `ERR_BAD_REQUEST` (`Unsupported protocol ftp:`) before anything is sent. A malformed `Location` header rejects with `ERR_BAD_RESPONSE`.
|
|
84
85
|
- **Network errors** keep `code: 'ERR_NETWORK'` (retry and the breaker depend on it); the Node error is in `error.cause`, so `error.cause.code` is `ECONNREFUSED`, `ECONNRESET`, `ENOTFOUND`, ... (axios puts that in `error.code` instead).
|
|
85
86
|
- **Bodies:** `FormData`, `Blob`, `URLSearchParams`, strings and typed arrays are buffered (so they are resent on retries and redirects, with an exact `Content-Length`); web `ReadableStream` and Node `Readable` bodies (including `fs` streams and the `form-data` package, whose `getHeaders()` boundary is used) are streamed and never retried. If a body stream fails, the request rejects with `ERR_BAD_REQUEST` (the stream's error is in `cause`), and an aborted or timed-out request destroys the body stream.
|
|
86
87
|
|
|
@@ -327,6 +328,103 @@ const api = exios.create({ cache: { provider: new MemoryCache({ maxEntries: 500
|
|
|
327
328
|
|
|
328
329
|
`invalidate()` needs a provider with `keys()`; without one it rejects with `ERR_NOT_SUPPORT`.
|
|
329
330
|
|
|
331
|
+
## Plugins
|
|
332
|
+
|
|
333
|
+
A plugin bundles behaviour you want on an instance (auth, logging, response unwrapping, fallbacks) behind one name. Every hook is optional.
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
import exios, { type ExiosPlugin } from "@indra211/exios";
|
|
337
|
+
|
|
338
|
+
const auth: ExiosPlugin = {
|
|
339
|
+
name: "auth",
|
|
340
|
+
async beforeRequest(config) {
|
|
341
|
+
config.headers.authorization = `Bearer ${await getToken()}`;
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
const unwrap: ExiosPlugin = {
|
|
346
|
+
name: "unwrap",
|
|
347
|
+
afterResponse: (response) => ({ ...response, data: response.data.data }), // { data: ... } envelopes
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
const offline: ExiosPlugin = {
|
|
351
|
+
name: "offline-fallback",
|
|
352
|
+
onError: (error, config) =>
|
|
353
|
+
config.method === "get" && exios.isExiosError(error) && error.code === "ERR_NETWORK"
|
|
354
|
+
? { data: readFromDisk(config.url), status: 200, statusText: "OK", headers: {}, config, request: null, meta: { attempts: 0 } }
|
|
355
|
+
: undefined, // undefined: keep failing
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const metrics: ExiosPlugin = {
|
|
359
|
+
name: "metrics",
|
|
360
|
+
setup: (instance) => instance.on("response", (e) => histogram.record(e.durationMs)), // returns the teardown
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
const api = exios.create({ baseURL: "https://api.example.com" });
|
|
364
|
+
const ejectAuth = api.use(auth);
|
|
365
|
+
api.use(unwrap);
|
|
366
|
+
api.use(offline);
|
|
367
|
+
api.use(metrics);
|
|
368
|
+
|
|
369
|
+
api.eject("metrics"); // by name (or by object); runs the teardown setup returned
|
|
370
|
+
ejectAuth(); // or call the function use() returned
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
| Hook | When | Return |
|
|
374
|
+
|---|---|---|
|
|
375
|
+
| `setup(instance)` | once, in `use()` | optionally a teardown function, called by `eject()` |
|
|
376
|
+
| `beforeRequest(config)` | after the request interceptors | a new config, or nothing (edit it in place) |
|
|
377
|
+
| `afterResponse(response, config)` | after a successful request | a new response, or nothing |
|
|
378
|
+
| `onError(error, config)` | after a failed request (not for cancellations) | a response to recover, or nothing to keep failing |
|
|
379
|
+
|
|
380
|
+
- **Order:** request interceptors → `beforeRequest` of each plugin in registration order → cache / dedupe / network (retry, breaker) → `afterResponse` / `onError` in reverse order → response interceptors. Plugins nest like layers, so the first plugin registered sees the final result last. An error thrown by a plugin hook goes to the `onError` of the plugins registered before it.
|
|
381
|
+
- Hooks run once per logical request (not per retry attempt). Cache hits and deduplicated requests go through `afterResponse` too.
|
|
382
|
+
- Hooks may be async. Names must be unique per instance; `use()` with a duplicate name, a missing name or a non-function hook throws `ERR_BAD_OPTION_VALUE`.
|
|
383
|
+
- Plugins belong to one instance and are **not** inherited by `create()` (like interceptors and event listeners). A request keeps the plugins it started with, even if one is ejected meanwhile.
|
|
384
|
+
|
|
385
|
+
## Testing with the mock adapter
|
|
386
|
+
|
|
387
|
+
`@indra211/exios/testing` replaces the network for unit tests. Only the transport is fake: transforms, `validateStatus`, retry, the circuit breaker, cache, dedupe, interceptors, plugins and events all run for real, so tests see what production code sees.
|
|
388
|
+
|
|
389
|
+
```ts
|
|
390
|
+
import exios from "@indra211/exios";
|
|
391
|
+
import { createMockAdapter } from "@indra211/exios/testing";
|
|
392
|
+
|
|
393
|
+
const api = exios.create({ baseURL: "https://api.example.com" });
|
|
394
|
+
const mock = createMockAdapter(api); // becomes api's adapter; mock.restore() undoes it
|
|
395
|
+
|
|
396
|
+
mock.onGet("/users/1").reply(200, { id: 1, name: "Ada" });
|
|
397
|
+
mock.onGet("/users", { params: { page: 2 } }).reply(200, []);
|
|
398
|
+
mock.onPost("/users", { data: { name: "Bob" } }).replyOnce(201, { id: 2 });
|
|
399
|
+
mock.onGet(/\/orders\/\d+/).reply(async (config) => [200, { url: config.url }, { "x-request": "1" }]);
|
|
400
|
+
mock.onGet("/flaky").networkErrorOnce().onGet("/flaky").reply(200, "ok"); // retry sees a real ERR_NETWORK
|
|
401
|
+
mock.onGet("/slow").delay(5000).reply(200); // with timeout: 1000 → ECONNABORTED after 1 s
|
|
402
|
+
mock.onGet("/down").timeout(); // fails at once with the timeout error
|
|
403
|
+
mock.onAny("/health").reply(204);
|
|
404
|
+
|
|
405
|
+
await api.get("/users/1");
|
|
406
|
+
expect(mock.history.get[0].url).toBe("https://api.example.com/users/1");
|
|
407
|
+
expect(mock.history.post[0].data).toEqual({ name: "Bob" }); // also .headers, .body (as sent), .config
|
|
408
|
+
|
|
409
|
+
mock.reset(); // handlers and history (or resetHandlers() / resetHistory())
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
- **Matching:** handlers are tried in the order they were added; the first match answers. A string URL matches the request's `url`, the full URL (with `baseURL`) or, when the string has no `?`, either one without its query. A `RegExp` or a function is tested against the same. Options: `params` (deep-equal; `1` matches `"1"`), `headers` (each listed one, case-insensitive name), `data` (deep-equal to the body, or a predicate), `match(config)`.
|
|
413
|
+
- **Replies:** `reply(status, data?, headers?)` or `reply(config => [status, data, headers])` (may be async). Plain objects and arrays are sent as JSON text, so each request gets its own copy and `transformResponse` parses it as it would a server's. `responseType: 'arraybuffer' | 'blob'` gets bytes. Every method has a `…Once` variant.
|
|
414
|
+
- **Errors look real:** `networkError()` rejects with `ERR_NETWORK`, `timeout()` with `ECONNABORTED` (`ETIMEDOUT` with `transitional.clarifyTimeoutError`) and the axios message; an abort rejects with `CanceledError`. They are the application's own `ExiosError` classes, so `instanceof` and retry/breaker rules work.
|
|
415
|
+
- **No match:** rejects with `ERR_MOCK_NO_MATCH` and a message naming the method and URL. `createMockAdapter(api, { onNoMatch: '404' })` answers 404 instead. `{ delay: ms }` delays every reply.
|
|
416
|
+
- Without an instance, `createMockAdapter()` returns a mock whose `mock.adapter` you pass yourself: `exios.create({ adapter: mock.adapter })`.
|
|
417
|
+
- Works in Node and browsers, ESM and CommonJS (`require('@indra211/exios/testing')`). It is a separate entry point, so it never ends up in your production bundle.
|
|
418
|
+
|
|
419
|
+
## Writing a custom adapter
|
|
420
|
+
|
|
421
|
+
An adapter is a function `(config: InternalConfig) => Promise<ExiosResponse>` (or a plain response), passed as `adapter` (alone or in a list with named adapters). The built-in adapters follow this contract; custom ones should too, so retry, the breaker and error handling treat them the same:
|
|
422
|
+
|
|
423
|
+
- **Request:** build the URL from `baseURL`, `url`, `params` and `paramsSerializer`; send `config.headers` (already flattened, lower-case names). `config.data` is the value the caller passed: run `config.transformRequest` on it if you want the default JSON / form encoding.
|
|
424
|
+
- **Response:** resolve with `{ data, status, statusText, headers, config, request }` for **every** HTTP status, including 4xx/5xx: `validateStatus` is applied after the adapter (and decides retries). Run `transformResponse` yourself if you want its parsing; `meta` and a missing `config` are filled in for you.
|
|
425
|
+
- **Errors:** reject with an `ExiosError` using the shared codes: `ERR_NETWORK` ("Network Error") when no response arrived, `ECONNABORTED` / `ETIMEDOUT` ("timeout of Nms exceeded") when `timeout` expired, `CanceledError` when `config.signal` aborted, `ERR_BAD_RESPONSE` when `maxContentLength` was exceeded. Retry retries `ERR_NETWORK`, `ECONNABORTED` and `ETIMEDOUT` (and the configured statuses); any other error is not retried.
|
|
426
|
+
- **Cancellation:** honour `config.signal` (CancelToken is already turned into it).
|
|
427
|
+
|
|
330
428
|
## Behavior rules
|
|
331
429
|
|
|
332
430
|
These are deliberate and tested.
|
|
@@ -350,6 +448,7 @@ Also:
|
|
|
350
448
|
|
|
351
449
|
## Not supported
|
|
352
450
|
|
|
451
|
+
- `data:` URLs on the `http` adapter (axios decodes them; exios rejects them).
|
|
353
452
|
- `maxRate` (bandwidth limits), `lookup` / `family` DNS options, HTTP/2 on the `http` adapter.
|
|
354
453
|
- `redirect: 'manual' | 'error'` and `fetchOptions` on the `xhr` adapter (browsers' XHR always follows redirects); use `adapter: 'fetch'` when you need them.
|
|
355
454
|
- Distributed or persisted breaker state.
|
package/dist/index.cjs
CHANGED
|
@@ -282,7 +282,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
|
|
|
282
282
|
if (!baseURL) return u;
|
|
283
283
|
if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
|
|
284
284
|
if (!u) return baseURL;
|
|
285
|
-
return `${baseURL
|
|
285
|
+
return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
|
|
286
|
+
}
|
|
287
|
+
function trimSlashes(s, side) {
|
|
288
|
+
if (side === "start") {
|
|
289
|
+
let i = 0;
|
|
290
|
+
while (s.charCodeAt(i) === 47) i++;
|
|
291
|
+
return s.slice(i);
|
|
292
|
+
}
|
|
293
|
+
let j = s.length;
|
|
294
|
+
while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
|
|
295
|
+
return s.slice(0, j);
|
|
286
296
|
}
|
|
287
297
|
|
|
288
298
|
// src/core/toFormData.ts
|
|
@@ -1590,6 +1600,8 @@ async function dispatchRequest(config, registry2, observer) {
|
|
|
1590
1600
|
breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
|
|
1591
1601
|
if (outcome.error) throw outcome.error;
|
|
1592
1602
|
const response = outcome.response;
|
|
1603
|
+
response.meta ??= { attempts };
|
|
1604
|
+
response.config ??= config;
|
|
1593
1605
|
response.meta.attempts = attempts;
|
|
1594
1606
|
if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
|
|
1595
1607
|
const { status } = response;
|
|
@@ -1972,6 +1984,61 @@ var InflightRequests = class {
|
|
|
1972
1984
|
}
|
|
1973
1985
|
};
|
|
1974
1986
|
|
|
1987
|
+
// src/core/plugins.ts
|
|
1988
|
+
var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
|
|
1989
|
+
function invalid(message) {
|
|
1990
|
+
throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
|
|
1991
|
+
}
|
|
1992
|
+
var PluginRegistry = class {
|
|
1993
|
+
list = [];
|
|
1994
|
+
get size() {
|
|
1995
|
+
return this.list.length;
|
|
1996
|
+
}
|
|
1997
|
+
add(plugin, instance) {
|
|
1998
|
+
if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
|
|
1999
|
+
if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
|
|
2000
|
+
for (const h of HOOKS)
|
|
2001
|
+
if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
|
|
2002
|
+
invalid(`plugin "${plugin.name}": ${h} must be a function`);
|
|
2003
|
+
if (this.list.some((r) => r.plugin.name === plugin.name))
|
|
2004
|
+
invalid(`a plugin named "${plugin.name}" is already registered`);
|
|
2005
|
+
const entry = { plugin };
|
|
2006
|
+
const teardown = plugin.setup?.(instance);
|
|
2007
|
+
if (typeof teardown === "function") entry.teardown = teardown;
|
|
2008
|
+
this.list = [...this.list, entry];
|
|
2009
|
+
return () => void this.remove(plugin);
|
|
2010
|
+
}
|
|
2011
|
+
remove(nameOrPlugin) {
|
|
2012
|
+
const entry = this.list.find(
|
|
2013
|
+
(r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
|
|
2014
|
+
);
|
|
2015
|
+
if (!entry) return false;
|
|
2016
|
+
this.list = this.list.filter((r) => r !== entry);
|
|
2017
|
+
entry.teardown?.();
|
|
2018
|
+
return true;
|
|
2019
|
+
}
|
|
2020
|
+
/** Run `final` wrapped in every plugin's hooks. */
|
|
2021
|
+
run(config, final) {
|
|
2022
|
+
const plugins = this.list.map((r) => r.plugin);
|
|
2023
|
+
const layer = async (i, cfg) => {
|
|
2024
|
+
if (i === plugins.length) return final(cfg);
|
|
2025
|
+
const p = plugins[i];
|
|
2026
|
+
const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
|
|
2027
|
+
let response;
|
|
2028
|
+
try {
|
|
2029
|
+
response = await layer(i + 1, c);
|
|
2030
|
+
} catch (err) {
|
|
2031
|
+
if (!p.onError || isCancel(err)) throw err;
|
|
2032
|
+
const recovered = await p.onError(err, c);
|
|
2033
|
+
if (recovered == null) throw err;
|
|
2034
|
+
return recovered;
|
|
2035
|
+
}
|
|
2036
|
+
return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
|
|
2037
|
+
};
|
|
2038
|
+
return layer(0, config);
|
|
2039
|
+
}
|
|
2040
|
+
};
|
|
2041
|
+
|
|
1975
2042
|
// src/core/requestCache.ts
|
|
1976
2043
|
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
1977
2044
|
var MemoryCache = class {
|
|
@@ -2202,6 +2269,9 @@ var Exios = class {
|
|
|
2202
2269
|
events = new EventHub();
|
|
2203
2270
|
memoryCache = new MemoryCache();
|
|
2204
2271
|
inflight = new InflightRequests();
|
|
2272
|
+
plugins = new PluginRegistry();
|
|
2273
|
+
/** The callable instance wrapping this context (given to plugin `setup`). */
|
|
2274
|
+
instance;
|
|
2205
2275
|
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2206
2276
|
cache;
|
|
2207
2277
|
constructor(defaults) {
|
|
@@ -2276,7 +2346,11 @@ var Exios = class {
|
|
|
2276
2346
|
synchronous = synchronous && h.synchronous;
|
|
2277
2347
|
requestChain.unshift(h);
|
|
2278
2348
|
});
|
|
2279
|
-
const dispatch = (c) =>
|
|
2349
|
+
const dispatch = (c) => {
|
|
2350
|
+
const finalized = finalizeConfig(c);
|
|
2351
|
+
if (this.plugins.size === 0) return this.dispatch(finalized);
|
|
2352
|
+
return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
|
|
2353
|
+
};
|
|
2280
2354
|
let promise;
|
|
2281
2355
|
if (synchronous) {
|
|
2282
2356
|
promise = this.runSync(requestChain, resolved, dispatch);
|
|
@@ -2294,6 +2368,14 @@ var Exios = class {
|
|
|
2294
2368
|
});
|
|
2295
2369
|
return promise;
|
|
2296
2370
|
}
|
|
2371
|
+
/** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
|
|
2372
|
+
use(plugin) {
|
|
2373
|
+
return this.plugins.add(plugin, this.instance);
|
|
2374
|
+
}
|
|
2375
|
+
/** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
|
|
2376
|
+
eject(nameOrPlugin) {
|
|
2377
|
+
return this.plugins.remove(nameOrPlugin);
|
|
2378
|
+
}
|
|
2297
2379
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
2298
2380
|
on(name, listener) {
|
|
2299
2381
|
return this.events.on(name, listener);
|
|
@@ -2597,6 +2679,8 @@ var Exios = class {
|
|
|
2597
2679
|
};
|
|
2598
2680
|
var METHODS = [
|
|
2599
2681
|
"request",
|
|
2682
|
+
"use",
|
|
2683
|
+
"eject",
|
|
2600
2684
|
"on",
|
|
2601
2685
|
"once",
|
|
2602
2686
|
"off",
|
|
@@ -2661,6 +2745,7 @@ function createInstance(defaults) {
|
|
|
2661
2745
|
set: (v) => context.defaults = v,
|
|
2662
2746
|
enumerable: true
|
|
2663
2747
|
});
|
|
2748
|
+
context.instance = instance;
|
|
2664
2749
|
instance.interceptors = context.interceptors;
|
|
2665
2750
|
instance.breaker = context.breaker;
|
|
2666
2751
|
instance.cache = context.cache;
|
|
@@ -2668,6 +2753,10 @@ function createInstance(defaults) {
|
|
|
2668
2753
|
return instance;
|
|
2669
2754
|
}
|
|
2670
2755
|
|
|
2756
|
+
// src/core/internals.ts
|
|
2757
|
+
var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
|
|
2758
|
+
var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
|
|
2759
|
+
|
|
2671
2760
|
// src/index.ts
|
|
2672
2761
|
registerXhrAdapter();
|
|
2673
2762
|
registerFetchAdapter();
|
|
@@ -2686,6 +2775,7 @@ var exios = Object.assign(
|
|
|
2686
2775
|
createInstance(createDefaults()),
|
|
2687
2776
|
statics
|
|
2688
2777
|
);
|
|
2778
|
+
Object.defineProperty(exios, INTERNALS, { value: internals });
|
|
2689
2779
|
var create = exios.create;
|
|
2690
2780
|
var src_default = exios;
|
|
2691
2781
|
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -401,6 +401,30 @@ declare class InterceptorManager<V> {
|
|
|
401
401
|
forEach(fn: (handler: InterceptorHandler<V>) => void): void;
|
|
402
402
|
}
|
|
403
403
|
|
|
404
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
405
|
+
/**
|
|
406
|
+
* A reusable bundle of behaviour for one instance. Every hook is optional.
|
|
407
|
+
*
|
|
408
|
+
* Order for one request: request interceptors → `beforeRequest` of each plugin in registration
|
|
409
|
+
* order → cache / dedupe / network → `afterResponse` (or `onError`) in reverse order → response
|
|
410
|
+
* interceptors. Plugins nest like layers: the first plugin registered is the outermost.
|
|
411
|
+
*/
|
|
412
|
+
interface ExiosPlugin {
|
|
413
|
+
/** Unique within an instance; `eject(name)` removes the plugin. */
|
|
414
|
+
name: string;
|
|
415
|
+
/** Called once by `use()`. Return a function to undo the setup (called by `eject()`). */
|
|
416
|
+
setup?(instance: ExiosInstance): void | (() => void);
|
|
417
|
+
/** Change the request config (return a new one or edit it in place). */
|
|
418
|
+
beforeRequest?(config: InternalConfig): MaybePromise<InternalConfig | void>;
|
|
419
|
+
/** Change the response (return a new one or edit it in place). */
|
|
420
|
+
afterResponse?(response: ExiosResponse, config: InternalConfig): MaybePromise<ExiosResponse | void>;
|
|
421
|
+
/**
|
|
422
|
+
* The request failed (cancellations excluded). Return a response to recover from the error;
|
|
423
|
+
* return nothing (or throw) to let it propagate to the plugins registered before this one.
|
|
424
|
+
*/
|
|
425
|
+
onError?(error: unknown, config: InternalConfig): MaybePromise<ExiosResponse | void>;
|
|
426
|
+
}
|
|
427
|
+
|
|
404
428
|
type Cfg<D> = ExiosRequestConfig<D>;
|
|
405
429
|
declare class Exios {
|
|
406
430
|
defaults: ExiosDefaults;
|
|
@@ -416,10 +440,17 @@ declare class Exios {
|
|
|
416
440
|
private readonly events;
|
|
417
441
|
private readonly memoryCache;
|
|
418
442
|
private readonly inflight;
|
|
443
|
+
private readonly plugins;
|
|
444
|
+
/** The callable instance wrapping this context (given to plugin `setup`). */
|
|
445
|
+
instance?: ExiosStatic;
|
|
419
446
|
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
420
447
|
cache: ExiosCache;
|
|
421
448
|
constructor(defaults: ExiosDefaults);
|
|
422
449
|
request<T = any, R = ExiosResponse<T>, D = any>(configOrUrl: string | Cfg<D>, config?: Cfg<D>): Promise<R>;
|
|
450
|
+
/** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
|
|
451
|
+
use(plugin: ExiosPlugin): () => void;
|
|
452
|
+
/** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
|
|
453
|
+
eject(nameOrPlugin: string | ExiosPlugin): boolean;
|
|
423
454
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
424
455
|
on<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
|
|
425
456
|
/** Like `on`, but the listener runs at most once. */
|
|
@@ -453,7 +484,7 @@ declare class Exios {
|
|
|
453
484
|
putForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
|
|
454
485
|
patchForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
|
|
455
486
|
}
|
|
456
|
-
declare const METHODS: readonly ["request", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
|
|
487
|
+
declare const METHODS: readonly ["request", "use", "eject", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
|
|
457
488
|
/** `instance.cache`: manage the instance's cache provider. */
|
|
458
489
|
interface ExiosCache {
|
|
459
490
|
/** Remove every entry. */
|
|
@@ -510,4 +541,4 @@ declare const exios: ExiosDefault;
|
|
|
510
541
|
declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
|
|
511
542
|
|
|
512
543
|
export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, MemoryCache, create, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
|
|
513
|
-
export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CacheConfig, CacheEntry, CacheProvider, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, DedupeConfig, ErrorEvent, ErrorMeta, ExiosCache, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Options, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };
|
|
544
|
+
export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CacheConfig, CacheEntry, CacheProvider, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, DedupeConfig, ErrorEvent, ErrorMeta, ExiosCache, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosPlugin, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Options, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };
|
package/dist/index.js
CHANGED
|
@@ -256,7 +256,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
|
|
|
256
256
|
if (!baseURL) return u;
|
|
257
257
|
if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
|
|
258
258
|
if (!u) return baseURL;
|
|
259
|
-
return `${baseURL
|
|
259
|
+
return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
|
|
260
|
+
}
|
|
261
|
+
function trimSlashes(s, side) {
|
|
262
|
+
if (side === "start") {
|
|
263
|
+
let i = 0;
|
|
264
|
+
while (s.charCodeAt(i) === 47) i++;
|
|
265
|
+
return s.slice(i);
|
|
266
|
+
}
|
|
267
|
+
let j = s.length;
|
|
268
|
+
while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
|
|
269
|
+
return s.slice(0, j);
|
|
260
270
|
}
|
|
261
271
|
|
|
262
272
|
// src/core/toFormData.ts
|
|
@@ -1564,6 +1574,8 @@ async function dispatchRequest(config, registry2, observer) {
|
|
|
1564
1574
|
breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
|
|
1565
1575
|
if (outcome.error) throw outcome.error;
|
|
1566
1576
|
const response = outcome.response;
|
|
1577
|
+
response.meta ??= { attempts };
|
|
1578
|
+
response.config ??= config;
|
|
1567
1579
|
response.meta.attempts = attempts;
|
|
1568
1580
|
if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
|
|
1569
1581
|
const { status } = response;
|
|
@@ -1946,6 +1958,61 @@ var InflightRequests = class {
|
|
|
1946
1958
|
}
|
|
1947
1959
|
};
|
|
1948
1960
|
|
|
1961
|
+
// src/core/plugins.ts
|
|
1962
|
+
var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
|
|
1963
|
+
function invalid(message) {
|
|
1964
|
+
throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
|
|
1965
|
+
}
|
|
1966
|
+
var PluginRegistry = class {
|
|
1967
|
+
list = [];
|
|
1968
|
+
get size() {
|
|
1969
|
+
return this.list.length;
|
|
1970
|
+
}
|
|
1971
|
+
add(plugin, instance) {
|
|
1972
|
+
if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
|
|
1973
|
+
if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
|
|
1974
|
+
for (const h of HOOKS)
|
|
1975
|
+
if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
|
|
1976
|
+
invalid(`plugin "${plugin.name}": ${h} must be a function`);
|
|
1977
|
+
if (this.list.some((r) => r.plugin.name === plugin.name))
|
|
1978
|
+
invalid(`a plugin named "${plugin.name}" is already registered`);
|
|
1979
|
+
const entry = { plugin };
|
|
1980
|
+
const teardown = plugin.setup?.(instance);
|
|
1981
|
+
if (typeof teardown === "function") entry.teardown = teardown;
|
|
1982
|
+
this.list = [...this.list, entry];
|
|
1983
|
+
return () => void this.remove(plugin);
|
|
1984
|
+
}
|
|
1985
|
+
remove(nameOrPlugin) {
|
|
1986
|
+
const entry = this.list.find(
|
|
1987
|
+
(r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
|
|
1988
|
+
);
|
|
1989
|
+
if (!entry) return false;
|
|
1990
|
+
this.list = this.list.filter((r) => r !== entry);
|
|
1991
|
+
entry.teardown?.();
|
|
1992
|
+
return true;
|
|
1993
|
+
}
|
|
1994
|
+
/** Run `final` wrapped in every plugin's hooks. */
|
|
1995
|
+
run(config, final) {
|
|
1996
|
+
const plugins = this.list.map((r) => r.plugin);
|
|
1997
|
+
const layer = async (i, cfg) => {
|
|
1998
|
+
if (i === plugins.length) return final(cfg);
|
|
1999
|
+
const p = plugins[i];
|
|
2000
|
+
const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
|
|
2001
|
+
let response;
|
|
2002
|
+
try {
|
|
2003
|
+
response = await layer(i + 1, c);
|
|
2004
|
+
} catch (err) {
|
|
2005
|
+
if (!p.onError || isCancel(err)) throw err;
|
|
2006
|
+
const recovered = await p.onError(err, c);
|
|
2007
|
+
if (recovered == null) throw err;
|
|
2008
|
+
return recovered;
|
|
2009
|
+
}
|
|
2010
|
+
return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
|
|
2011
|
+
};
|
|
2012
|
+
return layer(0, config);
|
|
2013
|
+
}
|
|
2014
|
+
};
|
|
2015
|
+
|
|
1949
2016
|
// src/core/requestCache.ts
|
|
1950
2017
|
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
1951
2018
|
var MemoryCache = class {
|
|
@@ -2176,6 +2243,9 @@ var Exios = class {
|
|
|
2176
2243
|
events = new EventHub();
|
|
2177
2244
|
memoryCache = new MemoryCache();
|
|
2178
2245
|
inflight = new InflightRequests();
|
|
2246
|
+
plugins = new PluginRegistry();
|
|
2247
|
+
/** The callable instance wrapping this context (given to plugin `setup`). */
|
|
2248
|
+
instance;
|
|
2179
2249
|
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2180
2250
|
cache;
|
|
2181
2251
|
constructor(defaults) {
|
|
@@ -2250,7 +2320,11 @@ var Exios = class {
|
|
|
2250
2320
|
synchronous = synchronous && h.synchronous;
|
|
2251
2321
|
requestChain.unshift(h);
|
|
2252
2322
|
});
|
|
2253
|
-
const dispatch = (c) =>
|
|
2323
|
+
const dispatch = (c) => {
|
|
2324
|
+
const finalized = finalizeConfig(c);
|
|
2325
|
+
if (this.plugins.size === 0) return this.dispatch(finalized);
|
|
2326
|
+
return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
|
|
2327
|
+
};
|
|
2254
2328
|
let promise;
|
|
2255
2329
|
if (synchronous) {
|
|
2256
2330
|
promise = this.runSync(requestChain, resolved, dispatch);
|
|
@@ -2268,6 +2342,14 @@ var Exios = class {
|
|
|
2268
2342
|
});
|
|
2269
2343
|
return promise;
|
|
2270
2344
|
}
|
|
2345
|
+
/** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
|
|
2346
|
+
use(plugin) {
|
|
2347
|
+
return this.plugins.add(plugin, this.instance);
|
|
2348
|
+
}
|
|
2349
|
+
/** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
|
|
2350
|
+
eject(nameOrPlugin) {
|
|
2351
|
+
return this.plugins.remove(nameOrPlugin);
|
|
2352
|
+
}
|
|
2271
2353
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
2272
2354
|
on(name, listener) {
|
|
2273
2355
|
return this.events.on(name, listener);
|
|
@@ -2571,6 +2653,8 @@ var Exios = class {
|
|
|
2571
2653
|
};
|
|
2572
2654
|
var METHODS = [
|
|
2573
2655
|
"request",
|
|
2656
|
+
"use",
|
|
2657
|
+
"eject",
|
|
2574
2658
|
"on",
|
|
2575
2659
|
"once",
|
|
2576
2660
|
"off",
|
|
@@ -2635,6 +2719,7 @@ function createInstance(defaults) {
|
|
|
2635
2719
|
set: (v) => context.defaults = v,
|
|
2636
2720
|
enumerable: true
|
|
2637
2721
|
});
|
|
2722
|
+
context.instance = instance;
|
|
2638
2723
|
instance.interceptors = context.interceptors;
|
|
2639
2724
|
instance.breaker = context.breaker;
|
|
2640
2725
|
instance.cache = context.cache;
|
|
@@ -2642,6 +2727,10 @@ function createInstance(defaults) {
|
|
|
2642
2727
|
return instance;
|
|
2643
2728
|
}
|
|
2644
2729
|
|
|
2730
|
+
// src/core/internals.ts
|
|
2731
|
+
var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
|
|
2732
|
+
var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
|
|
2733
|
+
|
|
2645
2734
|
// src/index.ts
|
|
2646
2735
|
registerXhrAdapter();
|
|
2647
2736
|
registerFetchAdapter();
|
|
@@ -2660,6 +2749,7 @@ var exios = Object.assign(
|
|
|
2660
2749
|
createInstance(createDefaults()),
|
|
2661
2750
|
statics
|
|
2662
2751
|
);
|
|
2752
|
+
Object.defineProperty(exios, INTERNALS, { value: internals });
|
|
2663
2753
|
var create = exios.create;
|
|
2664
2754
|
var index_default = exios;
|
|
2665
2755
|
export {
|