@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.
@@ -200,8 +200,8 @@ function serializeParams(params, opts2 = {}) {
200
200
  return parts.join("&");
201
201
  }
202
202
  function buildURL(url, params, serializer) {
203
- const hash = url.indexOf("#");
204
- if (hash !== -1) url = url.slice(0, hash);
203
+ const hash2 = url.indexOf("#");
204
+ if (hash2 !== -1) url = url.slice(0, hash2);
205
205
  if (params === void 0 || params === null) return url;
206
206
  let serialized;
207
207
  if (typeof serializer === "function") serialized = serializer(params);
@@ -2321,7 +2321,14 @@ var isPlainObject3 = (v) => {
2321
2321
  return p === Object.prototype || p === null;
2322
2322
  };
2323
2323
  var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
2324
- var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
2324
+ var SHALLOW_MERGE = /* @__PURE__ */ new Set([
2325
+ "auth",
2326
+ "transitional",
2327
+ "fetchOptions",
2328
+ "metadata",
2329
+ "cache",
2330
+ "dedupe"
2331
+ ]);
2325
2332
  function setCI(target, k, v) {
2326
2333
  const lk = k.toLowerCase();
2327
2334
  for (const existing of Object.keys(target)) {
@@ -2427,6 +2434,210 @@ function assertRequestBreaker(b) {
2427
2434
  }
2428
2435
  }
2429
2436
 
2437
+ // src/core/dedupe.ts
2438
+ var InflightRequests = class {
2439
+ flights = /* @__PURE__ */ new Map();
2440
+ get size() {
2441
+ return this.flights.size;
2442
+ }
2443
+ /**
2444
+ * Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
2445
+ * signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
2446
+ */
2447
+ join(key, config, start) {
2448
+ const token = config.cancelToken;
2449
+ if (token?.reason) {
2450
+ token.reason.config ??= config;
2451
+ return Promise.reject(token.reason);
2452
+ }
2453
+ const tokenSignal = token?.toAbortSignal();
2454
+ const signals = [config.signal, tokenSignal].filter((s) => !!s);
2455
+ const aborted = signals.find((s) => s.aborted);
2456
+ if (aborted) {
2457
+ tokenSignal?.unsubscribe();
2458
+ return Promise.reject(abortError(aborted, config));
2459
+ }
2460
+ let flight = this.flights.get(key);
2461
+ const leader = !flight;
2462
+ if (!flight) {
2463
+ const controller = new AbortController();
2464
+ const f2 = { controller, subscribers: 0, promise: void 0 };
2465
+ f2.promise = start(controller.signal).finally(() => {
2466
+ if (this.flights.get(key) === f2) this.flights.delete(key);
2467
+ });
2468
+ this.flights.set(key, f2);
2469
+ flight = f2;
2470
+ }
2471
+ const f = flight;
2472
+ f.subscribers++;
2473
+ return new Promise((resolve, reject) => {
2474
+ let settled = false;
2475
+ const detach = () => {
2476
+ settled = true;
2477
+ for (const s of signals) s.removeEventListener("abort", onAbort);
2478
+ tokenSignal?.unsubscribe();
2479
+ };
2480
+ const onAbort = (ev) => {
2481
+ if (settled) return;
2482
+ detach();
2483
+ const reason = abortError(ev.target, config);
2484
+ reject(reason);
2485
+ if (--f.subscribers === 0) {
2486
+ if (this.flights.get(key) === f) this.flights.delete(key);
2487
+ f.controller.abort(reason);
2488
+ }
2489
+ };
2490
+ for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
2491
+ f.promise.then(
2492
+ (response) => {
2493
+ if (settled) return;
2494
+ detach();
2495
+ f.subscribers--;
2496
+ resolve({ response, leader });
2497
+ },
2498
+ (err) => {
2499
+ if (settled) return;
2500
+ detach();
2501
+ f.subscribers--;
2502
+ reject(err);
2503
+ }
2504
+ );
2505
+ });
2506
+ }
2507
+ };
2508
+
2509
+ // src/core/requestCache.ts
2510
+ var SAFE_METHODS = Object.freeze(["get", "head"]);
2511
+ var MemoryCache = class {
2512
+ map = /* @__PURE__ */ new Map();
2513
+ maxEntries;
2514
+ constructor(options = {}) {
2515
+ const max = options.maxEntries ?? 100;
2516
+ if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
2517
+ this.maxEntries = max;
2518
+ }
2519
+ get size() {
2520
+ return this.map.size;
2521
+ }
2522
+ get(key) {
2523
+ const entry = this.map.get(key);
2524
+ if (!entry) return void 0;
2525
+ this.map.delete(key);
2526
+ if (entry.expiresAt <= Date.now()) return void 0;
2527
+ this.map.set(key, entry);
2528
+ return entry;
2529
+ }
2530
+ set(key, entry) {
2531
+ this.map.delete(key);
2532
+ this.map.set(key, entry);
2533
+ while (this.map.size > this.maxEntries)
2534
+ this.map.delete(this.map.keys().next().value);
2535
+ }
2536
+ delete(key) {
2537
+ this.map.delete(key);
2538
+ }
2539
+ clear() {
2540
+ this.map.clear();
2541
+ }
2542
+ keys() {
2543
+ return [...this.map.keys()];
2544
+ }
2545
+ };
2546
+ function hash(str) {
2547
+ let h1 = 3735928559;
2548
+ let h2 = 1103547991;
2549
+ for (let i = 0; i < str.length; i++) {
2550
+ const ch = str.charCodeAt(i);
2551
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2552
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2553
+ }
2554
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
2555
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2556
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2557
+ }
2558
+ var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2559
+ function requestTarget(config) {
2560
+ const url = buildURL(
2561
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
2562
+ config.params,
2563
+ config.paramsSerializer
2564
+ );
2565
+ return `${(config.method ?? "get").toUpperCase()} ${url}`;
2566
+ }
2567
+ function defaultRequestKey(config) {
2568
+ const skip = config.correlationIdHeader?.toLowerCase();
2569
+ const parts = [];
2570
+ for (const k of Object.keys(config.headers).sort())
2571
+ if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2572
+ if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2573
+ parts.push(`rt:${config.responseType ?? ""}`);
2574
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2575
+ }
2576
+ function keyURL(key) {
2577
+ const sp = key.indexOf(" ");
2578
+ const h = key.lastIndexOf(" #");
2579
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2580
+ }
2581
+ function keyFor(config, opts2) {
2582
+ if (!opts2.methods.includes(config.method)) return void 0;
2583
+ if (config.responseType === "stream") return void 0;
2584
+ if (opts2.key) return opts2.key(config);
2585
+ if (config.data !== void 0) return void 0;
2586
+ return defaultRequestKey(config);
2587
+ }
2588
+ function checkMethods(name, m) {
2589
+ if (!Array.isArray(m)) bad(name, m, "an array");
2590
+ return m.map((x) => String(x).toLowerCase());
2591
+ }
2592
+ function resolveDedupe(v) {
2593
+ if (v === void 0 || v === false) return false;
2594
+ if (v === true) return { methods: [...SAFE_METHODS] };
2595
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2596
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2597
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2598
+ }
2599
+ function resolveCache(v) {
2600
+ if (v === void 0 || v === false) return false;
2601
+ const o = v === true ? {} : v;
2602
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2603
+ const ttl = o.ttl ?? 6e4;
2604
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2605
+ bad("cache.ttl", ttl, "a finite number > 0");
2606
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2607
+ const p = o.provider;
2608
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2609
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2610
+ return {
2611
+ ttl,
2612
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2613
+ key: o.key,
2614
+ provider: p,
2615
+ respectCacheControl: o.respectCacheControl ?? true
2616
+ };
2617
+ }
2618
+ function parseCacheControl(value) {
2619
+ const out = /* @__PURE__ */ new Map();
2620
+ const raw = Array.isArray(value) ? value.join(",") : value;
2621
+ if (typeof raw !== "string") return out;
2622
+ for (const part of raw.split(",")) {
2623
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2624
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2625
+ }
2626
+ return out;
2627
+ }
2628
+ function cloneData(data) {
2629
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2630
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2631
+ try {
2632
+ return { ok: true, value: structuredClone(data) };
2633
+ } catch {
2634
+ return { ok: false, value: data };
2635
+ }
2636
+ }
2637
+ function reportCacheError(op, err) {
2638
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2639
+ }
2640
+
2430
2641
  // src/core/requestId.ts
2431
2642
  var seq = 0;
2432
2643
  function createRequestId() {
@@ -2458,6 +2669,10 @@ var Exios = class {
2458
2669
  breaker;
2459
2670
  registry;
2460
2671
  events = new EventHub();
2672
+ memoryCache = new MemoryCache();
2673
+ inflight = new InflightRequests();
2674
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2675
+ cache;
2461
2676
  constructor(defaults) {
2462
2677
  this.defaults = defaults;
2463
2678
  this.registry = new BreakerRegistry(
@@ -2474,6 +2689,50 @@ var Exios = class {
2474
2689
  state: (key) => this.registry.state(key),
2475
2690
  reset: (key) => this.registry.reset(key)
2476
2691
  };
2692
+ const provider = () => {
2693
+ const c = this.defaults.cache;
2694
+ return typeof c === "object" && c?.provider || this.memoryCache;
2695
+ };
2696
+ this.cache = {
2697
+ clear: async () => {
2698
+ await provider().clear();
2699
+ },
2700
+ delete: async (key) => {
2701
+ await provider().delete(key);
2702
+ },
2703
+ key: (cfg = {}) => {
2704
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2705
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2706
+ return c ? keyFor(resolved, c) : void 0;
2707
+ },
2708
+ invalidate: async (match) => {
2709
+ const p = provider();
2710
+ if (typeof p.keys !== "function")
2711
+ throw new ExiosError(
2712
+ "cache.invalidate needs a cache provider with keys()",
2713
+ ExiosError.ERR_NOT_SUPPORT
2714
+ );
2715
+ let test;
2716
+ if (typeof match === "function") test = match;
2717
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2718
+ else {
2719
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2720
+ const prefix = target.slice(target.indexOf(" ") + 1);
2721
+ test = (k) => {
2722
+ const u = keyURL(k);
2723
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2724
+ };
2725
+ }
2726
+ let n = 0;
2727
+ for (const k of [...await p.keys()]) {
2728
+ if (test(k)) {
2729
+ await p.delete(k);
2730
+ n++;
2731
+ }
2732
+ }
2733
+ return n;
2734
+ }
2735
+ };
2477
2736
  }
2478
2737
  async request(configOrUrl, config) {
2479
2738
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -2516,13 +2775,104 @@ var Exios = class {
2516
2775
  off(name, listener) {
2517
2776
  this.events.off(name, listener);
2518
2777
  }
2519
- /** Ids, correlation header, timing, error context and lifecycle events around dispatchRequest. */
2778
+ /**
2779
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2780
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2781
+ */
2520
2782
  async dispatch(config) {
2521
- const requestId = config.requestId ??= createRequestId();
2522
- const { correlationId } = config;
2783
+ const start = Date.now();
2784
+ config.requestId ??= createRequestId();
2785
+ const totalTimeout = config.totalTimeout ?? 0;
2786
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2787
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2788
+ const cacheCfg = resolveCache(config.cache);
2789
+ const dedupeCfg = resolveDedupe(config.dedupe);
2790
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2791
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2792
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2793
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2794
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2795
+ let entry;
2796
+ try {
2797
+ entry = await provider.get(cacheKey);
2798
+ } catch (e) {
2799
+ reportCacheError("get", e);
2800
+ }
2801
+ if (entry && entry.expiresAt > Date.now()) {
2802
+ const copy2 = cloneData(entry.data);
2803
+ return this.localResponse(config, start, {
2804
+ data: copy2.value,
2805
+ status: entry.status,
2806
+ statusText: entry.statusText,
2807
+ headers: { ...entry.headers },
2808
+ request: null,
2809
+ meta: { attempts: 0, cached: true }
2810
+ });
2811
+ }
2812
+ }
2523
2813
  const header = config.correlationIdHeader?.toLowerCase();
2524
2814
  if (header && config.headers[header] === void 0)
2525
- config.headers = { ...config.headers, [header]: correlationId ?? requestId };
2815
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2816
+ const network = async (c) => {
2817
+ const response2 = await this.network(c, start, totalTimeout);
2818
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2819
+ this.store(provider, cacheKey, response2, cacheCfg);
2820
+ return response2;
2821
+ };
2822
+ if (dedupeKey === void 0) return network(config);
2823
+ const { response, leader } = await this.inflight.join(
2824
+ dedupeKey,
2825
+ config,
2826
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2827
+ );
2828
+ if (leader) return response;
2829
+ const copy = cloneData(response.data);
2830
+ return this.localResponse(config, start, {
2831
+ ...response,
2832
+ data: copy.value,
2833
+ headers: { ...response.headers },
2834
+ meta: { attempts: response.meta.attempts, deduped: true }
2835
+ });
2836
+ }
2837
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2838
+ localResponse(config, start, r) {
2839
+ r.meta.requestId = config.requestId;
2840
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2841
+ r.meta.durationMs = Date.now() - start;
2842
+ return { ...r, config };
2843
+ }
2844
+ /** Store a successful response; provider failures are reported, never thrown. */
2845
+ store(provider, key, response, cfg) {
2846
+ if (response.status < 200 || response.status >= 300) return;
2847
+ let ttl = cfg.ttl;
2848
+ if (cfg.respectCacheControl) {
2849
+ const cc = parseCacheControl(response.headers["cache-control"]);
2850
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2851
+ const maxAge = Number(cc.get("max-age"));
2852
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2853
+ }
2854
+ if (ttl <= 0) return;
2855
+ const copy = cloneData(response.data);
2856
+ if (!copy.ok) return;
2857
+ const now = Date.now();
2858
+ try {
2859
+ const r = provider.set(key, {
2860
+ status: response.status,
2861
+ statusText: response.statusText,
2862
+ headers: { ...response.headers },
2863
+ data: copy.value,
2864
+ storedAt: now,
2865
+ expiresAt: now + ttl
2866
+ });
2867
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2868
+ } catch (e) {
2869
+ reportCacheError("set", e);
2870
+ }
2871
+ }
2872
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2873
+ async network(config, start, totalTimeout) {
2874
+ const requestId = config.requestId;
2875
+ const { correlationId, metadata } = config;
2526
2876
  const hub = this.events;
2527
2877
  const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
2528
2878
  const base = () => ({
@@ -2531,9 +2881,9 @@ var Exios = class {
2531
2881
  method: config.method,
2532
2882
  url,
2533
2883
  config,
2884
+ metadata,
2534
2885
  timestamp: Date.now()
2535
2886
  });
2536
- const start = Date.now();
2537
2887
  const observer = {
2538
2888
  onRetry: (o) => hub.emit("retry", () => ({
2539
2889
  ...base(),
@@ -2546,15 +2896,55 @@ var Exios = class {
2546
2896
  if (TIMEOUT_CODES.has(error.code ?? ""))
2547
2897
  hub.emit("timeout", () => ({
2548
2898
  ...base(),
2899
+ kind: "attempt",
2549
2900
  attempt,
2550
2901
  timeoutMs: config.timeout ?? 0,
2551
2902
  error
2552
2903
  }));
2553
2904
  }
2554
2905
  };
2906
+ let timer;
2907
+ let totalFired = false;
2908
+ let joined;
2909
+ let dispatchConfig = config;
2910
+ if (totalTimeout > 0) {
2911
+ const ac = new AbortController();
2912
+ timer = setTimeout(() => {
2913
+ totalFired = true;
2914
+ ac.abort(new Error("totalTimeout"));
2915
+ }, totalTimeout);
2916
+ joined = combineSignals(config.signal, ac.signal);
2917
+ dispatchConfig = { ...config, signal: joined.signal };
2918
+ }
2919
+ let deferCleanup = false;
2555
2920
  hub.emit("request", base);
2556
2921
  try {
2557
- const response = await dispatchRequest(config, this.registry, observer);
2922
+ let response;
2923
+ try {
2924
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2925
+ } catch (e) {
2926
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2927
+ const err = new ExiosError(
2928
+ `total timeout of ${totalTimeout}ms exceeded`,
2929
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2930
+ config,
2931
+ e.request
2932
+ );
2933
+ err.cause = e;
2934
+ err.meta.attempts = e.meta.attempts;
2935
+ hub.emit("timeout", () => ({
2936
+ ...base(),
2937
+ kind: "total",
2938
+ attempt: err.meta.attempts,
2939
+ timeoutMs: totalTimeout,
2940
+ error: err
2941
+ }));
2942
+ throw err;
2943
+ }
2944
+ if (joined && isOneShotBody(response.data)) {
2945
+ response.data = whenBodyDone(response.data, joined.cleanup);
2946
+ deferCleanup = true;
2947
+ }
2558
2948
  const durationMs = Date.now() - start;
2559
2949
  const meta = response.meta;
2560
2950
  meta.requestId = requestId;
@@ -2594,6 +2984,9 @@ var Exios = class {
2594
2984
  }));
2595
2985
  }
2596
2986
  throw e;
2987
+ } finally {
2988
+ if (timer !== void 0) clearTimeout(timer);
2989
+ if (joined && !deferCleanup) joined.cleanup();
2597
2990
  }
2598
2991
  }
2599
2992
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
@@ -2706,7 +3099,10 @@ function detachDefaults(d) {
2706
3099
  "transitional",
2707
3100
  "fetchOptions",
2708
3101
  "auth",
2709
- "breaker"
3102
+ "breaker",
3103
+ "metadata",
3104
+ "cache",
3105
+ "dedupe"
2710
3106
  ]) {
2711
3107
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
2712
3108
  }
@@ -2736,6 +3132,7 @@ function createInstance(defaults) {
2736
3132
  });
2737
3133
  instance.interceptors = context.interceptors;
2738
3134
  instance.breaker = context.breaker;
3135
+ instance.cache = context.cache;
2739
3136
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
2740
3137
  return instance;
2741
3138
  }
@@ -2751,7 +3148,8 @@ var statics = {
2751
3148
  isExiosError,
2752
3149
  isCancel,
2753
3150
  mergeConfig,
2754
- toFormData
3151
+ toFormData,
3152
+ MemoryCache
2755
3153
  };
2756
3154
  var exios = Object.assign(
2757
3155
  createInstance(createDefaults()),