@indra211/exios 3.0.0 → 3.1.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/dist/index.js CHANGED
@@ -213,8 +213,8 @@ function encode(s) {
213
213
  }
214
214
  function isPlainObject(v) {
215
215
  if (v === null || typeof v !== "object") return false;
216
- const proto = Object.getPrototypeOf(v);
217
- return proto === Object.prototype || proto === null;
216
+ const proto2 = Object.getPrototypeOf(v);
217
+ return proto2 === Object.prototype || proto2 === null;
218
218
  }
219
219
  function serializeParams(params, opts = {}) {
220
220
  if (params === void 0 || params === null) return "";
@@ -240,8 +240,8 @@ function serializeParams(params, opts = {}) {
240
240
  return parts.join("&");
241
241
  }
242
242
  function buildURL(url, params, serializer) {
243
- const hash = url.indexOf("#");
244
- if (hash !== -1) url = url.slice(0, hash);
243
+ const hash2 = url.indexOf("#");
244
+ if (hash2 !== -1) url = url.slice(0, hash2);
245
245
  if (params === void 0 || params === null) return url;
246
246
  let serialized;
247
247
  if (typeof serializer === "function") serialized = serializer(params);
@@ -282,8 +282,8 @@ function toFormData(obj, fd = new FormData()) {
282
282
  // src/core/transforms.ts
283
283
  function isPlainObject2(v) {
284
284
  if (v === null || typeof v !== "object") return false;
285
- const proto = Object.getPrototypeOf(v);
286
- return proto === Object.prototype || proto === null;
285
+ const proto2 = Object.getPrototypeOf(v);
286
+ return proto2 === Object.prototype || proto2 === null;
287
287
  }
288
288
  function isPassThrough(data) {
289
289
  return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams || isNodeStream(data);
@@ -1761,7 +1761,14 @@ var isPlainObject3 = (v) => {
1761
1761
  return p === Object.prototype || p === null;
1762
1762
  };
1763
1763
  var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
1764
- 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
+ ]);
1765
1772
  function setCI(target, k, v) {
1766
1773
  const lk = k.toLowerCase();
1767
1774
  for (const existing of Object.keys(target)) {
@@ -1867,6 +1874,275 @@ function assertRequestBreaker(b) {
1867
1874
  }
1868
1875
  }
1869
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, scope = "cache") {
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
+ parts.push(
2015
+ `shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
2016
+ );
2017
+ if (scope === "dedupe") {
2018
+ parts.push(
2019
+ `policy:${fingerprint([
2020
+ config.timeout,
2021
+ config.totalTimeout,
2022
+ config.validateStatus,
2023
+ config.retry,
2024
+ config.breaker,
2025
+ config.adapter,
2026
+ config.maxContentLength,
2027
+ config.maxRedirects,
2028
+ config.transitional
2029
+ ])}`
2030
+ );
2031
+ }
2032
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2033
+ }
2034
+ var fnIds = /* @__PURE__ */ new WeakMap();
2035
+ var nextFnId = 0;
2036
+ function fingerprint(v) {
2037
+ if (typeof v === "function") {
2038
+ let id = fnIds.get(v);
2039
+ if (id === void 0) fnIds.set(v, id = ++nextFnId);
2040
+ return `f${id}`;
2041
+ }
2042
+ if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
2043
+ if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
2044
+ const o = v;
2045
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
2046
+ }
2047
+ function keyURL(key) {
2048
+ const sp = key.indexOf(" ");
2049
+ const h = key.lastIndexOf(" #");
2050
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2051
+ }
2052
+ function keyFor(config, opts, scope = "cache") {
2053
+ if (!opts.methods.includes(config.method)) return void 0;
2054
+ if (config.responseType === "stream") return void 0;
2055
+ if (opts.key) return opts.key(config);
2056
+ if (config.data !== void 0) return void 0;
2057
+ return defaultRequestKey(config, scope);
2058
+ }
2059
+ function checkMethods(name, m) {
2060
+ if (!Array.isArray(m)) bad(name, m, "an array");
2061
+ return m.map((x) => String(x).toLowerCase());
2062
+ }
2063
+ function resolveDedupe(v) {
2064
+ if (v === void 0 || v === false) return false;
2065
+ if (v === true) return { methods: [...SAFE_METHODS] };
2066
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2067
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2068
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2069
+ }
2070
+ function resolveCache(v) {
2071
+ if (v === void 0 || v === false) return false;
2072
+ const o = v === true ? {} : v;
2073
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2074
+ const ttl = o.ttl ?? 6e4;
2075
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2076
+ bad("cache.ttl", ttl, "a finite number > 0");
2077
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2078
+ const p = o.provider;
2079
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2080
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2081
+ return {
2082
+ ttl,
2083
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2084
+ key: o.key,
2085
+ provider: p,
2086
+ respectCacheControl: o.respectCacheControl ?? true
2087
+ };
2088
+ }
2089
+ function parseCacheControl(value) {
2090
+ const out = /* @__PURE__ */ new Map();
2091
+ const raw = Array.isArray(value) ? value.join(",") : value;
2092
+ if (typeof raw !== "string") return out;
2093
+ for (const part of raw.split(",")) {
2094
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2095
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2096
+ }
2097
+ return out;
2098
+ }
2099
+ function cloneData(data) {
2100
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2101
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2102
+ if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
2103
+ try {
2104
+ return { ok: true, value: structuredClone(data) };
2105
+ } catch {
2106
+ return { ok: false, value: data };
2107
+ }
2108
+ }
2109
+ var proto = (v) => Object.getPrototypeOf(v);
2110
+ var VIEW_TYPES = [
2111
+ "Int8Array",
2112
+ "Uint8Array",
2113
+ "Uint8ClampedArray",
2114
+ "Int16Array",
2115
+ "Uint16Array",
2116
+ "Int32Array",
2117
+ "Uint32Array",
2118
+ "Float32Array",
2119
+ "Float64Array",
2120
+ "BigInt64Array",
2121
+ "BigUint64Array",
2122
+ "DataView"
2123
+ ];
2124
+ var isType = (v, name) => {
2125
+ const C = globalThis[name];
2126
+ return typeof C === "function" && v instanceof C;
2127
+ };
2128
+ function clonesFaithfully(v, seen) {
2129
+ if (typeof v === "function" || typeof v === "symbol") return false;
2130
+ if (v === null || typeof v !== "object") return true;
2131
+ if (seen.has(v)) return true;
2132
+ seen.add(v);
2133
+ if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
2134
+ if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
2135
+ if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
2136
+ const p = proto(v);
2137
+ if (p === Object.prototype || p === null)
2138
+ return Object.values(v).every((x) => clonesFaithfully(x, seen));
2139
+ return p === Date.prototype || p === RegExp.prototype || p === ArrayBuffer.prototype || VIEW_TYPES.some((name) => p === globalThis[name]?.prototype) || // exact built-ins only: byte-array subclasses would come back as Uint8Array
2140
+ isType(v, "Blob") || isType(v, "FormData");
2141
+ }
2142
+ function reportCacheError(op, err) {
2143
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2144
+ }
2145
+
1870
2146
  // src/core/requestId.ts
1871
2147
  var seq = 0;
1872
2148
  function createRequestId() {
@@ -1898,6 +2174,10 @@ var Exios = class {
1898
2174
  breaker;
1899
2175
  registry;
1900
2176
  events = new EventHub();
2177
+ memoryCache = new MemoryCache();
2178
+ inflight = new InflightRequests();
2179
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2180
+ cache;
1901
2181
  constructor(defaults) {
1902
2182
  this.defaults = defaults;
1903
2183
  this.registry = new BreakerRegistry(
@@ -1914,6 +2194,50 @@ var Exios = class {
1914
2194
  state: (key) => this.registry.state(key),
1915
2195
  reset: (key) => this.registry.reset(key)
1916
2196
  };
2197
+ const provider = () => {
2198
+ const c = this.defaults.cache;
2199
+ return typeof c === "object" && c?.provider || this.memoryCache;
2200
+ };
2201
+ this.cache = {
2202
+ clear: async () => {
2203
+ await provider().clear();
2204
+ },
2205
+ delete: async (key) => {
2206
+ await provider().delete(key);
2207
+ },
2208
+ key: (cfg = {}) => {
2209
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2210
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2211
+ return c ? keyFor(resolved, c) : void 0;
2212
+ },
2213
+ invalidate: async (match) => {
2214
+ const p = provider();
2215
+ if (typeof p.keys !== "function")
2216
+ throw new ExiosError(
2217
+ "cache.invalidate needs a cache provider with keys()",
2218
+ ExiosError.ERR_NOT_SUPPORT
2219
+ );
2220
+ let test;
2221
+ if (typeof match === "function") test = match;
2222
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2223
+ else {
2224
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2225
+ const prefix = target.slice(target.indexOf(" ") + 1);
2226
+ test = (k) => {
2227
+ const u = keyURL(k);
2228
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2229
+ };
2230
+ }
2231
+ let n = 0;
2232
+ for (const k of [...await p.keys()]) {
2233
+ if (test(k)) {
2234
+ await p.delete(k);
2235
+ n++;
2236
+ }
2237
+ }
2238
+ return n;
2239
+ }
2240
+ };
1917
2241
  }
1918
2242
  async request(configOrUrl, config) {
1919
2243
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -1956,13 +2280,104 @@ var Exios = class {
1956
2280
  off(name, listener) {
1957
2281
  this.events.off(name, listener);
1958
2282
  }
1959
- /** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
2283
+ /**
2284
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2285
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2286
+ */
1960
2287
  async dispatch(config) {
1961
- const requestId = config.requestId ??= createRequestId();
1962
- const { correlationId } = config;
2288
+ const start = Date.now();
2289
+ config.requestId ??= createRequestId();
2290
+ const totalTimeout = config.totalTimeout ?? 0;
2291
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2292
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2293
+ const cacheCfg = resolveCache(config.cache);
2294
+ const dedupeCfg = resolveDedupe(config.dedupe);
2295
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2296
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
2297
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2298
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2299
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2300
+ let entry;
2301
+ try {
2302
+ entry = await provider.get(cacheKey);
2303
+ } catch (e) {
2304
+ reportCacheError("get", e);
2305
+ }
2306
+ if (entry && entry.expiresAt > Date.now()) {
2307
+ const copy2 = cloneData(entry.data);
2308
+ return this.localResponse(config, start, {
2309
+ data: copy2.value,
2310
+ status: entry.status,
2311
+ statusText: entry.statusText,
2312
+ headers: { ...entry.headers },
2313
+ request: null,
2314
+ meta: { attempts: 0, cached: true }
2315
+ });
2316
+ }
2317
+ }
1963
2318
  const header = config.correlationIdHeader?.toLowerCase();
1964
2319
  if (header && config.headers[header] === void 0)
1965
- config.headers = { ...config.headers, [header]: correlationId ?? requestId };
2320
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2321
+ const network = async (c) => {
2322
+ const response2 = await this.network(c, start, totalTimeout);
2323
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2324
+ this.store(provider, cacheKey, response2, cacheCfg);
2325
+ return response2;
2326
+ };
2327
+ if (dedupeKey === void 0) return network(config);
2328
+ const { response, leader } = await this.inflight.join(
2329
+ dedupeKey,
2330
+ config,
2331
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2332
+ );
2333
+ if (leader) return response;
2334
+ const copy = cloneData(response.data);
2335
+ return this.localResponse(config, start, {
2336
+ ...response,
2337
+ data: copy.value,
2338
+ headers: { ...response.headers },
2339
+ meta: { attempts: response.meta.attempts, deduped: true }
2340
+ });
2341
+ }
2342
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2343
+ localResponse(config, start, r) {
2344
+ r.meta.requestId = config.requestId;
2345
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2346
+ r.meta.durationMs = Date.now() - start;
2347
+ return { ...r, config };
2348
+ }
2349
+ /** Store a successful response; provider failures are reported, never thrown. */
2350
+ store(provider, key, response, cfg) {
2351
+ if (response.status < 200 || response.status >= 300) return;
2352
+ let ttl = cfg.ttl;
2353
+ if (cfg.respectCacheControl) {
2354
+ const cc = parseCacheControl(response.headers["cache-control"]);
2355
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2356
+ const maxAge = Number(cc.get("max-age"));
2357
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2358
+ }
2359
+ if (ttl <= 0) return;
2360
+ const copy = cloneData(response.data);
2361
+ if (!copy.ok) return;
2362
+ const now = Date.now();
2363
+ try {
2364
+ const r = provider.set(key, {
2365
+ status: response.status,
2366
+ statusText: response.statusText,
2367
+ headers: { ...response.headers },
2368
+ data: copy.value,
2369
+ storedAt: now,
2370
+ expiresAt: now + ttl
2371
+ });
2372
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2373
+ } catch (e) {
2374
+ reportCacheError("set", e);
2375
+ }
2376
+ }
2377
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2378
+ async network(config, start, totalTimeout) {
2379
+ const requestId = config.requestId;
2380
+ const { correlationId, metadata } = config;
1966
2381
  const hub = this.events;
1967
2382
  const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
1968
2383
  const base = () => ({
@@ -1971,9 +2386,9 @@ var Exios = class {
1971
2386
  method: config.method,
1972
2387
  url,
1973
2388
  config,
2389
+ metadata,
1974
2390
  timestamp: Date.now()
1975
2391
  });
1976
- const start = Date.now();
1977
2392
  const observer = {
1978
2393
  onRetry: (o) => hub.emit("retry", () => ({
1979
2394
  ...base(),
@@ -1986,15 +2401,55 @@ var Exios = class {
1986
2401
  if (TIMEOUT_CODES.has(error.code ?? ""))
1987
2402
  hub.emit("timeout", () => ({
1988
2403
  ...base(),
2404
+ kind: "attempt",
1989
2405
  attempt,
1990
2406
  timeoutMs: config.timeout ?? 0,
1991
2407
  error
1992
2408
  }));
1993
2409
  }
1994
2410
  };
2411
+ let timer;
2412
+ let totalFired = false;
2413
+ let joined;
2414
+ let dispatchConfig = config;
2415
+ if (totalTimeout > 0) {
2416
+ const ac = new AbortController();
2417
+ timer = setTimeout(() => {
2418
+ totalFired = true;
2419
+ ac.abort(new Error("totalTimeout"));
2420
+ }, totalTimeout);
2421
+ joined = combineSignals(config.signal, ac.signal);
2422
+ dispatchConfig = { ...config, signal: joined.signal };
2423
+ }
2424
+ let deferCleanup = false;
1995
2425
  hub.emit("request", base);
1996
2426
  try {
1997
- const response = await dispatchRequest(config, this.registry, observer);
2427
+ let response;
2428
+ try {
2429
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2430
+ } catch (e) {
2431
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2432
+ const err = new ExiosError(
2433
+ `total timeout of ${totalTimeout}ms exceeded`,
2434
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2435
+ config,
2436
+ e.request
2437
+ );
2438
+ err.cause = e;
2439
+ err.meta.attempts = e.meta.attempts;
2440
+ hub.emit("timeout", () => ({
2441
+ ...base(),
2442
+ kind: "total",
2443
+ attempt: err.meta.attempts,
2444
+ timeoutMs: totalTimeout,
2445
+ error: err
2446
+ }));
2447
+ throw err;
2448
+ }
2449
+ if (joined && isOneShotBody(response.data)) {
2450
+ response.data = whenBodyDone(response.data, joined.cleanup);
2451
+ deferCleanup = true;
2452
+ }
1998
2453
  const durationMs = Date.now() - start;
1999
2454
  const meta = response.meta;
2000
2455
  meta.requestId = requestId;
@@ -2034,6 +2489,9 @@ var Exios = class {
2034
2489
  }));
2035
2490
  }
2036
2491
  throw e;
2492
+ } finally {
2493
+ if (timer !== void 0) clearTimeout(timer);
2494
+ if (joined && !deferCleanup) joined.cleanup();
2037
2495
  }
2038
2496
  }
2039
2497
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
@@ -2146,7 +2604,10 @@ function detachDefaults(d) {
2146
2604
  "transitional",
2147
2605
  "fetchOptions",
2148
2606
  "auth",
2149
- "breaker"
2607
+ "breaker",
2608
+ "metadata",
2609
+ "cache",
2610
+ "dedupe"
2150
2611
  ]) {
2151
2612
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
2152
2613
  }
@@ -2176,6 +2637,7 @@ function createInstance(defaults) {
2176
2637
  });
2177
2638
  instance.interceptors = context.interceptors;
2178
2639
  instance.breaker = context.breaker;
2640
+ instance.cache = context.cache;
2179
2641
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
2180
2642
  return instance;
2181
2643
  }
@@ -2191,7 +2653,8 @@ var statics = {
2191
2653
  isExiosError,
2192
2654
  isCancel,
2193
2655
  mergeConfig,
2194
- toFormData
2656
+ toFormData,
2657
+ MemoryCache
2195
2658
  };
2196
2659
  var exios = Object.assign(
2197
2660
  createInstance(createDefaults()),
@@ -2204,6 +2667,7 @@ export {
2204
2667
  CanceledError,
2205
2668
  CircuitOpenError,
2206
2669
  ExiosError,
2670
+ MemoryCache,
2207
2671
  create,
2208
2672
  index_default as default,
2209
2673
  isCancel,