@indra211/exios 2.0.1 → 3.1.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/dist/index.js CHANGED
@@ -1,3 +1,33 @@
1
+ // src/core/redact.ts
2
+ var REDACTED = "[REDACTED]";
3
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
4
+ "authorization",
5
+ "proxy-authorization",
6
+ "cookie",
7
+ "set-cookie",
8
+ "x-api-key",
9
+ "x-auth-token",
10
+ "x-xsrf-token",
11
+ "x-csrf-token"
12
+ ]);
13
+ function redactHeaders(headers) {
14
+ if (!headers || typeof headers !== "object") return headers;
15
+ const out = {};
16
+ for (const [k, v] of Object.entries(headers))
17
+ out[k] = SENSITIVE_HEADERS.has(k.toLowerCase()) ? REDACTED : v;
18
+ return out;
19
+ }
20
+ function redactConfig(config) {
21
+ if (!config || typeof config !== "object") return config;
22
+ const c = { ...config };
23
+ if (c.headers && typeof c.headers === "object") c.headers = redactHeaders(c.headers);
24
+ if (c.auth) c.auth = { username: c.auth.username, password: REDACTED };
25
+ if (c.proxy && typeof c.proxy === "object" && c.proxy.auth)
26
+ c.proxy = { ...c.proxy, auth: { username: c.proxy.auth.username, password: REDACTED } };
27
+ if (c.data !== void 0) c.data = REDACTED;
28
+ return c;
29
+ }
30
+
1
31
  // src/errors/ExiosError.ts
2
32
  var ExiosError = class _ExiosError extends Error {
3
33
  static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
@@ -27,13 +57,14 @@ var ExiosError = class _ExiosError extends Error {
27
57
  this.response = response;
28
58
  this.status = response?.status;
29
59
  }
60
+ /** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
30
61
  toJSON() {
31
62
  return {
32
63
  message: this.message,
33
64
  name: this.name,
34
65
  code: this.code,
35
66
  status: this.status,
36
- config: this.config,
67
+ config: redactConfig(this.config),
37
68
  meta: this.meta,
38
69
  stack: this.stack
39
70
  };
@@ -209,8 +240,8 @@ function serializeParams(params, opts = {}) {
209
240
  return parts.join("&");
210
241
  }
211
242
  function buildURL(url, params, serializer) {
212
- const hash = url.indexOf("#");
213
- if (hash !== -1) url = url.slice(0, hash);
243
+ const hash2 = url.indexOf("#");
244
+ if (hash2 !== -1) url = url.slice(0, hash2);
214
245
  if (params === void 0 || params === null) return url;
215
246
  let serialized;
216
247
  if (typeof serializer === "function") serialized = serializer(params);
@@ -1183,14 +1214,16 @@ function defaultIsFailure(o) {
1183
1214
  return status >= 500 || status === 408 || status === 429;
1184
1215
  }
1185
1216
  var CircuitBreaker = class {
1186
- constructor(key, cfg, now = Date.now) {
1217
+ constructor(key, cfg, now = Date.now, onTransition) {
1187
1218
  this.key = key;
1188
1219
  this.cfg = cfg;
1189
1220
  this.now = now;
1221
+ this.onTransition = onTransition;
1190
1222
  }
1191
1223
  key;
1192
1224
  cfg;
1193
1225
  now;
1226
+ onTransition;
1194
1227
  _state = "closed";
1195
1228
  epoch = 0;
1196
1229
  openedAt = 0;
@@ -1294,22 +1327,25 @@ var CircuitBreaker = class {
1294
1327
  this.cfg.onStateChange?.(this.key, from, to);
1295
1328
  } catch {
1296
1329
  }
1330
+ this.onTransition?.(this.key, from, to);
1297
1331
  }
1298
1332
  };
1299
1333
  var BreakerRegistry = class {
1300
- constructor(getConfig, now = Date.now) {
1334
+ constructor(getConfig, now = Date.now, onTransition) {
1301
1335
  this.getConfig = getConfig;
1302
1336
  this.now = now;
1337
+ this.onTransition = onTransition;
1303
1338
  }
1304
1339
  getConfig;
1305
1340
  now;
1341
+ onTransition;
1306
1342
  breakers = /* @__PURE__ */ new Map();
1307
1343
  get(key) {
1308
1344
  const cfg = this.getConfig();
1309
1345
  if (cfg === false) return null;
1310
1346
  let b = this.breakers.get(key);
1311
1347
  if (!b) {
1312
- b = new CircuitBreaker(key, cfg, this.now);
1348
+ b = new CircuitBreaker(key, cfg, this.now, this.onTransition);
1313
1349
  this.breakers.set(key, b);
1314
1350
  }
1315
1351
  return b;
@@ -1414,6 +1450,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
1414
1450
  cancelBody(outcome.response?.data);
1415
1451
  if (hooks.signal?.aborted) throw abortError(hooks.signal);
1416
1452
  cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1453
+ hooks.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1417
1454
  await sleep(delay, hooks.signal);
1418
1455
  hooks.beforeRetry?.();
1419
1456
  }
@@ -1435,7 +1472,7 @@ function defaultBreakerKey(config) {
1435
1472
  return full;
1436
1473
  }
1437
1474
  }
1438
- async function dispatchRequest(config, registry2) {
1475
+ async function dispatchRequest(config, registry2, observer) {
1439
1476
  const token = config.cancelToken;
1440
1477
  if (token) {
1441
1478
  if (token.reason) {
@@ -1452,7 +1489,8 @@ async function dispatchRequest(config, registry2) {
1452
1489
  try {
1453
1490
  const response = await dispatchRequest(
1454
1491
  { ...config, signal: joined.signal, cancelToken: void 0 },
1455
- registry2
1492
+ registry2,
1493
+ observer
1456
1494
  );
1457
1495
  if (isOneShotBody(response.data)) {
1458
1496
  response.data = whenBodyDone(response.data, release);
@@ -1471,6 +1509,7 @@ async function dispatchRequest(config, registry2) {
1471
1509
  const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
1472
1510
  const ticket = breaker?.acquire(config);
1473
1511
  let attempts = 0;
1512
+ let responseTimeMs;
1474
1513
  try {
1475
1514
  let adapter;
1476
1515
  try {
@@ -1483,15 +1522,31 @@ async function dispatchRequest(config, registry2) {
1483
1522
  try {
1484
1523
  result = await runWithRetry(
1485
1524
  () => {
1486
- attempts++;
1487
- return adapter(config);
1525
+ const n = ++attempts;
1526
+ const t0 = Date.now();
1527
+ const failed = (e) => {
1528
+ responseTimeMs = Date.now() - t0;
1529
+ if (isExiosError(e)) observer?.onAttemptError?.(n, e);
1530
+ throw e;
1531
+ };
1532
+ let result2;
1533
+ try {
1534
+ result2 = Promise.resolve(adapter(config));
1535
+ } catch (e) {
1536
+ return failed(e);
1537
+ }
1538
+ return result2.then((r) => {
1539
+ responseTimeMs = Date.now() - t0;
1540
+ return r;
1541
+ }, failed);
1488
1542
  },
1489
1543
  ticket?.probe ? false : config.retry,
1490
1544
  // half-open probes get exactly one attempt
1491
1545
  config,
1492
1546
  {
1493
1547
  signal: config.signal,
1494
- beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
1548
+ beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0,
1549
+ onRetry: observer?.onRetry
1495
1550
  }
1496
1551
  );
1497
1552
  } catch (e) {
@@ -1510,6 +1565,7 @@ async function dispatchRequest(config, registry2) {
1510
1565
  if (outcome.error) throw outcome.error;
1511
1566
  const response = outcome.response;
1512
1567
  response.meta.attempts = attempts;
1568
+ if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
1513
1569
  const { status } = response;
1514
1570
  if (config.validateStatus && !config.validateStatus(status)) {
1515
1571
  const err = new ExiosError(
@@ -1528,6 +1584,53 @@ async function dispatchRequest(config, registry2) {
1528
1584
  }
1529
1585
  }
1530
1586
 
1587
+ // src/core/events.ts
1588
+ var EventHub = class {
1589
+ listeners = /* @__PURE__ */ new Map();
1590
+ on(name, listener) {
1591
+ if (typeof listener !== "function")
1592
+ throw new TypeError(`exios: listener for "${name}" must be a function`);
1593
+ let set = this.listeners.get(name);
1594
+ if (!set) this.listeners.set(name, set = /* @__PURE__ */ new Set());
1595
+ set.add(listener);
1596
+ return () => this.off(name, listener);
1597
+ }
1598
+ once(name, listener) {
1599
+ const off = this.on(name, (e) => {
1600
+ off();
1601
+ listener(e);
1602
+ });
1603
+ return off;
1604
+ }
1605
+ off(name, listener) {
1606
+ const set = this.listeners.get(name);
1607
+ if (!set) return;
1608
+ if (listener === void 0) set.clear();
1609
+ else set.delete(listener);
1610
+ if (set.size === 0) this.listeners.delete(name);
1611
+ }
1612
+ has(name) {
1613
+ return this.listeners.has(name);
1614
+ }
1615
+ listenerCount(name) {
1616
+ return this.listeners.get(name)?.size ?? 0;
1617
+ }
1618
+ /** Build the payload only when someone listens: `emit('x', () => ({ ... }))`. */
1619
+ emit(name, payload) {
1620
+ const set = this.listeners.get(name);
1621
+ if (!set) return;
1622
+ const event = payload();
1623
+ for (const l of [...set]) {
1624
+ try {
1625
+ l(event);
1626
+ } catch (err) {
1627
+ if (typeof console !== "undefined")
1628
+ console.error(`[exios] "${name}" listener threw:`, err);
1629
+ }
1630
+ }
1631
+ }
1632
+ };
1633
+
1531
1634
  // src/core/InterceptorManager.ts
1532
1635
  var InterceptorManager = class {
1533
1636
  handlers = [];
@@ -1658,7 +1761,14 @@ var isPlainObject3 = (v) => {
1658
1761
  return p === Object.prototype || p === null;
1659
1762
  };
1660
1763
  var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
1661
- var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
1764
+ var SHALLOW_MERGE = /* @__PURE__ */ new Set([
1765
+ "auth",
1766
+ "transitional",
1767
+ "fetchOptions",
1768
+ "metadata",
1769
+ "cache",
1770
+ "dedupe"
1771
+ ]);
1662
1772
  function setCI(target, k, v) {
1663
1773
  const lk = k.toLowerCase();
1664
1774
  for (const existing of Object.keys(target)) {
@@ -1764,7 +1874,231 @@ function assertRequestBreaker(b) {
1764
1874
  }
1765
1875
  }
1766
1876
 
1877
+ // src/core/dedupe.ts
1878
+ var InflightRequests = class {
1879
+ flights = /* @__PURE__ */ new Map();
1880
+ get size() {
1881
+ return this.flights.size;
1882
+ }
1883
+ /**
1884
+ * Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
1885
+ * signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
1886
+ */
1887
+ join(key, config, start) {
1888
+ const token = config.cancelToken;
1889
+ if (token?.reason) {
1890
+ token.reason.config ??= config;
1891
+ return Promise.reject(token.reason);
1892
+ }
1893
+ const tokenSignal = token?.toAbortSignal();
1894
+ const signals = [config.signal, tokenSignal].filter((s) => !!s);
1895
+ const aborted = signals.find((s) => s.aborted);
1896
+ if (aborted) {
1897
+ tokenSignal?.unsubscribe();
1898
+ return Promise.reject(abortError(aborted, config));
1899
+ }
1900
+ let flight = this.flights.get(key);
1901
+ const leader = !flight;
1902
+ if (!flight) {
1903
+ const controller = new AbortController();
1904
+ const f2 = { controller, subscribers: 0, promise: void 0 };
1905
+ f2.promise = start(controller.signal).finally(() => {
1906
+ if (this.flights.get(key) === f2) this.flights.delete(key);
1907
+ });
1908
+ this.flights.set(key, f2);
1909
+ flight = f2;
1910
+ }
1911
+ const f = flight;
1912
+ f.subscribers++;
1913
+ return new Promise((resolve, reject) => {
1914
+ let settled = false;
1915
+ const detach = () => {
1916
+ settled = true;
1917
+ for (const s of signals) s.removeEventListener("abort", onAbort);
1918
+ tokenSignal?.unsubscribe();
1919
+ };
1920
+ const onAbort = (ev) => {
1921
+ if (settled) return;
1922
+ detach();
1923
+ const reason = abortError(ev.target, config);
1924
+ reject(reason);
1925
+ if (--f.subscribers === 0) {
1926
+ if (this.flights.get(key) === f) this.flights.delete(key);
1927
+ f.controller.abort(reason);
1928
+ }
1929
+ };
1930
+ for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
1931
+ f.promise.then(
1932
+ (response) => {
1933
+ if (settled) return;
1934
+ detach();
1935
+ f.subscribers--;
1936
+ resolve({ response, leader });
1937
+ },
1938
+ (err) => {
1939
+ if (settled) return;
1940
+ detach();
1941
+ f.subscribers--;
1942
+ reject(err);
1943
+ }
1944
+ );
1945
+ });
1946
+ }
1947
+ };
1948
+
1949
+ // src/core/requestCache.ts
1950
+ var SAFE_METHODS = Object.freeze(["get", "head"]);
1951
+ var MemoryCache = class {
1952
+ map = /* @__PURE__ */ new Map();
1953
+ maxEntries;
1954
+ constructor(options = {}) {
1955
+ const max = options.maxEntries ?? 100;
1956
+ if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
1957
+ this.maxEntries = max;
1958
+ }
1959
+ get size() {
1960
+ return this.map.size;
1961
+ }
1962
+ get(key) {
1963
+ const entry = this.map.get(key);
1964
+ if (!entry) return void 0;
1965
+ this.map.delete(key);
1966
+ if (entry.expiresAt <= Date.now()) return void 0;
1967
+ this.map.set(key, entry);
1968
+ return entry;
1969
+ }
1970
+ set(key, entry) {
1971
+ this.map.delete(key);
1972
+ this.map.set(key, entry);
1973
+ while (this.map.size > this.maxEntries)
1974
+ this.map.delete(this.map.keys().next().value);
1975
+ }
1976
+ delete(key) {
1977
+ this.map.delete(key);
1978
+ }
1979
+ clear() {
1980
+ this.map.clear();
1981
+ }
1982
+ keys() {
1983
+ return [...this.map.keys()];
1984
+ }
1985
+ };
1986
+ function hash(str) {
1987
+ let h1 = 3735928559;
1988
+ let h2 = 1103547991;
1989
+ for (let i = 0; i < str.length; i++) {
1990
+ const ch = str.charCodeAt(i);
1991
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1992
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1993
+ }
1994
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1995
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1996
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
1997
+ }
1998
+ var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
1999
+ function requestTarget(config) {
2000
+ const url = buildURL(
2001
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
2002
+ config.params,
2003
+ config.paramsSerializer
2004
+ );
2005
+ return `${(config.method ?? "get").toUpperCase()} ${url}`;
2006
+ }
2007
+ function defaultRequestKey(config) {
2008
+ const skip = config.correlationIdHeader?.toLowerCase();
2009
+ const parts = [];
2010
+ for (const k of Object.keys(config.headers).sort())
2011
+ if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2012
+ if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2013
+ parts.push(`rt:${config.responseType ?? ""}`);
2014
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2015
+ }
2016
+ function keyURL(key) {
2017
+ const sp = key.indexOf(" ");
2018
+ const h = key.lastIndexOf(" #");
2019
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2020
+ }
2021
+ function keyFor(config, opts) {
2022
+ if (!opts.methods.includes(config.method)) return void 0;
2023
+ if (config.responseType === "stream") return void 0;
2024
+ if (opts.key) return opts.key(config);
2025
+ if (config.data !== void 0) return void 0;
2026
+ return defaultRequestKey(config);
2027
+ }
2028
+ function checkMethods(name, m) {
2029
+ if (!Array.isArray(m)) bad(name, m, "an array");
2030
+ return m.map((x) => String(x).toLowerCase());
2031
+ }
2032
+ function resolveDedupe(v) {
2033
+ if (v === void 0 || v === false) return false;
2034
+ if (v === true) return { methods: [...SAFE_METHODS] };
2035
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2036
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2037
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2038
+ }
2039
+ function resolveCache(v) {
2040
+ if (v === void 0 || v === false) return false;
2041
+ const o = v === true ? {} : v;
2042
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2043
+ const ttl = o.ttl ?? 6e4;
2044
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2045
+ bad("cache.ttl", ttl, "a finite number > 0");
2046
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2047
+ const p = o.provider;
2048
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2049
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2050
+ return {
2051
+ ttl,
2052
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2053
+ key: o.key,
2054
+ provider: p,
2055
+ respectCacheControl: o.respectCacheControl ?? true
2056
+ };
2057
+ }
2058
+ function parseCacheControl(value) {
2059
+ const out = /* @__PURE__ */ new Map();
2060
+ const raw = Array.isArray(value) ? value.join(",") : value;
2061
+ if (typeof raw !== "string") return out;
2062
+ for (const part of raw.split(",")) {
2063
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2064
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2065
+ }
2066
+ return out;
2067
+ }
2068
+ function cloneData(data) {
2069
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2070
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2071
+ try {
2072
+ return { ok: true, value: structuredClone(data) };
2073
+ } catch {
2074
+ return { ok: false, value: data };
2075
+ }
2076
+ }
2077
+ function reportCacheError(op, err) {
2078
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2079
+ }
2080
+
2081
+ // src/core/requestId.ts
2082
+ var seq = 0;
2083
+ function createRequestId() {
2084
+ const c = globalThis.crypto;
2085
+ if (typeof c?.randomUUID === "function") {
2086
+ try {
2087
+ return c.randomUUID();
2088
+ } catch {
2089
+ }
2090
+ }
2091
+ seq = (seq + 1) % Number.MAX_SAFE_INTEGER;
2092
+ return `${Date.now().toString(36)}-${seq.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2093
+ }
2094
+
1767
2095
  // src/core/Exios.ts
2096
+ var CIRCUIT_EVENTS = {
2097
+ open: "circuitOpen",
2098
+ "half-open": "circuitHalfOpen",
2099
+ closed: "circuitClose"
2100
+ };
2101
+ var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ECONNABORTED", "ETIMEDOUT"]);
1768
2102
  var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
1769
2103
  var Exios = class {
1770
2104
  defaults;
@@ -1774,15 +2108,71 @@ var Exios = class {
1774
2108
  };
1775
2109
  breaker;
1776
2110
  registry;
2111
+ events = new EventHub();
2112
+ memoryCache = new MemoryCache();
2113
+ inflight = new InflightRequests();
2114
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2115
+ cache;
1777
2116
  constructor(defaults) {
1778
2117
  this.defaults = defaults;
1779
2118
  this.registry = new BreakerRegistry(
1780
- () => resolveBreaker(this.defaults.breaker)
2119
+ () => resolveBreaker(this.defaults.breaker),
2120
+ Date.now,
2121
+ (key, from, to) => this.events.emit(CIRCUIT_EVENTS[to], () => ({
2122
+ key,
2123
+ from,
2124
+ to,
2125
+ timestamp: Date.now()
2126
+ }))
1781
2127
  );
1782
2128
  this.breaker = {
1783
2129
  state: (key) => this.registry.state(key),
1784
2130
  reset: (key) => this.registry.reset(key)
1785
2131
  };
2132
+ const provider = () => {
2133
+ const c = this.defaults.cache;
2134
+ return typeof c === "object" && c?.provider || this.memoryCache;
2135
+ };
2136
+ this.cache = {
2137
+ clear: async () => {
2138
+ await provider().clear();
2139
+ },
2140
+ delete: async (key) => {
2141
+ await provider().delete(key);
2142
+ },
2143
+ key: (cfg = {}) => {
2144
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2145
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2146
+ return c ? keyFor(resolved, c) : void 0;
2147
+ },
2148
+ invalidate: async (match) => {
2149
+ const p = provider();
2150
+ if (typeof p.keys !== "function")
2151
+ throw new ExiosError(
2152
+ "cache.invalidate needs a cache provider with keys()",
2153
+ ExiosError.ERR_NOT_SUPPORT
2154
+ );
2155
+ let test;
2156
+ if (typeof match === "function") test = match;
2157
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2158
+ else {
2159
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2160
+ const prefix = target.slice(target.indexOf(" ") + 1);
2161
+ test = (k) => {
2162
+ const u = keyURL(k);
2163
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2164
+ };
2165
+ }
2166
+ let n = 0;
2167
+ for (const k of [...await p.keys()]) {
2168
+ if (test(k)) {
2169
+ await p.delete(k);
2170
+ n++;
2171
+ }
2172
+ }
2173
+ return n;
2174
+ }
2175
+ };
1786
2176
  }
1787
2177
  async request(configOrUrl, config) {
1788
2178
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -1795,7 +2185,7 @@ var Exios = class {
1795
2185
  synchronous = synchronous && h.synchronous;
1796
2186
  requestChain.unshift(h);
1797
2187
  });
1798
- const dispatch = (c) => dispatchRequest(finalizeConfig(c), this.registry);
2188
+ const dispatch = (c) => this.dispatch(finalizeConfig(c));
1799
2189
  let promise;
1800
2190
  if (synchronous) {
1801
2191
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -1813,6 +2203,232 @@ var Exios = class {
1813
2203
  });
1814
2204
  return promise;
1815
2205
  }
2206
+ /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2207
+ on(name, listener) {
2208
+ return this.events.on(name, listener);
2209
+ }
2210
+ /** Like `on`, but the listener runs at most once. */
2211
+ once(name, listener) {
2212
+ return this.events.once(name, listener);
2213
+ }
2214
+ /** Remove one listener, or every listener of `name` when `listener` is omitted. */
2215
+ off(name, listener) {
2216
+ this.events.off(name, listener);
2217
+ }
2218
+ /**
2219
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2220
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2221
+ */
2222
+ async dispatch(config) {
2223
+ const start = Date.now();
2224
+ config.requestId ??= createRequestId();
2225
+ const totalTimeout = config.totalTimeout ?? 0;
2226
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2227
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2228
+ const cacheCfg = resolveCache(config.cache);
2229
+ const dedupeCfg = resolveDedupe(config.dedupe);
2230
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2231
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2232
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2233
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2234
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2235
+ let entry;
2236
+ try {
2237
+ entry = await provider.get(cacheKey);
2238
+ } catch (e) {
2239
+ reportCacheError("get", e);
2240
+ }
2241
+ if (entry && entry.expiresAt > Date.now()) {
2242
+ const copy2 = cloneData(entry.data);
2243
+ return this.localResponse(config, start, {
2244
+ data: copy2.value,
2245
+ status: entry.status,
2246
+ statusText: entry.statusText,
2247
+ headers: { ...entry.headers },
2248
+ request: null,
2249
+ meta: { attempts: 0, cached: true }
2250
+ });
2251
+ }
2252
+ }
2253
+ const header = config.correlationIdHeader?.toLowerCase();
2254
+ if (header && config.headers[header] === void 0)
2255
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2256
+ const network = async (c) => {
2257
+ const response2 = await this.network(c, start, totalTimeout);
2258
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2259
+ this.store(provider, cacheKey, response2, cacheCfg);
2260
+ return response2;
2261
+ };
2262
+ if (dedupeKey === void 0) return network(config);
2263
+ const { response, leader } = await this.inflight.join(
2264
+ dedupeKey,
2265
+ config,
2266
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2267
+ );
2268
+ if (leader) return response;
2269
+ const copy = cloneData(response.data);
2270
+ return this.localResponse(config, start, {
2271
+ ...response,
2272
+ data: copy.value,
2273
+ headers: { ...response.headers },
2274
+ meta: { attempts: response.meta.attempts, deduped: true }
2275
+ });
2276
+ }
2277
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2278
+ localResponse(config, start, r) {
2279
+ r.meta.requestId = config.requestId;
2280
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2281
+ r.meta.durationMs = Date.now() - start;
2282
+ return { ...r, config };
2283
+ }
2284
+ /** Store a successful response; provider failures are reported, never thrown. */
2285
+ store(provider, key, response, cfg) {
2286
+ if (response.status < 200 || response.status >= 300) return;
2287
+ let ttl = cfg.ttl;
2288
+ if (cfg.respectCacheControl) {
2289
+ const cc = parseCacheControl(response.headers["cache-control"]);
2290
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2291
+ const maxAge = Number(cc.get("max-age"));
2292
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2293
+ }
2294
+ if (ttl <= 0) return;
2295
+ const copy = cloneData(response.data);
2296
+ if (!copy.ok) return;
2297
+ const now = Date.now();
2298
+ try {
2299
+ const r = provider.set(key, {
2300
+ status: response.status,
2301
+ statusText: response.statusText,
2302
+ headers: { ...response.headers },
2303
+ data: copy.value,
2304
+ storedAt: now,
2305
+ expiresAt: now + ttl
2306
+ });
2307
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2308
+ } catch (e) {
2309
+ reportCacheError("set", e);
2310
+ }
2311
+ }
2312
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2313
+ async network(config, start, totalTimeout) {
2314
+ const requestId = config.requestId;
2315
+ const { correlationId, metadata } = config;
2316
+ const hub = this.events;
2317
+ const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
2318
+ const base = () => ({
2319
+ requestId,
2320
+ correlationId,
2321
+ method: config.method,
2322
+ url,
2323
+ config,
2324
+ metadata,
2325
+ timestamp: Date.now()
2326
+ });
2327
+ const observer = {
2328
+ onRetry: (o) => hub.emit("retry", () => ({
2329
+ ...base(),
2330
+ attempt: o.attempt,
2331
+ delayMs: o.delayMs,
2332
+ error: o.error,
2333
+ status: o.response?.status ?? o.error?.response?.status
2334
+ })),
2335
+ onAttemptError: (attempt, error) => {
2336
+ if (TIMEOUT_CODES.has(error.code ?? ""))
2337
+ hub.emit("timeout", () => ({
2338
+ ...base(),
2339
+ kind: "attempt",
2340
+ attempt,
2341
+ timeoutMs: config.timeout ?? 0,
2342
+ error
2343
+ }));
2344
+ }
2345
+ };
2346
+ let timer;
2347
+ let totalFired = false;
2348
+ let joined;
2349
+ let dispatchConfig = config;
2350
+ if (totalTimeout > 0) {
2351
+ const ac = new AbortController();
2352
+ timer = setTimeout(() => {
2353
+ totalFired = true;
2354
+ ac.abort(new Error("totalTimeout"));
2355
+ }, totalTimeout);
2356
+ joined = combineSignals(config.signal, ac.signal);
2357
+ dispatchConfig = { ...config, signal: joined.signal };
2358
+ }
2359
+ let deferCleanup = false;
2360
+ hub.emit("request", base);
2361
+ try {
2362
+ let response;
2363
+ try {
2364
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2365
+ } catch (e) {
2366
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2367
+ const err = new ExiosError(
2368
+ `total timeout of ${totalTimeout}ms exceeded`,
2369
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2370
+ config,
2371
+ e.request
2372
+ );
2373
+ err.cause = e;
2374
+ err.meta.attempts = e.meta.attempts;
2375
+ hub.emit("timeout", () => ({
2376
+ ...base(),
2377
+ kind: "total",
2378
+ attempt: err.meta.attempts,
2379
+ timeoutMs: totalTimeout,
2380
+ error: err
2381
+ }));
2382
+ throw err;
2383
+ }
2384
+ if (joined && isOneShotBody(response.data)) {
2385
+ response.data = whenBodyDone(response.data, joined.cleanup);
2386
+ deferCleanup = true;
2387
+ }
2388
+ const durationMs = Date.now() - start;
2389
+ const meta = response.meta;
2390
+ meta.requestId = requestId;
2391
+ if (correlationId !== void 0) meta.correlationId = correlationId;
2392
+ meta.durationMs = durationMs;
2393
+ hub.emit("response", () => ({
2394
+ ...base(),
2395
+ response,
2396
+ status: response.status,
2397
+ attempts: meta.attempts,
2398
+ durationMs,
2399
+ responseTimeMs: meta.responseTimeMs ?? durationMs
2400
+ }));
2401
+ return response;
2402
+ } catch (e) {
2403
+ const durationMs = Date.now() - start;
2404
+ let attempts = 0;
2405
+ if (isExiosError(e)) {
2406
+ const meta = e.meta;
2407
+ meta.requestId ??= requestId;
2408
+ if (correlationId !== void 0) meta.correlationId ??= correlationId;
2409
+ meta.method ??= config.method;
2410
+ meta.url ??= url;
2411
+ meta.durationMs ??= durationMs;
2412
+ attempts = meta.attempts;
2413
+ }
2414
+ if (isCancel(e)) {
2415
+ hub.emit("canceled", () => ({ ...base(), error: e, attempts, durationMs }));
2416
+ } else {
2417
+ hub.emit("error", () => ({
2418
+ ...base(),
2419
+ error: e,
2420
+ code: isExiosError(e) ? e.code : void 0,
2421
+ status: isExiosError(e) ? e.status ?? e.response?.status : void 0,
2422
+ attempts,
2423
+ durationMs
2424
+ }));
2425
+ }
2426
+ throw e;
2427
+ } finally {
2428
+ if (timer !== void 0) clearTimeout(timer);
2429
+ if (joined && !deferCleanup) joined.cleanup();
2430
+ }
2431
+ }
1816
2432
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
1817
2433
  runSync(chain, config, dispatch) {
1818
2434
  let value = config;
@@ -1890,6 +2506,9 @@ var Exios = class {
1890
2506
  };
1891
2507
  var METHODS = [
1892
2508
  "request",
2509
+ "on",
2510
+ "once",
2511
+ "off",
1893
2512
  "getUri",
1894
2513
  "get",
1895
2514
  "delete",
@@ -1920,7 +2539,10 @@ function detachDefaults(d) {
1920
2539
  "transitional",
1921
2540
  "fetchOptions",
1922
2541
  "auth",
1923
- "breaker"
2542
+ "breaker",
2543
+ "metadata",
2544
+ "cache",
2545
+ "dedupe"
1924
2546
  ]) {
1925
2547
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
1926
2548
  }
@@ -1950,6 +2572,7 @@ function createInstance(defaults) {
1950
2572
  });
1951
2573
  instance.interceptors = context.interceptors;
1952
2574
  instance.breaker = context.breaker;
2575
+ instance.cache = context.cache;
1953
2576
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
1954
2577
  return instance;
1955
2578
  }
@@ -1965,7 +2588,8 @@ var statics = {
1965
2588
  isExiosError,
1966
2589
  isCancel,
1967
2590
  mergeConfig,
1968
- toFormData
2591
+ toFormData,
2592
+ MemoryCache
1969
2593
  };
1970
2594
  var exios = Object.assign(
1971
2595
  createInstance(createDefaults()),
@@ -1978,6 +2602,7 @@ export {
1978
2602
  CanceledError,
1979
2603
  CircuitOpenError,
1980
2604
  ExiosError,
2605
+ MemoryCache,
1981
2606
  create,
1982
2607
  index_default as default,
1983
2608
  isCancel,