@indra211/exios 3.1.2 → 3.3.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 CHANGED
@@ -235,6 +235,51 @@ api.off("retry"); // or remove every listener of an event
235
235
  - `retry.onRetry` and `breaker.onStateChange` keep working as before, and run before the events.
236
236
  - Events describe network requests: a cache hit or a deduplicated caller makes none, so it emits none.
237
237
 
238
+ ## Logging
239
+
240
+ `createLoggerPlugin()` writes one structured entry per lifecycle event. It never logs bodies, credentials, sensitive headers (`Authorization`, `Cookie`, API-key and CSRF headers) or credential-like query values (`token`, `api_key`, `access_token`, signed-URL signatures, ...).
241
+
242
+ ```ts
243
+ import exios, { createLoggerPlugin } from "@indra211/exios";
244
+
245
+ const api = exios.create({ baseURL: "https://api.example.com" });
246
+ api.use(createLoggerPlugin()); // console, level 'info'
247
+ // [exios] ← 200 GET https://api.example.com/users (84ms) { event: 'response', status: 200, requestId, durationMs, ... }
248
+
249
+ api.use(createLoggerPlugin({ logger: winston, level: "debug", headers: true }));
250
+ api.use(createLoggerPlugin({ log: (level, msg, fields) => pino[level](fields, msg) })); // pino takes (fields, msg)
251
+ ```
252
+
253
+ | Level | Entries |
254
+ |---|---|
255
+ | `debug` | request sent (with redacted headers if `headers: true`), cache hit / deduplicated request, canceled |
256
+ | `info` | response; circuit half-open / closed |
257
+ | `warn` | retry (attempt, reason, delay); timeout; response with a 4xx/5xx status that `validateStatus` accepted; circuit opened |
258
+ | `error` | the request finally failed (status or error code, attempts, duration) |
259
+
260
+ Options: `logger` (any object with `debug` / `info` / `warn` / `error` taking `(message, fields)`; default `console`), `log(level, message, fields)` instead of `logger`, `level` (`'debug' | 'info' | 'warn' | 'error' | 'silent'`, default `'info'`), `headers`, `metadata` (add `config.metadata` to entries), `name` (to register more than one logger). `fields` always has `event`, and for requests `requestId`, `method`, `url` (without params, credentials removed) and `correlationId` when set.
261
+
262
+ ## OpenTelemetry
263
+
264
+ `@indra211/exios/otel` traces requests with OpenTelemetry. It has no dependency of its own: you pass the `@opentelemetry/api` module your app already uses (1.x), and your SDK setup (exporters, sampling, propagators) applies.
265
+
266
+ ```ts
267
+ import * as otel from "@opentelemetry/api";
268
+ import exios from "@indra211/exios";
269
+ import { createOtelPlugin } from "@indra211/exios/otel";
270
+
271
+ const api = exios.create({ baseURL: "https://api.example.com" });
272
+ api.use(createOtelPlugin({ api: otel })); // register it first, so it wraps the other plugins
273
+ ```
274
+
275
+ - **Spans:** one `CLIENT` span per logical request, a child of the active span, named after the method (`GET`) as the HTTP semantic conventions prescribe. Attributes: `http.request.method`, `url.full` (credentials and credential-like query values redacted), `server.address`, `server.port`, `url.scheme`, `http.response.status_code`, `error.type`, `http.request.resend_count`, plus `exios.request_id`, `exios.attempts`, `exios.cached`, `exios.deduped`. Each retry is an `exios.retry` span event (attempt, delay, error or status).
276
+ - **Status:** `ERROR` for failed requests and for 4xx/5xx responses (`error.type` is the status code, or the exios code such as `ERR_NETWORK` / `ECONNABORTED` when there was no response); the exception is recorded. A cancellation ends the span with `error.type: 'ERR_CANCELED'` and no error status.
277
+ - **Propagation:** the registered propagator (W3C `traceparent` by default) injects headers into requests: every request on servers; **same-origin only in browsers**, because a new header on a cross-origin request triggers a CORS preflight the server must allow. Set `propagate: true | false | RegExp | (url) => boolean` to choose. A header you set yourself wins.
278
+ - **Metrics:** the `http.client.request.duration` histogram (seconds) with method, server, scheme, status and `error.type` attributes, when your API has a meter provider (`metrics: false` turns it off).
279
+ - Options: `spanName(config)` (e.g. a route template from `config.metadata`), `attributes(config)` for extra span attributes, `name` / `version` of the tracer and meter, `pluginName`.
280
+ - Tracing never breaks a request: a failing tracer or exporter is reported with `console.error` and the request goes on.
281
+ - Use it instead of, not together with, Node's HTTP auto-instrumentation for the same requests, or you get two client spans per request.
282
+
238
283
  ## Request management
