@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.cjs CHANGED
@@ -239,8 +239,8 @@ function encode(s) {
239
239
  }
240
240
  function isPlainObject(v) {
241
241
  if (v === null || typeof v !== "object") return false;
242
- const proto = Object.getPrototypeOf(v);
243
- return proto === Object.prototype || proto === null;
242
+ const proto2 = Object.getPrototypeOf(v);
243
+ return proto2 === Object.prototype || proto2 === null;
244
244
  }
245
245
  function serializeParams(params, opts = {}) {
246
246
  if (params === void 0 || params === null) return "";
@@ -266,8 +266,8 @@ function serializeParams(params, opts = {}) {
266
266
  return parts.join("&");
267
267
  }
268
268
  function buildURL(url, params, serializer) {
269
- const hash = url.indexOf("#");
270
- if (hash !== -1) url = url.slice(0, hash);
269
+ const hash2 = url.indexOf("#");
270
+ if (hash2 !== -1) url = url.slice(0, hash2);
271
271
  if (params === void 0 || params === null) return url;
272
272
  let serialized;
273
273
  if (typeof serializer === "function") serialized = serializer(params);
@@ -308,8 +308,8 @@ function toFormData(obj, fd = new FormData()) {
308
308
  // src/core/transforms.ts
309
309
  function isPlainObject2(v) {
310
310
  if (v === null || typeof v !== "object") return false;
311
- const proto = Object.getPrototypeOf(v);
312
- return proto === Object.prototype || proto === null;
311
+ const proto2 = Object.getPrototypeOf(v);
312
+ return proto2 === Object.prototype || proto2 === null;
313
313
  }
314
314
  function isPassThrough(data) {
315
315
  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);
@@ -1787,7 +1787,14 @@ var isPlainObject3 = (v) => {
1787
1787
  return p === Object.prototype || p === null;
1788
1788
  };
1789
1789
  var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
1790
- var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
1790
+ var SHALLOW_MERGE = /* @__PURE__ */ new Set([
1791
+ "auth",
1792
+ "transitional",
1793
+ "fetchOptions",
1794
+ "metadata",
1795
+ "cache",
1796
+ "dedupe"
1797
+ ]);
1791
1798
  function setCI(target, k, v) {
1792
1799
  const lk = k.toLowerCase();
1793
1800
  for (const existing of Object.keys(target)) {
@@ -1893,6 +1900,275 @@ function assertRequestBreaker(b) {
1893
1900
  }
1894
1901
  }
1895
1902
 
1903
+ // src/core/dedupe.ts
1904
+ var InflightRequests = class {
1905
+ flights = /* @__PURE__ */ new Map();
1906
+ get size() {
1907
+ return this.flights.size;
1908
+ }
1909
+ /**
1910
+ * Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
1911
+ * signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
1912
+ */
1913
+ join(key, config, start) {
1914
+ const token = config.cancelToken;
1915
+ if (token?.reason) {
1916
+ token.reason.config ??= config;
1917
+ return Promise.reject(token.reason);
1918
+ }
1919
+ const tokenSignal = token?.toAbortSignal();
1920
+ const signals = [config.signal, tokenSignal].filter((s) => !!s);
1921
+ const aborted = signals.find((s) => s.aborted);
1922
+ if (aborted) {
1923
+ tokenSignal?.unsubscribe();
1924
+ return Promise.reject(abortError(aborted, config));
1925
+ }
1926
+ let flight = this.flights.get(key);
1927
+ const leader = !flight;
1928
+ if (!flight) {
1929
+ const controller = new AbortController();
1930
+ const f2 = { controller, subscribers: 0, promise: void 0 };
1931
+ f2.promise = start(controller.signal).finally(() => {
1932
+ if (this.flights.get(key) === f2) this.flights.delete(key);
1933
+ });
1934
+ this.flights.set(key, f2);
1935
+ flight = f2;
1936
+ }
1937
+ const f = flight;
1938
+ f.subscribers++;
1939
+ return new Promise((resolve, reject) => {
1940
+ let settled = false;
1941
+ const detach = () => {
1942
+ settled = true;
1943
+ for (const s of signals) s.removeEventListener("abort", onAbort);
1944
+ tokenSignal?.unsubscribe();
1945
+ };
1946
+ const onAbort = (ev) => {
1947
+ if (settled) return;
1948
+ detach();
1949
+ const reason = abortError(ev.target, config);
1950
+ reject(reason);
1951
+ if (--f.subscribers === 0) {
1952
+ if (this.flights.get(key) === f) this.flights.delete(key);
1953
+ f.controller.abort(reason);
1954
+ }
1955
+ };
1956
+ for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
1957
+ f.promise.then(
1958
+ (response) => {
1959
+ if (settled) return;
1960
+ detach();
1961
+ f.subscribers--;
1962
+ resolve({ response, leader });
1963
+ },
1964
+ (err) => {
1965
+ if (settled) return;
1966
+ detach();
1967
+ f.subscribers--;
1968
+ reject(err);
1969
+ }
1970
+ );
1971
+ });
1972
+ }
1973
+ };
1974
+
1975
+ // src/core/requestCache.ts
1976
+ var SAFE_METHODS = Object.freeze(["get", "head"]);
1977
+ var MemoryCache = class {
1978
+ map = /* @__PURE__ */ new Map();
1979
+ maxEntries;
1980
+ constructor(options = {}) {
1981
+ const max = options.maxEntries ?? 100;
1982
+ if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
1983
+ this.maxEntries = max;
1984
+ }
1985
+ get size() {
1986
+ return this.map.size;
1987
+ }
1988
+ get(key) {
1989
+ const entry = this.map.get(key);
1990
+ if (!entry) return void 0;
1991
+ this.map.delete(key);
1992
+ if (entry.expiresAt <= Date.now()) return void 0;
1993
+ this.map.set(key, entry);
1994
+ return entry;
1995
+ }
1996
+ set(key, entry) {
1997
+ this.map.delete(key);
1998
+ this.map.set(key, entry);
1999
+ while (this.map.size > this.maxEntries)
2000
+ this.map.delete(this.map.keys().next().value);
2001
+ }
2002
+ delete(key) {
2003
+ this.map.delete(key);
2004
+ }
2005
+ clear() {
2006
+ this.map.clear();
2007
+ }
2008
+ keys() {
2009
+ return [...this.map.keys()];
2010
+ }
2011
+ };
2012
+ function hash(str) {
2013
+ let h1 = 3735928559;
2014
+ let h2 = 1103547991;
2015
+ for (let i = 0; i < str.length; i++) {
2016
+ const ch = str.charCodeAt(i);
2017
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2018
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2019
+ }
2020
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
2021
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2022
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2023
+ }
2024
+ var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2025
+ function requestTarget(config) {
2026
+ const url = buildURL(
2027
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
2028
+ config.params,
2029
+ config.paramsSerializer
2030
+ );
2031
+ return `${(config.method ?? "get").toUpperCase()} ${url}`;
2032
+ }
2033
+ function defaultRequestKey(config, scope = "cache") {
2034
+ const skip = config.correlationIdHeader?.toLowerCase();
2035
+ const parts = [];
2036
+ for (const k of Object.keys(config.headers).sort())
2037
+ if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2038
+ if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2039
+ parts.push(`rt:${config.responseType ?? ""}`);
2040
+ parts.push(
2041
+ `shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
2042
+ );
2043
+ if (scope === "dedupe") {
2044
+ parts.push(
2045
+ `policy:${fingerprint([
2046
+ config.timeout,
2047
+ config.totalTimeout,
2048
+ config.validateStatus,
2049
+ config.retry,
2050
+ config.breaker,
2051
+ config.adapter,
2052
+ config.maxContentLength,
2053
+ config.maxRedirects,
2054
+ config.transitional
2055
+ ])}`
2056
+ );
2057
+ }
2058
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2059
+ }
2060
+ var fnIds = /* @__PURE__ */ new WeakMap();
2061
+ var nextFnId = 0;
2062
+ function fingerprint(v) {
2063
+ if (typeof v === "function") {
2064
+ let id = fnIds.get(v);
2065
+ if (id === void 0) fnIds.set(v, id = ++nextFnId);
2066
+ return `f${id}`;
2067
+ }
2068
+ if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
2069
+ if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
2070
+ const o = v;
2071
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
2072
+ }
2073
+ function keyURL(key) {
2074
+ const sp = key.indexOf(" ");
2075
+ const h = key.lastIndexOf(" #");
2076
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2077
+ }
2078
+ function keyFor(config, opts, scope = "cache") {
2079
+ if (!opts.methods.includes(config.method)) return void 0;
2080
+ if (config.responseType === "stream") return void 0;
2081
+ if (opts.key) return opts.key(config);
2082
+ if (config.data !== void 0) return void 0;
2083
+ return defaultRequestKey(config, scope);
2084
+ }
2085
+ function checkMethods(name, m) {
2086
+ if (!Array.isArray(m)) bad(name, m, "an array");
2087
+ return m.map((x) => String(x).toLowerCase());
2088
+ }
2089
+ function resolveDedupe(v) {
2090
+ if (v === void 0 || v === false) return false;
2091
+ if (v === true) return { methods: [...SAFE_METHODS] };
2092
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2093
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2094
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2095
+ }
2096
+ function resolveCache(v) {
2097
+ if (v === void 0 || v === false) return false;
2098
+ const o = v === true ? {} : v;
2099
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2100
+ const ttl = o.ttl ?? 6e4;
2101
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2102
+ bad("cache.ttl", ttl, "a finite number > 0");
2103
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2104
+ const p = o.provider;
2105
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2106
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2107
+ return {
2108
+ ttl,
2109
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2110
+ key: o.key,
2111
+ provider: p,
2112
+ respectCacheControl: o.respectCacheControl ?? true
2113
+ };
2114
+ }
2115
+ function parseCacheControl(value) {
2116
+ const out = /* @__PURE__ */ new Map();
2117
+ const raw = Array.isArray(value) ? value.join(",") : value;
2118
+ if (typeof raw !== "string") return out;
2119
+ for (const part of raw.split(",")) {
2120
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2121
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2122
+ }
2123
+ return out;
2124
+ }
2125
+ function cloneData(data) {
2126
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2127
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2128
+ if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
2129
+ try {
2130
+ return { ok: true, value: structuredClone(data) };
2131
+ } catch {
2132
+ return { ok: false, value: data };
2133
+ }
2134
+ }
2135
+ var proto = (v) => Object.getPrototypeOf(v);
2136
+ var VIEW_TYPES = [
2137
+ "Int8Array",
2138
+ "Uint8Array",
2139
+ "Uint8ClampedArray",
2140
+ "Int16Array",
2141
+ "Uint16Array",
2142
+ "Int32Array",
2143
+ "Uint32Array",
2144
+ "Float32Array",
2145
+ "Float64Array",
2146
+ "BigInt64Array",
2147
+ "BigUint64Array",
2148
+ "DataView"
2149
+ ];
2150
+ var isType = (v, name) => {
2151
+ const C = globalThis[name];
2152
+ return typeof C === "function" && v instanceof C;
2153
+ };
2154
+ function clonesFaithfully(v, seen) {
2155
+ if (typeof v === "function" || typeof v === "symbol") return false;
2156
+ if (v === null || typeof v !== "object") return true;
2157
+ if (seen.has(v)) return true;
2158
+ seen.add(v);
2159
+ if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
2160
+ if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
2161
+ if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
2162
+ const p = proto(v);
2163
+ if (p === Object.prototype || p === null)
2164
+ return Object.values(v).every((x) => clonesFaithfully(x, seen));
2165
+ 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
2166
+ isType(v, "Blob") || isType(v, "FormData");
2167
+ }
2168
+ function reportCacheError(op, err) {
2169
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2170
+ }
2171
+
1896
2172
  // src/core/requestId.ts
1897
2173
  var seq = 0;
1898
2174
  function createRequestId() {
@@ -1924,6 +2200,10 @@ var Exios = class {
1924
2200
  breaker;
1925
2201
  registry;
1926
2202
  events = new EventHub();
2203
+ memoryCache = new MemoryCache();
2204
+ inflight = new InflightRequests();
2205
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2206
+ cache;
1927
2207
  constructor(defaults) {
1928
2208
  this.defaults = defaults;
1929
2209
  this.registry = new BreakerRegistry(
@@ -1940,6 +2220,50 @@ var Exios = class {
1940
2220
  state: (key) => this.registry.state(key),
1941
2221
  reset: (key) => this.registry.reset(key)
1942
2222
  };
2223
+ const provider = () => {
2224
+ const c = this.defaults.cache;
2225
+ return typeof c === "object" && c?.provider || this.memoryCache;
2226
+ };
2227
+ this.cache = {
2228
+ clear: async () => {
2229
+ await provider().clear();
2230
+ },
2231
+ delete: async (key) => {
2232
+ await provider().delete(key);
2233
+ },
2234
+ key: (cfg = {}) => {
2235
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2236
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2237
+ return c ? keyFor(resolved, c) : void 0;
2238
+ },
2239
+ invalidate: async (match) => {
2240
+ const p = provider();
2241
+ if (typeof p.keys !== "function")
2242
+ throw new ExiosError(
2243
+ "cache.invalidate needs a cache provider with keys()",
2244
+ ExiosError.ERR_NOT_SUPPORT
2245
+ );
2246
+ let test;
2247
+ if (typeof match === "function") test = match;
2248
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2249
+ else {
2250
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2251
+ const prefix = target.slice(target.indexOf(" ") + 1);
2252
+ test = (k) => {
2253
+ const u = keyURL(k);
2254
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2255
+ };
2256
+ }
2257
+ let n = 0;
2258
+ for (const k of [...await p.keys()]) {
2259
+ if (test(k)) {
2260
+ await p.delete(k);
2261
+ n++;
2262
+ }
2263
+ }
2264
+ return n;
2265
+ }
2266
+ };
1943
2267
  }
1944
2268
  async request(configOrUrl, config) {
1945
2269
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -1982,13 +2306,104 @@ var Exios = class {
1982
2306
  off(name, listener) {
1983
2307
  this.events.off(name, listener);
1984
2308
  }
1985
- /** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
2309
+ /**
2310
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2311
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2312
+ */
1986
2313
  async dispatch(config) {
1987
- const requestId = config.requestId ??= createRequestId();
1988
- const { correlationId } = config;
2314
+ const start = Date.now();
2315
+ config.requestId ??= createRequestId();
2316
+ const totalTimeout = config.totalTimeout ?? 0;
2317
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2318
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2319
+ const cacheCfg = resolveCache(config.cache);
2320
+ const dedupeCfg = resolveDedupe(config.dedupe);
2321
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2322
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
2323
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2324
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2325
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2326
+ let entry;
2327
+ try {
2328
+ entry = await provider.get(cacheKey);
2329
+ } catch (e) {
2330
+ reportCacheError("get", e);
2331
+ }
2332
+ if (entry && entry.expiresAt > Date.now()) {
2333
+ const copy2 = cloneData(entry.data);
2334
+ return this.localResponse(config, start, {
2335
+ data: copy2.value,
2336
+ status: entry.status,
2337
+ statusText: entry.statusText,
2338
+ headers: { ...entry.headers },
2339
+ request: null,
2340
+ meta: { attempts: 0, cached: true }
2341
+ });
2342
+ }
2343
+ }
1989
2344
  const header = config.correlationIdHeader?.toLowerCase();
1990
2345
  if (header && config.headers[header] === void 0)
1991
- config.headers = { ...config.headers, [header]: correlationId ?? requestId };
2346
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2347
+ const network = async (c) => {
2348
+ const response2 = await this.network(c, start, totalTimeout);
2349
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2350
+ this.store(provider, cacheKey, response2, cacheCfg);
2351
+ return response2;
2352
+ };
2353
+ if (dedupeKey === void 0) return network(config);
2354
+ const { response, leader } = await this.inflight.join(
2355
+ dedupeKey,
2356
+ config,
2357
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2358
+ );
2359
+ if (leader) return response;
2360
+ const copy = cloneData(response.data);
2361
+ return this.localResponse(config, start, {
2362
+ ...response,
2363
+ data: copy.value,
2364
+ headers: { ...response.headers },
2365
+ meta: { attempts: response.meta.attempts, deduped: true }
2366
+ });
2367
+ }
2368
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2369
+ localResponse(config, start, r) {
2370
+ r.meta.requestId = config.requestId;
2371
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2372
+ r.meta.durationMs = Date.now() - start;
2373
+ return { ...r, config };
2374
+ }
2375
+ /** Store a successful response; provider failures are reported, never thrown. */
2376
+ store(provider, key, response, cfg) {
2377
+ if (response.status < 200 || response.status >= 300) return;
2378
+ let ttl = cfg.ttl;
2379
+ if (cfg.respectCacheControl) {
2380
+ const cc = parseCacheControl(response.headers["cache-control"]);
2381
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2382
+ const maxAge = Number(cc.get("max-age"));
2383
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2384
+ }
2385
+ if (ttl <= 0) return;
2386
+ const copy = cloneData(response.data);
2387
+ if (!copy.ok) return;
2388
+ const now = Date.now();
2389
+ try {
2390
+ const r = provider.set(key, {
2391
+ status: response.status,
2392
+ statusText: response.statusText,
2393
+ headers: { ...response.headers },
2394
+ data: copy.value,
2395
+ storedAt: now,
2396
+ expiresAt: now + ttl
2397
+ });
2398
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2399
+ } catch (e) {
2400
+ reportCacheError("set", e);
2401
+ }
2402
+ }
2403
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2404
+ async network(config, start, totalTimeout) {
2405
+ const requestId = config.requestId;
2406
+ const { correlationId, metadata } = config;
1992
2407
  const hub = this.events;
1993
2408
  const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
1994
2409
  const base = () => ({
@@ -1997,9 +2412,9 @@ var Exios = class {
1997
2412
  method: config.method,
1998
2413
  url,
1999
2414
  config,
2415
+ metadata,
2000
2416
  timestamp: Date.now()
2001
2417
  });
2002
- const start = Date.now();
2003
2418
  const observer = {
2004
2419
  onRetry: (o) => hub.emit("retry", () => ({
2005
2420
  ...base(),
@@ -2012,15 +2427,55 @@ var Exios = class {
2012
2427
  if (TIMEOUT_CODES.has(error.code ?? ""))
2013
2428
  hub.emit("timeout", () => ({
2014
2429
  ...base(),
2430
+ kind: "attempt",
2015
2431
  attempt,
2016
2432
  timeoutMs: config.timeout ?? 0,
2017
2433
  error
2018
2434
  }));
2019
2435
  }
2020
2436
  };
2437
+ let timer;
2438
+ let totalFired = false;
2439
+ let joined;
2440
+ let dispatchConfig = config;
2441
+ if (totalTimeout > 0) {
2442
+ const ac = new AbortController();
2443
+ timer = setTimeout(() => {
2444
+ totalFired = true;
2445
+ ac.abort(new Error("totalTimeout"));
2446
+ }, totalTimeout);
2447
+ joined = combineSignals(config.signal, ac.signal);
2448
+ dispatchConfig = { ...config, signal: joined.signal };
2449
+ }
2450
+ let deferCleanup = false;
2021
2451
  hub.emit("request", base);
2022
2452
  try {
2023
- const response = await dispatchRequest(config, this.registry, observer);
2453
+ let response;
2454
+ try {
2455
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2456
+ } catch (e) {
2457
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2458
+ const err = new ExiosError(
2459
+ `total timeout of ${totalTimeout}ms exceeded`,
2460
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2461
+ config,
2462
+ e.request
2463
+ );
2464
+ err.cause = e;
2465
+ err.meta.attempts = e.meta.attempts;
2466
+ hub.emit("timeout", () => ({
2467
+ ...base(),
2468
+ kind: "total",
2469
+ attempt: err.meta.attempts,
2470
+ timeoutMs: totalTimeout,
2471
+ error: err
2472
+ }));
2473
+ throw err;
2474
+ }
2475
+ if (joined && isOneShotBody(response.data)) {
2476
+ response.data = whenBodyDone(response.data, joined.cleanup);
2477
+ deferCleanup = true;
2478
+ }
2024
2479
  const durationMs = Date.now() - start;
2025
2480
  const meta = response.meta;
2026
2481
  meta.requestId = requestId;
@@ -2060,6 +2515,9 @@ var Exios = class {
2060
2515
  }));
2061
2516
  }
2062
2517
  throw e;
2518
+ } finally {
2519
+ if (timer !== void 0) clearTimeout(timer);
2520
+ if (joined && !deferCleanup) joined.cleanup();
2063
2521
  }
2064
2522
  }
2065
2523
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
@@ -2172,7 +2630,10 @@ function detachDefaults(d) {
2172
2630
  "transitional",
2173
2631
  "fetchOptions",
2174
2632
  "auth",
2175
- "breaker"
2633
+ "breaker",
2634
+ "metadata",
2635
+ "cache",
2636
+ "dedupe"
2176
2637
  ]) {
2177
2638
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
2178
2639
  }
@@ -2202,6 +2663,7 @@ function createInstance(defaults) {
2202
2663
  });
2203
2664
  instance.interceptors = context.interceptors;
2204
2665
  instance.breaker = context.breaker;
2666
+ instance.cache = context.cache;
2205
2667
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
2206
2668
  return instance;
2207
2669
  }
@@ -2217,7 +2679,8 @@ var statics = {
2217
2679
  isExiosError,
2218
2680
  isCancel,
2219
2681
  mergeConfig,
2220
- toFormData
2682
+ toFormData,
2683
+ MemoryCache
2221
2684
  };
2222
2685
  var exios = Object.assign(
2223
2686
  createInstance(createDefaults()),
package/dist/index.d.cts CHANGED
@@ -34,6 +34,13 @@ declare namespace exios {
34
34
  type ResponseType = Pkg.ResponseType;
35
35
  type RetryConfig = Pkg.RetryConfig;
36
36
  type Transformer = Pkg.Transformer;
37
+ type CacheConfig = Pkg.CacheConfig;
38
+ type CacheEntry = Pkg.CacheEntry;
39
+ type CacheProvider = Pkg.CacheProvider;
40
+ type DedupeConfig = Pkg.DedupeConfig;
41
+ type ExiosCache = Pkg.ExiosCache;
42
+ type MemoryCache = Pkg.MemoryCache;
43
+ type Options<T> = Pkg.Options<T>;
37
44
  type CanceledEvent = Pkg.CanceledEvent;
38
45
  type CircuitEvent = Pkg.CircuitEvent;
39
46
  type ErrorEvent = Pkg.ErrorEvent;