@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/README.md +100 -2
- package/dist/index.cjs +478 -15
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +162 -53
- package/dist/index.js +479 -15
- package/dist/index.node.cjs +478 -15
- package/dist/index.node.js +479 -15
- package/package.json +1 -1
package/dist/index.node.js
CHANGED
|
@@ -137,8 +137,8 @@ function encode(s) {
|
|
|
137
137
|
}
|
|
138
138
|
function isPlainObject(v) {
|
|
139
139
|
if (v === null || typeof v !== "object") return false;
|
|
140
|
-
const
|
|
141
|
-
return
|
|
140
|
+
const proto2 = Object.getPrototypeOf(v);
|
|
141
|
+
return proto2 === Object.prototype || proto2 === null;
|
|
142
142
|
}
|
|
143
143
|
function serializeParams(params, opts2 = {}) {
|
|
144
144
|
if (params === void 0 || params === null) return "";
|
|
@@ -164,8 +164,8 @@ function serializeParams(params, opts2 = {}) {
|
|
|
164
164
|
return parts.join("&");
|
|
165
165
|
}
|
|
166
166
|
function buildURL(url, params, serializer) {
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
167
|
+
const hash2 = url.indexOf("#");
|
|
168
|
+
if (hash2 !== -1) url = url.slice(0, hash2);
|
|
169
169
|
if (params === void 0 || params === null) return url;
|
|
170
170
|
let serialized;
|
|
171
171
|
if (typeof serializer === "function") serialized = serializer(params);
|
|
@@ -206,8 +206,8 @@ function toFormData(obj, fd = new FormData()) {
|
|
|
206
206
|
// src/core/transforms.ts
|
|
207
207
|
function isPlainObject2(v) {
|
|
208
208
|
if (v === null || typeof v !== "object") return false;
|
|
209
|
-
const
|
|
210
|
-
return
|
|
209
|
+
const proto2 = Object.getPrototypeOf(v);
|
|
210
|
+
return proto2 === Object.prototype || proto2 === null;
|
|
211
211
|
}
|
|
212
212
|
function isPassThrough(data) {
|
|
213
213
|
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);
|
|
@@ -2285,7 +2285,14 @@ var isPlainObject3 = (v) => {
|
|
|
2285
2285
|
return p === Object.prototype || p === null;
|
|
2286
2286
|
};
|
|
2287
2287
|
var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
|
|
2288
|
-
var SHALLOW_MERGE = /* @__PURE__ */ new Set([
|
|
2288
|
+
var SHALLOW_MERGE = /* @__PURE__ */ new Set([
|
|
2289
|
+
"auth",
|
|
2290
|
+
"transitional",
|
|
2291
|
+
"fetchOptions",
|
|
2292
|
+
"metadata",
|
|
2293
|
+
"cache",
|
|
2294
|
+
"dedupe"
|
|
2295
|
+
]);
|
|
2289
2296
|
function setCI(target, k, v) {
|
|
2290
2297
|
const lk = k.toLowerCase();
|
|
2291
2298
|
for (const existing of Object.keys(target)) {
|
|
@@ -2391,6 +2398,275 @@ function assertRequestBreaker(b) {
|
|
|
2391
2398
|
}
|
|
2392
2399
|
}
|
|
2393
2400
|
|
|
2401
|
+
// src/core/dedupe.ts
|
|
2402
|
+
var InflightRequests = class {
|
|
2403
|
+
flights = /* @__PURE__ */ new Map();
|
|
2404
|
+
get size() {
|
|
2405
|
+
return this.flights.size;
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
|
|
2409
|
+
* signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
|
|
2410
|
+
*/
|
|
2411
|
+
join(key, config, start) {
|
|
2412
|
+
const token = config.cancelToken;
|
|
2413
|
+
if (token?.reason) {
|
|
2414
|
+
token.reason.config ??= config;
|
|
2415
|
+
return Promise.reject(token.reason);
|
|
2416
|
+
}
|
|
2417
|
+
const tokenSignal = token?.toAbortSignal();
|
|
2418
|
+
const signals = [config.signal, tokenSignal].filter((s) => !!s);
|
|
2419
|
+
const aborted = signals.find((s) => s.aborted);
|
|
2420
|
+
if (aborted) {
|
|
2421
|
+
tokenSignal?.unsubscribe();
|
|
2422
|
+
return Promise.reject(abortError(aborted, config));
|
|
2423
|
+
}
|
|
2424
|
+
let flight = this.flights.get(key);
|
|
2425
|
+
const leader = !flight;
|
|
2426
|
+
if (!flight) {
|
|
2427
|
+
const controller = new AbortController();
|
|
2428
|
+
const f2 = { controller, subscribers: 0, promise: void 0 };
|
|
2429
|
+
f2.promise = start(controller.signal).finally(() => {
|
|
2430
|
+
if (this.flights.get(key) === f2) this.flights.delete(key);
|
|
2431
|
+
});
|
|
2432
|
+
this.flights.set(key, f2);
|
|
2433
|
+
flight = f2;
|
|
2434
|
+
}
|
|
2435
|
+
const f = flight;
|
|
2436
|
+
f.subscribers++;
|
|
2437
|
+
return new Promise((resolve, reject) => {
|
|
2438
|
+
let settled = false;
|
|
2439
|
+
const detach = () => {
|
|
2440
|
+
settled = true;
|
|
2441
|
+
for (const s of signals) s.removeEventListener("abort", onAbort);
|
|
2442
|
+
tokenSignal?.unsubscribe();
|
|
2443
|
+
};
|
|
2444
|
+
const onAbort = (ev) => {
|
|
2445
|
+
if (settled) return;
|
|
2446
|
+
detach();
|
|
2447
|
+
const reason = abortError(ev.target, config);
|
|
2448
|
+
reject(reason);
|
|
2449
|
+
if (--f.subscribers === 0) {
|
|
2450
|
+
if (this.flights.get(key) === f) this.flights.delete(key);
|
|
2451
|
+
f.controller.abort(reason);
|
|
2452
|
+
}
|
|
2453
|
+
};
|
|
2454
|
+
for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
|
|
2455
|
+
f.promise.then(
|
|
2456
|
+
(response) => {
|
|
2457
|
+
if (settled) return;
|
|
2458
|
+
detach();
|
|
2459
|
+
f.subscribers--;
|
|
2460
|
+
resolve({ response, leader });
|
|
2461
|
+
},
|
|
2462
|
+
(err) => {
|
|
2463
|
+
if (settled) return;
|
|
2464
|
+
detach();
|
|
2465
|
+
f.subscribers--;
|
|
2466
|
+
reject(err);
|
|
2467
|
+
}
|
|
2468
|
+
);
|
|
2469
|
+
});
|
|
2470
|
+
}
|
|
2471
|
+
};
|
|
2472
|
+
|
|
2473
|
+
// src/core/requestCache.ts
|
|
2474
|
+
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
2475
|
+
var MemoryCache = class {
|
|
2476
|
+
map = /* @__PURE__ */ new Map();
|
|
2477
|
+
maxEntries;
|
|
2478
|
+
constructor(options = {}) {
|
|
2479
|
+
const max = options.maxEntries ?? 100;
|
|
2480
|
+
if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
|
|
2481
|
+
this.maxEntries = max;
|
|
2482
|
+
}
|
|
2483
|
+
get size() {
|
|
2484
|
+
return this.map.size;
|
|
2485
|
+
}
|
|
2486
|
+
get(key) {
|
|
2487
|
+
const entry = this.map.get(key);
|
|
2488
|
+
if (!entry) return void 0;
|
|
2489
|
+
this.map.delete(key);
|
|
2490
|
+
if (entry.expiresAt <= Date.now()) return void 0;
|
|
2491
|
+
this.map.set(key, entry);
|
|
2492
|
+
return entry;
|
|
2493
|
+
}
|
|
2494
|
+
set(key, entry) {
|
|
2495
|
+
this.map.delete(key);
|
|
2496
|
+
this.map.set(key, entry);
|
|
2497
|
+
while (this.map.size > this.maxEntries)
|
|
2498
|
+
this.map.delete(this.map.keys().next().value);
|
|
2499
|
+
}
|
|
2500
|
+
delete(key) {
|
|
2501
|
+
this.map.delete(key);
|
|
2502
|
+
}
|
|
2503
|
+
clear() {
|
|
2504
|
+
this.map.clear();
|
|
2505
|
+
}
|
|
2506
|
+
keys() {
|
|
2507
|
+
return [...this.map.keys()];
|
|
2508
|
+
}
|
|
2509
|
+
};
|
|
2510
|
+
function hash(str) {
|
|
2511
|
+
let h1 = 3735928559;
|
|
2512
|
+
let h2 = 1103547991;
|
|
2513
|
+
for (let i = 0; i < str.length; i++) {
|
|
2514
|
+
const ch = str.charCodeAt(i);
|
|
2515
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
2516
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
2517
|
+
}
|
|
2518
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
2519
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
2520
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
|
|
2521
|
+
}
|
|
2522
|
+
var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
|
|
2523
|
+
function requestTarget(config) {
|
|
2524
|
+
const url = buildURL(
|
|
2525
|
+
buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
|
|
2526
|
+
config.params,
|
|
2527
|
+
config.paramsSerializer
|
|
2528
|
+
);
|
|
2529
|
+
return `${(config.method ?? "get").toUpperCase()} ${url}`;
|
|
2530
|
+
}
|
|
2531
|
+
function defaultRequestKey(config, scope = "cache") {
|
|
2532
|
+
const skip = config.correlationIdHeader?.toLowerCase();
|
|
2533
|
+
const parts = [];
|
|
2534
|
+
for (const k of Object.keys(config.headers).sort())
|
|
2535
|
+
if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
|
|
2536
|
+
if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
|
|
2537
|
+
parts.push(`rt:${config.responseType ?? ""}`);
|
|
2538
|
+
parts.push(
|
|
2539
|
+
`shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
|
|
2540
|
+
);
|
|
2541
|
+
if (scope === "dedupe") {
|
|
2542
|
+
parts.push(
|
|
2543
|
+
`policy:${fingerprint([
|
|
2544
|
+
config.timeout,
|
|
2545
|
+
config.totalTimeout,
|
|
2546
|
+
config.validateStatus,
|
|
2547
|
+
config.retry,
|
|
2548
|
+
config.breaker,
|
|
2549
|
+
config.adapter,
|
|
2550
|
+
config.maxContentLength,
|
|
2551
|
+
config.maxRedirects,
|
|
2552
|
+
config.transitional
|
|
2553
|
+
])}`
|
|
2554
|
+
);
|
|
2555
|
+
}
|
|
2556
|
+
return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
|
|
2557
|
+
}
|
|
2558
|
+
var fnIds = /* @__PURE__ */ new WeakMap();
|
|
2559
|
+
var nextFnId = 0;
|
|
2560
|
+
function fingerprint(v) {
|
|
2561
|
+
if (typeof v === "function") {
|
|
2562
|
+
let id = fnIds.get(v);
|
|
2563
|
+
if (id === void 0) fnIds.set(v, id = ++nextFnId);
|
|
2564
|
+
return `f${id}`;
|
|
2565
|
+
}
|
|
2566
|
+
if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
|
|
2567
|
+
if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
|
|
2568
|
+
const o = v;
|
|
2569
|
+
return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
|
|
2570
|
+
}
|
|
2571
|
+
function keyURL(key) {
|
|
2572
|
+
const sp = key.indexOf(" ");
|
|
2573
|
+
const h = key.lastIndexOf(" #");
|
|
2574
|
+
return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
|
|
2575
|
+
}
|
|
2576
|
+
function keyFor(config, opts2, scope = "cache") {
|
|
2577
|
+
if (!opts2.methods.includes(config.method)) return void 0;
|
|
2578
|
+
if (config.responseType === "stream") return void 0;
|
|
2579
|
+
if (opts2.key) return opts2.key(config);
|
|
2580
|
+
if (config.data !== void 0) return void 0;
|
|
2581
|
+
return defaultRequestKey(config, scope);
|
|
2582
|
+
}
|
|
2583
|
+
function checkMethods(name, m) {
|
|
2584
|
+
if (!Array.isArray(m)) bad(name, m, "an array");
|
|
2585
|
+
return m.map((x) => String(x).toLowerCase());
|
|
2586
|
+
}
|
|
2587
|
+
function resolveDedupe(v) {
|
|
2588
|
+
if (v === void 0 || v === false) return false;
|
|
2589
|
+
if (v === true) return { methods: [...SAFE_METHODS] };
|
|
2590
|
+
if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
|
|
2591
|
+
if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
|
|
2592
|
+
return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
|
|
2593
|
+
}
|
|
2594
|
+
function resolveCache(v) {
|
|
2595
|
+
if (v === void 0 || v === false) return false;
|
|
2596
|
+
const o = v === true ? {} : v;
|
|
2597
|
+
if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
|
|
2598
|
+
const ttl = o.ttl ?? 6e4;
|
|
2599
|
+
if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
|
|
2600
|
+
bad("cache.ttl", ttl, "a finite number > 0");
|
|
2601
|
+
if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
|
|
2602
|
+
const p = o.provider;
|
|
2603
|
+
if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
|
|
2604
|
+
bad("cache.provider", p, "an object with get/set/delete/clear");
|
|
2605
|
+
return {
|
|
2606
|
+
ttl,
|
|
2607
|
+
methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
|
|
2608
|
+
key: o.key,
|
|
2609
|
+
provider: p,
|
|
2610
|
+
respectCacheControl: o.respectCacheControl ?? true
|
|
2611
|
+
};
|
|
2612
|
+
}
|
|
2613
|
+
function parseCacheControl(value) {
|
|
2614
|
+
const out = /* @__PURE__ */ new Map();
|
|
2615
|
+
const raw = Array.isArray(value) ? value.join(",") : value;
|
|
2616
|
+
if (typeof raw !== "string") return out;
|
|
2617
|
+
for (const part of raw.split(",")) {
|
|
2618
|
+
const [k, v] = part.split("=", 2).map((s) => s.trim());
|
|
2619
|
+
if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
|
|
2620
|
+
}
|
|
2621
|
+
return out;
|
|
2622
|
+
}
|
|
2623
|
+
function cloneData(data) {
|
|
2624
|
+
if (data === null || typeof data !== "object") return { ok: true, value: data };
|
|
2625
|
+
if (typeof structuredClone !== "function") return { ok: false, value: data };
|
|
2626
|
+
if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
|
|
2627
|
+
try {
|
|
2628
|
+
return { ok: true, value: structuredClone(data) };
|
|
2629
|
+
} catch {
|
|
2630
|
+
return { ok: false, value: data };
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
var proto = (v) => Object.getPrototypeOf(v);
|
|
2634
|
+
var VIEW_TYPES = [
|
|
2635
|
+
"Int8Array",
|
|
2636
|
+
"Uint8Array",
|
|
2637
|
+
"Uint8ClampedArray",
|
|
2638
|
+
"Int16Array",
|
|
2639
|
+
"Uint16Array",
|
|
2640
|
+
"Int32Array",
|
|
2641
|
+
"Uint32Array",
|
|
2642
|
+
"Float32Array",
|
|
2643
|
+
"Float64Array",
|
|
2644
|
+
"BigInt64Array",
|
|
2645
|
+
"BigUint64Array",
|
|
2646
|
+
"DataView"
|
|
2647
|
+
];
|
|
2648
|
+
var isType = (v, name) => {
|
|
2649
|
+
const C = globalThis[name];
|
|
2650
|
+
return typeof C === "function" && v instanceof C;
|
|
2651
|
+
};
|
|
2652
|
+
function clonesFaithfully(v, seen) {
|
|
2653
|
+
if (typeof v === "function" || typeof v === "symbol") return false;
|
|
2654
|
+
if (v === null || typeof v !== "object") return true;
|
|
2655
|
+
if (seen.has(v)) return true;
|
|
2656
|
+
seen.add(v);
|
|
2657
|
+
if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
|
|
2658
|
+
if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
|
|
2659
|
+
if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
|
|
2660
|
+
const p = proto(v);
|
|
2661
|
+
if (p === Object.prototype || p === null)
|
|
2662
|
+
return Object.values(v).every((x) => clonesFaithfully(x, seen));
|
|
2663
|
+
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
|
|
2664
|
+
isType(v, "Blob") || isType(v, "FormData");
|
|
2665
|
+
}
|
|
2666
|
+
function reportCacheError(op, err) {
|
|
2667
|
+
if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2394
2670
|
// src/core/requestId.ts
|
|
2395
2671
|
var seq = 0;
|
|
2396
2672
|
function createRequestId() {
|
|
@@ -2422,6 +2698,10 @@ var Exios = class {
|
|
|
2422
2698
|
breaker;
|
|
2423
2699
|
registry;
|
|
2424
2700
|
events = new EventHub();
|
|
2701
|
+
memoryCache = new MemoryCache();
|
|
2702
|
+
inflight = new InflightRequests();
|
|
2703
|
+
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2704
|
+
cache;
|
|
2425
2705
|
constructor(defaults) {
|
|
2426
2706
|
this.defaults = defaults;
|
|
2427
2707
|
this.registry = new BreakerRegistry(
|
|
@@ -2438,6 +2718,50 @@ var Exios = class {
|
|
|
2438
2718
|
state: (key) => this.registry.state(key),
|
|
2439
2719
|
reset: (key) => this.registry.reset(key)
|
|
2440
2720
|
};
|
|
2721
|
+
const provider = () => {
|
|
2722
|
+
const c = this.defaults.cache;
|
|
2723
|
+
return typeof c === "object" && c?.provider || this.memoryCache;
|
|
2724
|
+
};
|
|
2725
|
+
this.cache = {
|
|
2726
|
+
clear: async () => {
|
|
2727
|
+
await provider().clear();
|
|
2728
|
+
},
|
|
2729
|
+
delete: async (key) => {
|
|
2730
|
+
await provider().delete(key);
|
|
2731
|
+
},
|
|
2732
|
+
key: (cfg = {}) => {
|
|
2733
|
+
const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
|
|
2734
|
+
const c = resolveCache(resolved.cache) || resolveCache(true);
|
|
2735
|
+
return c ? keyFor(resolved, c) : void 0;
|
|
2736
|
+
},
|
|
2737
|
+
invalidate: async (match) => {
|
|
2738
|
+
const p = provider();
|
|
2739
|
+
if (typeof p.keys !== "function")
|
|
2740
|
+
throw new ExiosError(
|
|
2741
|
+
"cache.invalidate needs a cache provider with keys()",
|
|
2742
|
+
ExiosError.ERR_NOT_SUPPORT
|
|
2743
|
+
);
|
|
2744
|
+
let test;
|
|
2745
|
+
if (typeof match === "function") test = match;
|
|
2746
|
+
else if (match instanceof RegExp) test = (k) => match.test(k);
|
|
2747
|
+
else {
|
|
2748
|
+
const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
|
|
2749
|
+
const prefix = target.slice(target.indexOf(" ") + 1);
|
|
2750
|
+
test = (k) => {
|
|
2751
|
+
const u = keyURL(k);
|
|
2752
|
+
return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
let n = 0;
|
|
2756
|
+
for (const k of [...await p.keys()]) {
|
|
2757
|
+
if (test(k)) {
|
|
2758
|
+
await p.delete(k);
|
|
2759
|
+
n++;
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
return n;
|
|
2763
|
+
}
|
|
2764
|
+
};
|
|
2441
2765
|
}
|
|
2442
2766
|
async request(configOrUrl, config) {
|
|
2443
2767
|
const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
|
|
@@ -2480,13 +2804,104 @@ var Exios = class {
|
|
|
2480
2804
|
off(name, listener) {
|
|
2481
2805
|
this.events.off(name, listener);
|
|
2482
2806
|
}
|
|
2483
|
-
/**
|
|
2807
|
+
/**
|
|
2808
|
+
* After request interceptors: ids → cache read → dedupe → network → cache write.
|
|
2809
|
+
* Cache hits and deduplicated followers make no network request and emit no lifecycle events.
|
|
2810
|
+
*/
|
|
2484
2811
|
async dispatch(config) {
|
|
2485
|
-
const
|
|
2486
|
-
|
|
2812
|
+
const start = Date.now();
|
|
2813
|
+
config.requestId ??= createRequestId();
|
|
2814
|
+
const totalTimeout = config.totalTimeout ?? 0;
|
|
2815
|
+
if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
|
|
2816
|
+
bad("totalTimeout", totalTimeout, "a non-negative finite number");
|
|
2817
|
+
const cacheCfg = resolveCache(config.cache);
|
|
2818
|
+
const dedupeCfg = resolveDedupe(config.dedupe);
|
|
2819
|
+
const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
|
|
2820
|
+
const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
|
|
2821
|
+
const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
|
|
2822
|
+
const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
|
|
2823
|
+
if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
|
|
2824
|
+
let entry;
|
|
2825
|
+
try {
|
|
2826
|
+
entry = await provider.get(cacheKey);
|
|
2827
|
+
} catch (e) {
|
|
2828
|
+
reportCacheError("get", e);
|
|
2829
|
+
}
|
|
2830
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
2831
|
+
const copy2 = cloneData(entry.data);
|
|
2832
|
+
return this.localResponse(config, start, {
|
|
2833
|
+
data: copy2.value,
|
|
2834
|
+
status: entry.status,
|
|
2835
|
+
statusText: entry.statusText,
|
|
2836
|
+
headers: { ...entry.headers },
|
|
2837
|
+
request: null,
|
|
2838
|
+
meta: { attempts: 0, cached: true }
|
|
2839
|
+
});
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2487
2842
|
const header = config.correlationIdHeader?.toLowerCase();
|
|
2488
2843
|
if (header && config.headers[header] === void 0)
|
|
2489
|
-
config.headers = { ...config.headers, [header]: correlationId ?? requestId };
|
|
2844
|
+
config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
|
|
2845
|
+
const network = async (c) => {
|
|
2846
|
+
const response2 = await this.network(c, start, totalTimeout);
|
|
2847
|
+
if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
|
|
2848
|
+
this.store(provider, cacheKey, response2, cacheCfg);
|
|
2849
|
+
return response2;
|
|
2850
|
+
};
|
|
2851
|
+
if (dedupeKey === void 0) return network(config);
|
|
2852
|
+
const { response, leader } = await this.inflight.join(
|
|
2853
|
+
dedupeKey,
|
|
2854
|
+
config,
|
|
2855
|
+
(signal) => network({ ...config, signal, cancelToken: void 0 })
|
|
2856
|
+
);
|
|
2857
|
+
if (leader) return response;
|
|
2858
|
+
const copy = cloneData(response.data);
|
|
2859
|
+
return this.localResponse(config, start, {
|
|
2860
|
+
...response,
|
|
2861
|
+
data: copy.value,
|
|
2862
|
+
headers: { ...response.headers },
|
|
2863
|
+
meta: { attempts: response.meta.attempts, deduped: true }
|
|
2864
|
+
});
|
|
2865
|
+
}
|
|
2866
|
+
/** A response made without a network request of its own (cache hit, deduplicated follower). */
|
|
2867
|
+
localResponse(config, start, r) {
|
|
2868
|
+
r.meta.requestId = config.requestId;
|
|
2869
|
+
if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
|
|
2870
|
+
r.meta.durationMs = Date.now() - start;
|
|
2871
|
+
return { ...r, config };
|
|
2872
|
+
}
|
|
2873
|
+
/** Store a successful response; provider failures are reported, never thrown. */
|
|
2874
|
+
store(provider, key, response, cfg) {
|
|
2875
|
+
if (response.status < 200 || response.status >= 300) return;
|
|
2876
|
+
let ttl = cfg.ttl;
|
|
2877
|
+
if (cfg.respectCacheControl) {
|
|
2878
|
+
const cc = parseCacheControl(response.headers["cache-control"]);
|
|
2879
|
+
if (cc.has("no-store") || cc.has("no-cache")) return;
|
|
2880
|
+
const maxAge = Number(cc.get("max-age"));
|
|
2881
|
+
if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
|
|
2882
|
+
}
|
|
2883
|
+
if (ttl <= 0) return;
|
|
2884
|
+
const copy = cloneData(response.data);
|
|
2885
|
+
if (!copy.ok) return;
|
|
2886
|
+
const now = Date.now();
|
|
2887
|
+
try {
|
|
2888
|
+
const r = provider.set(key, {
|
|
2889
|
+
status: response.status,
|
|
2890
|
+
statusText: response.statusText,
|
|
2891
|
+
headers: { ...response.headers },
|
|
2892
|
+
data: copy.value,
|
|
2893
|
+
storedAt: now,
|
|
2894
|
+
expiresAt: now + ttl
|
|
2895
|
+
});
|
|
2896
|
+
if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
|
|
2897
|
+
} catch (e) {
|
|
2898
|
+
reportCacheError("set", e);
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
/** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
|
|
2902
|
+
async network(config, start, totalTimeout) {
|
|
2903
|
+
const requestId = config.requestId;
|
|
2904
|
+
const { correlationId, metadata } = config;
|
|
2490
2905
|
const hub = this.events;
|
|
2491
2906
|
const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
|
|
2492
2907
|
const base = () => ({
|
|
@@ -2495,9 +2910,9 @@ var Exios = class {
|
|
|
2495
2910
|
method: config.method,
|
|
2496
2911
|
url,
|
|
2497
2912
|
config,
|
|
2913
|
+
metadata,
|
|
2498
2914
|
timestamp: Date.now()
|
|
2499
2915
|
});
|
|
2500
|
-
const start = Date.now();
|
|
2501
2916
|
const observer = {
|
|
2502
2917
|
onRetry: (o) => hub.emit("retry", () => ({
|
|
2503
2918
|
...base(),
|
|
@@ -2510,15 +2925,55 @@ var Exios = class {
|
|
|
2510
2925
|
if (TIMEOUT_CODES.has(error.code ?? ""))
|
|
2511
2926
|
hub.emit("timeout", () => ({
|
|
2512
2927
|
...base(),
|
|
2928
|
+
kind: "attempt",
|
|
2513
2929
|
attempt,
|
|
2514
2930
|
timeoutMs: config.timeout ?? 0,
|
|
2515
2931
|
error
|
|
2516
2932
|
}));
|
|
2517
2933
|
}
|
|
2518
2934
|
};
|
|
2935
|
+
let timer;
|
|
2936
|
+
let totalFired = false;
|
|
2937
|
+
let joined;
|
|
2938
|
+
let dispatchConfig = config;
|
|
2939
|
+
if (totalTimeout > 0) {
|
|
2940
|
+
const ac = new AbortController();
|
|
2941
|
+
timer = setTimeout(() => {
|
|
2942
|
+
totalFired = true;
|
|
2943
|
+
ac.abort(new Error("totalTimeout"));
|
|
2944
|
+
}, totalTimeout);
|
|
2945
|
+
joined = combineSignals(config.signal, ac.signal);
|
|
2946
|
+
dispatchConfig = { ...config, signal: joined.signal };
|
|
2947
|
+
}
|
|
2948
|
+
let deferCleanup = false;
|
|
2519
2949
|
hub.emit("request", base);
|
|
2520
2950
|
try {
|
|
2521
|
-
|
|
2951
|
+
let response;
|
|
2952
|
+
try {
|
|
2953
|
+
response = await dispatchRequest(dispatchConfig, this.registry, observer);
|
|
2954
|
+
} catch (e) {
|
|
2955
|
+
if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
|
|
2956
|
+
const err = new ExiosError(
|
|
2957
|
+
`total timeout of ${totalTimeout}ms exceeded`,
|
|
2958
|
+
config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
|
|
2959
|
+
config,
|
|
2960
|
+
e.request
|
|
2961
|
+
);
|
|
2962
|
+
err.cause = e;
|
|
2963
|
+
err.meta.attempts = e.meta.attempts;
|
|
2964
|
+
hub.emit("timeout", () => ({
|
|
2965
|
+
...base(),
|
|
2966
|
+
kind: "total",
|
|
2967
|
+
attempt: err.meta.attempts,
|
|
2968
|
+
timeoutMs: totalTimeout,
|
|
2969
|
+
error: err
|
|
2970
|
+
}));
|
|
2971
|
+
throw err;
|
|
2972
|
+
}
|
|
2973
|
+
if (joined && isOneShotBody(response.data)) {
|
|
2974
|
+
response.data = whenBodyDone(response.data, joined.cleanup);
|
|
2975
|
+
deferCleanup = true;
|
|
2976
|
+
}
|
|
2522
2977
|
const durationMs = Date.now() - start;
|
|
2523
2978
|
const meta = response.meta;
|
|
2524
2979
|
meta.requestId = requestId;
|
|
@@ -2558,6 +3013,9 @@ var Exios = class {
|
|
|
2558
3013
|
}));
|
|
2559
3014
|
}
|
|
2560
3015
|
throw e;
|
|
3016
|
+
} finally {
|
|
3017
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
3018
|
+
if (joined && !deferCleanup) joined.cleanup();
|
|
2561
3019
|
}
|
|
2562
3020
|
}
|
|
2563
3021
|
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
@@ -2670,7 +3128,10 @@ function detachDefaults(d) {
|
|
|
2670
3128
|
"transitional",
|
|
2671
3129
|
"fetchOptions",
|
|
2672
3130
|
"auth",
|
|
2673
|
-
"breaker"
|
|
3131
|
+
"breaker",
|
|
3132
|
+
"metadata",
|
|
3133
|
+
"cache",
|
|
3134
|
+
"dedupe"
|
|
2674
3135
|
]) {
|
|
2675
3136
|
if (isPlainObject4(out[k])) out[k] = { ...out[k] };
|
|
2676
3137
|
}
|
|
@@ -2700,6 +3161,7 @@ function createInstance(defaults) {
|
|
|
2700
3161
|
});
|
|
2701
3162
|
instance.interceptors = context.interceptors;
|
|
2702
3163
|
instance.breaker = context.breaker;
|
|
3164
|
+
instance.cache = context.cache;
|
|
2703
3165
|
instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
|
|
2704
3166
|
return instance;
|
|
2705
3167
|
}
|
|
@@ -2715,7 +3177,8 @@ var statics = {
|
|
|
2715
3177
|
isExiosError,
|
|
2716
3178
|
isCancel,
|
|
2717
3179
|
mergeConfig,
|
|
2718
|
-
toFormData
|
|
3180
|
+
toFormData,
|
|
3181
|
+
MemoryCache
|
|
2719
3182
|
};
|
|
2720
3183
|
var exios = Object.assign(
|
|
2721
3184
|
createInstance(createDefaults()),
|
|
@@ -2732,6 +3195,7 @@ export {
|
|
|
2732
3195
|
CanceledError,
|
|
2733
3196
|
CircuitOpenError,
|
|
2734
3197
|
ExiosError,
|
|
3198
|
+
MemoryCache,
|
|
2735
3199
|
create,
|
|
2736
3200
|
node_default as default,
|
|
2737
3201
|
isCancel,
|
package/package.json
CHANGED