239
284
 
240
285
  All of these are **off by default**. Turning them on never changes retry or breaker behaviour.
@@ -300,7 +345,7 @@ res.meta.cached; // true
300
345
  - **What is stored:** only 2xx responses. Errors, request bodies and streams are never cached. Neither is data that `structuredClone` can't copy exactly: class instances (for example from a custom `transformResponse`), functions, or Node `Buffer`s anywhere in the data. Plain objects, arrays, `Date`, `Map`, `Set`, `RegExp`, typed arrays, `ArrayBuffer` and `Blob` are fine.
301
346
  - **Transforms:** the key includes `transformResponse` and `responseEncoding`, so differently transformed data is never mixed. An inline `transformResponse` written per call gets a new key each time, so it never hits the cache: define it once and reuse it.
302
347
  - **Isolated data:** every response read from the cache gets its own copy of `data`, so changing it can't affect the cache or other callers.
303
- - **Credentials:** the key includes a hash of the request headers and `auth`, so requests made with different credentials never share an entry. Secrets never appear in the key text.
348
+ - **Credentials:** the key includes a hash of the request headers and `auth`, so requests made with different credentials never share an entry. Secrets never appear in the key text. Headers that never change a response are left out of the hash: the correlation-ID header, `Cache-Control` / `Pragma`, and trace-context headers (`traceparent`, `tracestate`, `baggage`, B3, `uber-trace-id`, `sentry-trace`), so tracing does not defeat the cache or deduplication.
304
349
  - **Cache-Control:** a response with `no-store` or `no-cache` is not stored, and `max-age` shortens the `ttl`. A request sent with `Cache-Control: no-cache` skips the read and refreshes the entry; `no-store` skips both the read and the write.
305
350
  - **Per request:** `cache: false` bypasses the cache; `cache: { ttl: 5000 }` overrides the ttl.
306
351
  - **Failures:** a cache provider that throws never fails the request. The error is reported with `console.error`, and the request goes to the network.
