@indra211/exios 3.1.2 → 3.3.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.
@@ -0,0 +1,87 @@
1
+ import { AdapterFn, Method, InternalConfig, ExiosInstance } from '@indra211/exios';
2
+
3
+ /** `[status, data?, headers?]`: what a reply function returns. */
4
+ type MockReplyTuple = [status: number, data?: unknown, headers?: Record<string, string>];
5
+ type MockReplyFn = (config: InternalConfig) => MockReplyTuple | Promise<MockReplyTuple>;
6
+ /** Extra conditions for a handler; every given one must match. */
7
+ interface MockMatchOptions {
8
+ /** Deep-equal to `config.params`. */
9
+ params?: Record<string, unknown>;
10
+ /** Each listed header must be sent with this value (names are case-insensitive). */
11
+ headers?: Record<string, string>;
12
+ /** Deep-equal to the request body (a JSON string body is parsed first), or a predicate. */
13
+ data?: unknown;
14
+ /** Any other condition. */
15
+ match?: (config: InternalConfig) => boolean;
16
+ }
17
+ type MockUrlMatcher = string | RegExp | ((url: string) => boolean);
18
+ /** One recorded request. */
19
+ interface MockRequest {
20
+ method: Lowercase<Method>;
21
+ /** The full URL, with params. */
22
+ url: string;
23
+ /** The headers as sent. */
24
+ headers: Record<string, string>;
25
+ /** `config.data` as given (before transformRequest). */
26
+ data: unknown;
27
+ /** The body as sent (after transformRequest). */
28
+ body: unknown;
29
+ config: InternalConfig;
30
+ }
31
+ interface MockHandler {
32
+ /** Respond with this status, data and headers. Plain objects and arrays are sent as JSON. */
33
+ reply(status: number, data?: unknown, headers?: Record<string, string>): MockAdapter;
34
+ reply(fn: MockReplyFn): MockAdapter;
35
+ /** Like `reply`, for the next matching request only. */
36
+ replyOnce(status: number, data?: unknown, headers?: Record<string, string>): MockAdapter;
37
+ replyOnce(fn: MockReplyFn): MockAdapter;
38
+ /** Fail like a refused or dropped connection (`ERR_NETWORK`, retried like a real one). */
39
+ networkError(): MockAdapter;
40
+ networkErrorOnce(): MockAdapter;
41
+ /** Fail like an expired `timeout` (`ECONNABORTED`, or `ETIMEDOUT` with `transitional.clarifyTimeoutError`). */
42
+ timeout(): MockAdapter;
43
+ timeoutOnce(): MockAdapter;
44
+ /** Wait this long before answering (combined with `timeout`/`signal` like a slow server). */
45
+ delay(ms: number): MockHandler;
46
+ }
47
+ interface MockAdapterOptions {
48
+ /** Delay every reply (ms). Default 0. */
49
+ delay?: number;
50
+ /** A request no handler matches: `'throw'` (default) rejects with `ERR_MOCK_NO_MATCH`; `'404'` answers 404. */
51
+ onNoMatch?: "throw" | "404";
52
+ }
53
+ type HistoryMap = {
54
+ [M in Lowercase<Method>]: MockRequest[];
55
+ } & {
56
+ all: MockRequest[];
57
+ };
58
+ interface MockAdapter {
59
+ /** Use as `config.adapter` (or `createMockAdapter(instance)` sets it for you). */
60
+ readonly adapter: AdapterFn;
61
+ /** Requests received, all of them and per method. */
62
+ readonly history: HistoryMap;
63
+ onGet(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
64
+ onPost(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
65
+ onPut(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
66
+ onPatch(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
67
+ onDelete(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
68
+ onHead(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
69
+ onOptions(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
70
+ /** Any method. */
71
+ onAny(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
72
+ /** Remove every handler and the history. */
73
+ reset(): void;
74
+ resetHandlers(): void;
75
+ resetHistory(): void;
76
+ /** Give the instance back the adapter it had before `createMockAdapter(instance)`. */
77
+ restore(): void;
78
+ }
79
+ /**
80
+ * A mock adapter. With an instance, it becomes that instance's adapter (`restore()` undoes it); without
81
+ * one, pass `mock.adapter` as `config.adapter`. The rest of exios (transforms, validateStatus, retry,
82
+ * breaker, interceptors, plugins, events) runs for real on top of it.
83
+ */
84
+ declare function createMockAdapter(instance?: ExiosInstance, options?: MockAdapterOptions): MockAdapter;
85
+
86
+ export { createMockAdapter };
87
+ export type { MockAdapter, MockAdapterOptions, MockHandler, MockMatchOptions, MockReplyFn, MockReplyTuple, MockRequest, MockUrlMatcher };
@@ -0,0 +1,244 @@
1
+ // src/testing/index.ts
2
+ import exios from "@indra211/exios";
3
+
4
+ // src/core/internals.ts
5
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
6
+
7
+ // src/testing/index.ts
8
+ var core = exios[INTERNALS];
9
+ if (!core)
10
+ throw new Error("@indra211/exios/testing: the installed @indra211/exios is too old (needs 3.2.0 or newer)");
11
+ var { abortError, buildFullPath, finishResponse, prepareRequest } = core;
12
+ var { ExiosError } = exios;
13
+ var METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
14
+ function createMockAdapter(instance, options = {}) {
15
+ const handlers = [];
16
+ const history = emptyHistory();
17
+ const baseDelay = options.delay ?? 0;
18
+ checkDelay(baseDelay);
19
+ const previous = instance ? { adapter: instance.defaults.adapter } : void 0;
20
+ const adapter = async (config) => {
21
+ const prepared = prepareRequest(config);
22
+ const request = {
23
+ method: config.method,
24
+ url: prepared.url,
25
+ headers: prepared.headers,
26
+ data: config.data,
27
+ body: prepared.body,
28
+ config
29
+ };
30
+ history.all.push(request);
31
+ history[config.method]?.push(request);
32
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
33
+ const handler = handlers.find((h) => matches(h, config, request, fullPath));
34
+ if (handler?.once) handlers.splice(handlers.indexOf(handler), 1);
35
+ const ms = handler?.delay ?? baseDelay;
36
+ const reqInfo = { mock: true, method: config.method, url: prepared.url };
37
+ if (!handler) {
38
+ if (options.onNoMatch === "404") {
39
+ await wait(ms, config, reqInfo);
40
+ return finishResponse(config, { status: 404, statusText: "Not Found", headers: {}, data: "", request: reqInfo });
41
+ }
42
+ throw new ExiosError(
43
+ `[exios mock] no handler for ${config.method.toUpperCase()} ${prepared.url}`,
44
+ "ERR_MOCK_NO_MATCH",
45
+ config,
46
+ reqInfo
47
+ );
48
+ }
49
+ const r = handler.reply;
50
+ if (r.kind === "timeout") {
51
+ await wait(ms, config, reqInfo);
52
+ throw timeoutError(config, reqInfo);
53
+ }
54
+ await wait(ms, config, reqInfo);
55
+ if (r.kind === "networkError") throw new ExiosError("Network Error", ExiosError.ERR_NETWORK, config, reqInfo);
56
+ const [status, data, headers = {}] = await r.fn(config);
57
+ const raw = toRaw(data, headers, config);
58
+ return finishResponse(config, {
59
+ status,
60
+ statusText: STATUS_TEXT[status] ?? "",
61
+ headers: raw.headers,
62
+ data: raw.data,
63
+ request: reqInfo
64
+ });
65
+ };
66
+ const on = (method) => (url, opts = {}) => {
67
+ let delay;
68
+ const add = (reply, once) => {
69
+ handlers.push({ method, url, options: opts, reply, once, delay });
70
+ return mock;
71
+ };
72
+ const fnOf = (a, data, headers) => {
73
+ if (typeof a === "function") return a;
74
+ if (!Number.isInteger(a)) throw new TypeError(`[exios mock] reply status must be an integer (got ${String(a)})`);
75
+ return () => [a, data, headers];
76
+ };
77
+ const h = {
78
+ reply: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, false),
79
+ replyOnce: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, true),
80
+ networkError: () => add({ kind: "networkError" }, false),
81
+ networkErrorOnce: () => add({ kind: "networkError" }, true),
82
+ timeout: () => add({ kind: "timeout" }, false),
83
+ timeoutOnce: () => add({ kind: "timeout" }, true),
84
+ delay: (ms) => {
85
+ checkDelay(ms);
86
+ delay = ms;
87
+ return h;
88
+ }
89
+ };
90
+ return h;
91
+ };
92
+ const mock = {
93
+ adapter,
94
+ history,
95
+ onGet: on("get"),
96
+ onPost: on("post"),
97
+ onPut: on("put"),
98
+ onPatch: on("patch"),
99
+ onDelete: on("delete"),
100
+ onHead: on("head"),
101
+ onOptions: on("options"),
102
+ onAny: on("any"),
103
+ reset() {
104
+ handlers.length = 0;
105
+ mock.resetHistory();
106
+ },
107
+ resetHandlers() {
108
+ handlers.length = 0;
109
+ },
110
+ resetHistory() {
111
+ for (const list of Object.values(history)) list.length = 0;
112
+ },
113
+ restore() {
114
+ if (instance && previous && instance.defaults.adapter === adapter) instance.defaults.adapter = previous.adapter;
115
+ }
116
+ };
117
+ if (instance) instance.defaults.adapter = adapter;
118
+ return mock;
119
+ }
120
+ function emptyHistory() {
121
+ const h = { all: [] };
122
+ for (const m of METHODS) h[m] = [];
123
+ return h;
124
+ }
125
+ function checkDelay(ms) {
126
+ if (typeof ms !== "number" || !(ms >= 0) || !Number.isFinite(ms))
127
+ throw new TypeError(`[exios mock] delay must be a non-negative finite number (got ${String(ms)})`);
128
+ }
129
+ function matches(h, config, req, fullPath) {
130
+ if (h.method !== "any" && h.method !== config.method) return false;
131
+ if (h.url !== void 0 && !urlMatches(h.url, [config.url ?? "", fullPath, req.url])) return false;
132
+ const o = h.options;
133
+ if (o.params !== void 0 && !deepEqual(o.params, config.params ?? {})) return false;
134
+ if (o.headers !== void 0) {
135
+ const sent = lowerKeys(req.headers);
136
+ for (const [k, v] of Object.entries(o.headers)) if (sent[k.toLowerCase()] !== String(v)) return false;
137
+ }
138
+ if (o.data !== void 0) {
139
+ if (typeof o.data === "function") {
140
+ if (!o.data(config.data)) return false;
141
+ } else if (!deepEqual(o.data, parseBody(config.data))) return false;
142
+ }
143
+ return !o.match || o.match(config);
144
+ }
145
+ function urlMatches(m, candidates) {
146
+ if (typeof m === "function") return candidates.some(m);
147
+ if (m instanceof RegExp) return candidates.some((c) => test(m, c));
148
+ return candidates.some((c) => c === m || !m.includes("?") && c.split("?")[0] === m);
149
+ }
150
+ function test(re, s) {
151
+ re.lastIndex = 0;
152
+ return re.test(s);
153
+ }
154
+ function parseBody(data) {
155
+ if (typeof data !== "string") return data;
156
+ try {
157
+ return JSON.parse(data);
158
+ } catch {
159
+ return data;
160
+ }
161
+ }
162
+ function lowerKeys(h) {
163
+ const out = {};
164
+ for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
165
+ return out;
166
+ }
167
+ function deepEqual(a, b) {
168
+ if (Object.is(a, b)) return true;
169
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
170
+ return (typeof a === "number" || typeof b === "number") && String(a) === String(b);
171
+ }
172
+ if (a instanceof Date || b instanceof Date)
173
+ return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
174
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
175
+ const ka = Object.keys(a).filter((k) => a[k] !== void 0);
176
+ const kb = Object.keys(b).filter((k) => b[k] !== void 0);
177
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
178
+ }
179
+ var isPlain = (v) => Array.isArray(v) || typeof v === "object" && v !== null && [Object.prototype, null].includes(Object.getPrototypeOf(v));
180
+ function toRaw(data, headers, config) {
181
+ const h = lowerKeys(headers);
182
+ let body = data === void 0 ? "" : data;
183
+ if (isPlain(body)) {
184
+ body = JSON.stringify(body);
185
+ h["content-type"] ??= "application/json";
186
+ }
187
+ if (typeof body === "string") {
188
+ if (config.responseType === "arraybuffer") body = new TextEncoder().encode(body).buffer;
189
+ else if (config.responseType === "blob" && typeof Blob !== "undefined")
190
+ body = new Blob([body], h["content-type"] ? { type: h["content-type"] } : {});
191
+ }
192
+ return { data: body, headers: h };
193
+ }
194
+ function timeoutError(config, request) {
195
+ return new ExiosError(
196
+ config.timeoutErrorMessage ?? `timeout of ${config.timeout ?? 0}ms exceeded`,
197
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
198
+ config,
199
+ request
200
+ );
201
+ }
202
+ function wait(ms, config, request) {
203
+ const signal = config.signal;
204
+ if (signal?.aborted) return Promise.reject(abortError(signal, config, request));
205
+ const limit = config.timeout && config.timeout > 0 && config.timeout <= ms ? config.timeout : void 0;
206
+ if (ms === 0) return Promise.resolve();
207
+ return new Promise((resolve, reject) => {
208
+ const done = () => signal?.removeEventListener("abort", onAbort);
209
+ const timer = setTimeout(() => {
210
+ done();
211
+ if (limit !== void 0) reject(timeoutError(config, request));
212
+ else resolve();
213
+ }, limit ?? ms);
214
+ const onAbort = () => {
215
+ clearTimeout(timer);
216
+ done();
217
+ reject(abortError(signal, config, request));
218
+ };
219
+ signal?.addEventListener("abort", onAbort, { once: true });
220
+ });
221
+ }
222
+ var STATUS_TEXT = {
223
+ 200: "OK",
224
+ 201: "Created",
225
+ 202: "Accepted",
226
+ 204: "No Content",
227
+ 301: "Moved Permanently",
228
+ 302: "Found",
229
+ 304: "Not Modified",
230
+ 400: "Bad Request",
231
+ 401: "Unauthorized",
232
+ 403: "Forbidden",
233
+ 404: "Not Found",
234
+ 409: "Conflict",
235
+ 422: "Unprocessable Entity",
236
+ 429: "Too Many Requests",
237
+ 500: "Internal Server Error",
238
+ 502: "Bad Gateway",
239
+ 503: "Service Unavailable",
240
+ 504: "Gateway Timeout"
241
+ };
242
+ export {
243
+ createMockAdapter
244
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indra211/exios",
3
- "version": "3.1.2",
3
+ "version": "3.3.0",
4
4
  "description": "Zero-dependency axios-compatible HTTP client (XHR in browsers, Node http in Node, fetch fallback) with retry and a circuit breaker.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -11,6 +11,16 @@
11
11
  "main": "./dist/index.node.cjs",
12
12
  "module": "./dist/index.js",
13
13
  "types": "./dist/index.d.ts",
14
+ "typesVersions": {
15
+ "*": {
16
+ "testing": [
17
+ "./dist/testing.d.ts"
18
+ ],
19
+ "otel": [
20
+ "./dist/otel.d.ts"
21
+ ]
22
+ }
23
+ },
14
24
  "exports": {
15
25
  ".": {
16
26
  "deno": {
@@ -72,6 +82,26 @@
72
82
  "default": "./dist/index.cjs"
73
83
  }
74
84
  },
85
+ "./testing": {
86
+ "import": {
87
+ "types": "./dist/testing.d.ts",
88
+ "default": "./dist/testing.js"
89
+ },
90
+ "require": {
91
+ "types": "./dist/testing.d.cts",
92
+ "default": "./dist/testing.cjs"
93
+ }
94
+ },
95
+ "./otel": {
96
+ "import": {
97
+ "types": "./dist/otel.d.ts",
98
+ "default": "./dist/otel.js"
99
+ },
100
+ "require": {
101
+ "types": "./dist/otel.d.cts",
102
+ "default": "./dist/otel.cjs"
103
+ }
104
+ },
75
105
  "./package.json": "./package.json"
76
106
  },
77
107
  "files": [
@@ -98,6 +128,11 @@
98
128
  },
99
129
  "devDependencies": {
100
130
  "@arethetypeswrong/cli": "^0.18.5",
131
+ "@opentelemetry/api": "~1.9.0",
132
+ "@opentelemetry/context-async-hooks": "^2.12.1",
133
+ "@opentelemetry/core": "^2.12.1",
134
+ "@opentelemetry/sdk-metrics": "^2.12.1",
135
+ "@opentelemetry/sdk-trace-base": "^2.12.1",
101
136
  "@types/node": "^26.6.6",
102
137
  "@vitest/browser-playwright": "^5.1.0",
103
138
  "@vitest/browser-webdriverio": "^5.0.0",