@indra211/exios 0.0.0-stage → 2.0.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/LICENSE +21 -0
- package/README.md +187 -2
- package/dist/index.cjs +2007 -0
- package/dist/index.d.cts +38 -0
- package/dist/index.d.ts +299 -0
- package/dist/index.js +1987 -0
- package/dist/index.node.cjs +2545 -0
- package/dist/index.node.js +2515 -0
- package/package.json +106 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2007 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/cjs.ts
|
|
21
|
+
var cjs_exports = {};
|
|
22
|
+
__export(cjs_exports, {
|
|
23
|
+
default: () => cjs_default
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(cjs_exports);
|
|
26
|
+
|
|
27
|
+
// src/errors/ExiosError.ts
|
|
28
|
+
var ExiosError = class _ExiosError extends Error {
|
|
29
|
+
static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
|
|
30
|
+
static ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
|
|
31
|
+
static ERR_NETWORK = "ERR_NETWORK";
|
|
32
|
+
static ECONNABORTED = "ECONNABORTED";
|
|
33
|
+
static ETIMEDOUT = "ETIMEDOUT";
|
|
34
|
+
static ERR_CANCELED = "ERR_CANCELED";
|
|
35
|
+
static ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
|
|
36
|
+
static ERR_CIRCUIT_OPEN = "ERR_CIRCUIT_OPEN";
|
|
37
|
+
static ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
|
|
38
|
+
static ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
|
|
39
|
+
code;
|
|
40
|
+
config;
|
|
41
|
+
request;
|
|
42
|
+
response;
|
|
43
|
+
status;
|
|
44
|
+
isExiosError = true;
|
|
45
|
+
meta = { attempts: 0 };
|
|
46
|
+
constructor(message, code, config, request, response) {
|
|
47
|
+
super(message);
|
|
48
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
49
|
+
this.name = "ExiosError";
|
|
50
|
+
this.code = code;
|
|
51
|
+
this.config = config;
|
|
52
|
+
this.request = request;
|
|
53
|
+
this.response = response;
|
|
54
|
+
this.status = response?.status;
|
|
55
|
+
}
|
|
56
|
+
toJSON() {
|
|
57
|
+
return {
|
|
58
|
+
message: this.message,
|
|
59
|
+
name: this.name,
|
|
60
|
+
code: this.code,
|
|
61
|
+
status: this.status,
|
|
62
|
+
config: this.config,
|
|
63
|
+
meta: this.meta,
|
|
64
|
+
stack: this.stack
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
static from(err, code, config, request, response) {
|
|
68
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
69
|
+
const e = new _ExiosError(message, code, config, request, response);
|
|
70
|
+
e.cause = err;
|
|
71
|
+
return e;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
var CanceledError = class extends ExiosError {
|
|
75
|
+
constructor(message = "canceled", config, request) {
|
|
76
|
+
super(message, ExiosError.ERR_CANCELED, config, request);
|
|
77
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
78
|
+
this.name = "CanceledError";
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
var CircuitOpenError = class extends ExiosError {
|
|
82
|
+
origin;
|
|
83
|
+
retryAt;
|
|
84
|
+
constructor(origin, retryAt, config) {
|
|
85
|
+
super(`Circuit open for ${origin}`, ExiosError.ERR_CIRCUIT_OPEN, config);
|
|
86
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
87
|
+
this.name = "CircuitOpenError";
|
|
88
|
+
this.origin = origin;
|
|
89
|
+
this.retryAt = retryAt;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
function isExiosError(v) {
|
|
93
|
+
return v instanceof ExiosError || typeof v === "object" && v !== null && v.isExiosError === true;
|
|
94
|
+
}
|
|
95
|
+
function isCancel(v) {
|
|
96
|
+
return v instanceof CanceledError || isExiosError(v) && v.code === ExiosError.ERR_CANCELED;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/adapters/registry.ts
|
|
100
|
+
var registry = /* @__PURE__ */ new Map();
|
|
101
|
+
function registerAdapter(name, entry) {
|
|
102
|
+
registry.set(name, entry);
|
|
103
|
+
}
|
|
104
|
+
function isAdapterAvailable(name, config) {
|
|
105
|
+
const entry = registry.get(name);
|
|
106
|
+
return !!entry && entry.isAvailable(config);
|
|
107
|
+
}
|
|
108
|
+
function resolveAdapter(config) {
|
|
109
|
+
const list = config.adapter === void 0 ? [] : Array.isArray(config.adapter) ? config.adapter : [config.adapter];
|
|
110
|
+
for (const item of list) {
|
|
111
|
+
if (typeof item === "function") return item;
|
|
112
|
+
const entry = registry.get(item);
|
|
113
|
+
if (entry && entry.isAvailable(config)) return entry.adapter;
|
|
114
|
+
}
|
|
115
|
+
const names = list.map((a) => typeof a === "function" ? "custom" : a);
|
|
116
|
+
throw new ExiosError(
|
|
117
|
+
`Adapter ${names.join(", ") || "(none)"} is not available in this environment`,
|
|
118
|
+
ExiosError.ERR_NOT_SUPPORT,
|
|
119
|
+
config
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/core/headers.ts
|
|
124
|
+
var HEADER_BUCKETS = [
|
|
125
|
+
"common",
|
|
126
|
+
"get",
|
|
127
|
+
"post",
|
|
128
|
+
"put",
|
|
129
|
+
"patch",
|
|
130
|
+
"delete",
|
|
131
|
+
"head",
|
|
132
|
+
"options"
|
|
133
|
+
];
|
|
134
|
+
function normalizeHeaders(h) {
|
|
135
|
+
const out = {};
|
|
136
|
+
if (!h) return out;
|
|
137
|
+
if (typeof Headers !== "undefined" && h instanceof Headers) {
|
|
138
|
+
h.forEach((v, k) => {
|
|
139
|
+
out[k.toLowerCase()] = v;
|
|
140
|
+
});
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
for (const [k, v] of Object.entries(h)) {
|
|
144
|
+
if (v === null || v === void 0 || v === false) continue;
|
|
145
|
+
out[k.toLowerCase()] = String(v);
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
function flattenHeaders(h, method) {
|
|
150
|
+
if (!h) return {};
|
|
151
|
+
if (typeof Headers !== "undefined" && h instanceof Headers)
|
|
152
|
+
return normalizeHeaders(h);
|
|
153
|
+
const src = h;
|
|
154
|
+
const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
|
|
155
|
+
const bucket = (name) => {
|
|
156
|
+
const key = Object.keys(src).find((k) => k.toLowerCase() === name);
|
|
157
|
+
const v = key === void 0 ? void 0 : src[key];
|
|
158
|
+
return v && typeof v === "object" ? v : void 0;
|
|
159
|
+
};
|
|
160
|
+
const top = {};
|
|
161
|
+
for (const [k, v] of Object.entries(src)) {
|
|
162
|
+
if (isBucket2(k)) continue;
|
|
163
|
+
Object.assign(top, normalizeHeaders({ [k]: v }));
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
...normalizeHeaders(bucket("common")),
|
|
167
|
+
...normalizeHeaders(bucket(method)),
|
|
168
|
+
...top
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function finalizeHeaders(h, method) {
|
|
172
|
+
if (!h || typeof h !== "object") return {};
|
|
173
|
+
if (typeof Headers !== "undefined" && h instanceof Headers)
|
|
174
|
+
return normalizeHeaders(h);
|
|
175
|
+
const src = h;
|
|
176
|
+
const isBucket2 = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
|
|
177
|
+
const out = {};
|
|
178
|
+
for (const name of ["common", method]) {
|
|
179
|
+
for (const [k, v] of Object.entries(src)) {
|
|
180
|
+
if (k.toLowerCase() === name && v && typeof v === "object")
|
|
181
|
+
Object.assign(out, normalizeHeaders(v));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
for (const [k, v] of Object.entries(src)) {
|
|
185
|
+
if (isBucket2(k)) continue;
|
|
186
|
+
const lk = k.toLowerCase();
|
|
187
|
+
if (v === null || v === void 0 || v === false) delete out[lk];
|
|
188
|
+
else out[lk] = String(v);
|
|
189
|
+
}
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
function headersToObject(h) {
|
|
193
|
+
const out = {};
|
|
194
|
+
h.forEach((v, k) => {
|
|
195
|
+
if (k.toLowerCase() !== "set-cookie") out[k.toLowerCase()] = v;
|
|
196
|
+
});
|
|
197
|
+
if (h.has("set-cookie")) {
|
|
198
|
+
const cookies = h.getSetCookie?.();
|
|
199
|
+
out["set-cookie"] = cookies ?? h.get("set-cookie");
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/core/buildURL.ts
|
|
205
|
+
var ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
|
|
206
|
+
function encode(s) {
|
|
207
|
+
return encodeURIComponent(s).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
|
|
208
|
+
}
|
|
209
|
+
function isPlainObject(v) {
|
|
210
|
+
if (v === null || typeof v !== "object") return false;
|
|
211
|
+
const proto = Object.getPrototypeOf(v);
|
|
212
|
+
return proto === Object.prototype || proto === null;
|
|
213
|
+
}
|
|
214
|
+
function serializeParams(params, opts = {}) {
|
|
215
|
+
if (params === void 0 || params === null) return "";
|
|
216
|
+
if (params instanceof URLSearchParams) return params.toString();
|
|
217
|
+
const enc = opts.encode ?? encode;
|
|
218
|
+
const indexes = opts.indexes === void 0 ? false : opts.indexes;
|
|
219
|
+
const parts = [];
|
|
220
|
+
const add = (key, value) => {
|
|
221
|
+
if (value === void 0 || value === null) return;
|
|
222
|
+
if (value instanceof Date) {
|
|
223
|
+
parts.push(`${enc(key)}=${enc(value.toISOString())}`);
|
|
224
|
+
} else if (Array.isArray(value)) {
|
|
225
|
+
value.forEach(
|
|
226
|
+
(item, i) => add(indexes === null ? key : `${key}[${indexes ? i : ""}]`, item)
|
|
227
|
+
);
|
|
228
|
+
} else if (isPlainObject(value)) {
|
|
229
|
+
for (const k of Object.keys(value)) add(`${key}[${k}]`, value[k]);
|
|
230
|
+
} else {
|
|
231
|
+
parts.push(`${enc(key)}=${enc(String(value))}`);
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
for (const k of Object.keys(params)) add(k, params[k]);
|
|
235
|
+
return parts.join("&");
|
|
236
|
+
}
|
|
237
|
+
function buildURL(url, params, serializer) {
|
|
238
|
+
const hash = url.indexOf("#");
|
|
239
|
+
if (hash !== -1) url = url.slice(0, hash);
|
|
240
|
+
if (params === void 0 || params === null) return url;
|
|
241
|
+
let serialized;
|
|
242
|
+
if (typeof serializer === "function") serialized = serializer(params);
|
|
243
|
+
else if (serializer?.serialize) serialized = serializer.serialize(params);
|
|
244
|
+
else serialized = serializeParams(params, serializer ?? {});
|
|
245
|
+
if (!serialized) return url;
|
|
246
|
+
if (url.endsWith("?") || url.endsWith("&")) return url + serialized;
|
|
247
|
+
return url + (url.includes("?") ? "&" : "?") + serialized;
|
|
248
|
+
}
|
|
249
|
+
function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
|
|
250
|
+
const u = url ?? "";
|
|
251
|
+
if (!baseURL) return u;
|
|
252
|
+
if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
|
|
253
|
+
if (!u) return baseURL;
|
|
254
|
+
return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/core/toFormData.ts
|
|
258
|
+
function toFormData(obj, fd = new FormData()) {
|
|
259
|
+
const append = (key, value) => {
|
|
260
|
+
if (value === void 0 || value === null) return;
|
|
261
|
+
if (value instanceof Blob) {
|
|
262
|
+
fd.append(key, value);
|
|
263
|
+
} else if (value instanceof Date) {
|
|
264
|
+
fd.append(key, value.toISOString());
|
|
265
|
+
} else if (Array.isArray(value)) {
|
|
266
|
+
for (const item of value) append(`${key}[]`, item);
|
|
267
|
+
} else if (typeof value === "object") {
|
|
268
|
+
for (const [k, v] of Object.entries(value)) append(`${key}[${k}]`, v);
|
|
269
|
+
} else {
|
|
270
|
+
fd.append(key, String(value));
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
for (const [k, v] of Object.entries(obj)) append(k, v);
|
|
274
|
+
return fd;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/core/transforms.ts
|
|
278
|
+
function isPlainObject2(v) {
|
|
279
|
+
if (v === null || typeof v !== "object") return false;
|
|
280
|
+
const proto = Object.getPrototypeOf(v);
|
|
281
|
+
return proto === Object.prototype || proto === null;
|
|
282
|
+
}
|
|
283
|
+
function isPassThrough(data) {
|
|
284
|
+
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);
|
|
285
|
+
}
|
|
286
|
+
function isNodeStream(data) {
|
|
287
|
+
return typeof data === "object" && data !== null && typeof data.pipe === "function" && typeof data.on === "function";
|
|
288
|
+
}
|
|
289
|
+
function defaultTransformRequest(data, headers) {
|
|
290
|
+
if (data === void 0 || data === null) return void 0;
|
|
291
|
+
if (isPassThrough(data)) {
|
|
292
|
+
if (data instanceof URLSearchParams) {
|
|
293
|
+
if (!headers["content-type"])
|
|
294
|
+
headers["content-type"] = "application/x-www-form-urlencoded;charset=utf-8";
|
|
295
|
+
} else if (typeof FormData !== "undefined" && data instanceof FormData) {
|
|
296
|
+
delete headers["content-type"];
|
|
297
|
+
}
|
|
298
|
+
return data;
|
|
299
|
+
}
|
|
300
|
+
if (typeof data === "string") return data;
|
|
301
|
+
if (typeof data !== "object") return data;
|
|
302
|
+
const ct = (headers["content-type"] ?? "").toLowerCase();
|
|
303
|
+
if (isPlainObject2(data) || Array.isArray(data)) {
|
|
304
|
+
if (ct.includes("multipart/form-data")) {
|
|
305
|
+
delete headers["content-type"];
|
|
306
|
+
return toFormData(data);
|
|
307
|
+
}
|
|
308
|
+
if (ct.includes("application/x-www-form-urlencoded"))
|
|
309
|
+
return serializeParams(data);
|
|
310
|
+
}
|
|
311
|
+
if (!ct) headers["content-type"] = "application/json";
|
|
312
|
+
return JSON.stringify(data);
|
|
313
|
+
}
|
|
314
|
+
function defaultTransformResponse(data, headers, _status) {
|
|
315
|
+
const rt = this.responseType;
|
|
316
|
+
if ((rt === void 0 || rt === "json") && typeof data === "string") {
|
|
317
|
+
if (data === "") return "";
|
|
318
|
+
try {
|
|
319
|
+
return JSON.parse(data);
|
|
320
|
+
} catch (e) {
|
|
321
|
+
const isJson = (headers["content-type"] ?? "").toLowerCase().includes("json");
|
|
322
|
+
if (this.transitional?.silentJSONParsing === false && isJson) {
|
|
323
|
+
throw new ExiosError(
|
|
324
|
+
e.message,
|
|
325
|
+
ExiosError.ERR_BAD_RESPONSE,
|
|
326
|
+
this
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
return data;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return data;
|
|
333
|
+
}
|
|
334
|
+
function runTransforms(fns, config, data, headers, status) {
|
|
335
|
+
if (!fns) return data;
|
|
336
|
+
for (const fn of Array.isArray(fns) ? fns : [fns])
|
|
337
|
+
data = fn.call(config, data, headers, status);
|
|
338
|
+
return data;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/adapters/shared.ts
|
|
342
|
+
function basicAuth(auth) {
|
|
343
|
+
const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`);
|
|
344
|
+
let bin = "";
|
|
345
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
346
|
+
return `Basic ${btoa(bin)}`;
|
|
347
|
+
}
|
|
348
|
+
function bodyLength(body) {
|
|
349
|
+
if (typeof body === "string") return new TextEncoder().encode(body).byteLength;
|
|
350
|
+
if (typeof Blob !== "undefined" && body instanceof Blob) return body.size;
|
|
351
|
+
if (body instanceof ArrayBuffer) return body.byteLength;
|
|
352
|
+
if (ArrayBuffer.isView(body)) return body.byteLength;
|
|
353
|
+
if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams)
|
|
354
|
+
return new TextEncoder().encode(body.toString()).byteLength;
|
|
355
|
+
return void 0;
|
|
356
|
+
}
|
|
357
|
+
var isWebStream = (v) => typeof ReadableStream !== "undefined" && v instanceof ReadableStream;
|
|
358
|
+
function isSameOrigin(url) {
|
|
359
|
+
const loc = globalThis.location;
|
|
360
|
+
if (!loc) return false;
|
|
361
|
+
try {
|
|
362
|
+
return new URL(url, loc.href).origin === loc.origin;
|
|
363
|
+
} catch {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function readCookie(name) {
|
|
368
|
+
const doc = globalThis.document;
|
|
369
|
+
const cookie = doc?.cookie;
|
|
370
|
+
if (!cookie) return void 0;
|
|
371
|
+
for (const part of cookie.split(";")) {
|
|
372
|
+
const i = part.indexOf("=");
|
|
373
|
+
if (i < 0 || part.slice(0, i).trim() !== name) continue;
|
|
374
|
+
try {
|
|
375
|
+
return decodeURIComponent(part.slice(i + 1).trim());
|
|
376
|
+
} catch {
|
|
377
|
+
return part.slice(i + 1).trim();
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return void 0;
|
|
381
|
+
}
|
|
382
|
+
function applyXsrf(config, url, headers) {
|
|
383
|
+
if (!globalThis.document) return;
|
|
384
|
+
const opt = config.withXSRFToken;
|
|
385
|
+
const decision = typeof opt === "function" ? opt(config) : opt;
|
|
386
|
+
if (decision === false) return;
|
|
387
|
+
if (decision !== true && !isSameOrigin(url)) return;
|
|
388
|
+
const name = config.xsrfHeaderName?.toLowerCase();
|
|
389
|
+
if (!name || !config.xsrfCookieName || name in headers) return;
|
|
390
|
+
const value = readCookie(config.xsrfCookieName);
|
|
391
|
+
if (value !== void 0) headers[name] = value;
|
|
392
|
+
}
|
|
393
|
+
function prepareRequest(config) {
|
|
394
|
+
const url = buildURL(
|
|
395
|
+
buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
|
|
396
|
+
config.params,
|
|
397
|
+
config.paramsSerializer
|
|
398
|
+
);
|
|
399
|
+
const headers = { ...config.headers };
|
|
400
|
+
if (config.auth) headers.authorization = basicAuth(config.auth);
|
|
401
|
+
applyXsrf(config, url, headers);
|
|
402
|
+
const hasBody = config.method !== "get" && config.method !== "head";
|
|
403
|
+
const body = hasBody ? runTransforms(config.transformRequest, config, config.data, headers) : void 0;
|
|
404
|
+
const length = bodyLength(body);
|
|
405
|
+
const maxBody = config.maxBodyLength ?? -1;
|
|
406
|
+
if (maxBody > -1 && length !== void 0 && length > maxBody) {
|
|
407
|
+
throw new ExiosError(
|
|
408
|
+
`Request body larger than maxBodyLength limit`,
|
|
409
|
+
ExiosError.ERR_BAD_REQUEST,
|
|
410
|
+
config
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
url,
|
|
415
|
+
method: config.method.toUpperCase(),
|
|
416
|
+
headers,
|
|
417
|
+
body,
|
|
418
|
+
replayable: !isOneShotBody(body),
|
|
419
|
+
length
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
function decodeText(bytes, config) {
|
|
423
|
+
return new TextDecoder(config.responseEncoding ?? "utf-8").decode(bytes);
|
|
424
|
+
}
|
|
425
|
+
function assertEncoding(config) {
|
|
426
|
+
const enc = config.responseEncoding;
|
|
427
|
+
if (enc === void 0) return;
|
|
428
|
+
try {
|
|
429
|
+
new TextDecoder(enc);
|
|
430
|
+
} catch {
|
|
431
|
+
throw new ExiosError(
|
|
432
|
+
`Unsupported responseEncoding: ${enc}`,
|
|
433
|
+
ExiosError.ERR_BAD_OPTION_VALUE,
|
|
434
|
+
config
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
function finishResponse(config, raw) {
|
|
439
|
+
const response = {
|
|
440
|
+
data: raw.data,
|
|
441
|
+
status: raw.status,
|
|
442
|
+
statusText: raw.statusText,
|
|
443
|
+
headers: raw.headers,
|
|
444
|
+
config,
|
|
445
|
+
request: raw.request,
|
|
446
|
+
meta: { attempts: 0 }
|
|
447
|
+
};
|
|
448
|
+
try {
|
|
449
|
+
response.data = runTransforms(
|
|
450
|
+
config.transformResponse,
|
|
451
|
+
config,
|
|
452
|
+
raw.data,
|
|
453
|
+
raw.headers,
|
|
454
|
+
raw.status
|
|
455
|
+
);
|
|
456
|
+
} catch (err) {
|
|
457
|
+
cancelBody(raw.data);
|
|
458
|
+
if (err instanceof ExiosError) {
|
|
459
|
+
err.request ??= raw.request;
|
|
460
|
+
err.response ??= response;
|
|
461
|
+
err.status ??= response.status;
|
|
462
|
+
}
|
|
463
|
+
throw err;
|
|
464
|
+
}
|
|
465
|
+
return response;
|
|
466
|
+
}
|
|
467
|
+
function createProgress(cb, kind, total) {
|
|
468
|
+
let loaded = 0;
|
|
469
|
+
let reported = -1;
|
|
470
|
+
const start = Date.now();
|
|
471
|
+
const emit = (bytes, event) => {
|
|
472
|
+
if (!cb) return;
|
|
473
|
+
const elapsed = (Date.now() - start) / 1e3;
|
|
474
|
+
const rate = elapsed > 0 ? loaded / elapsed : void 0;
|
|
475
|
+
const e = {
|
|
476
|
+
loaded,
|
|
477
|
+
total,
|
|
478
|
+
progress: total ? loaded / total : void 0,
|
|
479
|
+
bytes,
|
|
480
|
+
rate,
|
|
481
|
+
estimated: rate && total ? (total - loaded) / rate : void 0
|
|
482
|
+
};
|
|
483
|
+
if (kind === "upload") e.upload = true;
|
|
484
|
+
else e.download = true;
|
|
485
|
+
if (event !== void 0) e.event = event;
|
|
486
|
+
reported = loaded;
|
|
487
|
+
cb(e);
|
|
488
|
+
};
|
|
489
|
+
return {
|
|
490
|
+
add(n, event) {
|
|
491
|
+
loaded += n;
|
|
492
|
+
emit(n, event);
|
|
493
|
+
},
|
|
494
|
+
done() {
|
|
495
|
+
if (reported !== loaded) emit(0);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
var isNodeStream2 = (v) => typeof v === "object" && v !== null && typeof v.pipe === "function" && typeof v.destroy === "function";
|
|
500
|
+
function cancelBody(data) {
|
|
501
|
+
try {
|
|
502
|
+
if (isWebStream(data)) {
|
|
503
|
+
if (!data.locked) data.cancel().catch(() => {
|
|
504
|
+
});
|
|
505
|
+
} else if (isNodeStream2(data)) data.destroy();
|
|
506
|
+
} catch {
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function abortError(signal, config, request) {
|
|
510
|
+
const r = signal?.reason;
|
|
511
|
+
if (r instanceof CanceledError) {
|
|
512
|
+
r.config ??= config;
|
|
513
|
+
r.request ??= request;
|
|
514
|
+
return r;
|
|
515
|
+
}
|
|
516
|
+
return new CanceledError("canceled", config, request);
|
|
517
|
+
}
|
|
518
|
+
function isOneShotBody(body) {
|
|
519
|
+
return isWebStream(body) || isNodeStream2(body);
|
|
520
|
+
}
|
|
521
|
+
function whenBodyDone(data, fn) {
|
|
522
|
+
let called = false;
|
|
523
|
+
const once = () => {
|
|
524
|
+
if (!called) {
|
|
525
|
+
called = true;
|
|
526
|
+
fn();
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
if (isNodeStream2(data)) {
|
|
530
|
+
data.once("close", once);
|
|
531
|
+
return data;
|
|
532
|
+
}
|
|
533
|
+
if (!isWebStream(data)) {
|
|
534
|
+
once();
|
|
535
|
+
return data;
|
|
536
|
+
}
|
|
537
|
+
const reader = data.getReader();
|
|
538
|
+
return new ReadableStream({
|
|
539
|
+
async pull(controller) {
|
|
540
|
+
try {
|
|
541
|
+
const r = await reader.read();
|
|
542
|
+
if (r.done) {
|
|
543
|
+
once();
|
|
544
|
+
controller.close();
|
|
545
|
+
} else controller.enqueue(r.value);
|
|
546
|
+
} catch (err) {
|
|
547
|
+
once();
|
|
548
|
+
controller.error(err);
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
cancel(reason) {
|
|
552
|
+
once();
|
|
553
|
+
return reader.cancel(reason);
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/adapters/fetch/uploadStream.ts
|
|
559
|
+
var CHUNK = 64 * 1024;
|
|
560
|
+
var streamSupport;
|
|
561
|
+
function supportsRequestStreams() {
|
|
562
|
+
if (streamSupport !== void 0) return streamSupport;
|
|
563
|
+
if (typeof globalThis.document !== "undefined")
|
|
564
|
+
return streamSupport = false;
|
|
565
|
+
try {
|
|
566
|
+
let duplexAccessed = false;
|
|
567
|
+
const hasContentType = new Request("http://localhost/", {
|
|
568
|
+
body: new ReadableStream(),
|
|
569
|
+
method: "POST",
|
|
570
|
+
get duplex() {
|
|
571
|
+
duplexAccessed = true;
|
|
572
|
+
return "half";
|
|
573
|
+
}
|
|
574
|
+
}).headers.has("content-type");
|
|
575
|
+
streamSupport = duplexAccessed && !hasContentType;
|
|
576
|
+
} catch {
|
|
577
|
+
streamSupport = false;
|
|
578
|
+
}
|
|
579
|
+
return streamSupport;
|
|
580
|
+
}
|
|
581
|
+
async function bodyBytes(body) {
|
|
582
|
+
const res = new Response(body);
|
|
583
|
+
return {
|
|
584
|
+
bytes: new Uint8Array(await res.arrayBuffer()),
|
|
585
|
+
contentType: res.headers.get("content-type") ?? void 0
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
function countingStream(source, progress) {
|
|
589
|
+
if (isWebStream(source)) {
|
|
590
|
+
return source.pipeThrough(
|
|
591
|
+
new TransformStream({
|
|
592
|
+
transform(chunk, controller) {
|
|
593
|
+
controller.enqueue(chunk);
|
|
594
|
+
progress.add(chunk.byteLength);
|
|
595
|
+
},
|
|
596
|
+
flush() {
|
|
597
|
+
progress.done();
|
|
598
|
+
}
|
|
599
|
+
})
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
let offset = 0;
|
|
603
|
+
return new ReadableStream({
|
|
604
|
+
pull(controller) {
|
|
605
|
+
if (offset >= source.byteLength) {
|
|
606
|
+
progress.done();
|
|
607
|
+
controller.close();
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
const chunk = source.subarray(offset, offset + CHUNK);
|
|
611
|
+
offset += chunk.byteLength;
|
|
612
|
+
controller.enqueue(chunk);
|
|
613
|
+
progress.add(chunk.byteLength);
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// src/adapters/fetch/linkStream.ts
|
|
619
|
+
function linkStream(body, signal, abortError2) {
|
|
620
|
+
if (!signal) return body;
|
|
621
|
+
const reader = body.getReader();
|
|
622
|
+
let detach = () => {
|
|
623
|
+
};
|
|
624
|
+
const safe = (fn) => {
|
|
625
|
+
try {
|
|
626
|
+
fn();
|
|
627
|
+
} catch {
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
return new ReadableStream({
|
|
631
|
+
start(controller) {
|
|
632
|
+
const onAbort = () => {
|
|
633
|
+
detach();
|
|
634
|
+
safe(() => controller.error(abortError2()));
|
|
635
|
+
reader.cancel(signal.reason).catch(() => {
|
|
636
|
+
});
|
|
637
|
+
};
|
|
638
|
+
if (signal.aborted) return onAbort();
|
|
639
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
640
|
+
detach = () => {
|
|
641
|
+
detach = () => {
|
|
642
|
+
};
|
|
643
|
+
signal.removeEventListener("abort", onAbort);
|
|
644
|
+
};
|
|
645
|
+
},
|
|
646
|
+
async pull(controller) {
|
|
647
|
+
try {
|
|
648
|
+
const { done, value } = await reader.read();
|
|
649
|
+
if (done) {
|
|
650
|
+
detach();
|
|
651
|
+
safe(() => controller.close());
|
|
652
|
+
} else safe(() => controller.enqueue(value));
|
|
653
|
+
} catch (err) {
|
|
654
|
+
detach();
|
|
655
|
+
safe(() => controller.error(signal.aborted ? abortError2() : err));
|
|
656
|
+
}
|
|
657
|
+
},
|
|
658
|
+
cancel(reason) {
|
|
659
|
+
detach();
|
|
660
|
+
return reader.cancel(reason);
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// src/adapters/fetch/readBody.ts
|
|
666
|
+
function convert(res, config, bytes) {
|
|
667
|
+
switch (config.responseType) {
|
|
668
|
+
case "blob":
|
|
669
|
+
return new Blob([bytes], { type: res.headers.get("content-type") ?? "" });
|
|
670
|
+
case "arraybuffer":
|
|
671
|
+
return bytes.buffer;
|
|
672
|
+
case "formData":
|
|
673
|
+
return new Response(bytes, { headers: res.headers }).formData();
|
|
674
|
+
default:
|
|
675
|
+
return decodeText(bytes, config);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
async function readBody(res, config, onProgress = config.onDownloadProgress) {
|
|
679
|
+
const type = config.responseType;
|
|
680
|
+
if (type === "stream") return res.body;
|
|
681
|
+
const max = config.maxContentLength ?? -1;
|
|
682
|
+
if (!onProgress && !(max > -1) || !res.body) {
|
|
683
|
+
switch (type) {
|
|
684
|
+
case "blob":
|
|
685
|
+
return res.blob();
|
|
686
|
+
case "arraybuffer":
|
|
687
|
+
return res.arrayBuffer();
|
|
688
|
+
case "formData":
|
|
689
|
+
return res.formData();
|
|
690
|
+
default:
|
|
691
|
+
return res.arrayBuffer().then((b) => decodeText(new Uint8Array(b), config));
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const lengthHeader = Number(res.headers.get("content-length"));
|
|
695
|
+
const total = lengthHeader > 0 ? lengthHeader : void 0;
|
|
696
|
+
const tooLarge = () => new ExiosError(
|
|
697
|
+
`maxContentLength size of ${max} exceeded`,
|
|
698
|
+
ExiosError.ERR_BAD_RESPONSE,
|
|
699
|
+
config
|
|
700
|
+
);
|
|
701
|
+
if (max > -1 && total !== void 0 && total > max) {
|
|
702
|
+
await res.body.cancel().catch(() => {
|
|
703
|
+
});
|
|
704
|
+
throw tooLarge();
|
|
705
|
+
}
|
|
706
|
+
const reader = res.body.getReader();
|
|
707
|
+
const chunks = [];
|
|
708
|
+
let loaded = 0;
|
|
709
|
+
const progress = createProgress(onProgress, "download", total);
|
|
710
|
+
for (; ; ) {
|
|
711
|
+
const { done, value } = await reader.read();
|
|
712
|
+
if (done) break;
|
|
713
|
+
loaded += value.byteLength;
|
|
714
|
+
if (max > -1 && loaded > max) {
|
|
715
|
+
await reader.cancel().catch(() => {
|
|
716
|
+
});
|
|
717
|
+
throw tooLarge();
|
|
718
|
+
}
|
|
719
|
+
chunks.push(value);
|
|
720
|
+
progress.add(value.byteLength);
|
|
721
|
+
}
|
|
722
|
+
progress.done();
|
|
723
|
+
const bytes = new Uint8Array(loaded);
|
|
724
|
+
let offset = 0;
|
|
725
|
+
for (const c of chunks) {
|
|
726
|
+
bytes.set(c, offset);
|
|
727
|
+
offset += c.byteLength;
|
|
728
|
+
}
|
|
729
|
+
return convert(res, config, bytes);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// src/adapters/signals.ts
|
|
733
|
+
function combineSignals(...signals) {
|
|
734
|
+
const controller = new AbortController();
|
|
735
|
+
const active = signals.filter((s) => !!s);
|
|
736
|
+
const listeners = [];
|
|
737
|
+
const cleanup = () => {
|
|
738
|
+
for (const off of listeners.splice(0)) off();
|
|
739
|
+
};
|
|
740
|
+
for (const s of active) {
|
|
741
|
+
if (s.aborted) {
|
|
742
|
+
controller.abort(s.reason);
|
|
743
|
+
cleanup();
|
|
744
|
+
return { signal: controller.signal, cleanup };
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
for (const s of active) {
|
|
748
|
+
const onAbort = () => {
|
|
749
|
+
controller.abort(s.reason);
|
|
750
|
+
cleanup();
|
|
751
|
+
};
|
|
752
|
+
s.addEventListener("abort", onAbort, { once: true });
|
|
753
|
+
listeners.push(() => s.removeEventListener("abort", onAbort));
|
|
754
|
+
}
|
|
755
|
+
return { signal: controller.signal, cleanup };
|
|
756
|
+
}
|
|
757
|
+
function attemptSignal(user, timeoutMs) {
|
|
758
|
+
const timer = new AbortController();
|
|
759
|
+
let fired = false;
|
|
760
|
+
let handle;
|
|
761
|
+
if (timeoutMs > 0) {
|
|
762
|
+
handle = setTimeout(() => {
|
|
763
|
+
fired = true;
|
|
764
|
+
timer.abort(new Error("timeout"));
|
|
765
|
+
}, timeoutMs);
|
|
766
|
+
}
|
|
767
|
+
const combined = combineSignals(user, timer.signal);
|
|
768
|
+
return {
|
|
769
|
+
signal: combined.signal,
|
|
770
|
+
timedOut: () => fired,
|
|
771
|
+
cleanup() {
|
|
772
|
+
if (handle !== void 0) clearTimeout(handle);
|
|
773
|
+
handle = void 0;
|
|
774
|
+
combined.cleanup();
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// src/adapters/fetch/index.ts
|
|
780
|
+
async function fetchAdapter(config) {
|
|
781
|
+
const { url, headers, body, length } = prepareRequest(config);
|
|
782
|
+
let userError;
|
|
783
|
+
const guard = (cb) => cb && ((ev) => {
|
|
784
|
+
try {
|
|
785
|
+
cb(ev);
|
|
786
|
+
} catch (err) {
|
|
787
|
+
userError ??= { err };
|
|
788
|
+
throw err;
|
|
789
|
+
}
|
|
790
|
+
});
|
|
791
|
+
let sendBody = body;
|
|
792
|
+
let uploadDone;
|
|
793
|
+
if (config.onUploadProgress && body !== void 0) {
|
|
794
|
+
const streaming = supportsRequestStreams();
|
|
795
|
+
if (isWebStream(body)) {
|
|
796
|
+
const progress = createProgress(guard(config.onUploadProgress), "upload", length);
|
|
797
|
+
if (streaming) sendBody = countingStream(body, progress);
|
|
798
|
+
else uploadDone = () => progress.done();
|
|
799
|
+
} else {
|
|
800
|
+
const { bytes, contentType } = await bodyBytes(body);
|
|
801
|
+
if (contentType && !headers["content-type"]) headers["content-type"] = contentType;
|
|
802
|
+
const progress = createProgress(guard(config.onUploadProgress), "upload", bytes.byteLength);
|
|
803
|
+
if (streaming) sendBody = countingStream(bytes, progress);
|
|
804
|
+
else {
|
|
805
|
+
sendBody = bytes;
|
|
806
|
+
uploadDone = () => {
|
|
807
|
+
progress.add(bytes.byteLength);
|
|
808
|
+
progress.done();
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const sig = attemptSignal(config.signal, config.timeout ?? 0);
|
|
814
|
+
try {
|
|
815
|
+
const init = {
|
|
816
|
+
...config.fetchOptions,
|
|
817
|
+
method: config.method.toUpperCase(),
|
|
818
|
+
headers,
|
|
819
|
+
body: sendBody,
|
|
820
|
+
credentials: config.withCredentials ? "include" : config.fetchOptions?.credentials ?? "same-origin",
|
|
821
|
+
signal: sig.signal
|
|
822
|
+
};
|
|
823
|
+
if (config.redirect) init.redirect = config.redirect;
|
|
824
|
+
if (isWebStream(sendBody)) init.duplex = "half";
|
|
825
|
+
let request;
|
|
826
|
+
try {
|
|
827
|
+
request = new Request(url, init);
|
|
828
|
+
} catch (err) {
|
|
829
|
+
const e = new ExiosError(
|
|
830
|
+
err instanceof Error ? err.message : String(err),
|
|
831
|
+
ExiosError.ERR_BAD_REQUEST,
|
|
832
|
+
config
|
|
833
|
+
);
|
|
834
|
+
e.cause = err;
|
|
835
|
+
throw e;
|
|
836
|
+
}
|
|
837
|
+
if (config.signal?.aborted)
|
|
838
|
+
throw abortError(config.signal, config, request);
|
|
839
|
+
const progress = guard(config.onDownloadProgress);
|
|
840
|
+
let res;
|
|
841
|
+
let data;
|
|
842
|
+
try {
|
|
843
|
+
res = await (config.fetch ?? globalThis.fetch)(request);
|
|
844
|
+
uploadDone?.();
|
|
845
|
+
data = await readBody(res, config, progress);
|
|
846
|
+
} catch (err) {
|
|
847
|
+
if (userError) throw userError.err;
|
|
848
|
+
if (isExios(err)) {
|
|
849
|
+
err.request ??= request;
|
|
850
|
+
throw err;
|
|
851
|
+
}
|
|
852
|
+
if (config.signal?.aborted)
|
|
853
|
+
throw abortError(config.signal, config, request);
|
|
854
|
+
if (sig.timedOut()) {
|
|
855
|
+
const code = config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED;
|
|
856
|
+
throw new ExiosError(
|
|
857
|
+
config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`,
|
|
858
|
+
code,
|
|
859
|
+
config,
|
|
860
|
+
request
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
const netErr = new ExiosError(
|
|
864
|
+
"Network Error",
|
|
865
|
+
ExiosError.ERR_NETWORK,
|
|
866
|
+
config,
|
|
867
|
+
request
|
|
868
|
+
);
|
|
869
|
+
netErr.cause = err;
|
|
870
|
+
throw netErr;
|
|
871
|
+
}
|
|
872
|
+
if (config.responseType === "stream" && typeof ReadableStream !== "undefined" && data instanceof ReadableStream) {
|
|
873
|
+
data = linkStream(
|
|
874
|
+
data,
|
|
875
|
+
config.signal,
|
|
876
|
+
() => abortError(config.signal, config, request)
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
return finishResponse(config, {
|
|
880
|
+
status: res.status,
|
|
881
|
+
statusText: res.statusText,
|
|
882
|
+
headers: headersToObject(res.headers),
|
|
883
|
+
data,
|
|
884
|
+
request
|
|
885
|
+
});
|
|
886
|
+
} finally {
|
|
887
|
+
sig.cleanup();
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
function isExios(e) {
|
|
891
|
+
return e instanceof ExiosError;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// src/adapters/fetch/register.ts
|
|
895
|
+
function registerFetchAdapter() {
|
|
896
|
+
registerAdapter("fetch", {
|
|
897
|
+
adapter: fetchAdapter,
|
|
898
|
+
isAvailable: (config) => typeof (config.fetch ?? globalThis.fetch) === "function"
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
// src/adapters/xhr/index.ts
|
|
903
|
+
function parseHeaders(raw) {
|
|
904
|
+
const out = {};
|
|
905
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
906
|
+
const i = line.indexOf(":");
|
|
907
|
+
if (i <= 0) continue;
|
|
908
|
+
const key = line.slice(0, i).trim().toLowerCase();
|
|
909
|
+
const value = line.slice(i + 1).trim();
|
|
910
|
+
out[key] = key in out ? `${out[key]}, ${value}` : value;
|
|
911
|
+
}
|
|
912
|
+
return out;
|
|
913
|
+
}
|
|
914
|
+
function xhrAdapter(config) {
|
|
915
|
+
if (isWebStream(config.data)) {
|
|
916
|
+
return new Response(config.data).blob().then((blob) => xhrAdapter({ ...config, data: blob }));
|
|
917
|
+
}
|
|
918
|
+
if (config.responseType === "stream") {
|
|
919
|
+
if (isAdapterAvailable("fetch", config)) return fetchAdapter(config);
|
|
920
|
+
return Promise.reject(
|
|
921
|
+
new ExiosError(
|
|
922
|
+
"responseType 'stream' needs fetch, which is not available",
|
|
923
|
+
ExiosError.ERR_NOT_SUPPORT,
|
|
924
|
+
config
|
|
925
|
+
)
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
return new Promise((resolve, reject) => {
|
|
929
|
+
let prepared;
|
|
930
|
+
try {
|
|
931
|
+
prepared = prepareRequest(config);
|
|
932
|
+
} catch (e) {
|
|
933
|
+
return reject(e);
|
|
934
|
+
}
|
|
935
|
+
const { url, method, headers, body } = prepared;
|
|
936
|
+
const xhr = new XMLHttpRequest();
|
|
937
|
+
const signal = config.signal;
|
|
938
|
+
let settled = false;
|
|
939
|
+
let userError;
|
|
940
|
+
const cleanup = () => signal?.removeEventListener("abort", onAbort);
|
|
941
|
+
const fail = (err) => {
|
|
942
|
+
if (settled) return;
|
|
943
|
+
settled = true;
|
|
944
|
+
cleanup();
|
|
945
|
+
reject(err);
|
|
946
|
+
};
|
|
947
|
+
const onAbort = () => {
|
|
948
|
+
xhr.abort();
|
|
949
|
+
fail(abortError(signal, config, xhr));
|
|
950
|
+
};
|
|
951
|
+
const guard = (cb) => cb && ((e) => {
|
|
952
|
+
try {
|
|
953
|
+
cb(e);
|
|
954
|
+
} catch (err) {
|
|
955
|
+
userError ??= { err };
|
|
956
|
+
xhr.abort();
|
|
957
|
+
fail(err);
|
|
958
|
+
}
|
|
959
|
+
});
|
|
960
|
+
try {
|
|
961
|
+
xhr.open(method, url, true);
|
|
962
|
+
} catch (err) {
|
|
963
|
+
const e = new ExiosError(
|
|
964
|
+
err instanceof Error ? err.message : String(err),
|
|
965
|
+
ExiosError.ERR_BAD_REQUEST,
|
|
966
|
+
config,
|
|
967
|
+
xhr
|
|
968
|
+
);
|
|
969
|
+
e.cause = err;
|
|
970
|
+
return reject(e);
|
|
971
|
+
}
|
|
972
|
+
xhr.timeout = config.timeout ?? 0;
|
|
973
|
+
xhr.withCredentials = !!config.withCredentials;
|
|
974
|
+
const type = config.responseType;
|
|
975
|
+
xhr.responseType = type === "blob" || type === "formData" ? "blob" : "arraybuffer";
|
|
976
|
+
try {
|
|
977
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
978
|
+
if (k === "content-type" && body instanceof FormData) continue;
|
|
979
|
+
xhr.setRequestHeader(k, v);
|
|
980
|
+
}
|
|
981
|
+
} catch (err) {
|
|
982
|
+
const e = new ExiosError(
|
|
983
|
+
err instanceof Error ? err.message : String(err),
|
|
984
|
+
ExiosError.ERR_BAD_REQUEST,
|
|
985
|
+
config,
|
|
986
|
+
xhr
|
|
987
|
+
);
|
|
988
|
+
e.cause = err;
|
|
989
|
+
return reject(e);
|
|
990
|
+
}
|
|
991
|
+
const max = config.maxContentLength ?? -1;
|
|
992
|
+
const onDownload = guard(config.onDownloadProgress);
|
|
993
|
+
if (onDownload || max > -1) {
|
|
994
|
+
let progress;
|
|
995
|
+
let seen = 0;
|
|
996
|
+
xhr.onprogress = (ev) => {
|
|
997
|
+
if (max > -1 && ev.loaded > max) {
|
|
998
|
+
xhr.abort();
|
|
999
|
+
return fail(
|
|
1000
|
+
new ExiosError(
|
|
1001
|
+
`maxContentLength size of ${max} exceeded`,
|
|
1002
|
+
ExiosError.ERR_BAD_RESPONSE,
|
|
1003
|
+
config,
|
|
1004
|
+
xhr
|
|
1005
|
+
)
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
progress ??= createProgress(
|
|
1009
|
+
onDownload,
|
|
1010
|
+
"download",
|
|
1011
|
+
ev.lengthComputable ? ev.total : void 0
|
|
1012
|
+
);
|
|
1013
|
+
progress.add(ev.loaded - seen, ev);
|
|
1014
|
+
seen = ev.loaded;
|
|
1015
|
+
};
|
|
1016
|
+
xhr.onload = () => progress?.done();
|
|
1017
|
+
}
|
|
1018
|
+
const onUpload = guard(config.onUploadProgress);
|
|
1019
|
+
if (onUpload && body !== void 0) {
|
|
1020
|
+
let progress;
|
|
1021
|
+
let seen = 0;
|
|
1022
|
+
xhr.upload.onprogress = (ev) => {
|
|
1023
|
+
progress ??= createProgress(
|
|
1024
|
+
onUpload,
|
|
1025
|
+
"upload",
|
|
1026
|
+
ev.lengthComputable ? ev.total : void 0
|
|
1027
|
+
);
|
|
1028
|
+
progress.add(ev.loaded - seen, ev);
|
|
1029
|
+
seen = ev.loaded;
|
|
1030
|
+
};
|
|
1031
|
+
xhr.upload.onload = () => progress?.done();
|
|
1032
|
+
}
|
|
1033
|
+
xhr.ontimeout = () => fail(
|
|
1034
|
+
new ExiosError(
|
|
1035
|
+
config.timeoutErrorMessage ?? `timeout of ${config.timeout}ms exceeded`,
|
|
1036
|
+
config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
|
|
1037
|
+
config,
|
|
1038
|
+
xhr
|
|
1039
|
+
)
|
|
1040
|
+
);
|
|
1041
|
+
xhr.onerror = () => {
|
|
1042
|
+
const e = new ExiosError("Network Error", ExiosError.ERR_NETWORK, config, xhr);
|
|
1043
|
+
fail(e);
|
|
1044
|
+
};
|
|
1045
|
+
xhr.onloadend = () => {
|
|
1046
|
+
if (settled || userError) return;
|
|
1047
|
+
if (xhr.readyState !== 4 || xhr.status === 0) return;
|
|
1048
|
+
void (async () => {
|
|
1049
|
+
try {
|
|
1050
|
+
const resHeaders = parseHeaders(xhr.getAllResponseHeaders());
|
|
1051
|
+
let data = xhr.response;
|
|
1052
|
+
if (type === "formData") {
|
|
1053
|
+
data = await new Response(data, {
|
|
1054
|
+
headers: { "content-type": resHeaders["content-type"] ?? "" }
|
|
1055
|
+
}).formData();
|
|
1056
|
+
} else if (type !== "blob" && type !== "arraybuffer") {
|
|
1057
|
+
data = decodeText(new Uint8Array(data), config);
|
|
1058
|
+
}
|
|
1059
|
+
const response = finishResponse(config, {
|
|
1060
|
+
status: xhr.status,
|
|
1061
|
+
statusText: xhr.statusText,
|
|
1062
|
+
headers: resHeaders,
|
|
1063
|
+
data,
|
|
1064
|
+
request: xhr
|
|
1065
|
+
});
|
|
1066
|
+
if (settled) return;
|
|
1067
|
+
settled = true;
|
|
1068
|
+
cleanup();
|
|
1069
|
+
resolve(response);
|
|
1070
|
+
} catch (err) {
|
|
1071
|
+
fail(err);
|
|
1072
|
+
}
|
|
1073
|
+
})();
|
|
1074
|
+
};
|
|
1075
|
+
if (signal?.aborted) return onAbort();
|
|
1076
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1077
|
+
xhr.send(body ?? null);
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// src/adapters/xhr/register.ts
|
|
1082
|
+
function registerXhrAdapter() {
|
|
1083
|
+
registerAdapter("xhr", {
|
|
1084
|
+
adapter: xhrAdapter,
|
|
1085
|
+
isAvailable: () => typeof XMLHttpRequest !== "undefined"
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// src/cancel/CancelToken.ts
|
|
1090
|
+
var CancelToken = class _CancelToken {
|
|
1091
|
+
reason;
|
|
1092
|
+
promise;
|
|
1093
|
+
listeners = [];
|
|
1094
|
+
constructor(executor) {
|
|
1095
|
+
if (typeof executor !== "function")
|
|
1096
|
+
throw new TypeError("executor must be a function.");
|
|
1097
|
+
let resolve;
|
|
1098
|
+
this.promise = new Promise((r) => resolve = r);
|
|
1099
|
+
executor((message, config, request) => {
|
|
1100
|
+
if (this.reason) return;
|
|
1101
|
+
this.reason = new CanceledError(message ?? "canceled", config, request);
|
|
1102
|
+
resolve(this.reason);
|
|
1103
|
+
const ls = this.listeners;
|
|
1104
|
+
this.listeners = [];
|
|
1105
|
+
for (const l of ls) l(this.reason);
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
throwIfRequested() {
|
|
1109
|
+
if (this.reason) throw this.reason;
|
|
1110
|
+
}
|
|
1111
|
+
subscribe(listener) {
|
|
1112
|
+
if (this.reason) listener(this.reason);
|
|
1113
|
+
else this.listeners.push(listener);
|
|
1114
|
+
}
|
|
1115
|
+
unsubscribe(listener) {
|
|
1116
|
+
this.listeners = this.listeners.filter((l) => l !== listener);
|
|
1117
|
+
}
|
|
1118
|
+
/** An AbortSignal that aborts with the reason; call `signal.unsubscribe()` when done with it. */
|
|
1119
|
+
toAbortSignal() {
|
|
1120
|
+
const ac = new AbortController();
|
|
1121
|
+
const abort = (reason) => ac.abort(reason);
|
|
1122
|
+
this.subscribe(abort);
|
|
1123
|
+
return Object.assign(ac.signal, { unsubscribe: () => this.unsubscribe(abort) });
|
|
1124
|
+
}
|
|
1125
|
+
static source() {
|
|
1126
|
+
let cancel;
|
|
1127
|
+
const token = new _CancelToken((c) => cancel = c);
|
|
1128
|
+
return { token, cancel };
|
|
1129
|
+
}
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
// src/core/defaults.ts
|
|
1133
|
+
var DEFAULT_RETRY = Object.freeze({
|
|
1134
|
+
retries: 3,
|
|
1135
|
+
methods: Object.freeze([
|
|
1136
|
+
"get",
|
|
1137
|
+
"head",
|
|
1138
|
+
"options",
|
|
1139
|
+
"put",
|
|
1140
|
+
"delete"
|
|
1141
|
+
]),
|
|
1142
|
+
statusCodes: Object.freeze([408, 429, 500, 502, 503, 504]),
|
|
1143
|
+
retryOnNetworkError: true,
|
|
1144
|
+
baseDelayMs: 300,
|
|
1145
|
+
maxDelayMs: 3e4,
|
|
1146
|
+
factor: 2,
|
|
1147
|
+
jitter: "full",
|
|
1148
|
+
respectRetryAfter: true
|
|
1149
|
+
});
|
|
1150
|
+
var DEFAULT_BREAKER = Object.freeze({
|
|
1151
|
+
failureThreshold: 5,
|
|
1152
|
+
minRequests: 10,
|
|
1153
|
+
failureRateThreshold: 0.5,
|
|
1154
|
+
resetTimeoutMs: 3e4,
|
|
1155
|
+
halfOpenMaxRequests: 1,
|
|
1156
|
+
successThreshold: 1
|
|
1157
|
+
});
|
|
1158
|
+
function createHeaderBuckets(common = {}) {
|
|
1159
|
+
return {
|
|
1160
|
+
common,
|
|
1161
|
+
get: {},
|
|
1162
|
+
post: {},
|
|
1163
|
+
put: {},
|
|
1164
|
+
patch: {},
|
|
1165
|
+
delete: {},
|
|
1166
|
+
head: {},
|
|
1167
|
+
options: {}
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
function createDefaults() {
|
|
1171
|
+
return {
|
|
1172
|
+
adapter: ["xhr", "http", "fetch"],
|
|
1173
|
+
xsrfCookieName: "XSRF-TOKEN",
|
|
1174
|
+
xsrfHeaderName: "X-XSRF-TOKEN",
|
|
1175
|
+
maxRedirects: 21,
|
|
1176
|
+
decompress: true,
|
|
1177
|
+
timeout: 0,
|
|
1178
|
+
responseType: "json",
|
|
1179
|
+
headers: createHeaderBuckets({
|
|
1180
|
+
Accept: "application/json, text/plain, */*"
|
|
1181
|
+
}),
|
|
1182
|
+
transformRequest: [defaultTransformRequest],
|
|
1183
|
+
transformResponse: [defaultTransformResponse],
|
|
1184
|
+
validateStatus: (s) => s >= 200 && s < 300,
|
|
1185
|
+
maxContentLength: -1,
|
|
1186
|
+
maxBodyLength: -1,
|
|
1187
|
+
transitional: { silentJSONParsing: true, clarifyTimeoutError: false },
|
|
1188
|
+
retry: {
|
|
1189
|
+
...DEFAULT_RETRY,
|
|
1190
|
+
methods: [...DEFAULT_RETRY.methods],
|
|
1191
|
+
statusCodes: [...DEFAULT_RETRY.statusCodes]
|
|
1192
|
+
},
|
|
1193
|
+
breaker: { ...DEFAULT_BREAKER }
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// src/resilience/breaker.ts
|
|
1198
|
+
var FAILURE_CODES = /* @__PURE__ */ new Set([
|
|
1199
|
+
ExiosError.ERR_NETWORK,
|
|
1200
|
+
ExiosError.ECONNABORTED,
|
|
1201
|
+
ExiosError.ETIMEDOUT
|
|
1202
|
+
]);
|
|
1203
|
+
function defaultIsFailure(o) {
|
|
1204
|
+
const code = o.error?.code;
|
|
1205
|
+
if (code === ExiosError.ERR_CANCELED) return false;
|
|
1206
|
+
if (code !== void 0 && FAILURE_CODES.has(code)) return true;
|
|
1207
|
+
const status = o.response?.status ?? o.error?.response?.status;
|
|
1208
|
+
if (status === void 0) return false;
|
|
1209
|
+
return status >= 500 || status === 408 || status === 429;
|
|
1210
|
+
}
|
|
1211
|
+
var CircuitBreaker = class {
|
|
1212
|
+
constructor(key, cfg, now = Date.now) {
|
|
1213
|
+
this.key = key;
|
|
1214
|
+
this.cfg = cfg;
|
|
1215
|
+
this.now = now;
|
|
1216
|
+
}
|
|
1217
|
+
key;
|
|
1218
|
+
cfg;
|
|
1219
|
+
now;
|
|
1220
|
+
_state = "closed";
|
|
1221
|
+
epoch = 0;
|
|
1222
|
+
openedAt = 0;
|
|
1223
|
+
consecutive = 0;
|
|
1224
|
+
samples = [];
|
|
1225
|
+
probes = /* @__PURE__ */ new Set();
|
|
1226
|
+
windowFailures = 0;
|
|
1227
|
+
probeSuccesses = 0;
|
|
1228
|
+
/** Stored state; open -> half-open happens lazily on `acquire` (no timers). */
|
|
1229
|
+
get state() {
|
|
1230
|
+
return this._state;
|
|
1231
|
+
}
|
|
1232
|
+
retryAt() {
|
|
1233
|
+
return this.openedAt + this.cfg.resetTimeoutMs;
|
|
1234
|
+
}
|
|
1235
|
+
acquire(config) {
|
|
1236
|
+
if (this._state === "open") {
|
|
1237
|
+
if (this.now() < this.retryAt())
|
|
1238
|
+
throw new CircuitOpenError(this.key, this.retryAt(), config);
|
|
1239
|
+
this.transition("half-open");
|
|
1240
|
+
}
|
|
1241
|
+
if (this._state === "half-open") {
|
|
1242
|
+
const cutoff = this.now() - this.cfg.resetTimeoutMs;
|
|
1243
|
+
for (const p of this.probes) {
|
|
1244
|
+
if (p.at <= cutoff) {
|
|
1245
|
+
this.transition("open");
|
|
1246
|
+
throw new CircuitOpenError(this.key, this.retryAt(), config);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
if (this.probes.size >= this.cfg.halfOpenMaxRequests) {
|
|
1250
|
+
throw new CircuitOpenError(this.key, this.now(), config);
|
|
1251
|
+
}
|
|
1252
|
+
const probe = {
|
|
1253
|
+
probe: true,
|
|
1254
|
+
done: false,
|
|
1255
|
+
epoch: this.epoch,
|
|
1256
|
+
at: this.now()
|
|
1257
|
+
};
|
|
1258
|
+
this.probes.add(probe);
|
|
1259
|
+
return probe;
|
|
1260
|
+
}
|
|
1261
|
+
return { probe: false, done: false, epoch: this.epoch, at: this.now() };
|
|
1262
|
+
}
|
|
1263
|
+
/** Called before each retry: a non-probe ticket may not continue unless closed. */
|
|
1264
|
+
check(ticket) {
|
|
1265
|
+
if (this._state === "closed" || ticket.probe && ticket.epoch === this.epoch)
|
|
1266
|
+
return;
|
|
1267
|
+
throw new CircuitOpenError(
|
|
1268
|
+
this.key,
|
|
1269
|
+
this._state === "open" ? this.retryAt() : this.now()
|
|
1270
|
+
);
|
|
1271
|
+
}
|
|
1272
|
+
record(ticket, failed) {
|
|
1273
|
+
if (ticket.done) return;
|
|
1274
|
+
ticket.done = true;
|
|
1275
|
+
if (ticket.epoch !== this.epoch) return;
|
|
1276
|
+
if (ticket.probe) {
|
|
1277
|
+
this.probes.delete(ticket);
|
|
1278
|
+
if (this._state !== "half-open") return;
|
|
1279
|
+
if (failed) return this.transition("open");
|
|
1280
|
+
if (++this.probeSuccesses >= this.cfg.successThreshold)
|
|
1281
|
+
this.transition("closed");
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
if (this._state !== "closed") return;
|
|
1285
|
+
if (this.cfg.windowMs !== void 0) {
|
|
1286
|
+
const t = this.now();
|
|
1287
|
+
this.samples.push({ t, failed });
|
|
1288
|
+
if (failed) this.windowFailures++;
|
|
1289
|
+
let i = 0;
|
|
1290
|
+
while (i < this.samples.length && t - this.samples[i].t > this.cfg.windowMs) {
|
|
1291
|
+
if (this.samples[i].failed) this.windowFailures--;
|
|
1292
|
+
i++;
|
|
1293
|
+
}
|
|
1294
|
+
if (i > 0) this.samples.splice(0, i);
|
|
1295
|
+
if (this.samples.length >= this.cfg.minRequests && this.windowFailures / this.samples.length >= this.cfg.failureRateThreshold) {
|
|
1296
|
+
this.transition("open");
|
|
1297
|
+
}
|
|
1298
|
+
return;
|
|
1299
|
+
}
|
|
1300
|
+
this.consecutive = failed ? this.consecutive + 1 : 0;
|
|
1301
|
+
if (this.consecutive >= this.cfg.failureThreshold) this.transition("open");
|
|
1302
|
+
}
|
|
1303
|
+
/** No outcome (cancel): frees a probe slot, never changes state. */
|
|
1304
|
+
release(ticket) {
|
|
1305
|
+
if (ticket.done) return;
|
|
1306
|
+
ticket.done = true;
|
|
1307
|
+
if (ticket.probe && ticket.epoch === this.epoch) this.probes.delete(ticket);
|
|
1308
|
+
}
|
|
1309
|
+
transition(to) {
|
|
1310
|
+
const from = this._state;
|
|
1311
|
+
this._state = to;
|
|
1312
|
+
this.epoch++;
|
|
1313
|
+
this.probes = /* @__PURE__ */ new Set();
|
|
1314
|
+
this.windowFailures = 0;
|
|
1315
|
+
this.probeSuccesses = 0;
|
|
1316
|
+
this.consecutive = 0;
|
|
1317
|
+
this.samples = [];
|
|
1318
|
+
if (to === "open") this.openedAt = this.now();
|
|
1319
|
+
try {
|
|
1320
|
+
this.cfg.onStateChange?.(this.key, from, to);
|
|
1321
|
+
} catch {
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
var BreakerRegistry = class {
|
|
1326
|
+
constructor(getConfig, now = Date.now) {
|
|
1327
|
+
this.getConfig = getConfig;
|
|
1328
|
+
this.now = now;
|
|
1329
|
+
}
|
|
1330
|
+
getConfig;
|
|
1331
|
+
now;
|
|
1332
|
+
breakers = /* @__PURE__ */ new Map();
|
|
1333
|
+
get(key) {
|
|
1334
|
+
const cfg = this.getConfig();
|
|
1335
|
+
if (cfg === false) return null;
|
|
1336
|
+
let b = this.breakers.get(key);
|
|
1337
|
+
if (!b) {
|
|
1338
|
+
b = new CircuitBreaker(key, cfg, this.now);
|
|
1339
|
+
this.breakers.set(key, b);
|
|
1340
|
+
}
|
|
1341
|
+
return b;
|
|
1342
|
+
}
|
|
1343
|
+
state(key) {
|
|
1344
|
+
return this.breakers.get(key)?.state ?? "closed";
|
|
1345
|
+
}
|
|
1346
|
+
reset(key) {
|
|
1347
|
+
if (key === void 0) this.breakers.clear();
|
|
1348
|
+
else this.breakers.delete(key);
|
|
1349
|
+
}
|
|
1350
|
+
};
|
|
1351
|
+
|
|
1352
|
+
// src/resilience/backoff.ts
|
|
1353
|
+
function computeDelay(attempt, cfg, random = Math.random) {
|
|
1354
|
+
const capped = Math.min(
|
|
1355
|
+
cfg.maxDelayMs,
|
|
1356
|
+
cfg.baseDelayMs * cfg.factor ** (attempt - 1)
|
|
1357
|
+
);
|
|
1358
|
+
return cfg.jitter === "full" ? Math.floor(random() * capped) : capped;
|
|
1359
|
+
}
|
|
1360
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
1361
|
+
if (value === void 0) return void 0;
|
|
1362
|
+
const v = value.trim();
|
|
1363
|
+
if (/^\d+$/.test(v)) return Number(v) * 1e3;
|
|
1364
|
+
if (!/^[A-Za-z]{3,9},? /.test(v)) return void 0;
|
|
1365
|
+
const date = Date.parse(v);
|
|
1366
|
+
if (Number.isNaN(date)) return void 0;
|
|
1367
|
+
return Math.max(0, date - now);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// src/resilience/retry.ts
|
|
1371
|
+
var NEVER_RETRY = /* @__PURE__ */ new Set([
|
|
1372
|
+
"ERR_CANCELED",
|
|
1373
|
+
"ERR_CIRCUIT_OPEN",
|
|
1374
|
+
"ERR_BAD_OPTION_VALUE",
|
|
1375
|
+
"ERR_NOT_SUPPORT",
|
|
1376
|
+
"ERR_FR_TOO_MANY_REDIRECTS"
|
|
1377
|
+
]);
|
|
1378
|
+
var RETRYABLE_ERRORS = /* @__PURE__ */ new Set(["ERR_NETWORK", "ECONNABORTED", "ETIMEDOUT"]);
|
|
1379
|
+
function defaultShouldRetry(o, cfg, config) {
|
|
1380
|
+
if (!cfg.methods.includes(config.method)) return false;
|
|
1381
|
+
if (o.response) return cfg.statusCodes.includes(o.response.status);
|
|
1382
|
+
if (o.error)
|
|
1383
|
+
return cfg.retryOnNetworkError && RETRYABLE_ERRORS.has(o.error.code ?? "");
|
|
1384
|
+
return false;
|
|
1385
|
+
}
|
|
1386
|
+
function defaultSleep(ms, signal) {
|
|
1387
|
+
return new Promise((resolve, reject) => {
|
|
1388
|
+
if (signal?.aborted) return reject(abortError(signal));
|
|
1389
|
+
const onAbort = () => {
|
|
1390
|
+
clearTimeout(timer);
|
|
1391
|
+
reject(abortError(signal));
|
|
1392
|
+
};
|
|
1393
|
+
const timer = setTimeout(() => {
|
|
1394
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1395
|
+
resolve();
|
|
1396
|
+
}, ms);
|
|
1397
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
async function runWithRetry(attempt, cfg, config, hooks) {
|
|
1401
|
+
const sleep = hooks.sleep ?? defaultSleep;
|
|
1402
|
+
const now = hooks.now ?? Date.now;
|
|
1403
|
+
const start = now();
|
|
1404
|
+
const isStream = isOneShotBody(config.data);
|
|
1405
|
+
let attempts = 0;
|
|
1406
|
+
for (; ; ) {
|
|
1407
|
+
attempts++;
|
|
1408
|
+
let outcome;
|
|
1409
|
+
try {
|
|
1410
|
+
outcome = { response: await attempt() };
|
|
1411
|
+
} catch (e) {
|
|
1412
|
+
if (!isExiosError(e)) throw e;
|
|
1413
|
+
outcome = { error: e };
|
|
1414
|
+
}
|
|
1415
|
+
if (cfg === false || attempts > cfg.retries || isStream)
|
|
1416
|
+
return { outcome, attempts };
|
|
1417
|
+
if (outcome.response && outcome.response.status >= 200 && outcome.response.status < 300)
|
|
1418
|
+
return { outcome, attempts };
|
|
1419
|
+
if (NEVER_RETRY.has(outcome.error?.code ?? ""))
|
|
1420
|
+
return { outcome, attempts };
|
|
1421
|
+
let decide;
|
|
1422
|
+
try {
|
|
1423
|
+
decide = cfg.shouldRetry ? await cfg.shouldRetry({ ...outcome, attempt: attempts, config }) : defaultShouldRetry(outcome, cfg, config);
|
|
1424
|
+
} catch (e) {
|
|
1425
|
+
cancelBody(outcome.response?.data);
|
|
1426
|
+
throw e;
|
|
1427
|
+
}
|
|
1428
|
+
if (!decide) return { outcome, attempts };
|
|
1429
|
+
let delay;
|
|
1430
|
+
if (cfg.respectRetryAfter) {
|
|
1431
|
+
const raw = outcome.response?.headers["retry-after"];
|
|
1432
|
+
const parsed = parseRetryAfter(Array.isArray(raw) ? raw[0] : raw, now());
|
|
1433
|
+
if (parsed !== void 0)
|
|
1434
|
+
delay = Math.min(Math.max(parsed, 0), cfg.maxDelayMs);
|
|
1435
|
+
}
|
|
1436
|
+
delay ??= computeDelay(attempts, cfg, hooks.random);
|
|
1437
|
+
if (cfg.maxElapsedMs !== void 0 && now() - start + delay > cfg.maxElapsedMs) {
|
|
1438
|
+
return { outcome, attempts };
|
|
1439
|
+
}
|
|
1440
|
+
cancelBody(outcome.response?.data);
|
|
1441
|
+
if (hooks.signal?.aborted) throw abortError(hooks.signal);
|
|
1442
|
+
cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
|
|
1443
|
+
await sleep(delay, hooks.signal);
|
|
1444
|
+
hooks.beforeRetry?.();
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
// src/core/dispatchRequest.ts
|
|
1449
|
+
function defaultBreakerKey(config) {
|
|
1450
|
+
const full = buildFullPath(
|
|
1451
|
+
config.baseURL,
|
|
1452
|
+
config.url,
|
|
1453
|
+
config.allowAbsoluteUrls
|
|
1454
|
+
);
|
|
1455
|
+
try {
|
|
1456
|
+
return new URL(
|
|
1457
|
+
full,
|
|
1458
|
+
globalThis.location?.href
|
|
1459
|
+
).origin;
|
|
1460
|
+
} catch {
|
|
1461
|
+
return full;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
async function dispatchRequest(config, registry2) {
|
|
1465
|
+
const token = config.cancelToken;
|
|
1466
|
+
if (token) {
|
|
1467
|
+
if (token.reason) {
|
|
1468
|
+
token.reason.config ??= config;
|
|
1469
|
+
throw token.reason;
|
|
1470
|
+
}
|
|
1471
|
+
const tokenSignal = token.toAbortSignal();
|
|
1472
|
+
const joined = combineSignals(config.signal, tokenSignal);
|
|
1473
|
+
const release = () => {
|
|
1474
|
+
joined.cleanup();
|
|
1475
|
+
tokenSignal.unsubscribe();
|
|
1476
|
+
};
|
|
1477
|
+
let deferred = false;
|
|
1478
|
+
try {
|
|
1479
|
+
const response = await dispatchRequest(
|
|
1480
|
+
{ ...config, signal: joined.signal, cancelToken: void 0 },
|
|
1481
|
+
registry2
|
|
1482
|
+
);
|
|
1483
|
+
if (isOneShotBody(response.data)) {
|
|
1484
|
+
response.data = whenBodyDone(response.data, release);
|
|
1485
|
+
deferred = true;
|
|
1486
|
+
}
|
|
1487
|
+
return response;
|
|
1488
|
+
} catch (e) {
|
|
1489
|
+
if (isExiosError(e)) e.config ??= config;
|
|
1490
|
+
throw e;
|
|
1491
|
+
} finally {
|
|
1492
|
+
if (!deferred) release();
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
if (config.signal?.aborted) throw abortError(config.signal, config);
|
|
1496
|
+
const bcfg = config.breaker;
|
|
1497
|
+
const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
|
|
1498
|
+
const ticket = breaker?.acquire(config);
|
|
1499
|
+
let attempts = 0;
|
|
1500
|
+
try {
|
|
1501
|
+
let adapter;
|
|
1502
|
+
try {
|
|
1503
|
+
adapter = resolveAdapter(config);
|
|
1504
|
+
} catch (e) {
|
|
1505
|
+
if (isExiosError(e)) e.config ??= config;
|
|
1506
|
+
throw e;
|
|
1507
|
+
}
|
|
1508
|
+
let result;
|
|
1509
|
+
try {
|
|
1510
|
+
result = await runWithRetry(
|
|
1511
|
+
() => {
|
|
1512
|
+
attempts++;
|
|
1513
|
+
return adapter(config);
|
|
1514
|
+
},
|
|
1515
|
+
ticket?.probe ? false : config.retry,
|
|
1516
|
+
// half-open probes get exactly one attempt
|
|
1517
|
+
config,
|
|
1518
|
+
{
|
|
1519
|
+
signal: config.signal,
|
|
1520
|
+
beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
|
|
1521
|
+
}
|
|
1522
|
+
);
|
|
1523
|
+
} catch (e) {
|
|
1524
|
+
if (isExiosError(e)) {
|
|
1525
|
+
e.config ??= config;
|
|
1526
|
+
e.meta.attempts = attempts;
|
|
1527
|
+
}
|
|
1528
|
+
throw e;
|
|
1529
|
+
}
|
|
1530
|
+
const { outcome } = result;
|
|
1531
|
+
attempts = result.attempts;
|
|
1532
|
+
if (outcome.error) outcome.error.meta.attempts = attempts;
|
|
1533
|
+
if (outcome.error?.code === ExiosError.ERR_CANCELED) throw outcome.error;
|
|
1534
|
+
if (breaker && ticket && bcfg)
|
|
1535
|
+
breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
|
|
1536
|
+
if (outcome.error) throw outcome.error;
|
|
1537
|
+
const response = outcome.response;
|
|
1538
|
+
response.meta.attempts = attempts;
|
|
1539
|
+
const { status } = response;
|
|
1540
|
+
if (config.validateStatus && !config.validateStatus(status)) {
|
|
1541
|
+
const err = new ExiosError(
|
|
1542
|
+
"Request failed with status code " + status,
|
|
1543
|
+
status >= 500 ? ExiosError.ERR_BAD_RESPONSE : ExiosError.ERR_BAD_REQUEST,
|
|
1544
|
+
config,
|
|
1545
|
+
response.request,
|
|
1546
|
+
response
|
|
1547
|
+
);
|
|
1548
|
+
err.meta.attempts = attempts;
|
|
1549
|
+
throw err;
|
|
1550
|
+
}
|
|
1551
|
+
return response;
|
|
1552
|
+
} finally {
|
|
1553
|
+
if (breaker && ticket) breaker.release(ticket);
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
// src/core/InterceptorManager.ts
|
|
1558
|
+
var InterceptorManager = class {
|
|
1559
|
+
handlers = [];
|
|
1560
|
+
use(onFulfilled, onRejected, opts) {
|
|
1561
|
+
this.handlers.push({
|
|
1562
|
+
fulfilled: onFulfilled,
|
|
1563
|
+
rejected: onRejected,
|
|
1564
|
+
synchronous: opts?.synchronous ?? false,
|
|
1565
|
+
runWhen: opts?.runWhen ?? null
|
|
1566
|
+
});
|
|
1567
|
+
return this.handlers.length - 1;
|
|
1568
|
+
}
|
|
1569
|
+
eject(id) {
|
|
1570
|
+
if (this.handlers[id]) this.handlers[id] = null;
|
|
1571
|
+
}
|
|
1572
|
+
clear() {
|
|
1573
|
+
this.handlers = [];
|
|
1574
|
+
}
|
|
1575
|
+
forEach(fn) {
|
|
1576
|
+
for (const h of this.handlers) if (h) fn(h);
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
|
|
1580
|
+
// src/core/resilienceConfig.ts
|
|
1581
|
+
function defined(o) {
|
|
1582
|
+
const out = {};
|
|
1583
|
+
if (!o) return out;
|
|
1584
|
+
for (const [k, v] of Object.entries(o))
|
|
1585
|
+
if (v !== void 0) out[k] = v;
|
|
1586
|
+
return out;
|
|
1587
|
+
}
|
|
1588
|
+
function bad(name, value, rule) {
|
|
1589
|
+
throw new ExiosError(
|
|
1590
|
+
`ERR_BAD_OPTION_VALUE: ${name} must be ${rule} (got ${String(value)})`,
|
|
1591
|
+
ExiosError.ERR_BAD_OPTION_VALUE
|
|
1592
|
+
);
|
|
1593
|
+
}
|
|
1594
|
+
var isNum = (v) => typeof v === "number" && !Number.isNaN(v);
|
|
1595
|
+
function check(name, v, ok, rule) {
|
|
1596
|
+
if (!isNum(v) || !ok(v)) bad(name, v, rule);
|
|
1597
|
+
}
|
|
1598
|
+
var nonNegFinite = (n) => n >= 0 && Number.isFinite(n);
|
|
1599
|
+
function resolveRetry(v) {
|
|
1600
|
+
if (v === false) return false;
|
|
1601
|
+
if (v !== void 0 && (typeof v !== "object" || v === null))
|
|
1602
|
+
bad("retry", v, "false or an object");
|
|
1603
|
+
const r = { ...DEFAULT_RETRY, ...defined(v) };
|
|
1604
|
+
if (!Array.isArray(r.methods)) bad("retry.methods", r.methods, "an array");
|
|
1605
|
+
if (!Array.isArray(r.statusCodes))
|
|
1606
|
+
bad("retry.statusCodes", r.statusCodes, "an array");
|
|
1607
|
+
r.methods = [...r.methods];
|
|
1608
|
+
r.statusCodes = [...r.statusCodes];
|
|
1609
|
+
check(
|
|
1610
|
+
"retry.retries",
|
|
1611
|
+
r.retries,
|
|
1612
|
+
nonNegFinite,
|
|
1613
|
+
"a non-negative finite number"
|
|
1614
|
+
);
|
|
1615
|
+
check(
|
|
1616
|
+
"retry.baseDelayMs",
|
|
1617
|
+
r.baseDelayMs,
|
|
1618
|
+
nonNegFinite,
|
|
1619
|
+
"a non-negative finite number"
|
|
1620
|
+
);
|
|
1621
|
+
check(
|
|
1622
|
+
"retry.maxDelayMs",
|
|
1623
|
+
r.maxDelayMs,
|
|
1624
|
+
nonNegFinite,
|
|
1625
|
+
"a non-negative finite number"
|
|
1626
|
+
);
|
|
1627
|
+
if (r.maxElapsedMs !== void 0) {
|
|
1628
|
+
check(
|
|
1629
|
+
"retry.maxElapsedMs",
|
|
1630
|
+
r.maxElapsedMs,
|
|
1631
|
+
nonNegFinite,
|
|
1632
|
+
"a non-negative finite number"
|
|
1633
|
+
);
|
|
1634
|
+
}
|
|
1635
|
+
check(
|
|
1636
|
+
"retry.factor",
|
|
1637
|
+
r.factor,
|
|
1638
|
+
(n) => n >= 1 && Number.isFinite(n),
|
|
1639
|
+
"a finite number >= 1"
|
|
1640
|
+
);
|
|
1641
|
+
return r;
|
|
1642
|
+
}
|
|
1643
|
+
function resolveBreaker(v) {
|
|
1644
|
+
if (v === false) return false;
|
|
1645
|
+
if (v !== void 0 && (typeof v !== "object" || v === null))
|
|
1646
|
+
bad("breaker", v, "false or an object");
|
|
1647
|
+
const b = { ...DEFAULT_BREAKER, ...defined(v) };
|
|
1648
|
+
const positive = (n) => n > 0;
|
|
1649
|
+
check(
|
|
1650
|
+
"breaker.failureThreshold",
|
|
1651
|
+
b.failureThreshold,
|
|
1652
|
+
positive,
|
|
1653
|
+
"a number > 0"
|
|
1654
|
+
);
|
|
1655
|
+
check("breaker.resetTimeoutMs", b.resetTimeoutMs, positive, "a number > 0");
|
|
1656
|
+
check("breaker.minRequests", b.minRequests, positive, "a number > 0");
|
|
1657
|
+
check(
|
|
1658
|
+
"breaker.failureRateThreshold",
|
|
1659
|
+
b.failureRateThreshold,
|
|
1660
|
+
(n) => n > 0 && n <= 1,
|
|
1661
|
+
"in (0, 1]"
|
|
1662
|
+
);
|
|
1663
|
+
check(
|
|
1664
|
+
"breaker.halfOpenMaxRequests",
|
|
1665
|
+
b.halfOpenMaxRequests,
|
|
1666
|
+
(n) => n >= 1,
|
|
1667
|
+
"a number >= 1"
|
|
1668
|
+
);
|
|
1669
|
+
check(
|
|
1670
|
+
"breaker.successThreshold",
|
|
1671
|
+
b.successThreshold,
|
|
1672
|
+
(n) => n >= 1,
|
|
1673
|
+
"a number >= 1"
|
|
1674
|
+
);
|
|
1675
|
+
if (b.windowMs !== void 0)
|
|
1676
|
+
check("breaker.windowMs", b.windowMs, positive, "a number > 0");
|
|
1677
|
+
return b;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// src/core/mergeConfig.ts
|
|
1681
|
+
var isPlainObject3 = (v) => {
|
|
1682
|
+
if (typeof v !== "object" || v === null) return false;
|
|
1683
|
+
const p = Object.getPrototypeOf(v);
|
|
1684
|
+
return p === Object.prototype || p === null;
|
|
1685
|
+
};
|
|
1686
|
+
var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
|
|
1687
|
+
var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
|
|
1688
|
+
function setCI(target, k, v) {
|
|
1689
|
+
const lk = k.toLowerCase();
|
|
1690
|
+
for (const existing of Object.keys(target)) {
|
|
1691
|
+
if (existing.toLowerCase() === lk) delete target[existing];
|
|
1692
|
+
}
|
|
1693
|
+
target[k] = v;
|
|
1694
|
+
}
|
|
1695
|
+
function toPlainHeaders(h) {
|
|
1696
|
+
if (!h) return {};
|
|
1697
|
+
if (typeof Headers !== "undefined" && h instanceof Headers)
|
|
1698
|
+
return normalizeHeaders(h);
|
|
1699
|
+
return h;
|
|
1700
|
+
}
|
|
1701
|
+
function mergeFlat(a, b) {
|
|
1702
|
+
const out = { ...a };
|
|
1703
|
+
for (const [k, v] of Object.entries(b)) setCI(out, k, v);
|
|
1704
|
+
return out;
|
|
1705
|
+
}
|
|
1706
|
+
function mergeHeaders(a, b) {
|
|
1707
|
+
const pa = toPlainHeaders(a);
|
|
1708
|
+
const pb = toPlainHeaders(b);
|
|
1709
|
+
const out = {};
|
|
1710
|
+
for (const [k, v] of Object.entries(pa))
|
|
1711
|
+
setCI(out, k, isBucket(k) && isPlainObject3(v) ? { ...v } : v);
|
|
1712
|
+
for (const [k, v] of Object.entries(pb)) {
|
|
1713
|
+
const existingKey = Object.keys(out).find(
|
|
1714
|
+
(e) => e.toLowerCase() === k.toLowerCase()
|
|
1715
|
+
);
|
|
1716
|
+
const existing = existingKey === void 0 ? void 0 : out[existingKey];
|
|
1717
|
+
if (isBucket(k) && isPlainObject3(v) && isPlainObject3(existing))
|
|
1718
|
+
setCI(out, k, mergeFlat(existing, v));
|
|
1719
|
+
else setCI(out, k, isBucket(k) && isPlainObject3(v) ? { ...v } : v);
|
|
1720
|
+
}
|
|
1721
|
+
return out;
|
|
1722
|
+
}
|
|
1723
|
+
function mergeRetry(a, b) {
|
|
1724
|
+
if (b === false) return false;
|
|
1725
|
+
if (b === void 0) return a;
|
|
1726
|
+
return { ...a || DEFAULT_RETRY, ...defined(b) };
|
|
1727
|
+
}
|
|
1728
|
+
function mergeBreaker(a, b) {
|
|
1729
|
+
if (b === false) return false;
|
|
1730
|
+
if (b === void 0) return a;
|
|
1731
|
+
return { ...a || DEFAULT_BREAKER, ...defined(b) };
|
|
1732
|
+
}
|
|
1733
|
+
function mergeConfig(a, b = {}) {
|
|
1734
|
+
const out = {};
|
|
1735
|
+
const A = a;
|
|
1736
|
+
const B = b;
|
|
1737
|
+
for (const k of /* @__PURE__ */ new Set([...Object.keys(A), ...Object.keys(B)])) {
|
|
1738
|
+
if (k === "url" || k === "method" || k === "data" || k === "headers" || k === "retry" || k === "breaker")
|
|
1739
|
+
continue;
|
|
1740
|
+
if (SHALLOW_MERGE.has(k) && isPlainObject3(A[k]) && isPlainObject3(B[k]))
|
|
1741
|
+
out[k] = { ...A[k], ...B[k] };
|
|
1742
|
+
else out[k] = B[k] !== void 0 ? B[k] : A[k];
|
|
1743
|
+
}
|
|
1744
|
+
out.url = B.url;
|
|
1745
|
+
out.method = B.method;
|
|
1746
|
+
out.data = B.data;
|
|
1747
|
+
out.headers = mergeHeaders(A.headers, B.headers);
|
|
1748
|
+
const retry = mergeRetry(a.retry, b.retry);
|
|
1749
|
+
const breaker = mergeBreaker(a.breaker, b.breaker);
|
|
1750
|
+
if (retry !== void 0) out.retry = retry;
|
|
1751
|
+
if (breaker !== void 0) out.breaker = breaker;
|
|
1752
|
+
return out;
|
|
1753
|
+
}
|
|
1754
|
+
function resolveConfig(merged) {
|
|
1755
|
+
const method = (merged.method ?? "get").toLowerCase();
|
|
1756
|
+
const { retry, breaker, headers: _h, ...rest } = merged;
|
|
1757
|
+
return {
|
|
1758
|
+
...rest,
|
|
1759
|
+
method,
|
|
1760
|
+
headers: normalizeHeaders(flattenHeaders(merged.headers, method)),
|
|
1761
|
+
retry: resolveRetry(retry),
|
|
1762
|
+
breaker: resolveBreaker(breaker)
|
|
1763
|
+
};
|
|
1764
|
+
}
|
|
1765
|
+
function finalizeConfig(config) {
|
|
1766
|
+
assertEncoding(config);
|
|
1767
|
+
const method = (config.method ?? "get").toLowerCase();
|
|
1768
|
+
return {
|
|
1769
|
+
...config,
|
|
1770
|
+
method,
|
|
1771
|
+
headers: finalizeHeaders(config.headers, method),
|
|
1772
|
+
retry: resolveRetry(config.retry),
|
|
1773
|
+
breaker: resolveBreaker(config.breaker)
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
function assertRequestBreaker(b) {
|
|
1777
|
+
if (b === void 0 || b === false) return;
|
|
1778
|
+
if (typeof b !== "object" || b === null) {
|
|
1779
|
+
throw new ExiosError(
|
|
1780
|
+
"Per-request breaker must be false or an object",
|
|
1781
|
+
ExiosError.ERR_BAD_OPTION_VALUE
|
|
1782
|
+
);
|
|
1783
|
+
}
|
|
1784
|
+
const bad2 = Object.keys(b).filter((k) => k !== "key" && k !== "isFailure");
|
|
1785
|
+
if (bad2.length) {
|
|
1786
|
+
throw new ExiosError(
|
|
1787
|
+
`ERR_BAD_OPTION_VALUE: per-request breaker only accepts "key" and "isFailure" (got ${bad2.join(", ")})`,
|
|
1788
|
+
ExiosError.ERR_BAD_OPTION_VALUE
|
|
1789
|
+
);
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// src/core/Exios.ts
|
|
1794
|
+
var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
|
|
1795
|
+
var Exios = class {
|
|
1796
|
+
defaults;
|
|
1797
|
+
interceptors = {
|
|
1798
|
+
request: new InterceptorManager(),
|
|
1799
|
+
response: new InterceptorManager()
|
|
1800
|
+
};
|
|
1801
|
+
breaker;
|
|
1802
|
+
registry;
|
|
1803
|
+
constructor(defaults) {
|
|
1804
|
+
this.defaults = defaults;
|
|
1805
|
+
this.registry = new BreakerRegistry(
|
|
1806
|
+
() => resolveBreaker(this.defaults.breaker)
|
|
1807
|
+
);
|
|
1808
|
+
this.breaker = {
|
|
1809
|
+
state: (key) => this.registry.state(key),
|
|
1810
|
+
reset: (key) => this.registry.reset(key)
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
async request(configOrUrl, config) {
|
|
1814
|
+
const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
|
|
1815
|
+
assertRequestBreaker(cfg.breaker);
|
|
1816
|
+
const resolved = resolveConfig(mergeConfig(this.defaults, cfg));
|
|
1817
|
+
const requestChain = [];
|
|
1818
|
+
let synchronous = true;
|
|
1819
|
+
this.interceptors.request.forEach((h) => {
|
|
1820
|
+
if (h.runWhen && h.runWhen(resolved) === false) return;
|
|
1821
|
+
synchronous = synchronous && h.synchronous;
|
|
1822
|
+
requestChain.unshift(h);
|
|
1823
|
+
});
|
|
1824
|
+
const dispatch = (c) => dispatchRequest(finalizeConfig(c), this.registry);
|
|
1825
|
+
let promise;
|
|
1826
|
+
if (synchronous) {
|
|
1827
|
+
promise = this.runSync(requestChain, resolved, dispatch);
|
|
1828
|
+
} else {
|
|
1829
|
+
promise = Promise.resolve(resolved);
|
|
1830
|
+
for (const h of requestChain)
|
|
1831
|
+
promise = promise.then(
|
|
1832
|
+
h.fulfilled ?? void 0,
|
|
1833
|
+
h.rejected ?? void 0
|
|
1834
|
+
);
|
|
1835
|
+
promise = promise.then(dispatch);
|
|
1836
|
+
}
|
|
1837
|
+
this.interceptors.response.forEach((h) => {
|
|
1838
|
+
promise = promise.then(h.fulfilled ?? void 0, h.rejected ?? void 0);
|
|
1839
|
+
});
|
|
1840
|
+
return promise;
|
|
1841
|
+
}
|
|
1842
|
+
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
1843
|
+
runSync(chain, config, dispatch) {
|
|
1844
|
+
let value = config;
|
|
1845
|
+
let failed = false;
|
|
1846
|
+
let error;
|
|
1847
|
+
for (const h of chain) {
|
|
1848
|
+
try {
|
|
1849
|
+
if (!failed) {
|
|
1850
|
+
if (h.fulfilled) value = h.fulfilled(value);
|
|
1851
|
+
} else if (h.rejected) {
|
|
1852
|
+
value = h.rejected(error);
|
|
1853
|
+
failed = false;
|
|
1854
|
+
}
|
|
1855
|
+
} catch (e) {
|
|
1856
|
+
failed = true;
|
|
1857
|
+
error = e;
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
if (failed) return Promise.reject(error);
|
|
1861
|
+
return isThenable(value) ? Promise.resolve(value).then((c) => dispatch(c)) : dispatch(value);
|
|
1862
|
+
}
|
|
1863
|
+
getUri(config) {
|
|
1864
|
+
const c = mergeConfig(this.defaults, config);
|
|
1865
|
+
return buildURL(
|
|
1866
|
+
buildFullPath(c.baseURL, c.url, c.allowAbsoluteUrls),
|
|
1867
|
+
c.params,
|
|
1868
|
+
c.paramsSerializer
|
|
1869
|
+
);
|
|
1870
|
+
}
|
|
1871
|
+
noData(method, url, config) {
|
|
1872
|
+
return this.request({ ...config, method, url });
|
|
1873
|
+
}
|
|
1874
|
+
withData(method, url, data, config, form = false) {
|
|
1875
|
+
const c = { ...config, method, url, data };
|
|
1876
|
+
if (form) {
|
|
1877
|
+
const h = config?.headers;
|
|
1878
|
+
const plain = typeof Headers !== "undefined" && h instanceof Headers ? normalizeHeaders(h) : h;
|
|
1879
|
+
c.headers = {
|
|
1880
|
+
...plain,
|
|
1881
|
+
"content-type": "multipart/form-data"
|
|
1882
|
+
};
|
|
1883
|
+
}
|
|
1884
|
+
return this.request(c);
|
|
1885
|
+
}
|
|
1886
|
+
get(url, config) {
|
|
1887
|
+
return this.noData("get", url, config);
|
|
1888
|
+
}
|
|
1889
|
+
delete(url, config) {
|
|
1890
|
+
return this.noData("delete", url, config);
|
|
1891
|
+
}
|
|
1892
|
+
head(url, config) {
|
|
1893
|
+
return this.noData("head", url, config);
|
|
1894
|
+
}
|
|
1895
|
+
options(url, config) {
|
|
1896
|
+
return this.noData("options", url, config);
|
|
1897
|
+
}
|
|
1898
|
+
post(url, data, config) {
|
|
1899
|
+
return this.withData("post", url, data, config);
|
|
1900
|
+
}
|
|
1901
|
+
put(url, data, config) {
|
|
1902
|
+
return this.withData("put", url, data, config);
|
|
1903
|
+
}
|
|
1904
|
+
patch(url, data, config) {
|
|
1905
|
+
return this.withData("patch", url, data, config);
|
|
1906
|
+
}
|
|
1907
|
+
postForm(url, data, config) {
|
|
1908
|
+
return this.withData("post", url, data, config, true);
|
|
1909
|
+
}
|
|
1910
|
+
putForm(url, data, config) {
|
|
1911
|
+
return this.withData("put", url, data, config, true);
|
|
1912
|
+
}
|
|
1913
|
+
patchForm(url, data, config) {
|
|
1914
|
+
return this.withData("patch", url, data, config, true);
|
|
1915
|
+
}
|
|
1916
|
+
};
|
|
1917
|
+
var METHODS = [
|
|
1918
|
+
"request",
|
|
1919
|
+
"getUri",
|
|
1920
|
+
"get",
|
|
1921
|
+
"delete",
|
|
1922
|
+
"head",
|
|
1923
|
+
"options",
|
|
1924
|
+
"post",
|
|
1925
|
+
"put",
|
|
1926
|
+
"patch",
|
|
1927
|
+
"postForm",
|
|
1928
|
+
"putForm",
|
|
1929
|
+
"patchForm"
|
|
1930
|
+
];
|
|
1931
|
+
var isPlainObject4 = (v) => typeof v === "object" && v !== null && [Object.prototype, null].includes(Object.getPrototypeOf(v));
|
|
1932
|
+
function detachDefaults(d) {
|
|
1933
|
+
const out = { ...d };
|
|
1934
|
+
const headers = isPlainObject4(out.headers) ? out.headers : normalizeHeaders(out.headers);
|
|
1935
|
+
out.headers = Object.assign(createHeaderBuckets(), headers);
|
|
1936
|
+
for (const b of HEADER_BUCKETS) {
|
|
1937
|
+
const existing = Object.keys(headers).find((k) => k.toLowerCase() === b);
|
|
1938
|
+
if (existing !== void 0 && existing !== b) {
|
|
1939
|
+
out.headers[b] = out.headers[existing];
|
|
1940
|
+
delete out.headers[existing];
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
out.retry ??= { ...DEFAULT_RETRY };
|
|
1944
|
+
out.breaker ??= { ...DEFAULT_BREAKER };
|
|
1945
|
+
for (const k of [
|
|
1946
|
+
"transitional",
|
|
1947
|
+
"fetchOptions",
|
|
1948
|
+
"auth",
|
|
1949
|
+
"breaker"
|
|
1950
|
+
]) {
|
|
1951
|
+
if (isPlainObject4(out[k])) out[k] = { ...out[k] };
|
|
1952
|
+
}
|
|
1953
|
+
if (isPlainObject4(out.retry)) {
|
|
1954
|
+
out.retry = { ...out.retry };
|
|
1955
|
+
if (Array.isArray(out.retry.methods))
|
|
1956
|
+
out.retry.methods = [...out.retry.methods];
|
|
1957
|
+
if (Array.isArray(out.retry.statusCodes))
|
|
1958
|
+
out.retry.statusCodes = [...out.retry.statusCodes];
|
|
1959
|
+
}
|
|
1960
|
+
for (const k of ["transformRequest", "transformResponse"]) {
|
|
1961
|
+
if (Array.isArray(out[k])) out[k] = [...out[k]];
|
|
1962
|
+
}
|
|
1963
|
+
return out;
|
|
1964
|
+
}
|
|
1965
|
+
function createInstance(defaults) {
|
|
1966
|
+
const context = new Exios(defaults);
|
|
1967
|
+
const instance = ((configOrUrl, config) => context.request(configOrUrl, config));
|
|
1968
|
+
for (const m of METHODS)
|
|
1969
|
+
instance[m] = context[m].bind(
|
|
1970
|
+
context
|
|
1971
|
+
);
|
|
1972
|
+
Object.defineProperty(instance, "defaults", {
|
|
1973
|
+
get: () => context.defaults,
|
|
1974
|
+
set: (v) => context.defaults = v,
|
|
1975
|
+
enumerable: true
|
|
1976
|
+
});
|
|
1977
|
+
instance.interceptors = context.interceptors;
|
|
1978
|
+
instance.breaker = context.breaker;
|
|
1979
|
+
instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
|
|
1980
|
+
return instance;
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
// src/index.ts
|
|
1984
|
+
registerXhrAdapter();
|
|
1985
|
+
registerFetchAdapter();
|
|
1986
|
+
var statics = {
|
|
1987
|
+
CancelToken,
|
|
1988
|
+
ExiosError,
|
|
1989
|
+
CanceledError,
|
|
1990
|
+
CircuitOpenError,
|
|
1991
|
+
isExiosError,
|
|
1992
|
+
isCancel,
|
|
1993
|
+
mergeConfig,
|
|
1994
|
+
toFormData
|
|
1995
|
+
};
|
|
1996
|
+
var exios = Object.assign(
|
|
1997
|
+
createInstance(createDefaults()),
|
|
1998
|
+
statics
|
|
1999
|
+
);
|
|
2000
|
+
var create = exios.create;
|
|
2001
|
+
var src_default = exios;
|
|
2002
|
+
|
|
2003
|
+
// src/cjs.ts
|
|
2004
|
+
var cjs = src_default;
|
|
2005
|
+
cjs.default = cjs;
|
|
2006
|
+
var cjs_default = cjs;
|
|
2007
|
+
module.exports = module.exports.default;
|