@indra211/exios 3.1.1 → 3.2.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.
@@ -216,7 +216,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
216
216
  if (!baseURL) return u;
217
217
  if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
218
218
  if (!u) return baseURL;
219
- return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
219
+ return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
220
+ }
221
+ function trimSlashes(s, side) {
222
+ if (side === "start") {
223
+ let i = 0;
224
+ while (s.charCodeAt(i) === 47) i++;
225
+ return s.slice(i);
226
+ }
227
+ let j = s.length;
228
+ while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
229
+ return s.slice(0, j);
220
230
  }
221
231
 
222
232
  // src/core/toFormData.ts
@@ -748,6 +758,7 @@ function canReplay(next) {
748
758
  }
749
759
 
750
760
  // src/adapters/http/index.ts
761
+ var SUPPORTED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
751
762
  var CHUNK = 64 * 1024;
752
763
  var DEFAULT_ACCEPT_ENCODING = "gzip, compress, deflate, br";
753
764
  function requestOptions(hop, config) {
@@ -835,6 +846,8 @@ async function httpAdapter(config) {
835
846
  e.cause = err;
836
847
  throw e;
837
848
  }
849
+ if (!SUPPORTED_PROTOCOLS.has(url.protocol))
850
+ throw new ExiosError(`Unsupported protocol ${url.protocol}`, ExiosError.ERR_BAD_REQUEST, config);
838
851
  const hop = { url, method: prepared.method, headers, body };
839
852
  return new Promise((resolve, reject) => {
840
853
  const signal = config.signal;
@@ -929,7 +942,28 @@ async function httpAdapter(config) {
929
942
  async function onResponse(incoming) {
930
943
  const resHeaders = headersOf(incoming);
931
944
  const status = incoming.statusCode ?? 0;
932
- const next = maxRedirects > 0 ? nextRedirect(current, status, incoming.headers.location) : null;
945
+ let next = null;
946
+ if (maxRedirects > 0) {
947
+ try {
948
+ next = nextRedirect(current, status, incoming.headers.location);
949
+ } catch (err) {
950
+ incoming.resume();
951
+ const e = new ExiosError(
952
+ `Invalid redirect location: ${incoming.headers.location}`,
953
+ ExiosError.ERR_BAD_RESPONSE,
954
+ config,
955
+ req
956
+ );
957
+ e.cause = err;
958
+ return fail(e);
959
+ }
960
+ }
961
+ if (next && !SUPPORTED_PROTOCOLS.has(next.url.protocol)) {
962
+ incoming.resume();
963
+ return fail(
964
+ new ExiosError(`Unsupported protocol ${next.url.protocol}`, ExiosError.ERR_BAD_REQUEST, config, req)
965
+ );
966
+ }
933
967
  if (next && canReplay(next)) {
934
968
  if (++redirects > maxRedirects) {
935
969
  incoming.resume();
@@ -2124,6 +2158,8 @@ async function dispatchRequest(config, registry2, observer) {
2124
2158
  breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
2125
2159
  if (outcome.error) throw outcome.error;
2126
2160
  const response = outcome.response;
2161
+ response.meta ??= { attempts };
2162
+ response.config ??= config;
2127
2163
  response.meta.attempts = attempts;
2128
2164
  if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
2129
2165
  const { status } = response;
@@ -2506,6 +2542,61 @@ var InflightRequests = class {
2506
2542
  }
2507
2543
  };
2508
2544
 
2545
+ // src/core/plugins.ts
2546
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2547
+ function invalid(message) {
2548
+ throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2549
+ }
2550
+ var PluginRegistry = class {
2551
+ list = [];
2552
+ get size() {
2553
+ return this.list.length;
2554
+ }
2555
+ add(plugin, instance) {
2556
+ if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
2557
+ if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
2558
+ for (const h of HOOKS)
2559
+ if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
2560
+ invalid(`plugin "${plugin.name}": ${h} must be a function`);
2561
+ if (this.list.some((r) => r.plugin.name === plugin.name))
2562
+ invalid(`a plugin named "${plugin.name}" is already registered`);
2563
+ const entry = { plugin };
2564
+ const teardown = plugin.setup?.(instance);
2565
+ if (typeof teardown === "function") entry.teardown = teardown;
2566
+ this.list = [...this.list, entry];
2567
+ return () => void this.remove(plugin);
2568
+ }
2569
+ remove(nameOrPlugin) {
2570
+ const entry = this.list.find(
2571
+ (r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
2572
+ );
2573
+ if (!entry) return false;
2574
+ this.list = this.list.filter((r) => r !== entry);
2575
+ entry.teardown?.();
2576
+ return true;
2577
+ }
2578
+ /** Run `final` wrapped in every plugin's hooks. */
2579
+ run(config, final) {
2580
+ const plugins = this.list.map((r) => r.plugin);
2581
+ const layer = async (i, cfg) => {
2582
+ if (i === plugins.length) return final(cfg);
2583
+ const p = plugins[i];
2584
+ const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
2585
+ let response;
2586
+ try {
2587
+ response = await layer(i + 1, c);
2588
+ } catch (err) {
2589
+ if (!p.onError || isCancel(err)) throw err;
2590
+ const recovered = await p.onError(err, c);
2591
+ if (recovered == null) throw err;
2592
+ return recovered;
2593
+ }
2594
+ return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
2595
+ };
2596
+ return layer(0, config);
2597
+ }
2598
+ };
2599
+
2509
2600
  // src/core/requestCache.ts
2510
2601
  var SAFE_METHODS = Object.freeze(["get", "head"]);
2511
2602
  var MemoryCache = class {
@@ -2736,6 +2827,9 @@ var Exios = class {
2736
2827
  events = new EventHub();
2737
2828
  memoryCache = new MemoryCache();
2738
2829
  inflight = new InflightRequests();
2830
+ plugins = new PluginRegistry();
2831
+ /** The callable instance wrapping this context (given to plugin `setup`). */
2832
+ instance;
2739
2833
  /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2740
2834
  cache;
2741
2835
  constructor(defaults) {
@@ -2810,7 +2904,11 @@ var Exios = class {
2810
2904
  synchronous = synchronous && h.synchronous;
2811
2905
  requestChain.unshift(h);
2812
2906
  });
2813
- const dispatch = (c) => this.dispatch(finalizeConfig(c));
2907
+ const dispatch = (c) => {
2908
+ const finalized = finalizeConfig(c);
2909
+ if (this.plugins.size === 0) return this.dispatch(finalized);
2910
+ return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
2911
+ };
2814
2912
  let promise;
2815
2913
  if (synchronous) {
2816
2914
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -2828,6 +2926,14 @@ var Exios = class {
2828
2926
  });
2829
2927
  return promise;
2830
2928
  }
2929
+ /** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
2930
+ use(plugin) {
2931
+ return this.plugins.add(plugin, this.instance);
2932
+ }
2933
+ /** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
2934
+ eject(nameOrPlugin) {
2935
+ return this.plugins.remove(nameOrPlugin);
2936
+ }
2831
2937
  /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2832
2938
  on(name, listener) {
2833
2939
  return this.events.on(name, listener);
@@ -3131,6 +3237,8 @@ var Exios = class {
3131
3237
  };
3132
3238
  var METHODS = [
3133
3239
  "request",
3240
+ "use",
3241
+ "eject",
3134
3242
  "on",
3135
3243
  "once",
3136
3244
  "off",
@@ -3195,6 +3303,7 @@ function createInstance(defaults) {
3195
3303
  set: (v) => context.defaults = v,
3196
3304
  enumerable: true
3197
3305
  });
3306
+ context.instance = instance;
3198
3307
  instance.interceptors = context.interceptors;
3199
3308
  instance.breaker = context.breaker;
3200
3309
  instance.cache = context.cache;
@@ -3202,6 +3311,10 @@ function createInstance(defaults) {
3202
3311
  return instance;
3203
3312
  }
3204
3313
 
3314
+ // src/core/internals.ts
3315
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
3316
+ var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
3317
+
3205
3318
  // src/index.ts
3206
3319
  registerXhrAdapter();
3207
3320
  registerFetchAdapter();
@@ -3220,6 +3333,7 @@ var exios = Object.assign(
3220
3333
  createInstance(createDefaults()),
3221
3334
  statics
3222
3335
  );
3336
+ Object.defineProperty(exios, INTERNALS, { value: internals });
3223
3337
  var create = exios.create;
3224
3338
  var src_default = exios;
3225
3339
 
@@ -180,7 +180,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
180
180
  if (!baseURL) return u;
181
181
  if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
182
182
  if (!u) return baseURL;
183
- return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
183
+ return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
184
+ }
185
+ function trimSlashes(s, side) {
186
+ if (side === "start") {
187
+ let i = 0;
188
+ while (s.charCodeAt(i) === 47) i++;
189
+ return s.slice(i);
190
+ }
191
+ let j = s.length;
192
+ while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
193
+ return s.slice(0, j);
184
194
  }
185
195
 
186
196
  // src/core/toFormData.ts
@@ -712,6 +722,7 @@ function canReplay(next) {
712
722
  }
713
723
 
714
724
  // src/adapters/http/index.ts
725
+ var SUPPORTED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
715
726
  var CHUNK = 64 * 1024;
716
727
  var DEFAULT_ACCEPT_ENCODING = "gzip, compress, deflate, br";
717
728
  function requestOptions(hop, config) {
@@ -799,6 +810,8 @@ async function httpAdapter(config) {
799
810
  e.cause = err;
800
811
  throw e;
801
812
  }
813
+ if (!SUPPORTED_PROTOCOLS.has(url.protocol))
814
+ throw new ExiosError(`Unsupported protocol ${url.protocol}`, ExiosError.ERR_BAD_REQUEST, config);
802
815
  const hop = { url, method: prepared.method, headers, body };
803
816
  return new Promise((resolve, reject) => {
804
817
  const signal = config.signal;
@@ -893,7 +906,28 @@ async function httpAdapter(config) {
893
906
  async function onResponse(incoming) {
894
907
  const resHeaders = headersOf(incoming);
895
908
  const status = incoming.statusCode ?? 0;
896
- const next = maxRedirects > 0 ? nextRedirect(current, status, incoming.headers.location) : null;
909
+ let next = null;
910
+ if (maxRedirects > 0) {
911
+ try {
912
+ next = nextRedirect(current, status, incoming.headers.location);
913
+ } catch (err) {
914
+ incoming.resume();
915
+ const e = new ExiosError(
916
+ `Invalid redirect location: ${incoming.headers.location}`,
917
+ ExiosError.ERR_BAD_RESPONSE,
918
+ config,
919
+ req
920
+ );
921
+ e.cause = err;
922
+ return fail(e);
923
+ }
924
+ }
925
+ if (next && !SUPPORTED_PROTOCOLS.has(next.url.protocol)) {
926
+ incoming.resume();
927
+ return fail(
928
+ new ExiosError(`Unsupported protocol ${next.url.protocol}`, ExiosError.ERR_BAD_REQUEST, config, req)
929
+ );
930
+ }
897
931
  if (next && canReplay(next)) {
898
932
  if (++redirects > maxRedirects) {
899
933
  incoming.resume();
@@ -2088,6 +2122,8 @@ async function dispatchRequest(config, registry2, observer) {
2088
2122
  breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
2089
2123
  if (outcome.error) throw outcome.error;
2090
2124
  const response = outcome.response;
2125
+ response.meta ??= { attempts };
2126
+ response.config ??= config;
2091
2127
  response.meta.attempts = attempts;
2092
2128
  if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
2093
2129
  const { status } = response;
@@ -2470,6 +2506,61 @@ var InflightRequests = class {
2470
2506
  }
2471
2507
  };
2472
2508
 
2509
+ // src/core/plugins.ts
2510
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2511
+ function invalid(message) {
2512
+ throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2513
+ }
2514
+ var PluginRegistry = class {
2515
+ list = [];
2516
+ get size() {
2517
+ return this.list.length;
2518
+ }
2519
+ add(plugin, instance) {
2520
+ if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
2521
+ if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
2522
+ for (const h of HOOKS)
2523
+ if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
2524
+ invalid(`plugin "${plugin.name}": ${h} must be a function`);
2525
+ if (this.list.some((r) => r.plugin.name === plugin.name))
2526
+ invalid(`a plugin named "${plugin.name}" is already registered`);
2527
+ const entry = { plugin };
2528
+ const teardown = plugin.setup?.(instance);
2529
+ if (typeof teardown === "function") entry.teardown = teardown;
2530
+ this.list = [...this.list, entry];
2531
+ return () => void this.remove(plugin);
2532
+ }
2533
+ remove(nameOrPlugin) {
2534
+ const entry = this.list.find(
2535
+ (r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
2536
+ );
2537
+ if (!entry) return false;
2538
+ this.list = this.list.filter((r) => r !== entry);
2539
+ entry.teardown?.();
2540
+ return true;
2541
+ }
2542
+ /** Run `final` wrapped in every plugin's hooks. */
2543
+ run(config, final) {
2544
+ const plugins = this.list.map((r) => r.plugin);
2545
+ const layer = async (i, cfg) => {
2546
+ if (i === plugins.length) return final(cfg);
2547
+ const p = plugins[i];
2548
+ const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
2549
+ let response;
2550
+ try {
2551
+ response = await layer(i + 1, c);
2552
+ } catch (err) {
2553
+ if (!p.onError || isCancel(err)) throw err;
2554
+ const recovered = await p.onError(err, c);
2555
+ if (recovered == null) throw err;
2556
+ return recovered;
2557
+ }
2558
+ return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
2559
+ };
2560
+ return layer(0, config);
2561
+ }
2562
+ };
2563
+
2473
2564
  // src/core/requestCache.ts
2474
2565
  var SAFE_METHODS = Object.freeze(["get", "head"]);
2475
2566
  var MemoryCache = class {
@@ -2700,6 +2791,9 @@ var Exios = class {
2700
2791
  events = new EventHub();
2701
2792
  memoryCache = new MemoryCache();
2702
2793
  inflight = new InflightRequests();
2794
+ plugins = new PluginRegistry();
2795
+ /** The callable instance wrapping this context (given to plugin `setup`). */
2796
+ instance;
2703
2797
  /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2704
2798
  cache;
2705
2799
  constructor(defaults) {
@@ -2774,7 +2868,11 @@ var Exios = class {
2774
2868
  synchronous = synchronous && h.synchronous;
2775
2869
  requestChain.unshift(h);
2776
2870
  });
2777
- const dispatch = (c) => this.dispatch(finalizeConfig(c));
2871
+ const dispatch = (c) => {
2872
+ const finalized = finalizeConfig(c);
2873
+ if (this.plugins.size === 0) return this.dispatch(finalized);
2874
+ return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
2875
+ };
2778
2876
  let promise;
2779
2877
  if (synchronous) {
2780
2878
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -2792,6 +2890,14 @@ var Exios = class {
2792
2890
  });
2793
2891
  return promise;
2794
2892
  }
2893
+ /** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
2894
+ use(plugin) {
2895
+ return this.plugins.add(plugin, this.instance);
2896
+ }
2897
+ /** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
2898
+ eject(nameOrPlugin) {
2899
+ return this.plugins.remove(nameOrPlugin);
2900
+ }
2795
2901
  /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2796
2902
  on(name, listener) {
2797
2903
  return this.events.on(name, listener);
@@ -3095,6 +3201,8 @@ var Exios = class {
3095
3201
  };
3096
3202
  var METHODS = [
3097
3203
  "request",
3204
+ "use",
3205
+ "eject",
3098
3206
  "on",
3099
3207
  "once",
3100
3208
  "off",
@@ -3159,6 +3267,7 @@ function createInstance(defaults) {
3159
3267
  set: (v) => context.defaults = v,
3160
3268
  enumerable: true
3161
3269
  });
3270
+ context.instance = instance;
3162
3271
  instance.interceptors = context.interceptors;
3163
3272
  instance.breaker = context.breaker;
3164
3273
  instance.cache = context.cache;
@@ -3166,6 +3275,10 @@ function createInstance(defaults) {
3166
3275
  return instance;
3167
3276
  }
3168
3277
 
3278
+ // src/core/internals.ts
3279
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
3280
+ var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
3281
+
3169
3282
  // src/index.ts
3170
3283
  registerXhrAdapter();
3171
3284
  registerFetchAdapter();
@@ -3184,6 +3297,7 @@ var exios = Object.assign(
3184
3297
  createInstance(createDefaults()),
3185
3298
  statics
3186
3299
  );
3300
+ Object.defineProperty(exios, INTERNALS, { value: internals });
3187
3301
  var create = exios.create;
3188
3302
  var src_default = exios;
3189
3303
 
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/testing/index.ts
31
+ var testing_exports = {};
32
+ __export(testing_exports, {
33
+ createMockAdapter: () => createMockAdapter
34
+ });
35
+ module.exports = __toCommonJS(testing_exports);
36
+ var import_exios = __toESM(require("@indra211/exios"), 1);
37
+
38
+ // src/core/internals.ts
39
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
40
+
41
+ // src/testing/index.ts
42
+ var core = import_exios.default[INTERNALS];
43
+ if (!core)
44
+ throw new Error("@indra211/exios/testing: the installed @indra211/exios is too old (needs 3.2.0 or newer)");
45
+ var { abortError, buildFullPath, finishResponse, prepareRequest } = core;
46
+ var { ExiosError } = import_exios.default;
47
+ var METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
48
+ function createMockAdapter(instance, options = {}) {
49
+ const handlers = [];
50
+ const history = emptyHistory();
51
+ const baseDelay = options.delay ?? 0;
52
+ checkDelay(baseDelay);
53
+ const previous = instance ? { adapter: instance.defaults.adapter } : void 0;
54
+ const adapter = async (config) => {
55
+ const prepared = prepareRequest(config);
56
+ const request = {
57
+ method: config.method,
58
+ url: prepared.url,
59
+ headers: prepared.headers,
60
+ data: config.data,
61
+ body: prepared.body,
62
+ config
63
+ };
64
+ history.all.push(request);
65
+ history[config.method]?.push(request);
66
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
67
+ const handler = handlers.find((h) => matches(h, config, request, fullPath));
68
+ if (handler?.once) handlers.splice(handlers.indexOf(handler), 1);
69
+ const ms = handler?.delay ?? baseDelay;
70
+ const reqInfo = { mock: true, method: config.method, url: prepared.url };
71
+ if (!handler) {
72
+ if (options.onNoMatch === "404") {
73
+ await wait(ms, config, reqInfo);
74
+ return finishResponse(config, { status: 404, statusText: "Not Found", headers: {}, data: "", request: reqInfo });
75
+ }
76
+ throw new ExiosError(
77
+ `[exios mock] no handler for ${config.method.toUpperCase()} ${prepared.url}`,
78
+ "ERR_MOCK_NO_MATCH",
79
+ config,
80
+ reqInfo
81
+ );
82
+ }
83
+ const r = handler.reply;
84
+ if (r.kind === "timeout") {
85
+ await wait(ms, config, reqInfo);
86
+ throw timeoutError(config, reqInfo);
87
+ }
88
+ await wait(ms, config, reqInfo);
89
+ if (r.kind === "networkError") throw new ExiosError("Network Error", ExiosError.ERR_NETWORK, config, reqInfo);
90
+ const [status, data, headers = {}] = await r.fn(config);
91
+ const raw = toRaw(data, headers, config);
92
+ return finishResponse(config, {
93
+ status,
94
+ statusText: STATUS_TEXT[status] ?? "",
95
+ headers: raw.headers,
96
+ data: raw.data,
97
+ request: reqInfo
98
+ });
99
+ };
100
+ const on = (method) => (url, opts = {}) => {
101
+ let delay;
102
+ const add = (reply, once) => {
103
+ handlers.push({ method, url, options: opts, reply, once, delay });
104
+ return mock;
105
+ };
106
+ const fnOf = (a, data, headers) => {
107
+ if (typeof a === "function") return a;
108
+ if (!Number.isInteger(a)) throw new TypeError(`[exios mock] reply status must be an integer (got ${String(a)})`);
109
+ return () => [a, data, headers];
110
+ };
111
+ const h = {
112
+ reply: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, false),
113
+ replyOnce: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, true),
114
+ networkError: () => add({ kind: "networkError" }, false),
115
+ networkErrorOnce: () => add({ kind: "networkError" }, true),
116
+ timeout: () => add({ kind: "timeout" }, false),
117
+ timeoutOnce: () => add({ kind: "timeout" }, true),
118
+ delay: (ms) => {
119
+ checkDelay(ms);
120
+ delay = ms;
121
+ return h;
122
+ }
123
+ };
124
+ return h;
125
+ };
126
+ const mock = {
127
+ adapter,
128
+ history,
129
+ onGet: on("get"),
130
+ onPost: on("post"),
131
+ onPut: on("put"),
132
+ onPatch: on("patch"),
133
+ onDelete: on("delete"),
134
+ onHead: on("head"),
135
+ onOptions: on("options"),
136
+ onAny: on("any"),
137
+ reset() {
138
+ handlers.length = 0;
139
+ mock.resetHistory();
140
+ },
141
+ resetHandlers() {
142
+ handlers.length = 0;
143
+ },
144
+ resetHistory() {
145
+ for (const list of Object.values(history)) list.length = 0;
146
+ },
147
+ restore() {
148
+ if (instance && previous && instance.defaults.adapter === adapter) instance.defaults.adapter = previous.adapter;
149
+ }
150
+ };
151
+ if (instance) instance.defaults.adapter = adapter;
152
+ return mock;
153
+ }
154
+ function emptyHistory() {
155
+ const h = { all: [] };
156
+ for (const m of METHODS) h[m] = [];
157
+ return h;
158
+ }
159
+ function checkDelay(ms) {
160
+ if (typeof ms !== "number" || !(ms >= 0) || !Number.isFinite(ms))
161
+ throw new TypeError(`[exios mock] delay must be a non-negative finite number (got ${String(ms)})`);
162
+ }
163
+ function matches(h, config, req, fullPath) {
164
+ if (h.method !== "any" && h.method !== config.method) return false;
165
+ if (h.url !== void 0 && !urlMatches(h.url, [config.url ?? "", fullPath, req.url])) return false;
166
+ const o = h.options;
167
+ if (o.params !== void 0 && !deepEqual(o.params, config.params ?? {})) return false;
168
+ if (o.headers !== void 0) {
169
+ const sent = lowerKeys(req.headers);
170
+ for (const [k, v] of Object.entries(o.headers)) if (sent[k.toLowerCase()] !== String(v)) return false;
171
+ }
172
+ if (o.data !== void 0) {
173
+ if (typeof o.data === "function") {
174
+ if (!o.data(config.data)) return false;
175
+ } else if (!deepEqual(o.data, parseBody(config.data))) return false;
176
+ }
177
+ return !o.match || o.match(config);
178
+ }
179
+ function urlMatches(m, candidates) {
180
+ if (typeof m === "function") return candidates.some(m);
181
+ if (m instanceof RegExp) return candidates.some((c) => test(m, c));
182
+ return candidates.some((c) => c === m || !m.includes("?") && c.split("?")[0] === m);
183
+ }
184
+ function test(re, s) {
185
+ re.lastIndex = 0;
186
+ return re.test(s);
187
+ }
188
+ function parseBody(data) {
189
+ if (typeof data !== "string") return data;
190
+ try {
191
+ return JSON.parse(data);
192
+ } catch {
193
+ return data;
194
+ }
195
+ }
196
+ function lowerKeys(h) {
197
+ const out = {};
198
+ for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
199
+ return out;
200
+ }
201
+ function deepEqual(a, b) {
202
+ if (Object.is(a, b)) return true;
203
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
204
+ return (typeof a === "number" || typeof b === "number") && String(a) === String(b);
205
+ }
206
+ if (a instanceof Date || b instanceof Date)
207
+ return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
208
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
209
+ const ka = Object.keys(a).filter((k) => a[k] !== void 0);
210
+ const kb = Object.keys(b).filter((k) => b[k] !== void 0);
211
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
212
+ }
213
+ var isPlain = (v) => Array.isArray(v) || typeof v === "object" && v !== null && [Object.prototype, null].includes(Object.getPrototypeOf(v));
214
+ function toRaw(data, headers, config) {
215
+ const h = lowerKeys(headers);
216
+ let body = data === void 0 ? "" : data;
217
+ if (isPlain(body)) {
218
+ body = JSON.stringify(body);
219
+ h["content-type"] ??= "application/json";
220
+ }
221
+ if (typeof body === "string") {
222
+ if (config.responseType === "arraybuffer") body = new TextEncoder().encode(body).buffer;
223
+ else if (config.responseType === "blob" && typeof Blob !== "undefined")
224
+ body = new Blob([body], h["content-type"] ? { type: h["content-type"] } : {});
225
+ }
226
+ return { data: body, headers: h };
227
+ }
228
+ function timeoutError(config, request) {
229
+ return new ExiosError(
230
+ config.timeoutErrorMessage ?? `timeout of ${config.timeout ?? 0}ms exceeded`,
231
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
232
+ config,
233
+ request
234
+ );
235
+ }
236
+ function wait(ms, config, request) {
237
+ const signal = config.signal;
238
+ if (signal?.aborted) return Promise.reject(abortError(signal, config, request));
239
+ const limit = config.timeout && config.timeout > 0 && config.timeout <= ms ? config.timeout : void 0;
240
+ if (ms === 0) return Promise.resolve();
241
+ return new Promise((resolve, reject) => {
242
+ const done = () => signal?.removeEventListener("abort", onAbort);
243
+ const timer = setTimeout(() => {
244
+ done();
245
+ if (limit !== void 0) reject(timeoutError(config, request));
246
+ else resolve();
247
+ }, limit ?? ms);
248
+ const onAbort = () => {
249
+ clearTimeout(timer);
250
+ done();
251
+ reject(abortError(signal, config, request));
252
+ };
253
+ signal?.addEventListener("abort", onAbort, { once: true });
254
+ });
255
+ }
256
+ var STATUS_TEXT = {
257
+ 200: "OK",
258
+ 201: "Created",
259
+ 202: "Accepted",
260
+ 204: "No Content",
261
+ 301: "Moved Permanently",
262
+ 302: "Found",
263
+ 304: "Not Modified",
264
+ 400: "Bad Request",
265
+ 401: "Unauthorized",
266
+ 403: "Forbidden",
267
+ 404: "Not Found",
268
+ 409: "Conflict",
269
+ 422: "Unprocessable Entity",
270
+ 429: "Too Many Requests",
271
+ 500: "Internal Server Error",
272
+ 502: "Bad Gateway",
273
+ 503: "Service Unavailable",
274
+ 504: "Gateway Timeout"
275
+ };