@indra211/exios 3.2.0 → 3.3.1

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.
@@ -376,6 +421,7 @@ ejectAuth(); // or call the function use() returned
376
421
  | `beforeRequest(config)` | after the request interceptors | a new config, or nothing (edit it in place) |
377
422
  | `afterResponse(response, config)` | after a successful request | a new response, or nothing |
378
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) |
379
425
 
380
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.
381
427
  - Hooks run once per logical request (not per retry attempt). Cache hits and deduplicated requests go through `afterResponse` too.
@@ -469,6 +515,10 @@ Real Safari is driven by macOS's built-in `safaridriver`. It does not work yet:
469
515
  2. Settings > Developer > tick "Allow remote automation".
470
516
  3. In a terminal: `safaridriver --enable` (asks for your password).
471
517
 
518
+ ## Issues and contributions
519
+
520
+ Found a bug or want a feature? [Open an issue](https://github.com/Indra211/exios/issues) with the exios version, your runtime (Node, browser, Deno, ...) and a small example. Pull requests are welcome: fork [the repository](https://github.com/Indra211/exios), make your change on a branch, and open a pull request against `main`.
521
+
472
522
  ## Author
473
523
 
474
524
  Questions, bugs or ideas: [work.indrasena@outlook.com](mailto:work.indrasena@outlook.com)
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 {
@@ -1985,7 +2030,7 @@ var InflightRequests = class {
1985
2030
  };
1986
2031
 
1987
2032
  // src/core/plugins.ts
1988
- var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2033
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError", "onCancel"];
1989
2034
  function invalid(message) {
1990
2035
  throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
1991
2036
  }
@@ -2028,7 +2073,17 @@ var PluginRegistry = class {
2028
2073
  try {
2029
2074
  response = await layer(i + 1, c);
2030
2075
  } catch (err) {
2031
- if (!p.onError || isCancel(err)) throw 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;
2032
2087
  const recovered = await p.onError(err, c);
2033
2088
  if (recovered == null) throw err;
2034
2089
  return recovered;
@@ -2038,6 +2093,9 @@ var PluginRegistry = class {
2038
2093
  return layer(0, config);
2039
2094
  }
2040
2095
  };
2096
+ function report(name, err) {
2097
+ if (typeof console !== "undefined") console.error(`[exios] plugin "${name}" onCancel failed:`, err);
2098
+ }
2041
2099
 
2042
2100
  // src/core/requestCache.ts
2043
2101
  var SAFE_METHODS = Object.freeze(["get", "head"]);
@@ -2088,7 +2146,21 @@ function hash(str) {
2088
2146
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2089
2147
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2090
2148
  }
2091
- 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
+ ]);
2092
2164
  function requestTarget(config) {
2093
2165
  const url = buildURL(
2094
2166
  buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
@@ -2101,7 +2173,7 @@ function defaultRequestKey(config, scope = "cache") {
2101
2173
  const skip = config.correlationIdHeader?.toLowerCase();
2102
2174
  const parts = [];
2103
2175
  for (const k of Object.keys(config.headers).sort())
2104
- 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]}`);
2105
2177
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2106
2178
  parts.push(`rt:${config.responseType ?? ""}`);
2107
2179
  parts.push(
@@ -2755,7 +2827,106 @@ function createInstance(defaults) {
2755
2827
 
2756
2828
  // src/core/internals.ts
2757
2829
  var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
2758
- var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
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
+ }
2759
2930
 
2760
2931
  // src/index.ts
2761
2932
  registerXhrAdapter();
@@ -2769,7 +2940,8 @@ var statics = {
2769
2940
  isCancel,
2770
2941
  mergeConfig,
2771
2942
  toFormData,
2772
- MemoryCache
2943
+ MemoryCache,
2944
+ createLoggerPlugin
2773
2945
  };
2774
2946
  var exios = Object.assign(
2775
2947
  createInstance(createDefaults()),
package/dist/index.d.cts CHANGED
@@ -55,5 +55,9 @@ declare namespace exios {
55
55
  type RetryEvent = Pkg.RetryEvent;
56
56
  type TimeoutEvent = Pkg.TimeoutEvent;
57
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;
58
62
  }
59
63
  export = exios;
package/dist/index.d.ts CHANGED
@@ -423,6 +423,8 @@ interface ExiosPlugin {
423
423
  * return nothing (or throw) to let it propagate to the plugins registered before this one.
424
424
  */
425
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;
426
428
  }
427
429
 
428
430
  type Cfg<D> = ExiosRequestConfig<D>;
@@ -506,6 +508,61 @@ interface ExiosStatic extends Pick<Exios, (typeof METHODS)[number] | "defaults"
506
508
  }
507
509
  type ExiosInstance = ExiosStatic;
508
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
+
509
566
  declare function mergeConfig(a: ExiosRequestConfig, b?: ExiosRequestConfig): ExiosRequestConfig;
510
567
 
511
568
  /** In-memory LRU cache: the default provider. Expired entries are dropped when read. */
@@ -535,10 +592,11 @@ declare const statics: {
535
592
  mergeConfig: typeof mergeConfig;
536
593
  toFormData: typeof toFormData;
537
594
  MemoryCache: typeof MemoryCache;
595
+ createLoggerPlugin: typeof createLoggerPlugin;
538
596
  };
539
597
  type ExiosDefault = ExiosStatic & typeof statics;
540
598
  declare const exios: ExiosDefault;
541
599
  declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
542
600
 
543
- export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, MemoryCache, create, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
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 };
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 };
package/dist/index.js CHANGED
@@ -27,6 +27,51 @@ function redactConfig(config) {
27
27
  if (c.data !== void 0) c.data = REDACTED;
28
28
  return c;
29
29
  }
30
+ var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
31
+ "access_token",
32
+ "api_key",
33
+ "apikey",
34
+ "auth",
35
+ "client_secret",
36
+ "id_token",
37
+ "key",
38
+ "password",
39
+ "refresh_token",
40
+ "secret",
41
+ "sig",
42
+ "signature",
43
+ "token",
44
+ "awsaccesskeyid",
45
+ "x-amz-credential",
46
+ "x-amz-security-token",
47
+ "x-amz-signature",
48
+ "x-goog-credential",
49
+ "x-goog-signature"
50
+ ]);
51
+ function redactURL(url) {
52
+ const absolute = /^[a-z][a-z\d+\-.]*:\/\//i.test(url);
53
+ let u;
54
+ try {
55
+ u = absolute ? new URL(url) : new URL(url, "http://exios.invalid");
56
+ } catch {
57
+ const q2 = url.indexOf("?");
58
+ return q2 === -1 ? url : url.slice(0, q2);
59
+ }
60
+ u.username = "";
61
+ u.password = "";
62
+ let changed = false;
63
+ const params = new URLSearchParams(u.search);
64
+ for (const k of new Set(params.keys()))
65
+ if (SENSITIVE_QUERY_PARAMS.has(k.toLowerCase())) {
66
+ params.set(k, REDACTED);
67
+ changed = true;
68
+ }
69
+ if (changed) u.search = params.toString().replaceAll("%5BREDACTED%5D", REDACTED);
70
+ if (absolute) return u.href;
71
+ const q = url.indexOf("?");
72
+ const path = q === -1 ? url : url.slice(0, q);
73
+ return changed ? path + u.search : url;
74
+ }
30
75
 
31
76
  // src/errors/ExiosError.ts
32
77
  var ExiosError = class _ExiosError extends Error {
@@ -1959,7 +2004,7 @@ var InflightRequests = class {
1959
2004
  };
1960
2005
 
1961
2006
  // src/core/plugins.ts
1962
- var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2007
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError", "onCancel"];
1963
2008
  function invalid(message) {
1964
2009
  throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
1965
2010
  }
@@ -2002,7 +2047,17 @@ var PluginRegistry = class {
2002
2047
  try {
2003
2048
  response = await layer(i + 1, c);
2004
2049
  } catch (err) {
2005
- if (!p.onError || isCancel(err)) throw err;
2050
+ if (isCancel(err)) {
2051
+ if (p.onCancel) {
2052
+ try {
2053
+ p.onCancel(err, c);
2054
+ } catch (hookErr) {
2055
+ report(p.name, hookErr);
2056
+ }
2057
+ }
2058
+ throw err;
2059
+ }
2060
+ if (!p.onError) throw err;
2006
2061
  const recovered = await p.onError(err, c);
2007
2062
  if (recovered == null) throw err;
2008
2063
  return recovered;
@@ -2012,6 +2067,9 @@ var PluginRegistry = class {
2012
2067
  return layer(0, config);
2013
2068
  }
2014
2069
  };
2070
+ function report(name, err) {
2071
+ if (typeof console !== "undefined") console.error(`[exios] plugin "${name}" onCancel failed:`, err);
2072
+ }
2015
2073
 
2016
2074
  // src/core/requestCache.ts
2017
2075
  var SAFE_METHODS = Object.freeze(["get", "head"]);
@@ -2062,7 +2120,21 @@ function hash(str) {
2062
2120
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2063
2121
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2064
2122
  }
2065
- var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2123
+ var KEY_IGNORED_HEADERS = /* @__PURE__ */ new Set([
2124
+ "cache-control",
2125
+ "pragma",
2126
+ "traceparent",
2127
+ "tracestate",
2128
+ "baggage",
2129
+ "b3",
2130
+ "x-b3-traceid",
2131
+ "x-b3-spanid",
2132
+ "x-b3-parentspanid",
2133
+ "x-b3-sampled",
2134
+ "x-b3-flags",
2135
+ "uber-trace-id",
2136
+ "sentry-trace"
2137
+ ]);
2066
2138
  function requestTarget(config) {
2067
2139
  const url = buildURL(
2068
2140
  buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
@@ -2075,7 +2147,7 @@ function defaultRequestKey(config, scope = "cache") {
2075
2147
  const skip = config.correlationIdHeader?.toLowerCase();
2076
2148
  const parts = [];
2077
2149
  for (const k of Object.keys(config.headers).sort())
2078
- if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2150
+ if (k !== skip && !KEY_IGNORED_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2079
2151
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2080
2152
  parts.push(`rt:${config.responseType ?? ""}`);
2081
2153
  parts.push(
@@ -2729,7 +2801,106 @@ function createInstance(defaults) {
2729
2801
 
2730
2802
  // src/core/internals.ts
2731
2803
  var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
2732
- var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
2804
+ var internals = {
2805
+ abortError,
2806
+ buildFullPath,
2807
+ buildURL,
2808
+ createRequestId,
2809
+ finishResponse,
2810
+ prepareRequest,
2811
+ redactURL
2812
+ };
2813
+
2814
+ // src/core/logger.ts
2815
+ var RANK = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
2816
+ function createLoggerPlugin(options = {}) {
2817
+ const min = RANK[options.level ?? "info"];
2818
+ if (min === void 0) throw new TypeError(`createLoggerPlugin: unknown level ${String(options.level)}`);
2819
+ const target = options.logger ?? (typeof console !== "undefined" ? console : void 0);
2820
+ const write = (level, message, fields) => {
2821
+ if (RANK[level] < min) return;
2822
+ if (options.log) return options.log(level, message, fields);
2823
+ const fn = target?.[level];
2824
+ if (typeof fn === "function") fn.call(target, message, fields);
2825
+ };
2826
+ const base = (e) => {
2827
+ const url = redactURL(e.url);
2828
+ const fields = {
2829
+ label: `${e.method.toUpperCase()} ${url}`,
2830
+ event: "request",
2831
+ requestId: e.requestId,
2832
+ method: e.method.toUpperCase(),
2833
+ url
2834
+ };
2835
+ if (e.correlationId !== void 0) fields.correlationId = e.correlationId;
2836
+ if (options.metadata && e.metadata) fields.metadata = e.metadata;
2837
+ return fields;
2838
+ };
2839
+ const entry = (level, msg, f) => {
2840
+ const { label, ...fields } = f;
2841
+ write(level, `[exios] ${msg(label)}`, fields);
2842
+ };
2843
+ return {
2844
+ name: options.name ?? "logger",
2845
+ setup(instance) {
2846
+ if (min === RANK.silent) return;
2847
+ const offs = [
2848
+ instance.on("request", (e) => {
2849
+ const f = base(e);
2850
+ if (options.headers) f.headers = redactHeaders(e.config.headers);
2851
+ entry("debug", (l) => `\u2192 ${l}`, f);
2852
+ }),
2853
+ instance.on("response", (e) => {
2854
+ const f = { ...base(e), event: "response", status: e.status, attempts: e.attempts, durationMs: e.durationMs };
2855
+ const retries = e.attempts > 1 ? `, ${e.attempts} attempts` : "";
2856
+ entry(e.status >= 400 ? "warn" : "info", (l) => `\u2190 ${e.status} ${l} (${e.durationMs}ms${retries})`, f);
2857
+ }),
2858
+ instance.on("retry", (e) => {
2859
+ const reason = e.status !== void 0 ? `status ${e.status}` : e.error?.code ?? "error";
2860
+ const f = { ...base(e), event: "retry", attempt: e.attempt, delayMs: e.delayMs };
2861
+ if (e.status !== void 0) f.status = e.status;
2862
+ if (e.error?.code) f.code = e.error.code;
2863
+ entry("warn", (l) => `\u21BB ${l} attempt ${e.attempt} failed (${reason}), retrying in ${e.delayMs}ms`, f);
2864
+ }),
2865
+ instance.on("timeout", (e) => {
2866
+ const f = { ...base(e), event: "timeout", attempt: e.attempt, timeoutMs: e.timeoutMs };
2867
+ if (e.error.code) f.code = e.error.code;
2868
+ entry("warn", (l) => `\u23F1 ${l} ${e.kind === "total" ? "total timeout" : "timeout"} of ${e.timeoutMs}ms`, f);
2869
+ }),
2870
+ instance.on("error", (e) => {
2871
+ const f = { ...base(e), event: "error", attempts: e.attempts, durationMs: e.durationMs };
2872
+ if (e.status !== void 0) f.status = e.status;
2873
+ if (e.code !== void 0) f.code = e.code;
2874
+ const what = e.status !== void 0 ? `${e.status}` : e.code ?? "failed";
2875
+ entry("error", (l) => `\u2715 ${l} ${what} (${e.durationMs}ms)`, f);
2876
+ }),
2877
+ instance.on("canceled", (e) => {
2878
+ entry("debug", (l) => `\u2298 ${l} canceled`, { ...base(e), event: "canceled", attempts: e.attempts, durationMs: e.durationMs });
2879
+ }),
2880
+ ...["circuitOpen", "circuitHalfOpen", "circuitClose"].map(
2881
+ (name) => instance.on(name, (e) => {
2882
+ const fields = { event: name, key: e.key, from: e.from, to: e.to };
2883
+ write(name === "circuitOpen" ? "warn" : "info", `[exios] circuit ${e.key} ${e.from} \u2192 ${e.to}`, fields);
2884
+ })
2885
+ )
2886
+ ];
2887
+ return () => {
2888
+ for (const off of offs) off();
2889
+ };
2890
+ },
2891
+ // Cache hits and deduplicated followers make no network request, so they emit no events.
2892
+ afterResponse(response, config) {
2893
+ const source = response.meta.cached ? "cached" : response.meta.deduped ? "deduped" : void 0;
2894
+ if (!source || RANK.debug < min) return;
2895
+ const c = response.config ?? config;
2896
+ const url = redactURL(buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls));
2897
+ const fields = { event: "cache", source, method: c.method.toUpperCase(), url, status: response.status };
2898
+ if (c.requestId !== void 0) fields.requestId = c.requestId;
2899
+ if (c.correlationId !== void 0) fields.correlationId = c.correlationId;
2900
+ write("debug", `[exios] \u26A1 ${fields.method} ${url} ${source} (${response.status})`, fields);
2901
+ }
2902
+ };
2903
+ }
2733
2904
 
2734
2905
  // src/index.ts
2735
2906
  registerXhrAdapter();
@@ -2743,7 +2914,8 @@ var statics = {
2743
2914
  isCancel,
2744
2915
  mergeConfig,
2745
2916
  toFormData,
2746
- MemoryCache
2917
+ MemoryCache,
2918
+ createLoggerPlugin
2747
2919
  };
2748
2920
  var exios = Object.assign(
2749
2921
  createInstance(createDefaults()),
@@ -2759,6 +2931,7 @@ export {
2759
2931
  ExiosError,
2760
2932
  MemoryCache,
2761
2933
  create,
2934
+ createLoggerPlugin,
2762
2935
  index_default as default,
2763
2936
  isCancel,
2764
2937
  isExiosError,