@indra211/exios 3.1.2 → 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 +97 -0
- package/dist/index.cjs +81 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +33 -2
- package/dist/index.js +81 -1
- package/dist/index.node.cjs +81 -1
- package/dist/index.node.js +81 -1
- 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
|
@@ -328,6 +328,103 @@ const api = exios.create({ cache: { provider: new MemoryCache({ maxEntries: 500
|
|
|
328
328
|
|
|
329
329
|
`invalidate()` needs a provider with `keys()`; without one it rejects with `ERR_NOT_SUPPORT`.
|
|
330
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
|
+
|
|
331
428
|
## Behavior rules
|
|
332
429
|
|
|
333
430
|
These are deliberate and tested.
|
package/dist/index.cjs
CHANGED
|
@@ -1600,6 +1600,8 @@ async function dispatchRequest(config, registry2, observer) {
|
|
|
1600
1600
|
breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
|
|
1601
1601
|
if (outcome.error) throw outcome.error;
|
|
1602
1602
|
const response = outcome.response;
|
|
1603
|
+
response.meta ??= { attempts };
|
|
1604
|
+
response.config ??= config;
|
|
1603
1605
|
response.meta.attempts = attempts;
|
|
1604
1606
|
if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
|
|
1605
1607
|
const { status } = response;
|
|
@@ -1982,6 +1984,61 @@ var InflightRequests = class {
|
|
|
1982
1984
|
}
|
|
1983
1985
|
};
|
|
1984
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
|
+
|
|
1985
2042
|
// src/core/requestCache.ts
|
|
1986
2043
|
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
1987
2044
|
var MemoryCache = class {
|
|
@@ -2212,6 +2269,9 @@ var Exios = class {
|
|
|
2212
2269
|
events = new EventHub();
|
|
2213
2270
|
memoryCache = new MemoryCache();
|
|
2214
2271
|
inflight = new InflightRequests();
|
|
2272
|
+
plugins = new PluginRegistry();
|
|
2273
|
+
/** The callable instance wrapping this context (given to plugin `setup`). */
|
|
2274
|
+
instance;
|
|
2215
2275
|
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2216
2276
|
cache;
|
|
2217
2277
|
constructor(defaults) {
|
|
@@ -2286,7 +2346,11 @@ var Exios = class {
|
|
|
2286
2346
|
synchronous = synchronous && h.synchronous;
|
|
2287
2347
|
requestChain.unshift(h);
|
|
2288
2348
|
});
|
|
2289
|
-
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
|
+
};
|
|
2290
2354
|
let promise;
|
|
2291
2355
|
if (synchronous) {
|
|
2292
2356
|
promise = this.runSync(requestChain, resolved, dispatch);
|
|
@@ -2304,6 +2368,14 @@ var Exios = class {
|
|
|
2304
2368
|
});
|
|
2305
2369
|
return promise;
|
|
2306
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
|
+
}
|
|
2307
2379
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
2308
2380
|
on(name, listener) {
|
|
2309
2381
|
return this.events.on(name, listener);
|
|
@@ -2607,6 +2679,8 @@ var Exios = class {
|
|
|
2607
2679
|
};
|
|
2608
2680
|
var METHODS = [
|
|
2609
2681
|
"request",
|
|
2682
|
+
"use",
|
|
2683
|
+
"eject",
|
|
2610
2684
|
"on",
|
|
2611
2685
|
"once",
|
|
2612
2686
|
"off",
|
|
@@ -2671,6 +2745,7 @@ function createInstance(defaults) {
|
|
|
2671
2745
|
set: (v) => context.defaults = v,
|
|
2672
2746
|
enumerable: true
|
|
2673
2747
|
});
|
|
2748
|
+
context.instance = instance;
|
|
2674
2749
|
instance.interceptors = context.interceptors;
|
|
2675
2750
|
instance.breaker = context.breaker;
|
|
2676
2751
|
instance.cache = context.cache;
|
|
@@ -2678,6 +2753,10 @@ function createInstance(defaults) {
|
|
|
2678
2753
|
return instance;
|
|
2679
2754
|
}
|
|
2680
2755
|
|
|
2756
|
+
// src/core/internals.ts
|
|
2757
|
+
var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
|
|
2758
|
+
var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
|
|
2759
|
+
|
|
2681
2760
|
// src/index.ts
|
|
2682
2761
|
registerXhrAdapter();
|
|
2683
2762
|
registerFetchAdapter();
|
|
@@ -2696,6 +2775,7 @@ var exios = Object.assign(
|
|
|
2696
2775
|
createInstance(createDefaults()),
|
|
2697
2776
|
statics
|
|
2698
2777
|
);
|
|
2778
|
+
Object.defineProperty(exios, INTERNALS, { value: internals });
|
|
2699
2779
|
var create = exios.create;
|
|
2700
2780
|
var src_default = exios;
|
|
2701
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
|
@@ -1574,6 +1574,8 @@ async function dispatchRequest(config, registry2, observer) {
|
|
|
1574
1574
|
breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
|
|
1575
1575
|
if (outcome.error) throw outcome.error;
|
|
1576
1576
|
const response = outcome.response;
|
|
1577
|
+
response.meta ??= { attempts };
|
|
1578
|
+
response.config ??= config;
|
|
1577
1579
|
response.meta.attempts = attempts;
|
|
1578
1580
|
if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
|
|
1579
1581
|
const { status } = response;
|
|
@@ -1956,6 +1958,61 @@ var InflightRequests = class {
|
|
|
1956
1958
|
}
|
|
1957
1959
|
};
|
|
1958
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
|
+
|
|
1959
2016
|
// src/core/requestCache.ts
|
|
1960
2017
|
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
1961
2018
|
var MemoryCache = class {
|
|
@@ -2186,6 +2243,9 @@ var Exios = class {
|
|
|
2186
2243
|
events = new EventHub();
|
|
2187
2244
|
memoryCache = new MemoryCache();
|
|
2188
2245
|
inflight = new InflightRequests();
|
|
2246
|
+
plugins = new PluginRegistry();
|
|
2247
|
+
/** The callable instance wrapping this context (given to plugin `setup`). */
|
|
2248
|
+
instance;
|
|
2189
2249
|
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2190
2250
|
cache;
|
|
2191
2251
|
constructor(defaults) {
|
|
@@ -2260,7 +2320,11 @@ var Exios = class {
|
|
|
2260
2320
|
synchronous = synchronous && h.synchronous;
|
|
2261
2321
|
requestChain.unshift(h);
|
|
2262
2322
|
});
|
|
2263
|
-
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
|
+
};
|
|
2264
2328
|
let promise;
|
|
2265
2329
|
if (synchronous) {
|
|
2266
2330
|
promise = this.runSync(requestChain, resolved, dispatch);
|
|
@@ -2278,6 +2342,14 @@ var Exios = class {
|
|
|
2278
2342
|
});
|
|
2279
2343
|
return promise;
|
|
2280
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
|
+
}
|
|
2281
2353
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
2282
2354
|
on(name, listener) {
|
|
2283
2355
|
return this.events.on(name, listener);
|
|
@@ -2581,6 +2653,8 @@ var Exios = class {
|
|
|
2581
2653
|
};
|
|
2582
2654
|
var METHODS = [
|
|
2583
2655
|
"request",
|
|
2656
|
+
"use",
|
|
2657
|
+
"eject",
|
|
2584
2658
|
"on",
|
|
2585
2659
|
"once",
|
|
2586
2660
|
"off",
|
|
@@ -2645,6 +2719,7 @@ function createInstance(defaults) {
|
|
|
2645
2719
|
set: (v) => context.defaults = v,
|
|
2646
2720
|
enumerable: true
|
|
2647
2721
|
});
|
|
2722
|
+
context.instance = instance;
|
|
2648
2723
|
instance.interceptors = context.interceptors;
|
|
2649
2724
|
instance.breaker = context.breaker;
|
|
2650
2725
|
instance.cache = context.cache;
|
|
@@ -2652,6 +2727,10 @@ function createInstance(defaults) {
|
|
|
2652
2727
|
return instance;
|
|
2653
2728
|
}
|
|
2654
2729
|
|
|
2730
|
+
// src/core/internals.ts
|
|
2731
|
+
var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
|
|
2732
|
+
var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
|
|
2733
|
+
|
|
2655
2734
|
// src/index.ts
|
|
2656
2735
|
registerXhrAdapter();
|
|
2657
2736
|
registerFetchAdapter();
|
|
@@ -2670,6 +2749,7 @@ var exios = Object.assign(
|
|
|
2670
2749
|
createInstance(createDefaults()),
|
|
2671
2750
|
statics
|
|
2672
2751
|
);
|
|
2752
|
+
Object.defineProperty(exios, INTERNALS, { value: internals });
|
|
2673
2753
|
var create = exios.create;
|
|
2674
2754
|
var index_default = exios;
|
|
2675
2755
|
export {
|
package/dist/index.node.cjs
CHANGED
|
@@ -2158,6 +2158,8 @@ async function dispatchRequest(config, registry2, observer) {
|
|
|
2158
2158
|
breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
|
|
2159
2159
|
if (outcome.error) throw outcome.error;
|
|
2160
2160
|
const response = outcome.response;
|
|
2161
|
+
response.meta ??= { attempts };
|
|
2162
|
+
response.config ??= config;
|
|
2161
2163
|
response.meta.attempts = attempts;
|
|
2162
2164
|
if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
|
|
2163
2165
|
const { status } = response;
|
|
@@ -2540,6 +2542,61 @@ var InflightRequests = class {
|
|
|
2540
2542
|
}
|
|
2541
2543
|
};
|
|
2542
2544
|
|
|
2545
|
+
// src/core/plugins.ts
|
|
2546
|
+
var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
|
|
2547
|
+
function invalid(message) {
|
|
2548
|
+
throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
|
|
2549
|
+
}
|
|
2550
|
+
var PluginRegistry = class {
|
|
2551
|
+
list = [];
|
|
2552
|
+
get size() {
|
|
2553
|
+
return this.list.length;
|
|
2554
|
+
}
|
|
2555
|
+
add(plugin, instance) {
|
|
2556
|
+
if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
|
|
2557
|
+
if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
|
|
2558
|
+
for (const h of HOOKS)
|
|
2559
|
+
if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
|
|
2560
|
+
invalid(`plugin "${plugin.name}": ${h} must be a function`);
|
|
2561
|
+
if (this.list.some((r) => r.plugin.name === plugin.name))
|
|
2562
|
+
invalid(`a plugin named "${plugin.name}" is already registered`);
|
|
2563
|
+
const entry = { plugin };
|
|
2564
|
+
const teardown = plugin.setup?.(instance);
|
|
2565
|
+
if (typeof teardown === "function") entry.teardown = teardown;
|
|
2566
|
+
this.list = [...this.list, entry];
|
|
2567
|
+
return () => void this.remove(plugin);
|
|
2568
|
+
}
|
|
2569
|
+
remove(nameOrPlugin) {
|
|
2570
|
+
const entry = this.list.find(
|
|
2571
|
+
(r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
|
|
2572
|
+
);
|
|
2573
|
+
if (!entry) return false;
|
|
2574
|
+
this.list = this.list.filter((r) => r !== entry);
|
|
2575
|
+
entry.teardown?.();
|
|
2576
|
+
return true;
|
|
2577
|
+
}
|
|
2578
|
+
/** Run `final` wrapped in every plugin's hooks. */
|
|
2579
|
+
run(config, final) {
|
|
2580
|
+
const plugins = this.list.map((r) => r.plugin);
|
|
2581
|
+
const layer = async (i, cfg) => {
|
|
2582
|
+
if (i === plugins.length) return final(cfg);
|
|
2583
|
+
const p = plugins[i];
|
|
2584
|
+
const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
|
|
2585
|
+
let response;
|
|
2586
|
+
try {
|
|
2587
|
+
response = await layer(i + 1, c);
|
|
2588
|
+
} catch (err) {
|
|
2589
|
+
if (!p.onError || isCancel(err)) throw err;
|
|
2590
|
+
const recovered = await p.onError(err, c);
|
|
2591
|
+
if (recovered == null) throw err;
|
|
2592
|
+
return recovered;
|
|
2593
|
+
}
|
|
2594
|
+
return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
|
|
2595
|
+
};
|
|
2596
|
+
return layer(0, config);
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
|
|
2543
2600
|
// src/core/requestCache.ts
|
|
2544
2601
|
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
2545
2602
|
var MemoryCache = class {
|
|
@@ -2770,6 +2827,9 @@ var Exios = class {
|
|
|
2770
2827
|
events = new EventHub();
|
|
2771
2828
|
memoryCache = new MemoryCache();
|
|
2772
2829
|
inflight = new InflightRequests();
|
|
2830
|
+
plugins = new PluginRegistry();
|
|
2831
|
+
/** The callable instance wrapping this context (given to plugin `setup`). */
|
|
2832
|
+
instance;
|
|
2773
2833
|
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2774
2834
|
cache;
|
|
2775
2835
|
constructor(defaults) {
|
|
@@ -2844,7 +2904,11 @@ var Exios = class {
|
|
|
2844
2904
|
synchronous = synchronous && h.synchronous;
|
|
2845
2905
|
requestChain.unshift(h);
|
|
2846
2906
|
});
|
|
2847
|
-
const dispatch = (c) =>
|
|
2907
|
+
const dispatch = (c) => {
|
|
2908
|
+
const finalized = finalizeConfig(c);
|
|
2909
|
+
if (this.plugins.size === 0) return this.dispatch(finalized);
|
|
2910
|
+
return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
|
|
2911
|
+
};
|
|
2848
2912
|
let promise;
|
|
2849
2913
|
if (synchronous) {
|
|
2850
2914
|
promise = this.runSync(requestChain, resolved, dispatch);
|
|
@@ -2862,6 +2926,14 @@ var Exios = class {
|
|
|
2862
2926
|
});
|
|
2863
2927
|
return promise;
|
|
2864
2928
|
}
|
|
2929
|
+
/** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
|
|
2930
|
+
use(plugin) {
|
|
2931
|
+
return this.plugins.add(plugin, this.instance);
|
|
2932
|
+
}
|
|
2933
|
+
/** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
|
|
2934
|
+
eject(nameOrPlugin) {
|
|
2935
|
+
return this.plugins.remove(nameOrPlugin);
|
|
2936
|
+
}
|
|
2865
2937
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
2866
2938
|
on(name, listener) {
|
|
2867
2939
|
return this.events.on(name, listener);
|
|
@@ -3165,6 +3237,8 @@ var Exios = class {
|
|
|
3165
3237
|
};
|
|
3166
3238
|
var METHODS = [
|
|
3167
3239
|
"request",
|
|
3240
|
+
"use",
|
|
3241
|
+
"eject",
|
|
3168
3242
|
"on",
|
|
3169
3243
|
"once",
|
|
3170
3244
|
"off",
|
|
@@ -3229,6 +3303,7 @@ function createInstance(defaults) {
|
|
|
3229
3303
|
set: (v) => context.defaults = v,
|
|
3230
3304
|
enumerable: true
|
|
3231
3305
|
});
|
|
3306
|
+
context.instance = instance;
|
|
3232
3307
|
instance.interceptors = context.interceptors;
|
|
3233
3308
|
instance.breaker = context.breaker;
|
|
3234
3309
|
instance.cache = context.cache;
|
|
@@ -3236,6 +3311,10 @@ function createInstance(defaults) {
|
|
|
3236
3311
|
return instance;
|
|
3237
3312
|
}
|
|
3238
3313
|
|
|
3314
|
+
// src/core/internals.ts
|
|
3315
|
+
var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
|
|
3316
|
+
var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
|
|
3317
|
+
|
|
3239
3318
|
// src/index.ts
|
|
3240
3319
|
registerXhrAdapter();
|
|
3241
3320
|
registerFetchAdapter();
|
|
@@ -3254,6 +3333,7 @@ var exios = Object.assign(
|
|
|
3254
3333
|
createInstance(createDefaults()),
|
|
3255
3334
|
statics
|
|
3256
3335
|
);
|
|
3336
|
+
Object.defineProperty(exios, INTERNALS, { value: internals });
|
|
3257
3337
|
var create = exios.create;
|
|
3258
3338
|
var src_default = exios;
|
|
3259
3339
|
|