@indra211/exios 3.0.0 → 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/README.md CHANGED
@@ -211,11 +211,11 @@ off(); // unsubscribe one listener
211
211
  api.off("retry"); // or remove every listener of an event
212
212
  ```
213
213
 
214
- | Event | When | Payload (besides `requestId`, `correlationId`, `method`, `url`, `config`, `timestamp`) |
214
+ | Event | When | Payload (besides `requestId`, `correlationId`, `method`, `url`, `config`, `metadata`, `timestamp`) |
215
215
  | ----------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
216
216
  | `request` | Once per logical request, after request interceptors, before the breaker | none |
217
217
  | `retry` | Before each backoff sleep | `attempt` (the one that failed), `delayMs`, `error?`, `status?` |
218
- | `timeout` | Every time an attempt times out (it may then be retried) | `attempt`, `timeoutMs`, `error` |
218
+ | `timeout` | An attempt hit `timeout` (it may be retried), or `totalTimeout` ended the request | `kind` (`'attempt'` / `'total'`), `attempt`, `timeoutMs`, `error` |
219
219
  | `response` | Final success, before response interceptors | `response`, `status`, `attempts`, `durationMs`, `responseTimeMs` |
220
220
  | `error` | Final failure, cancellations excluded | `error`, `code?`, `status?`, `attempts`, `durationMs` |
221
221
  | `canceled` | The request was canceled (`signal` or `CancelToken`) | `error`, `attempts`, `durationMs` |
@@ -228,6 +228,99 @@ api.off("retry"); // or remove every listener of an event
228
228
  - Listeners belong to one instance. `create()` does not copy them, just as it does not copy interceptors.
229
229
  - A request rejected by a request interceptor never dispatches, so it emits no events.
230
230
  - `retry.onRetry` and `breaker.onStateChange` keep working as before, and run before the events.
231
+ - Events describe network requests: a cache hit or a deduplicated caller makes none, so it emits none.
232
+
233
+ ## Request management
234
+
235
+ All of these are **off by default**. Turning them on never changes retry or breaker behaviour.
236
+
237
+ ### Total timeout
238
+
239
+ `timeout` limits each attempt. `totalTimeout` limits the whole request: every attempt, retry and backoff sleep.
240
+
241
+ ```js
242
+ api.get("/report", { timeout: 2000, totalTimeout: 10000 });
243
+ // at most 10 s in total, however many retries are left
244
+ ```
245
+
246
+ When it fires, the request rejects with `code: 'ECONNABORTED'` (`'ETIMEDOUT'` with `transitional.clarifyTimeoutError`) and the message `total timeout of 10000ms exceeded`. The `timeout` event fires with `kind: 'total'`. Like a cancellation, it does **not** count as a circuit breaker failure. Your own `signal` / `CancelToken` still produce a `CanceledError`. For `responseType: 'stream'` the limit ends when the headers arrive.
247
+
248
+ ### Request metadata
249
+
250
+ `metadata` is free-form data that travels with a request. It is readable in interceptors, adapters and every event (`event.metadata`), and it is never sent to the server. Instance and request metadata are merged.
251
+
252
+ ```js
253
+ const api = exios.create({ metadata: { feature: "checkout" } });
254
+ api.on("error", (e) => report(e.metadata?.feature, e.code));
255
+ api.get("/cart", { metadata: { step: "load" } }); // metadata: { feature: "checkout", step: "load" }
256
+ ```
257
+
258
+ ### Request deduplication
259
+
260
+ With `dedupe: true`, identical requests made while one is already in flight share a single network request.
261
+
262
+ ```js
263
+ const api = exios.create({ baseURL: "https://api.example.com", dedupe: true });
264
+ const [a, b] = await Promise.all([api.get("/me"), api.get("/me")]); // one network request
265
+ b.meta.deduped; // true
266
+ ```
267
+
268
+ - **What counts as identical:** same method, URL, params, headers, `auth` and `responseType`. Requests with different `Authorization` headers are never shared.
269
+ - **Methods:** only `GET` and `HEAD` are deduplicated, unless you list others in `dedupe: { methods: [...] }`. Requests with a body, and `responseType: 'stream'`, are never shared.
270
+ - **Cancellation:** each caller keeps its own `signal` / `CancelToken`. A caller that aborts is rejected at once, and the others still get the response. The network request is aborted only when **every** caller has aborted.
271
+ - **Separate results:** every caller gets its own response object, with its own `requestId` and a cloned copy of `data`, and runs its own response interceptors. Errors are passed to every caller.
272
+ - **Custom key:** `dedupe: { key: (config) => string | undefined }`. Return `undefined` to skip deduplication for a request.
273
+ - **Events:** lifecycle events and request interceptors see the first caller's request. `onDownloadProgress` / `onUploadProgress` fire only for that caller.
274
+
275
+ ### Response caching
276
+
277
+ ```js
278
+ const api = exios.create({
279
+ baseURL: "https://api.example.com",
280
+ cache: { ttl: 30_000 }, // or cache: true (ttl 60 s)
281
+ });
282
+ await api.get("/products"); // network
283
+ const res = await api.get("/products"); // from memory
284
+ res.meta.cached; // true
285
+ ```
286
+
287
+ | Option | Default | Meaning |
288
+ | --------------------- | ---------------------------- | ----------------------------------------------------------------------------------------- |
289
+ | `ttl` | `60000` | Time to live in ms |
290
+ | `methods` | `['get', 'head']` | Methods whose responses may be cached |
291
+ | `respectCacheControl` | `true` | Honour `no-store`, `no-cache` and `max-age` on requests and responses |
292
+ | `key` | method + URL + params + headers hash | `(config) => string \| undefined`; `undefined` skips the cache for that request |
293
+ | `provider` | built-in memory LRU (100 entries) | Any object with `get` / `set` / `delete` / `clear` (sync or async), plus optional `keys` |
294
+
295
+ - **What is stored:** only 2xx responses. Errors, request bodies, streams and data that `structuredClone` can't copy are never cached.
296
+ - **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.
297
+ - **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.
298
+ - **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.
299
+ - **Per request:** `cache: false` bypasses the cache; `cache: { ttl: 5000 }` overrides the ttl.
300
+ - **Failures:** a cache provider that throws never fails the request. The error is reported with `console.error`, and the request goes to the network.
301
+ - **Instances:** each instance (including each `create()` child) has its own memory cache, unless you pass a `provider`.
302
+
303
+ Managing the cache:
304
+
305
+ ```js
306
+ await api.cache.invalidate("/products"); // /products, /products?page=2, /products/42 (not /products-old)
307
+ await api.cache.invalidate(/\/users\//); // RegExp tested against keys
308
+ await api.cache.invalidate((key) => key.startsWith("GET")); // predicate; resolves with the number removed
309
+ await api.cache.delete(api.cache.key({ url: "/products" })); // one entry
310
+ await api.cache.clear();
311
+ ```
312
+
313
+ A custom provider, for example backed by `localStorage` or Redis:
314
+
315
+ ```js
316
+ import { MemoryCache } from "@indra211/exios";
317
+
318
+ const api = exios.create({ cache: { provider: new MemoryCache({ maxEntries: 500 }) } });
319
+ // or: { get(key), set(key, entry), delete(key), clear(), keys?() }; entries are plain objects
320
+ // { status, statusText, headers, data, storedAt, expiresAt }
321
+ ```
322
+
323
+ `invalidate()` needs a provider with `keys()`; without one it rejects with `ERR_NOT_SUPPORT`.
231
324
 
232
325
  ## Behavior rules
233
326
 
package/dist/index.cjs CHANGED
@@ -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);
@@ -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,210 @@ 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) {
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
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2041
+ }
2042
+ function keyURL(key) {
2043
+ const sp = key.indexOf(" ");
2044
+ const h = key.lastIndexOf(" #");
2045
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2046
+ }
2047
+ function keyFor(config, opts) {
2048
+ if (!opts.methods.includes(config.method)) return void 0;
2049
+ if (config.responseType === "stream") return void 0;
2050
+ if (opts.key) return opts.key(config);
2051
+ if (config.data !== void 0) return void 0;
2052
+ return defaultRequestKey(config);
2053
+ }
2054
+ function checkMethods(name, m) {
2055
+ if (!Array.isArray(m)) bad(name, m, "an array");
2056
+ return m.map((x) => String(x).toLowerCase());
2057
+ }
2058
+ function resolveDedupe(v) {
2059
+ if (v === void 0 || v === false) return false;
2060
+ if (v === true) return { methods: [...SAFE_METHODS] };
2061
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2062
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2063
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2064
+ }
2065
+ function resolveCache(v) {
2066
+ if (v === void 0 || v === false) return false;
2067
+ const o = v === true ? {} : v;
2068
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2069
+ const ttl = o.ttl ?? 6e4;
2070
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2071
+ bad("cache.ttl", ttl, "a finite number > 0");
2072
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2073
+ const p = o.provider;
2074
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2075
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2076
+ return {
2077
+ ttl,
2078
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2079
+ key: o.key,
2080
+ provider: p,
2081
+ respectCacheControl: o.respectCacheControl ?? true
2082
+ };
2083
+ }
2084
+ function parseCacheControl(value) {
2085
+ const out = /* @__PURE__ */ new Map();
2086
+ const raw = Array.isArray(value) ? value.join(",") : value;
2087
+ if (typeof raw !== "string") return out;
2088
+ for (const part of raw.split(",")) {
2089
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2090
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2091
+ }
2092
+ return out;
2093
+ }
2094
+ function cloneData(data) {
2095
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2096
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2097
+ try {
2098
+ return { ok: true, value: structuredClone(data) };
2099
+ } catch {
2100
+ return { ok: false, value: data };
2101
+ }
2102
+ }
2103
+ function reportCacheError(op, err) {
2104
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2105
+ }
2106
+
1896
2107
  // src/core/requestId.ts
1897
2108
  var seq = 0;
1898
2109
  function createRequestId() {
@@ -1924,6 +2135,10 @@ var Exios = class {
1924
2135
  breaker;
1925
2136
  registry;
1926
2137
  events = new EventHub();
2138
+ memoryCache = new MemoryCache();
2139
+ inflight = new InflightRequests();
2140
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2141
+ cache;
1927
2142
  constructor(defaults) {
1928
2143
  this.defaults = defaults;
1929
2144
  this.registry = new BreakerRegistry(
@@ -1940,6 +2155,50 @@ var Exios = class {
1940
2155
  state: (key) => this.registry.state(key),
1941
2156
  reset: (key) => this.registry.reset(key)
1942
2157
  };
2158
+ const provider = () => {
2159
+ const c = this.defaults.cache;
2160
+ return typeof c === "object" && c?.provider || this.memoryCache;
2161
+ };
2162
+ this.cache = {
2163
+ clear: async () => {
2164
+ await provider().clear();
2165
+ },
2166
+ delete: async (key) => {
2167
+ await provider().delete(key);
2168
+ },
2169
+ key: (cfg = {}) => {
2170
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2171
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2172
+ return c ? keyFor(resolved, c) : void 0;
2173
+ },
2174
+ invalidate: async (match) => {
2175
+ const p = provider();
2176
+ if (typeof p.keys !== "function")
2177
+ throw new ExiosError(
2178
+ "cache.invalidate needs a cache provider with keys()",
2179
+ ExiosError.ERR_NOT_SUPPORT
2180
+ );
2181
+ let test;
2182
+ if (typeof match === "function") test = match;
2183
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2184
+ else {
2185
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2186
+ const prefix = target.slice(target.indexOf(" ") + 1);
2187
+ test = (k) => {
2188
+ const u = keyURL(k);
2189
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2190
+ };
2191
+ }
2192
+ let n = 0;
2193
+ for (const k of [...await p.keys()]) {
2194
+ if (test(k)) {
2195
+ await p.delete(k);
2196
+ n++;
2197
+ }
2198
+ }
2199
+ return n;
2200
+ }
2201
+ };
1943
2202
  }
1944
2203
  async request(configOrUrl, config) {
1945
2204
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -1982,13 +2241,104 @@ var Exios = class {
1982
2241
  off(name, listener) {
1983
2242
  this.events.off(name, listener);
1984
2243
  }
1985
- /** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
2244
+ /**
2245
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2246
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2247
+ */
1986
2248
  async dispatch(config) {
1987
- const requestId = config.requestId ??= createRequestId();
1988
- const { correlationId } = config;
2249
+ const start = Date.now();
2250
+ config.requestId ??= createRequestId();
2251
+ const totalTimeout = config.totalTimeout ?? 0;
2252
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2253
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2254
+ const cacheCfg = resolveCache(config.cache);
2255
+ const dedupeCfg = resolveDedupe(config.dedupe);
2256
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2257
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2258
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2259
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2260
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2261
+ let entry;
2262
+ try {
2263
+ entry = await provider.get(cacheKey);
2264
+ } catch (e) {
2265
+ reportCacheError("get", e);
2266
+ }
2267
+ if (entry && entry.expiresAt > Date.now()) {
2268
+ const copy2 = cloneData(entry.data);
2269
+ return this.localResponse(config, start, {
2270
+ data: copy2.value,
2271
+ status: entry.status,
2272
+ statusText: entry.statusText,
2273
+ headers: { ...entry.headers },
2274
+ request: null,
2275
+ meta: { attempts: 0, cached: true }
2276
+ });
2277
+ }
2278
+ }
1989
2279
  const header = config.correlationIdHeader?.toLowerCase();
1990
2280
  if (header && config.headers[header] === void 0)
1991
- config.headers = { ...config.headers, [header]: correlationId ?? requestId };
2281
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2282
+ const network = async (c) => {
2283
+ const response2 = await this.network(c, start, totalTimeout);
2284
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2285
+ this.store(provider, cacheKey, response2, cacheCfg);
2286
+ return response2;
2287
+ };
2288
+ if (dedupeKey === void 0) return network(config);
2289
+ const { response, leader } = await this.inflight.join(
2290
+ dedupeKey,
2291
+ config,
2292
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2293
+ );
2294
+ if (leader) return response;
2295
+ const copy = cloneData(response.data);
2296
+ return this.localResponse(config, start, {
2297
+ ...response,
2298
+ data: copy.value,
2299
+ headers: { ...response.headers },
2300
+ meta: { attempts: response.meta.attempts, deduped: true }
2301
+ });
2302
+ }
2303
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2304
+ localResponse(config, start, r) {
2305
+ r.meta.requestId = config.requestId;
2306
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2307
+ r.meta.durationMs = Date.now() - start;
2308
+ return { ...r, config };
2309
+ }
2310
+ /** Store a successful response; provider failures are reported, never thrown. */
2311
+ store(provider, key, response, cfg) {
2312
+ if (response.status < 200 || response.status >= 300) return;
2313
+ let ttl = cfg.ttl;
2314
+ if (cfg.respectCacheControl) {
2315
+ const cc = parseCacheControl(response.headers["cache-control"]);
2316
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2317
+ const maxAge = Number(cc.get("max-age"));
2318
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2319
+ }
2320
+ if (ttl <= 0) return;
2321
+ const copy = cloneData(response.data);
2322
+ if (!copy.ok) return;
2323
+ const now = Date.now();
2324
+ try {
2325
+ const r = provider.set(key, {
2326
+ status: response.status,
2327
+ statusText: response.statusText,
2328
+ headers: { ...response.headers },
2329
+ data: copy.value,
2330
+ storedAt: now,
2331
+ expiresAt: now + ttl
2332
+ });
2333
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2334
+ } catch (e) {
2335
+ reportCacheError("set", e);
2336
+ }
2337
+ }
2338
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2339
+ async network(config, start, totalTimeout) {
2340
+ const requestId = config.requestId;
2341
+ const { correlationId, metadata } = config;
1992
2342
  const hub = this.events;
1993
2343
  const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
1994
2344
  const base = () => ({
@@ -1997,9 +2347,9 @@ var Exios = class {
1997
2347
  method: config.method,
1998
2348
  url,
1999
2349
  config,
2350
+ metadata,
2000
2351
  timestamp: Date.now()
2001
2352
  });
2002
- const start = Date.now();
2003
2353
  const observer = {
2004
2354
  onRetry: (o) => hub.emit("retry", () => ({
2005
2355
  ...base(),
@@ -2012,15 +2362,55 @@ var Exios = class {
2012
2362
  if (TIMEOUT_CODES.has(error.code ?? ""))
2013
2363
  hub.emit("timeout", () => ({
2014
2364
  ...base(),
2365
+ kind: "attempt",
2015
2366
  attempt,
2016
2367
  timeoutMs: config.timeout ?? 0,
2017
2368
  error
2018
2369
  }));
2019
2370
  }
2020
2371
  };
2372
+ let timer;
2373
+ let totalFired = false;
2374
+ let joined;
2375
+ let dispatchConfig = config;
2376
+ if (totalTimeout > 0) {
2377
+ const ac = new AbortController();
2378
+ timer = setTimeout(() => {
2379
+ totalFired = true;
2380
+ ac.abort(new Error("totalTimeout"));
2381
+ }, totalTimeout);
2382
+ joined = combineSignals(config.signal, ac.signal);
2383
+ dispatchConfig = { ...config, signal: joined.signal };
2384
+ }
2385
+ let deferCleanup = false;
2021
2386
  hub.emit("request", base);
2022
2387
  try {
2023
- const response = await dispatchRequest(config, this.registry, observer);
2388
+ let response;
2389
+ try {
2390
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2391
+ } catch (e) {
2392
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2393
+ const err = new ExiosError(
2394
+ `total timeout of ${totalTimeout}ms exceeded`,
2395
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2396
+ config,
2397
+ e.request
2398
+ );
2399
+ err.cause = e;
2400
+ err.meta.attempts = e.meta.attempts;
2401
+ hub.emit("timeout", () => ({
2402
+ ...base(),
2403
+ kind: "total",
2404
+ attempt: err.meta.attempts,
2405
+ timeoutMs: totalTimeout,
2406
+ error: err
2407
+ }));
2408
+ throw err;
2409
+ }
2410
+ if (joined && isOneShotBody(response.data)) {
2411
+ response.data = whenBodyDone(response.data, joined.cleanup);
2412
+ deferCleanup = true;
2413
+ }
2024
2414
  const durationMs = Date.now() - start;
2025
2415
  const meta = response.meta;
2026
2416
  meta.requestId = requestId;
@@ -2060,6 +2450,9 @@ var Exios = class {
2060
2450
  }));
2061
2451
  }
2062
2452
  throw e;
2453
+ } finally {
2454
+ if (timer !== void 0) clearTimeout(timer);
2455
+ if (joined && !deferCleanup) joined.cleanup();
2063
2456
  }
2064
2457
  }
2065
2458
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
@@ -2172,7 +2565,10 @@ function detachDefaults(d) {
2172
2565
  "transitional",
2173
2566
  "fetchOptions",
2174
2567
  "auth",
2175
- "breaker"
2568
+ "breaker",
2569
+ "metadata",
2570
+ "cache",
2571
+ "dedupe"
2176
2572
  ]) {
2177
2573
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
2178
2574
  }
@@ -2202,6 +2598,7 @@ function createInstance(defaults) {
2202
2598
  });
2203
2599
  instance.interceptors = context.interceptors;
2204
2600
  instance.breaker = context.breaker;
2601
+ instance.cache = context.cache;
2205
2602
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
2206
2603
  return instance;
2207
2604
  }
@@ -2217,7 +2614,8 @@ var statics = {
2217
2614
  isExiosError,
2218
2615
  isCancel,
2219
2616
  mergeConfig,
2220
- toFormData
2617
+ toFormData,
2618
+ MemoryCache
2221
2619
  };
2222
2620
  var exios = Object.assign(
2223
2621
  createInstance(createDefaults()),
package/dist/index.d.cts CHANGED
@@ -34,6 +34,12 @@ 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;
37
43
  type CanceledEvent = Pkg.CanceledEvent;
38
44
  type CircuitEvent = Pkg.CircuitEvent;
39
45
  type ErrorEvent = Pkg.ErrorEvent;