@@ -328,6 +373,104 @@ const api = exios.create({ cache: { provider: new MemoryCache({ maxEntries: 500
328
373
 
329
374
  `invalidate()` needs a provider with `keys()`; without one it rejects with `ERR_NOT_SUPPORT`.
330
375
 
376
+ ## Plugins
377
+
378
+ A plugin bundles behaviour you want on an instance (auth, logging, response unwrapping, fallbacks) behind one name. Every hook is optional.
379
+
380
+ ```ts
381
+ import exios, { type ExiosPlugin } from "@indra211/exios";
382
+
383
+ const auth: ExiosPlugin = {
384
+ name: "auth",
385
+ async beforeRequest(config) {
386
+ config.headers.authorization = `Bearer ${await getToken()}`;
387
+ },
388
+ };
389
+
390
+ const unwrap: ExiosPlugin = {
391
+ name: "unwrap",
392
+ afterResponse: (response) => ({ ...response, data: response.data.data }), // { data: ... } envelopes
393
+ };
394
+
395
+ const offline: ExiosPlugin = {
396
+ name: "offline-fallback",
397
+ onError: (error, config) =>
398
+ config.method === "get" && exios.isExiosError(error) && error.code === "ERR_NETWORK"
399
+ ? { data: readFromDisk(config.url), status: 200, statusText: "OK", headers: {}, config, request: null, meta: { attempts: 0 } }
400
+ : undefined, // undefined: keep failing
401
+ };
402
+
403
+ const metrics: ExiosPlugin = {
404
+ name: "metrics",
405
+ setup: (instance) => instance.on("response", (e) => histogram.record(e.durationMs)), // returns the teardown
406
+ };
407
+
408
+ const api = exios.create({ baseURL: "https://api.example.com" });
409
+ const ejectAuth = api.use(auth);
410
+ api.use(unwrap);
411
+ api.use(offline);
412
+ api.use(metrics);
413
+
414
+ api.eject("metrics"); // by name (or by object); runs the teardown setup returned
415
+ ejectAuth(); // or call the function use() returned
416
+ ```
417
+
418
+ | Hook | When | Return |
419
+ |---|---|---|
420
+ | `setup(instance)` | once, in `use()` | optionally a teardown function, called by `eject()` |
421
+ | `beforeRequest(config)` | after the request interceptors | a new config, or nothing (edit it in place) |
422
+ | `afterResponse(response, config)` | after a successful request | a new response, or nothing |
423
+ | `onError(error, config)` | after a failed request (not for cancellations) | a response to recover, or nothing to keep failing |
424
+ | `onCancel(error, config)` | the request was canceled | nothing (a notification; the cancellation propagates) |
425
+
426
+ - **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.
427
+ - Hooks run once per logical request (not per retry attempt). Cache hits and deduplicated requests go through `afterResponse` too.
428
+ - 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`.
429
+ - 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.
430
+
431
+ ## Testing with the mock adapter
432
+
433
+ `@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.
434
+
435
+ ```ts
436
+ import exios from "@indra211/exios";
437
+ import { createMockAdapter } from "@indra211/exios/testing";
438
+
439
+ const api = exios.create({ baseURL: "https://api.example.com" });
440
+ const mock = createMockAdapter(api); // becomes api's adapter; mock.restore() undoes it
441
+
442
+ mock.onGet("/users/1").reply(200, { id: 1, name: "Ada" });
443
+ mock.onGet("/users", { params: { page: 2 } }).reply(200, []);
444
+ mock.onPost("/users", { data: { name: "Bob" } }).replyOnce(201, { id: 2 });
445
+ mock.onGet(/\/orders\/\d+/).reply(async (config) => [200, { url: config.url }, { "x-request": "1" }]);
446
+ mock.onGet("/flaky").networkErrorOnce().onGet("/flaky").reply(200, "ok"); // retry sees a real ERR_NETWORK
447
+ mock.onGet("/slow").delay(5000).reply(200); // with timeout: 1000 → ECONNABORTED after 1 s
448
+ mock.onGet("/down").timeout(); // fails at once with the timeout error
449
+ mock.onAny("/health").reply(204);
450
+
451
+ await api.get("/users/1");
452
+ expect(mock.history.get[0].url).toBe("https://api.example.com/users/1");
453
+ expect(mock.history.post[0].data).toEqual({ name: "Bob" }); // also .headers, .body (as sent), .config
454
+
455
+ mock.reset(); // handlers and history (or resetHandlers() / resetHistory())
456
+ ```
457
+
458
+ - **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)`.
459
+ - **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.
460
+ - **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.
461
+ - **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.
462
+ - Without an instance, `createMockAdapter()` returns a mock whose `mock.adapter` you pass yourself: `exios.create({ adapter: mock.adapter })`.
463
+ - 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.
464
+
465
+ ## Writing a custom adapter
466
+
467
+ 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:
468
+
469
+ - **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.
470
+ - **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.
471
+ - **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.
472
+ - **Cancellation:** honour `config.signal` (CancelToken is already turned into it).
473
+
331
474
  ## Behavior rules
332
475
 
333
476
  These are deliberate and tested.
package/dist/index.cjs CHANGED
@@ -53,6 +53,51 @@ function redactConfig(config) {
53
53
  if (c.data !== void 0) c.data = REDACTED;
54
54
  return c;
55
55
  }
56
+ var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
57
+ "access_token",
58
+ "api_key",
59
+ "apikey",
60
+ "auth",
61
+ "client_secret",
62
+ "id_token",
63
+ "key",
64
+ "password",
65
+ "refresh_token",
66
+ "secret",
67
+ "sig",
68
+ "signature",
69
+ "token",
70
+ "awsaccesskeyid",
71
+ "x-amz-credential",
72
+ "x-amz-security-token",
73
+ "x-amz-signature",
74
+ "x-goog-credential",
75
+ "x-goog-signature"
76
+ ]);
77
+ function redactURL(url) {
78
+ const absolute = /^[a-z][a-z\d+\-.]*:\/\//i.test(url);
79
+ let u;
80
+ try {
81
+ u = absolute ? new URL(url) : new URL(url, "http://exios.invalid");
82
+ } catch {
83
+ const q2 = url.indexOf("?");
84
+ return q2 === -1 ? url : url.slice(0, q2);
85
+ }
86
+ u.username = "";
87
+ u.password = "";
88
+ let changed = false;
89
+ const params = new URLSearchParams(u.search);
90
+ for (const k of new Set(params.keys()))
91
+ if (SENSITIVE_QUERY_PARAMS.has(k.toLowerCase())) {
92
+ params.set(k, REDACTED);
93
+ changed = true;
94
+ }
95
+ if (changed) u.search = params.toString().replaceAll("%5BREDACTED%5D", REDACTED);
96
+ if (absolute) return u.href;
97
+ const q = url.indexOf("?");
98
+ const path = q === -1 ? url : url.slice(0, q);
99
+ return changed ? path + u.search : url;
100
+ }
56
101
 
57
102
  // src/errors/ExiosError.ts
58
103
  var ExiosError = class _ExiosError extends Error {
@@ -1600,6 +1645,8 @@ async function dispatchRequest(config, registry2, observer) {
1600
1645
  breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
1601
1646
  if (outcome.error) throw outcome.error;
1602
1647
  const response = outcome.response;
1648
+ response.meta ??= { attempts };
1649
+ response.config ??= config;
1603
1650
  response.meta.attempts = attempts;
1604
1651
  if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
1605
1652
  const { status } = response;
@@ -1982,6 +2029,74 @@ var InflightRequests = class {
1982
2029
  }
1983
2030
  };
1984
2031
 
2032
+ // src/core/plugins.ts
2033
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError", "onCancel"];
2034
+ function invalid(message) {
2035
+ throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2036
+ }
2037
+ var PluginRegistry = class {
2038
+ list = [];
2039
+ get size() {
2040
+ return this.list.length;
2041
+ }
2042
+ add(plugin, instance) {
2043
+ if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
2044
+ if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
2045
+ for (const h of HOOKS)
2046
+ if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
2047
+ invalid(`plugin "${plugin.name}": ${h} must be a function`);
2048
+ if (this.list.some((r) => r.plugin.name === plugin.name))
2049
+ invalid(`a plugin named "${plugin.name}" is already registered`);
2050
+ const entry = { plugin };
2051
+ const teardown = plugin.setup?.(instance);
2052
+ if (typeof teardown === "function") entry.teardown = teardown;
2053
+ this.list = [...this.list, entry];
2054
+ return () => void this.remove(plugin);
2055
+ }
2056
+ remove(nameOrPlugin) {
2057
+ const entry = this.list.find(
2058
+ (r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
2059
+ );
2060
+ if (!entry) return false;
2061
+ this.list = this.list.filter((r) => r !== entry);
2062
+ entry.teardown?.();
2063
+ return true;
2064
+ }
2065
+ /** Run `final` wrapped in every plugin's hooks. */
2066
+ run(config, final) {
2067
+ const plugins = this.list.map((r) => r.plugin);
2068
+ const layer = async (i, cfg) => {
2069
+ if (i === plugins.length) return final(cfg);
2070
+ const p = plugins[i];
2071
+ const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
2072
+ let response;
2073
+ try {
2074
+ response = await layer(i + 1, c);
2075
+ } catch (err) {
2076
+ if (isCancel(err)) {
2077
+ if (p.onCancel) {
2078
+ try {
2079
+ p.onCancel(err, c);
2080
+ } catch (hookErr) {
2081
+ report(p.name, hookErr);
2082
+ }
2083
+ }
2084
+ throw err;
2085
+ }
2086
+ if (!p.onError) throw err;
2087
+ const recovered = await p.onError(err, c);
2088
+ if (recovered == null) throw err;
2089
+ return recovered;
2090
+ }
2091
+ return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
2092
+ };
2093
+ return layer(0, config);
2094
+ }
2095
+ };
2096
+ function report(name, err) {
2097
+ if (typeof console !== "undefined") console.error(`[exios] plugin "${name}" onCancel failed:`, err);
2098
+ }
2099
+
1985
2100
  // src/core/requestCache.ts
1986
2101
  var SAFE_METHODS = Object.freeze(["get", "head"]);
1987
2102
  var MemoryCache = class {
@@ -2031,7 +2146,21 @@ function hash(str) {
2031
2146
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2032
2147
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2033
2148
  }
2034
- var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2149
+ var KEY_IGNORED_HEADERS = /* @__PURE__ */ new Set([
2150
+ "cache-control",
2151
+ "pragma",
2152
+ "traceparent",
2153
+ "tracestate",
2154
+ "baggage",
2155
+ "b3",
2156
+ "x-b3-traceid",
2157
+ "x-b3-spanid",
2158
+ "x-b3-parentspanid",
2159
+ "x-b3-sampled",
2160
+ "x-b3-flags",
2161
+ "uber-trace-id",
2162
+ "sentry-trace"
2163
+ ]);
2035
2164
  function requestTarget(config) {
2036
2165
  const url = buildURL(
2037
2166
  buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
@@ -2044,7 +2173,7 @@ function defaultRequestKey(config, scope = "cache") {
2044
2173
  const skip = config.correlationIdHeader?.toLowerCase();
2045
2174
  const parts = [];
2046
2175
  for (const k of Object.keys(config.headers).sort())
2047
- if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2176
+ if (k !== skip && !KEY_IGNORED_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2048
2177
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2049
2178
  parts.push(`rt:${config.responseType ?? ""}`);
2050
2179
  parts.push(
@@ -2212,6 +2341,9 @@ var Exios = class {
2212
2341
  events = new EventHub();
2213
2342
  memoryCache = new MemoryCache();
2214
2343
  inflight = new InflightRequests();
2344
+ plugins = new PluginRegistry();
2345
+ /** The callable instance wrapping this context (given to plugin `setup`). */
2346
+ instance;
2215
2347
  /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2216
2348
  cache;
2217
2349
  constructor(defaults) {
@@ -2286,7 +2418,11 @@ var Exios = class {
2286
2418
  synchronous = synchronous && h.synchronous;
2287
2419
  requestChain.unshift(h);
2288
2420
  });
2289
- const dispatch = (c) => this.dispatch(finalizeConfig(c));
2421
+ const dispatch = (c) => {
2422
+ const finalized = finalizeConfig(c);
2423
+ if (this.plugins.size === 0) return this.dispatch(finalized);
2424
+ return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
2425
+ };
2290
2426
  let promise;
2291
2427
  if (synchronous) {
2292
2428
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -2304,6 +2440,14 @@ var Exios = class {
2304
2440
  });
2305
2441
  return promise;
2306
2442
  }
2443
+ /** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
2444
+ use(plugin) {
2445
+ return this.plugins.add(plugin, this.instance);
2446
+ }
2447
+ /** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
2448
+ eject(nameOrPlugin) {
2449
+ return this.plugins.remove(nameOrPlugin);
2450
+ }
2307
2451
  /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2308
2452
  on(name, listener) {
2309
2453
  return this.events.on(name, listener);
@@ -2607,6 +2751,8 @@ var Exios = class {
2607
2751
  };
2608
2752
  var METHODS = [
2609
2753
  "request",
2754
+ "use",
2755
+ "eject",
2610
2756
  "on",
2611
2757
  "once",
2612
2758
  "off",
@@ -2671,6 +2817,7 @@ function createInstance(defaults) {
2671
2817
  set: (v) => context.defaults = v,
2672
2818
  enumerable: true
2673
2819
  });
2820
+ context.instance = instance;
2674
2821
  instance.interceptors = context.interceptors;
2675
2822
  instance.breaker = context.breaker;
2676
2823
  instance.cache = context.cache;
@@ -2678,6 +2825,109 @@ function createInstance(defaults) {
2678
2825
  return instance;
2679
2826
  }
2680
2827
 
2828
+ // src/core/internals.ts
2829
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
2830
+ var internals = {
2831
+ abortError,
2832
+ buildFullPath,
2833
+ buildURL,
2834
+ createRequestId,
2835
+ finishResponse,
2836
+ prepareRequest,
2837
+ redactURL
2838
+ };
2839
+
2840
+ // src/core/logger.ts
2841
+ var RANK = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
2842
+ function createLoggerPlugin(options = {}) {
2843
+ const min = RANK[options.level ?? "info"];
2844
+ if (min === void 0) throw new TypeError(`createLoggerPlugin: unknown level ${String(options.level)}`);
2845
+ const target = options.logger ?? (typeof console !== "undefined" ? console : void 0);
2846
+ const write = (level, message, fields) => {
2847
+ if (RANK[level] < min) return;
2848
+ if (options.log) return options.log(level, message, fields);
2849
+ const fn = target?.[level];
2850
+ if (typeof fn === "function") fn.call(target, message, fields);
2851
+ };
2852
+ const base = (e) => {
2853
+ const url = redactURL(e.url);
2854
+ const fields = {
2855
+ label: `${e.method.toUpperCase()} ${url}`,
2856
+ event: "request",
2857
+ requestId: e.requestId,
2858
+ method: e.method.toUpperCase(),
2859
+ url
2860
+ };
2861
+ if (e.correlationId !== void 0) fields.correlationId = e.correlationId;
2862
+ if (options.metadata && e.metadata) fields.metadata = e.metadata;
2863
+ return fields;
2864
+ };
2865
+ const entry = (level, msg, f) => {
2866
+ const { label, ...fields } = f;
2867
+ write(level, `[exios] ${msg(label)}`, fields);
2868
+ };
2869
+ return {
2870
+ name: options.name ?? "logger",
2871
+ setup(instance) {
2872
+ if (min === RANK.silent) return;
2873
+ const offs = [
2874
+ instance.on("request", (e) => {
2875
+ const f = base(e);
2876
+ if (options.headers) f.headers = redactHeaders(e.config.headers);
2877
+ entry("debug", (l) => `\u2192 ${l}`, f);
2878
+ }),
2879
+ instance.on("response", (e) => {
2880
+ const f = { ...base(e), event: "response", status: e.status, attempts: e.attempts, durationMs: e.durationMs };
2881
+ const retries = e.attempts > 1 ? `, ${e.attempts} attempts` : "";
2882
+ entry(e.status >= 400 ? "warn" : "info", (l) => `\u2190 ${e.status} ${l} (${e.durationMs}ms${retries})`, f);
2883
+ }),
2884
+ instance.on("retry", (e) => {
2885
+ const reason = e.status !== void 0 ? `status ${e.status}` : e.error?.code ?? "error";
2886
+ const f = { ...base(e), event: "retry", attempt: e.attempt, delayMs: e.delayMs };
2887
+ if (e.status !== void 0) f.status = e.status;
2888
+ if (e.error?.code) f.code = e.error.code;
2889
+ entry("warn", (l) => `\u21BB ${l} attempt ${e.attempt} failed (${reason}), retrying in ${e.delayMs}ms`, f);
2890
+ }),
2891
+ instance.on("timeout", (e) => {
2892
+ const f = { ...base(e), event: "timeout", attempt: e.attempt, timeoutMs: e.timeoutMs };
2893
+ if (e.error.code) f.code = e.error.code;
2894
+ entry("warn", (l) => `\u23F1 ${l} ${e.kind === "total" ? "total timeout" : "timeout"} of ${e.timeoutMs}ms`, f);
2895
+ }),
2896
+ instance.on("error", (e) => {
2897
+ const f = { ...base(e), event: "error", attempts: e.attempts, durationMs: e.durationMs };
2898
+ if (e.status !== void 0) f.status = e.status;
2899
+ if (e.code !== void 0) f.code = e.code;
2900
+ const what = e.status !== void 0 ? `${e.status}` : e.code ?? "failed";
2901
+ entry("error", (l) => `\u2715 ${l} ${what} (${e.durationMs}ms)`, f);
2902
+ }),
2903
+ instance.on("canceled", (e) => {
2904
+ entry("debug", (l) => `\u2298 ${l} canceled`, { ...base(e), event: "canceled", attempts: e.attempts, durationMs: e.durationMs });
2905
+ }),
2906
+ ...["circuitOpen", "circuitHalfOpen", "circuitClose"].map(
2907
+ (name) => instance.on(name, (e) => {
2908
+ const fields = { event: name, key: e.key, from: e.from, to: e.to };
2909
+ write(name === "circuitOpen" ? "warn" : "info", `[exios] circuit ${e.key} ${e.from} \u2192 ${e.to}`, fields);
2910
+ })
2911
+ )
2912
+ ];
2913
+ return () => {
2914
+ for (const off of offs) off();
2915
+ };
2916
+ },
2917
+ // Cache hits and deduplicated followers make no network request, so they emit no events.
2918
+ afterResponse(response, config) {
2919
+ const source = response.meta.cached ? "cached" : response.meta.deduped ? "deduped" : void 0;
2920
+ if (!source || RANK.debug < min) return;
2921
+ const c = response.config ?? config;
2922
+ const url = redactURL(buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls));
2923
+ const fields = { event: "cache", source, method: c.method.toUpperCase(), url, status: response.status };
2924
+ if (c.requestId !== void 0) fields.requestId = c.requestId;
2925
+ if (c.correlationId !== void 0) fields.correlationId = c.correlationId;
2926
+ write("debug", `[exios] \u26A1 ${fields.method} ${url} ${source} (${response.status})`, fields);
2927
+ }
2928
+ };
2929
+ }
2930
+
2681
2931
  // src/index.ts
2682
2932
  registerXhrAdapter();
2683
2933
  registerFetchAdapter();
@@ -2690,12 +2940,14 @@ var statics = {
2690
2940
  isCancel,
2691
2941
  mergeConfig,
2692
2942
  toFormData,
2693
- MemoryCache
2943
+ MemoryCache,
2944
+ createLoggerPlugin
2694
2945
  };
2695
2946
  var exios = Object.assign(
2696
2947
  createInstance(createDefaults()),
2697
2948
  statics
2698
2949
  );
2950
+ Object.defineProperty(exios, INTERNALS, { value: internals });
2699
2951
  var create = exios.create;
2700
2952
  var src_default = exios;
2701
2953
 
package/dist/index.d.cts CHANGED
@@ -54,5 +54,10 @@ declare namespace exios {
54
54
  type ResponseMeta = Pkg.ResponseMeta;
55
55
  type RetryEvent = Pkg.RetryEvent;
56
56
  type TimeoutEvent = Pkg.TimeoutEvent;
57
+ type ExiosPlugin = Pkg.ExiosPlugin;
58
+ type ExiosLogger = Pkg.ExiosLogger;
59
+ type LogFields = Pkg.LogFields;
60
+ type LoggerPluginOptions = Pkg.LoggerPluginOptions;
61
+ type LogLevel = Pkg.LogLevel;
57
62
  }
58
63
  export = exios;
package/dist/index.d.ts CHANGED
@@ -401,6 +401,32 @@ 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
+ /** The request was canceled (signal, CancelToken). Notification only: the cancellation propagates. */
427
+ onCancel?(error: CanceledError, config: InternalConfig): void;
428
+ }
429
+
404
430
  type Cfg<D> = ExiosRequestConfig<D>;
405
431
  declare class Exios {
406
432
  defaults: ExiosDefaults;
@@ -416,10 +442,17 @@ declare class Exios {
416
442
  private readonly events;
417
443
  private readonly memoryCache;
418
444
  private readonly inflight;
445
+ private readonly plugins;
446
+ /** The callable instance wrapping this context (given to plugin `setup`). */
447
+ instance?: ExiosStatic;
419
448
  /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
420
449
  cache: ExiosCache;
421
450
  constructor(defaults: ExiosDefaults);
422
451
  request<T = any, R = ExiosResponse<T>, D = any>(configOrUrl: string | Cfg<D>, config?: Cfg<D>): Promise<R>;
452
+ /** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
453
+ use(plugin: ExiosPlugin): () => void;
454
+ /** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
455
+ eject(nameOrPlugin: string | ExiosPlugin): boolean;
423
456
  /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
424
457
  on<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
425
458
  /** Like `on`, but the listener runs at most once. */
@@ -453,7 +486,7 @@ declare class Exios {
453
486
  putForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
454
487
  patchForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
455
488
  }
456
- declare const METHODS: readonly ["request", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
489
+ declare const METHODS: readonly ["request", "use", "eject", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
457
490
  /** `instance.cache`: manage the instance's cache provider. */
458
491
  interface ExiosCache {
459
492
  /** Remove every entry. */
@@ -475,6 +508,61 @@ interface ExiosStatic extends Pick<Exios, (typeof METHODS)[number] | "defaults"
475
508
  }
476
509
  type ExiosInstance = ExiosStatic;
477
510
 
511
+ type LogLevel = "debug" | "info" | "warn" | "error";
512
+ /** Anything with level methods taking `(message, fields)`: `console`, winston, consola, ... */
513
+ interface ExiosLogger {
514
+ debug?(message: string, fields: LogFields): void;
515
+ info?(message: string, fields: LogFields): void;
516
+ warn?(message: string, fields: LogFields): void;
517
+ error?(message: string, fields: LogFields): void;
518
+ }
519
+ /** Structured fields of one log entry. Secrets are never included. */
520
+ interface LogFields {
521
+ event: "request" | "response" | "error" | "retry" | "timeout" | "canceled" | "cache" | "circuitOpen" | "circuitHalfOpen" | "circuitClose";
522
+ requestId?: string;
523
+ correlationId?: string;
524
+ method?: string;
525
+ /** baseURL + url (without params); credentials removed. */
526
+ url?: string;
527
+ status?: number;
528
+ code?: string;
529
+ attempt?: number;
530
+ attempts?: number;
531
+ delayMs?: number;
532
+ durationMs?: number;
533
+ timeoutMs?: number;
534
+ /** "cached" or "deduped" for `event: 'cache'`. */
535
+ source?: string;
536
+ /** Circuit breaker key and transition. */
537
+ key?: string;
538
+ from?: string;
539
+ to?: string;
540
+ /** Request headers, sensitive ones redacted (only with `headers: true`). */
541
+ headers?: Record<string, unknown>;
542
+ metadata?: Record<string, unknown>;
543
+ }
544
+ interface LoggerPluginOptions {
545
+ /** Where entries go. Default `console`. */
546
+ logger?: ExiosLogger;
547
+ /** Instead of `logger`: one function for every entry (e.g. pino: `(l, m, f) => pino[l](f, m)`). */
548
+ log?: (level: LogLevel, message: string, fields: LogFields) => void;
549
+ /** Lowest level written. Default `'info'`; `'silent'` writes nothing. */
550
+ level?: LogLevel | "silent";
551
+ /** Add the request headers (sensitive ones redacted) to `request` entries. Default false. */
552
+ headers?: boolean;
553
+ /** Add `config.metadata` to every request entry. Default false. */
554
+ metadata?: boolean;
555
+ /** Plugin name, to register more than one logger on an instance. Default `'logger'`. */
556
+ name?: string;
557
+ }
558
+ /**
559
+ * Structured request logging, built on lifecycle events: request (debug), response (info, or warn for a
560
+ * 4xx/5xx accepted by validateStatus), retry and timeout (warn), error (error), canceled (debug), cache
561
+ * hits and deduplicated requests (debug), circuit breaker transitions (warn when opening, info otherwise).
562
+ * Never logs bodies, credentials, sensitive headers or credential-like query values.
563
+ */
564
+ declare function createLoggerPlugin(options?: LoggerPluginOptions): ExiosPlugin;
565
+
478
566
  declare function mergeConfig(a: ExiosRequestConfig, b?: ExiosRequestConfig): ExiosRequestConfig;
479
567
 
480
568
  /** In-memory LRU cache: the default provider. Expired entries are dropped when read. */
@@ -504,10 +592,11 @@ declare const statics: {
504
592
  mergeConfig: typeof mergeConfig;
505
593
  toFormData: typeof toFormData;
506
594
  MemoryCache: typeof MemoryCache;
595
+ createLoggerPlugin: typeof createLoggerPlugin;
507
596
  };
508
597
  type ExiosDefault = ExiosStatic & typeof statics;
509
598
  declare const exios: ExiosDefault;
510
599
  declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
511
600
 
512
- 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 };
601
+ export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, MemoryCache, create, createLoggerPlugin, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
602
+ export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CacheConfig, CacheEntry, CacheProvider, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, DedupeConfig, ErrorEvent, ErrorMeta, ExiosCache, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosLogger, ExiosPlugin, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, LogFields, LogLevel, LoggerPluginOptions, Method, Options, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };