@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.
package/dist/otel.d.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { InternalConfig, ExiosPlugin } from '@indra211/exios';
2
+
3
+ /** Same shape as `AttributeValue` in @opentelemetry/api (homogeneous arrays). */
4
+ type AttributeValue = string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>;
5
+ type OtelAttributes = Record<string, AttributeValue | undefined>;
6
+ interface OtelSpan {
7
+ setAttribute(key: string, value: AttributeValue): unknown;
8
+ setAttributes(attributes: OtelAttributes): unknown;
9
+ addEvent(name: string, attributes?: OtelAttributes): unknown;
10
+ setStatus(status: {
11
+ code: number;
12
+ message?: string;
13
+ }): unknown;
14
+ recordException(exception: Error | string): void;
15
+ end(): void;
16
+ }
17
+ /** The parts of `@opentelemetry/api` the plugin uses (pass the module itself). */
18
+ interface OtelApi {
19
+ trace: {
20
+ getTracer(name: string, version?: string): {
21
+ startSpan(name: string, options?: {
22
+ kind?: number;
23
+ attributes?: OtelAttributes;
24
+ }, context?: unknown): OtelSpan;
25
+ };
26
+ setSpan(context: unknown, span: OtelSpan): unknown;
27
+ };
28
+ context: {
29
+ active(): unknown;
30
+ };
31
+ propagation: {
32
+ inject(context: unknown, carrier: unknown): void;
33
+ };
34
+ metrics?: {
35
+ getMeter(name: string, version?: string): {
36
+ createHistogram(name: string, options?: {
37
+ description?: string;
38
+ unit?: string;
39
+ advice?: {
40
+ explicitBucketBoundaries?: number[];
41
+ };
42
+ }): {
43
+ record(value: number, attributes?: OtelAttributes): void;
44
+ };
45
+ };
46
+ };
47
+ }
48
+ interface OtelPluginOptions {
49
+ /** The `@opentelemetry/api` module: `import * as api from '@opentelemetry/api'`. */
50
+ api: OtelApi;
51
+ /** Tracer and meter name. Default `'@indra211/exios'`. */
52
+ name?: string;
53
+ /** Tracer and meter version. */
54
+ version?: string;
55
+ /**
56
+ * Which requests get trace-context headers (`traceparent`, ... from the registered propagator).
57
+ * Default: every request in Node and other servers; same-origin requests only in browsers (a new header
58
+ * on a cross-origin request triggers a CORS preflight and must be allowed by the server). A RegExp is
59
+ * tested against the full URL.
60
+ */
61
+ propagate?: boolean | RegExp | ((url: string) => boolean);
62
+ /** Record the `http.client.request.duration` histogram. Default true (when the API has metrics). */
63
+ metrics?: boolean;
64
+ /** Span name. Default: the HTTP method, as the semantic conventions prescribe (e.g. `GET`). */
65
+ spanName?: (config: InternalConfig) => string;
66
+ /** Extra span attributes, e.g. from `config.metadata`. Called once, when the span starts. */
67
+ attributes?: (config: InternalConfig) => OtelAttributes;
68
+ /** Plugin name. Default `'otel'`. */
69
+ pluginName?: string;
70
+ }
71
+ /**
72
+ * One CLIENT span per logical request (retries are span events on it), following the OpenTelemetry HTTP
73
+ * client semantic conventions, plus trace-context propagation and the `http.client.request.duration`
74
+ * histogram. Register it first, so it sees what every other plugin does.
75
+ */
76
+ declare function createOtelPlugin(options: OtelPluginOptions): ExiosPlugin;
77
+
78
+ export { createOtelPlugin };
79
+ export type { OtelApi, OtelAttributes, OtelPluginOptions, OtelSpan };
package/dist/otel.js ADDED
@@ -0,0 +1,168 @@
1
+ // src/otel/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/otel/index.ts
8
+ var core = exios[INTERNALS];
9
+ if (!core)
10
+ throw new Error("@indra211/exios/otel: the installed @indra211/exios is too old (needs 3.3.0 or newer)");
11
+ var { buildFullPath, buildURL, createRequestId, redactURL } = core;
12
+ var SPAN_KIND_CLIENT = 2;
13
+ var STATUS_ERROR = 2;
14
+ var KNOWN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]);
15
+ var DURATION_BUCKETS = [5e-3, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10];
16
+ var now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
17
+ function createOtelPlugin(options) {
18
+ const api = options?.api;
19
+ if (!api?.trace || !api.context || !api.propagation)
20
+ throw new TypeError("createOtelPlugin: pass the @opentelemetry/api module as `api`");
21
+ const name = options.name ?? "@indra211/exios";
22
+ const tracer = api.trace.getTracer(name, options.version);
23
+ const histogram = options.metrics !== false && api.metrics ? api.metrics.getMeter(name, options.version).createHistogram("http.client.request.duration", {
24
+ description: "Duration of HTTP client requests.",
25
+ unit: "s",
26
+ advice: { explicitBucketBoundaries: DURATION_BUCKETS }
27
+ }) : void 0;
28
+ const shouldPropagate = propagationRule(options.propagate);
29
+ const byConfig = /* @__PURE__ */ new WeakMap();
30
+ const byId = /* @__PURE__ */ new Map();
31
+ const finish = (config, outcome) => {
32
+ const state = byConfig.get(config);
33
+ if (!state) return;
34
+ byConfig.delete(config);
35
+ if (config.requestId !== void 0 && byId.get(config.requestId) === state) byId.delete(config.requestId);
36
+ const { span } = state;
37
+ const status = outcome.response?.status ?? outcome.status;
38
+ let errorType = outcome.errorType;
39
+ if (errorType === void 0 && status !== void 0 && status >= 400) errorType = String(status);
40
+ const end = {};
41
+ if (status !== void 0) end["http.response.status_code"] = status;
42
+ if (errorType !== void 0) end["error.type"] = errorType;
43
+ const meta = outcome.response?.meta;
44
+ const attempts = meta?.attempts ?? outcome.attempts;
45
+ if (attempts !== void 0) {
46
+ end["exios.attempts"] = attempts;
47
+ if (attempts > 1) end["http.request.resend_count"] = attempts - 1;
48
+ }
49
+ if (meta?.cached) end["exios.cached"] = true;
50
+ if (meta?.deduped) end["exios.deduped"] = true;
51
+ try {
52
+ span.setAttributes(end);
53
+ if (outcome.error !== void 0) {
54
+ const err = outcome.error;
55
+ span.recordException(err instanceof Error ? err : String(err));
56
+ }
57
+ if (errorType !== void 0 && errorType !== "ERR_CANCELED") {
58
+ const message = outcome.error instanceof Error ? outcome.error.message : void 0;
59
+ span.setStatus(message === void 0 ? { code: STATUS_ERROR } : { code: STATUS_ERROR, message });
60
+ }
61
+ span.end();
62
+ histogram?.record((now() - state.start) / 1e3, {
63
+ ...state.common,
64
+ ...status !== void 0 ? { "http.response.status_code": status } : {},
65
+ ...errorType !== void 0 ? { "error.type": errorType } : {}
66
+ });
67
+ } catch (e) {
68
+ report(e);
69
+ }
70
+ };
71
+ return {
72
+ name: options.pluginName ?? "otel",
73
+ setup(instance) {
74
+ return instance.on("retry", (e) => {
75
+ const state = byId.get(e.requestId);
76
+ if (!state) return;
77
+ const attrs = { "exios.retry.attempt": e.attempt, "exios.retry.delay_ms": e.delayMs };
78
+ if (e.status !== void 0) attrs["http.response.status_code"] = e.status;
79
+ if (e.error?.code !== void 0) attrs["error.type"] = e.error.code;
80
+ state.span.addEvent("exios.retry", attrs);
81
+ });
82
+ },
83
+ beforeRequest(config) {
84
+ try {
85
+ config.requestId ??= createRequestId();
86
+ const url = buildURL(
87
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
88
+ config.params,
89
+ config.paramsSerializer
90
+ );
91
+ const method = config.method.toUpperCase();
92
+ const common = { "http.request.method": KNOWN_METHODS.has(method) ? method : "_OTHER" };
93
+ const target = parseURL(url);
94
+ if (target) {
95
+ common["server.address"] = target.hostname.replace(/^\[|\]$/g, "");
96
+ common["server.port"] = Number(target.port) || (target.protocol === "https:" ? 443 : 80);
97
+ common["url.scheme"] = target.protocol.replace(/:$/, "");
98
+ }
99
+ const attributes = {
100
+ ...common,
101
+ "url.full": redactURL(target ? target.href : url),
102
+ "exios.request_id": config.requestId,
103
+ ...KNOWN_METHODS.has(method) ? {} : { "http.request.method_original": method },
104
+ ...options.attributes?.(config)
105
+ };
106
+ const parent = api.context.active();
107
+ const span = tracer.startSpan(options.spanName?.(config) ?? (KNOWN_METHODS.has(method) ? method : "HTTP"), { kind: SPAN_KIND_CLIENT, attributes }, parent);
108
+ const state = { span, start: now(), common };
109
+ byConfig.set(config, state);
110
+ byId.set(config.requestId, state);
111
+ if (shouldPropagate(target ? target.href : url, target)) {
112
+ const carrier = {};
113
+ api.propagation.inject(api.trace.setSpan(parent, span), carrier);
114
+ for (const [k, v] of Object.entries(carrier))
115
+ if (config.headers[k] === void 0) config.headers[k] = v;
116
+ }
117
+ } catch (e) {
118
+ report(e);
119
+ }
120
+ return config;
121
+ },
122
+ afterResponse(response, config) {
123
+ finish(config, { response });
124
+ },
125
+ onError(error, config) {
126
+ const e = error;
127
+ const status = e?.response?.status ?? e?.status;
128
+ const outcome = {
129
+ error,
130
+ // Semantic conventions: the status code when there was an error response, else the error kind.
131
+ errorType: status !== void 0 ? String(status) : e?.code ?? e?.name ?? "_OTHER"
132
+ };
133
+ if (status !== void 0) outcome.status = status;
134
+ if (e?.meta?.attempts !== void 0) outcome.attempts = e.meta.attempts;
135
+ finish(config, outcome);
136
+ },
137
+ onCancel(error, config) {
138
+ finish(config, { errorType: "ERR_CANCELED", attempts: error.meta.attempts });
139
+ }
140
+ };
141
+ }
142
+ function parseURL(url) {
143
+ try {
144
+ const base = typeof location !== "undefined" ? location.href : void 0;
145
+ return base === void 0 ? new URL(url) : new URL(url, base);
146
+ } catch {
147
+ return void 0;
148
+ }
149
+ }
150
+ function propagationRule(rule) {
151
+ if (rule === false) return () => false;
152
+ if (rule === true) return () => true;
153
+ if (typeof rule === "function") return rule;
154
+ if (rule instanceof RegExp)
155
+ return (url) => {
156
+ rule.lastIndex = 0;
157
+ return rule.test(url);
158
+ };
159
+ if (rule !== void 0) throw new TypeError("createOtelPlugin: propagate must be a boolean, a RegExp or a function");
160
+ if (typeof location === "undefined" || !location.origin || location.origin === "null") return () => true;
161
+ return (_url, target) => target?.origin === location.origin;
162
+ }
163
+ function report(err) {
164
+ if (typeof console !== "undefined") console.error("[exios] otel plugin failed:", err);
165
+ }
166
+ export {
167
+ createOtelPlugin
168
+ };
@@ -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
+ };
@@ -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 };