@snail-js/api 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2955 @@
1
+ (function(global2, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.SnailApi = {}));
3
+ })(this, function(exports2) {
4
+ "use strict";var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+
8
+ const apiKey = (apiInstance) => {
9
+ const { version, method, url, params, headers } = apiInstance;
10
+ return `[${method}]${version ? `-v${version}` : ""}-${url}${params ? `-${recordToString(params)}` : ""}${headers ? `-${recordToString(headers)}` : ""}`;
11
+ };
12
+ function recordToString(record) {
13
+ return Object.keys(record).map((key) => {
14
+ return `${key}=${record[key]}`;
15
+ }).sort((a, b) => a.localeCompare(b)).join("&");
16
+ }
17
+ function getResponseDataFromCache(cacheKey) {
18
+ return cacheKey;
19
+ }
20
+ function deepCopy(obj) {
21
+ if (typeof obj !== "object" || obj === null) {
22
+ return obj;
23
+ }
24
+ if (Array.isArray(obj)) {
25
+ return obj.map((item) => deepCopy(item));
26
+ }
27
+ const copy = {};
28
+ for (const key in obj) {
29
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
30
+ copy[key] = deepCopy(obj[key]);
31
+ }
32
+ }
33
+ return copy;
34
+ }
35
+ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
36
+ RequestMethod2["GET"] = "GET";
37
+ RequestMethod2["HEAD"] = "HEAD";
38
+ RequestMethod2["POST"] = "POST";
39
+ RequestMethod2["PUT"] = "PUT";
40
+ RequestMethod2["DELETE"] = "DELETE";
41
+ RequestMethod2["PATCH"] = "PATCH";
42
+ RequestMethod2["OPTIONS"] = "OPTIONS";
43
+ return RequestMethod2;
44
+ })(RequestMethod || {});
45
+ var VersioningType = /* @__PURE__ */ ((VersioningType2) => {
46
+ VersioningType2[VersioningType2["Uri"] = 0] = "Uri";
47
+ VersioningType2[VersioningType2["Header"] = 1] = "Header";
48
+ VersioningType2[VersioningType2["Query"] = 2] = "Query";
49
+ VersioningType2[VersioningType2["Custom"] = 3] = "Custom";
50
+ return VersioningType2;
51
+ })(VersioningType || {});
52
+ var CacheType = /* @__PURE__ */ ((CacheType2) => {
53
+ CacheType2[CacheType2["Memory"] = 0] = "Memory";
54
+ CacheType2[CacheType2["IndexDB"] = 1] = "IndexDB";
55
+ CacheType2[CacheType2["LocalStorage"] = 2] = "LocalStorage";
56
+ return CacheType2;
57
+ })(CacheType || {});
58
+ const versionHandlers = {
59
+ [VersioningType.Uri]: (version, versioning) => {
60
+ const prefix = versioning.prefix || "v";
61
+ return {
62
+ url: `${prefix}${version}`
63
+ };
64
+ },
65
+ [VersioningType.Header]: (version, versioning) => {
66
+ const headers = {
67
+ [versioning.header]: version
68
+ };
69
+ return {
70
+ headers
71
+ };
72
+ },
73
+ [VersioningType.Query]: (version, versioning) => {
74
+ const key = versioning.key || "version";
75
+ const separator = "?";
76
+ return {
77
+ url: `${separator}${key}=${version}`
78
+ };
79
+ },
80
+ [VersioningType.Custom]: (version, versioning) => {
81
+ return versioning.extractor({
82
+ version
83
+ });
84
+ }
85
+ };
86
+ function applyVersioning(version, versioning) {
87
+ const handler = versionHandlers[versioning.type];
88
+ return handler(
89
+ version,
90
+ versioning
91
+ );
92
+ }
93
+ class Api {
94
+ constructor(method, url, context, config) {
95
+ __publicField(this, "baseURL");
96
+ __publicField(this, "url");
97
+ __publicField(this, "data");
98
+ __publicField(this, "params");
99
+ __publicField(this, "headers");
100
+ __publicField(this, "key");
101
+ // public config: ApiConfig<R> | undefined;
102
+ __publicField(this, "method");
103
+ __publicField(this, "hitCache");
104
+ __publicField(this, "context");
105
+ __publicField(this, "version");
106
+ __publicField(this, "versioning");
107
+ __publicField(this, "name");
108
+ __publicField(this, "hitSource");
109
+ __publicField(this, "timeout");
110
+ __publicField(this, "transform");
111
+ __publicField(this, "pipes", []);
112
+ var _a;
113
+ const instance = this;
114
+ instance.name = config == null ? void 0 : config.name;
115
+ instance.name ?? this.context.cacheSource.push(this);
116
+ instance.hitSource = config == null ? void 0 : config.hitSource;
117
+ instance.method = method;
118
+ instance.url = url;
119
+ instance.params = config == null ? void 0 : config.params;
120
+ instance.headers = config == null ? void 0 : config.headers;
121
+ instance.transform = config == null ? void 0 : config.transform;
122
+ instance.context = context;
123
+ instance.version = (config == null ? void 0 : config.version) || ((_a = instance.context.versioning) == null ? void 0 : _a.defaultVersion);
124
+ this.timeout = (config == null ? void 0 : config.timeout) || this.context.options.timeout || 5e3;
125
+ this.handleVersioning();
126
+ this.key = apiKey(this);
127
+ }
128
+ handleVersioning(version) {
129
+ if (!this.context) return;
130
+ const { versioning } = this.context;
131
+ if (versioning) {
132
+ const { url, headers } = applyVersioning(
133
+ version || this.version,
134
+ versioning
135
+ );
136
+ this.versioning = {
137
+ url,
138
+ headers
139
+ };
140
+ }
141
+ return;
142
+ }
143
+ /**
144
+ *
145
+ * @param options 发送配置:子项params,data
146
+ * 泛型<R = any, E = any>R返回数据类型, E返回错误类型(code!=0)
147
+ * @returns
148
+ */
149
+ send(options) {
150
+ this.data = options == null ? void 0 : options.data;
151
+ this.params = options == null ? void 0 : options.params;
152
+ if ((options == null ? void 0 : options.params) || (options == null ? void 0 : options.data)) {
153
+ this.key = apiKey(this);
154
+ }
155
+ const version = (options == null ? void 0 : options.version) || this.version;
156
+ console.log("send version:", version);
157
+ this.handleVersioning(version);
158
+ return new Promise(async (resolve, reject) => {
159
+ var _a, _b, _c;
160
+ const { data, headers } = this.processRequestPipes();
161
+ this.data = data;
162
+ this.headers = headers;
163
+ this.key = apiKey(this);
164
+ const cachedResponse = await this.checkCache(version);
165
+ if (cachedResponse) {
166
+ const versionUrl = ((_a = this.versioning) == null ? void 0 : _a.url) ? (_b = this.versioning) == null ? void 0 : _b.url : "";
167
+ console.warn(
168
+ `请求[${this.context.baseURL}/${versionUrl == "" ? "" : `${versionUrl}/`}${this.url}]命中缓存`
169
+ );
170
+ return resolve({
171
+ error: null,
172
+ data: cachedResponse,
173
+ hitCache: this.hitCache,
174
+ Catch: (handler) => handler()
175
+ });
176
+ }
177
+ try {
178
+ const response = await this.sendRequest();
179
+ const { code, data: data2, message } = response.data;
180
+ if (code !== 0) {
181
+ reject({
182
+ error: new Error(message, { cause: { code, data: data2 } }),
183
+ data: null,
184
+ hitCache: false,
185
+ Catch: (handler) => handler()
186
+ });
187
+ }
188
+ const transformedData = this.transform ? this.transform(data2) : data2;
189
+ (_c = this.context.cacheStorage) == null ? void 0 : _c.set(this.key, transformedData);
190
+ resolve({
191
+ error: null,
192
+ data: transformedData,
193
+ hitCache: false,
194
+ Catch: (handler) => handler()
195
+ });
196
+ this.lapsed(version);
197
+ } catch (error) {
198
+ resolve({
199
+ error,
200
+ data: null,
201
+ hitCache: false,
202
+ Catch: (handler) => handler(error)
203
+ });
204
+ }
205
+ });
206
+ }
207
+ async checkCache(version) {
208
+ if (!this.context.cacheStorage) return null;
209
+ return new Promise(async (resolve) => {
210
+ if (!this.context.cacheStorage) {
211
+ return resolve(null);
212
+ }
213
+ let tempKey;
214
+ if (version) {
215
+ tempKey = apiKey({
216
+ ...this,
217
+ version
218
+ });
219
+ }
220
+ const { error, data } = await this.context.cacheStorage.get(
221
+ tempKey ? tempKey : this.key
222
+ );
223
+ if (error) {
224
+ console.warn(error);
225
+ return resolve(null);
226
+ }
227
+ this.hitCache = true;
228
+ return resolve(data);
229
+ });
230
+ }
231
+ async delCache(version) {
232
+ let tempKey;
233
+ if (version) {
234
+ tempKey = apiKey({
235
+ ...this,
236
+ version
237
+ });
238
+ }
239
+ await this.context.cacheStorage.delete(tempKey ? tempKey : this.key);
240
+ }
241
+ use(pipe) {
242
+ this.pipes.push(pipe);
243
+ }
244
+ processRequestPipes() {
245
+ let requestData = this.data;
246
+ let requestHeaders = this.headers || {};
247
+ if (this.pipes.length > 0) {
248
+ const pipeResult = this.pipes.reduce(
249
+ (result, pipe) => {
250
+ return pipe(result.data, result.headers);
251
+ },
252
+ { data: requestData, headers: requestHeaders }
253
+ );
254
+ requestData = pipeResult.data;
255
+ requestHeaders = pipeResult.headers;
256
+ }
257
+ return { data: requestData, headers: requestHeaders };
258
+ }
259
+ async sendRequest() {
260
+ var _a, _b, _c;
261
+ const headers = {
262
+ ...this.headers,
263
+ ...(_a = this.versioning) == null ? void 0 : _a.headers
264
+ };
265
+ const versionUrl = ((_b = this.versioning) == null ? void 0 : _b.url) ? (_c = this.versioning) == null ? void 0 : _c.url : "";
266
+ return await this.context.axiosInstance.request({
267
+ url: `${versionUrl}/${this.url}`,
268
+ method: this.method,
269
+ data: this.data,
270
+ headers,
271
+ params: this.params,
272
+ timeout: this.timeout
273
+ });
274
+ }
275
+ async lapsed(version) {
276
+ if (!this.hitSource) return;
277
+ if (typeof this.hitSource === "string") {
278
+ const { cacheSource } = this.context;
279
+ const source = cacheSource.find((api) => api.name == this.hitSource);
280
+ source ?? source.delCache(version);
281
+ } else {
282
+ this.hitSource.delCache(version);
283
+ }
284
+ }
285
+ }
286
+ function bind(fn, thisArg) {
287
+ return function wrap() {
288
+ return fn.apply(thisArg, arguments);
289
+ };
290
+ }
291
+ const { toString } = Object.prototype;
292
+ const { getPrototypeOf } = Object;
293
+ const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
294
+ const str = toString.call(thing);
295
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
296
+ })(/* @__PURE__ */ Object.create(null));
297
+ const kindOfTest = (type) => {
298
+ type = type.toLowerCase();
299
+ return (thing) => kindOf(thing) === type;
300
+ };
301
+ const typeOfTest = (type) => (thing) => typeof thing === type;
302
+ const { isArray } = Array;
303
+ const isUndefined = typeOfTest("undefined");
304
+ function isBuffer(val) {
305
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
306
+ }
307
+ const isArrayBuffer = kindOfTest("ArrayBuffer");
308
+ function isArrayBufferView(val) {
309
+ let result;
310
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
311
+ result = ArrayBuffer.isView(val);
312
+ } else {
313
+ result = val && val.buffer && isArrayBuffer(val.buffer);
314
+ }
315
+ return result;
316
+ }
317
+ const isString = typeOfTest("string");
318
+ const isFunction = typeOfTest("function");
319
+ const isNumber = typeOfTest("number");
320
+ const isObject = (thing) => thing !== null && typeof thing === "object";
321
+ const isBoolean = (thing) => thing === true || thing === false;
322
+ const isPlainObject = (val) => {
323
+ if (kindOf(val) !== "object") {
324
+ return false;
325
+ }
326
+ const prototype2 = getPrototypeOf(val);
327
+ return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
328
+ };
329
+ const isDate = kindOfTest("Date");
330
+ const isFile = kindOfTest("File");
331
+ const isBlob = kindOfTest("Blob");
332
+ const isFileList = kindOfTest("FileList");
333
+ const isStream = (val) => isObject(val) && isFunction(val.pipe);
334
+ const isFormData = (thing) => {
335
+ let kind;
336
+ return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
337
+ kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
338
+ };
339
+ const isURLSearchParams = kindOfTest("URLSearchParams");
340
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
341
+ const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
342
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
343
+ if (obj === null || typeof obj === "undefined") {
344
+ return;
345
+ }
346
+ let i;
347
+ let l;
348
+ if (typeof obj !== "object") {
349
+ obj = [obj];
350
+ }
351
+ if (isArray(obj)) {
352
+ for (i = 0, l = obj.length; i < l; i++) {
353
+ fn.call(null, obj[i], i, obj);
354
+ }
355
+ } else {
356
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
357
+ const len = keys.length;
358
+ let key;
359
+ for (i = 0; i < len; i++) {
360
+ key = keys[i];
361
+ fn.call(null, obj[key], key, obj);
362
+ }
363
+ }
364
+ }
365
+ function findKey(obj, key) {
366
+ key = key.toLowerCase();
367
+ const keys = Object.keys(obj);
368
+ let i = keys.length;
369
+ let _key;
370
+ while (i-- > 0) {
371
+ _key = keys[i];
372
+ if (key === _key.toLowerCase()) {
373
+ return _key;
374
+ }
375
+ }
376
+ return null;
377
+ }
378
+ const _global = (() => {
379
+ if (typeof globalThis !== "undefined") return globalThis;
380
+ return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
381
+ })();
382
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
383
+ function merge() {
384
+ const { caseless } = isContextDefined(this) && this || {};
385
+ const result = {};
386
+ const assignValue = (val, key) => {
387
+ const targetKey = caseless && findKey(result, key) || key;
388
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
389
+ result[targetKey] = merge(result[targetKey], val);
390
+ } else if (isPlainObject(val)) {
391
+ result[targetKey] = merge({}, val);
392
+ } else if (isArray(val)) {
393
+ result[targetKey] = val.slice();
394
+ } else {
395
+ result[targetKey] = val;
396
+ }
397
+ };
398
+ for (let i = 0, l = arguments.length; i < l; i++) {
399
+ arguments[i] && forEach(arguments[i], assignValue);
400
+ }
401
+ return result;
402
+ }
403
+ const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
404
+ forEach(b, (val, key) => {
405
+ if (thisArg && isFunction(val)) {
406
+ a[key] = bind(val, thisArg);
407
+ } else {
408
+ a[key] = val;
409
+ }
410
+ }, { allOwnKeys });
411
+ return a;
412
+ };
413
+ const stripBOM = (content) => {
414
+ if (content.charCodeAt(0) === 65279) {
415
+ content = content.slice(1);
416
+ }
417
+ return content;
418
+ };
419
+ const inherits = (constructor, superConstructor, props, descriptors2) => {
420
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
421
+ constructor.prototype.constructor = constructor;
422
+ Object.defineProperty(constructor, "super", {
423
+ value: superConstructor.prototype
424
+ });
425
+ props && Object.assign(constructor.prototype, props);
426
+ };
427
+ const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
428
+ let props;
429
+ let i;
430
+ let prop;
431
+ const merged = {};
432
+ destObj = destObj || {};
433
+ if (sourceObj == null) return destObj;
434
+ do {
435
+ props = Object.getOwnPropertyNames(sourceObj);
436
+ i = props.length;
437
+ while (i-- > 0) {
438
+ prop = props[i];
439
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
440
+ destObj[prop] = sourceObj[prop];
441
+ merged[prop] = true;
442
+ }
443
+ }
444
+ sourceObj = filter !== false && getPrototypeOf(sourceObj);
445
+ } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
446
+ return destObj;
447
+ };
448
+ const endsWith = (str, searchString, position) => {
449
+ str = String(str);
450
+ if (position === void 0 || position > str.length) {
451
+ position = str.length;
452
+ }
453
+ position -= searchString.length;
454
+ const lastIndex = str.indexOf(searchString, position);
455
+ return lastIndex !== -1 && lastIndex === position;
456
+ };
457
+ const toArray = (thing) => {
458
+ if (!thing) return null;
459
+ if (isArray(thing)) return thing;
460
+ let i = thing.length;
461
+ if (!isNumber(i)) return null;
462
+ const arr = new Array(i);
463
+ while (i-- > 0) {
464
+ arr[i] = thing[i];
465
+ }
466
+ return arr;
467
+ };
468
+ const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
469
+ return (thing) => {
470
+ return TypedArray && thing instanceof TypedArray;
471
+ };
472
+ })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
473
+ const forEachEntry = (obj, fn) => {
474
+ const generator = obj && obj[Symbol.iterator];
475
+ const iterator = generator.call(obj);
476
+ let result;
477
+ while ((result = iterator.next()) && !result.done) {
478
+ const pair = result.value;
479
+ fn.call(obj, pair[0], pair[1]);
480
+ }
481
+ };
482
+ const matchAll = (regExp, str) => {
483
+ let matches;
484
+ const arr = [];
485
+ while ((matches = regExp.exec(str)) !== null) {
486
+ arr.push(matches);
487
+ }
488
+ return arr;
489
+ };
490
+ const isHTMLForm = kindOfTest("HTMLFormElement");
491
+ const toCamelCase = (str) => {
492
+ return str.toLowerCase().replace(
493
+ /[-_\s]([a-z\d])(\w*)/g,
494
+ function replacer(m, p1, p2) {
495
+ return p1.toUpperCase() + p2;
496
+ }
497
+ );
498
+ };
499
+ const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
500
+ const isRegExp = kindOfTest("RegExp");
501
+ const reduceDescriptors = (obj, reducer) => {
502
+ const descriptors2 = Object.getOwnPropertyDescriptors(obj);
503
+ const reducedDescriptors = {};
504
+ forEach(descriptors2, (descriptor, name) => {
505
+ let ret;
506
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
507
+ reducedDescriptors[name] = ret || descriptor;
508
+ }
509
+ });
510
+ Object.defineProperties(obj, reducedDescriptors);
511
+ };
512
+ const freezeMethods = (obj) => {
513
+ reduceDescriptors(obj, (descriptor, name) => {
514
+ if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
515
+ return false;
516
+ }
517
+ const value = obj[name];
518
+ if (!isFunction(value)) return;
519
+ descriptor.enumerable = false;
520
+ if ("writable" in descriptor) {
521
+ descriptor.writable = false;
522
+ return;
523
+ }
524
+ if (!descriptor.set) {
525
+ descriptor.set = () => {
526
+ throw Error("Can not rewrite read-only method '" + name + "'");
527
+ };
528
+ }
529
+ });
530
+ };
531
+ const toObjectSet = (arrayOrString, delimiter) => {
532
+ const obj = {};
533
+ const define2 = (arr) => {
534
+ arr.forEach((value) => {
535
+ obj[value] = true;
536
+ });
537
+ };
538
+ isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter));
539
+ return obj;
540
+ };
541
+ const noop = () => {
542
+ };
543
+ const toFiniteNumber = (value, defaultValue) => {
544
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
545
+ };
546
+ const ALPHA = "abcdefghijklmnopqrstuvwxyz";
547
+ const DIGIT = "0123456789";
548
+ const ALPHABET = {
549
+ DIGIT,
550
+ ALPHA,
551
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
552
+ };
553
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
554
+ let str = "";
555
+ const { length } = alphabet;
556
+ while (size--) {
557
+ str += alphabet[Math.random() * length | 0];
558
+ }
559
+ return str;
560
+ };
561
+ function isSpecCompliantForm(thing) {
562
+ return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
563
+ }
564
+ const toJSONObject = (obj) => {
565
+ const stack = new Array(10);
566
+ const visit = (source, i) => {
567
+ if (isObject(source)) {
568
+ if (stack.indexOf(source) >= 0) {
569
+ return;
570
+ }
571
+ if (!("toJSON" in source)) {
572
+ stack[i] = source;
573
+ const target = isArray(source) ? [] : {};
574
+ forEach(source, (value, key) => {
575
+ const reducedValue = visit(value, i + 1);
576
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
577
+ });
578
+ stack[i] = void 0;
579
+ return target;
580
+ }
581
+ }
582
+ return source;
583
+ };
584
+ return visit(obj, 0);
585
+ };
586
+ const isAsyncFn = kindOfTest("AsyncFunction");
587
+ const isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
588
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
589
+ if (setImmediateSupported) {
590
+ return setImmediate;
591
+ }
592
+ return postMessageSupported ? ((token, callbacks) => {
593
+ _global.addEventListener("message", ({ source, data }) => {
594
+ if (source === _global && data === token) {
595
+ callbacks.length && callbacks.shift()();
596
+ }
597
+ }, false);
598
+ return (cb) => {
599
+ callbacks.push(cb);
600
+ _global.postMessage(token, "*");
601
+ };
602
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
603
+ })(
604
+ typeof setImmediate === "function",
605
+ isFunction(_global.postMessage)
606
+ );
607
+ const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
608
+ const utils$1 = {
609
+ isArray,
610
+ isArrayBuffer,
611
+ isBuffer,
612
+ isFormData,
613
+ isArrayBufferView,
614
+ isString,
615
+ isNumber,
616
+ isBoolean,
617
+ isObject,
618
+ isPlainObject,
619
+ isReadableStream,
620
+ isRequest,
621
+ isResponse,
622
+ isHeaders,
623
+ isUndefined,
624
+ isDate,
625
+ isFile,
626
+ isBlob,
627
+ isRegExp,
628
+ isFunction,
629
+ isStream,
630
+ isURLSearchParams,
631
+ isTypedArray,
632
+ isFileList,
633
+ forEach,
634
+ merge,
635
+ extend,
636
+ trim,
637
+ stripBOM,
638
+ inherits,
639
+ toFlatObject,
640
+ kindOf,
641
+ kindOfTest,
642
+ endsWith,
643
+ toArray,
644
+ forEachEntry,
645
+ matchAll,
646
+ isHTMLForm,
647
+ hasOwnProperty,
648
+ hasOwnProp: hasOwnProperty,
649
+ // an alias to avoid ESLint no-prototype-builtins detection
650
+ reduceDescriptors,
651
+ freezeMethods,
652
+ toObjectSet,
653
+ toCamelCase,
654
+ noop,
655
+ toFiniteNumber,
656
+ findKey,
657
+ global: _global,
658
+ isContextDefined,
659
+ ALPHABET,
660
+ generateString,
661
+ isSpecCompliantForm,
662
+ toJSONObject,
663
+ isAsyncFn,
664
+ isThenable,
665
+ setImmediate: _setImmediate,
666
+ asap
667
+ };
668
+ function AxiosError(message, code, config, request, response) {
669
+ Error.call(this);
670
+ if (Error.captureStackTrace) {
671
+ Error.captureStackTrace(this, this.constructor);
672
+ } else {
673
+ this.stack = new Error().stack;
674
+ }
675
+ this.message = message;
676
+ this.name = "AxiosError";
677
+ code && (this.code = code);
678
+ config && (this.config = config);
679
+ request && (this.request = request);
680
+ if (response) {
681
+ this.response = response;
682
+ this.status = response.status ? response.status : null;
683
+ }
684
+ }
685
+ utils$1.inherits(AxiosError, Error, {
686
+ toJSON: function toJSON() {
687
+ return {
688
+ // Standard
689
+ message: this.message,
690
+ name: this.name,
691
+ // Microsoft
692
+ description: this.description,
693
+ number: this.number,
694
+ // Mozilla
695
+ fileName: this.fileName,
696
+ lineNumber: this.lineNumber,
697
+ columnNumber: this.columnNumber,
698
+ stack: this.stack,
699
+ // Axios
700
+ config: utils$1.toJSONObject(this.config),
701
+ code: this.code,
702
+ status: this.status
703
+ };
704
+ }
705
+ });
706
+ const prototype$1 = AxiosError.prototype;
707
+ const descriptors = {};
708
+ [
709
+ "ERR_BAD_OPTION_VALUE",
710
+ "ERR_BAD_OPTION",
711
+ "ECONNABORTED",
712
+ "ETIMEDOUT",
713
+ "ERR_NETWORK",
714
+ "ERR_FR_TOO_MANY_REDIRECTS",
715
+ "ERR_DEPRECATED",
716
+ "ERR_BAD_RESPONSE",
717
+ "ERR_BAD_REQUEST",
718
+ "ERR_CANCELED",
719
+ "ERR_NOT_SUPPORT",
720
+ "ERR_INVALID_URL"
721
+ // eslint-disable-next-line func-names
722
+ ].forEach((code) => {
723
+ descriptors[code] = { value: code };
724
+ });
725
+ Object.defineProperties(AxiosError, descriptors);
726
+ Object.defineProperty(prototype$1, "isAxiosError", { value: true });
727
+ AxiosError.from = (error, code, config, request, response, customProps) => {
728
+ const axiosError = Object.create(prototype$1);
729
+ utils$1.toFlatObject(error, axiosError, function filter(obj) {
730
+ return obj !== Error.prototype;
731
+ }, (prop) => {
732
+ return prop !== "isAxiosError";
733
+ });
734
+ AxiosError.call(axiosError, error.message, code, config, request, response);
735
+ axiosError.cause = error;
736
+ axiosError.name = error.name;
737
+ customProps && Object.assign(axiosError, customProps);
738
+ return axiosError;
739
+ };
740
+ const httpAdapter = null;
741
+ function isVisitable(thing) {
742
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
743
+ }
744
+ function removeBrackets(key) {
745
+ return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
746
+ }
747
+ function renderKey(path, key, dots) {
748
+ if (!path) return key;
749
+ return path.concat(key).map(function each(token, i) {
750
+ token = removeBrackets(token);
751
+ return !dots && i ? "[" + token + "]" : token;
752
+ }).join(dots ? "." : "");
753
+ }
754
+ function isFlatArray(arr) {
755
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
756
+ }
757
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
758
+ return /^is[A-Z]/.test(prop);
759
+ });
760
+ function toFormData(obj, formData, options) {
761
+ if (!utils$1.isObject(obj)) {
762
+ throw new TypeError("target must be an object");
763
+ }
764
+ formData = formData || new FormData();
765
+ options = utils$1.toFlatObject(options, {
766
+ metaTokens: true,
767
+ dots: false,
768
+ indexes: false
769
+ }, false, function defined(option, source) {
770
+ return !utils$1.isUndefined(source[option]);
771
+ });
772
+ const metaTokens = options.metaTokens;
773
+ const visitor = options.visitor || defaultVisitor;
774
+ const dots = options.dots;
775
+ const indexes = options.indexes;
776
+ const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
777
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
778
+ if (!utils$1.isFunction(visitor)) {
779
+ throw new TypeError("visitor must be a function");
780
+ }
781
+ function convertValue(value) {
782
+ if (value === null) return "";
783
+ if (utils$1.isDate(value)) {
784
+ return value.toISOString();
785
+ }
786
+ if (!useBlob && utils$1.isBlob(value)) {
787
+ throw new AxiosError("Blob is not supported. Use a Buffer instead.");
788
+ }
789
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
790
+ return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
791
+ }
792
+ return value;
793
+ }
794
+ function defaultVisitor(value, key, path) {
795
+ let arr = value;
796
+ if (value && !path && typeof value === "object") {
797
+ if (utils$1.endsWith(key, "{}")) {
798
+ key = metaTokens ? key : key.slice(0, -2);
799
+ value = JSON.stringify(value);
800
+ } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
801
+ key = removeBrackets(key);
802
+ arr.forEach(function each(el, index) {
803
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
804
+ // eslint-disable-next-line no-nested-ternary
805
+ indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
806
+ convertValue(el)
807
+ );
808
+ });
809
+ return false;
810
+ }
811
+ }
812
+ if (isVisitable(value)) {
813
+ return true;
814
+ }
815
+ formData.append(renderKey(path, key, dots), convertValue(value));
816
+ return false;
817
+ }
818
+ const stack = [];
819
+ const exposedHelpers = Object.assign(predicates, {
820
+ defaultVisitor,
821
+ convertValue,
822
+ isVisitable
823
+ });
824
+ function build(value, path) {
825
+ if (utils$1.isUndefined(value)) return;
826
+ if (stack.indexOf(value) !== -1) {
827
+ throw Error("Circular reference detected in " + path.join("."));
828
+ }
829
+ stack.push(value);
830
+ utils$1.forEach(value, function each(el, key) {
831
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
832
+ formData,
833
+ el,
834
+ utils$1.isString(key) ? key.trim() : key,
835
+ path,
836
+ exposedHelpers
837
+ );
838
+ if (result === true) {
839
+ build(el, path ? path.concat(key) : [key]);
840
+ }
841
+ });
842
+ stack.pop();
843
+ }
844
+ if (!utils$1.isObject(obj)) {
845
+ throw new TypeError("data must be an object");
846
+ }
847
+ build(obj);
848
+ return formData;
849
+ }
850
+ function encode$1(str) {
851
+ const charMap = {
852
+ "!": "%21",
853
+ "'": "%27",
854
+ "(": "%28",
855
+ ")": "%29",
856
+ "~": "%7E",
857
+ "%20": "+",
858
+ "%00": "\0"
859
+ };
860
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
861
+ return charMap[match];
862
+ });
863
+ }
864
+ function AxiosURLSearchParams(params, options) {
865
+ this._pairs = [];
866
+ params && toFormData(params, this, options);
867
+ }
868
+ const prototype = AxiosURLSearchParams.prototype;
869
+ prototype.append = function append(name, value) {
870
+ this._pairs.push([name, value]);
871
+ };
872
+ prototype.toString = function toString2(encoder) {
873
+ const _encode = encoder ? function(value) {
874
+ return encoder.call(this, value, encode$1);
875
+ } : encode$1;
876
+ return this._pairs.map(function each(pair) {
877
+ return _encode(pair[0]) + "=" + _encode(pair[1]);
878
+ }, "").join("&");
879
+ };
880
+ function encode(val) {
881
+ return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
882
+ }
883
+ function buildURL(url, params, options) {
884
+ if (!params) {
885
+ return url;
886
+ }
887
+ const _encode = options && options.encode || encode;
888
+ if (utils$1.isFunction(options)) {
889
+ options = {
890
+ serialize: options
891
+ };
892
+ }
893
+ const serializeFn = options && options.serialize;
894
+ let serializedParams;
895
+ if (serializeFn) {
896
+ serializedParams = serializeFn(params, options);
897
+ } else {
898
+ serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode);
899
+ }
900
+ if (serializedParams) {
901
+ const hashmarkIndex = url.indexOf("#");
902
+ if (hashmarkIndex !== -1) {
903
+ url = url.slice(0, hashmarkIndex);
904
+ }
905
+ url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
906
+ }
907
+ return url;
908
+ }
909
+ class InterceptorManager {
910
+ constructor() {
911
+ this.handlers = [];
912
+ }
913
+ /**
914
+ * Add a new interceptor to the stack
915
+ *
916
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
917
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
918
+ *
919
+ * @return {Number} An ID used to remove interceptor later
920
+ */
921
+ use(fulfilled, rejected, options) {
922
+ this.handlers.push({
923
+ fulfilled,
924
+ rejected,
925
+ synchronous: options ? options.synchronous : false,
926
+ runWhen: options ? options.runWhen : null
927
+ });
928
+ return this.handlers.length - 1;
929
+ }
930
+ /**
931
+ * Remove an interceptor from the stack
932
+ *
933
+ * @param {Number} id The ID that was returned by `use`
934
+ *
935
+ * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
936
+ */
937
+ eject(id) {
938
+ if (this.handlers[id]) {
939
+ this.handlers[id] = null;
940
+ }
941
+ }
942
+ /**
943
+ * Clear all interceptors from the stack
944
+ *
945
+ * @returns {void}
946
+ */
947
+ clear() {
948
+ if (this.handlers) {
949
+ this.handlers = [];
950
+ }
951
+ }
952
+ /**
953
+ * Iterate over all the registered interceptors
954
+ *
955
+ * This method is particularly useful for skipping over any
956
+ * interceptors that may have become `null` calling `eject`.
957
+ *
958
+ * @param {Function} fn The function to call for each interceptor
959
+ *
960
+ * @returns {void}
961
+ */
962
+ forEach(fn) {
963
+ utils$1.forEach(this.handlers, function forEachHandler(h) {
964
+ if (h !== null) {
965
+ fn(h);
966
+ }
967
+ });
968
+ }
969
+ }
970
+ const transitionalDefaults = {
971
+ silentJSONParsing: true,
972
+ forcedJSONParsing: true,
973
+ clarifyTimeoutError: false
974
+ };
975
+ const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
976
+ const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
977
+ const Blob$1 = typeof Blob !== "undefined" ? Blob : null;
978
+ const platform$1 = {
979
+ isBrowser: true,
980
+ classes: {
981
+ URLSearchParams: URLSearchParams$1,
982
+ FormData: FormData$1,
983
+ Blob: Blob$1
984
+ },
985
+ protocols: ["http", "https", "file", "blob", "url", "data"]
986
+ };
987
+ const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
988
+ const _navigator = typeof navigator === "object" && navigator || void 0;
989
+ const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
990
+ const hasStandardBrowserWebWorkerEnv = (() => {
991
+ return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
992
+ self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
993
+ })();
994
+ const origin = hasBrowserEnv && window.location.href || "http://localhost";
995
+ const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
996
+ __proto__: null,
997
+ hasBrowserEnv,
998
+ hasStandardBrowserEnv,
999
+ hasStandardBrowserWebWorkerEnv,
1000
+ navigator: _navigator,
1001
+ origin
1002
+ }, Symbol.toStringTag, { value: "Module" }));
1003
+ const platform = {
1004
+ ...utils,
1005
+ ...platform$1
1006
+ };
1007
+ function toURLEncodedForm(data, options) {
1008
+ return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1009
+ visitor: function(value, key, path, helpers) {
1010
+ if (platform.isNode && utils$1.isBuffer(value)) {
1011
+ this.append(key, value.toString("base64"));
1012
+ return false;
1013
+ }
1014
+ return helpers.defaultVisitor.apply(this, arguments);
1015
+ }
1016
+ }, options));
1017
+ }
1018
+ function parsePropPath(name) {
1019
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
1020
+ return match[0] === "[]" ? "" : match[1] || match[0];
1021
+ });
1022
+ }
1023
+ function arrayToObject(arr) {
1024
+ const obj = {};
1025
+ const keys = Object.keys(arr);
1026
+ let i;
1027
+ const len = keys.length;
1028
+ let key;
1029
+ for (i = 0; i < len; i++) {
1030
+ key = keys[i];
1031
+ obj[key] = arr[key];
1032
+ }
1033
+ return obj;
1034
+ }
1035
+ function formDataToJSON(formData) {
1036
+ function buildPath(path, value, target, index) {
1037
+ let name = path[index++];
1038
+ if (name === "__proto__") return true;
1039
+ const isNumericKey = Number.isFinite(+name);
1040
+ const isLast = index >= path.length;
1041
+ name = !name && utils$1.isArray(target) ? target.length : name;
1042
+ if (isLast) {
1043
+ if (utils$1.hasOwnProp(target, name)) {
1044
+ target[name] = [target[name], value];
1045
+ } else {
1046
+ target[name] = value;
1047
+ }
1048
+ return !isNumericKey;
1049
+ }
1050
+ if (!target[name] || !utils$1.isObject(target[name])) {
1051
+ target[name] = [];
1052
+ }
1053
+ const result = buildPath(path, value, target[name], index);
1054
+ if (result && utils$1.isArray(target[name])) {
1055
+ target[name] = arrayToObject(target[name]);
1056
+ }
1057
+ return !isNumericKey;
1058
+ }
1059
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1060
+ const obj = {};
1061
+ utils$1.forEachEntry(formData, (name, value) => {
1062
+ buildPath(parsePropPath(name), value, obj, 0);
1063
+ });
1064
+ return obj;
1065
+ }
1066
+ return null;
1067
+ }
1068
+ function stringifySafely(rawValue, parser, encoder) {
1069
+ if (utils$1.isString(rawValue)) {
1070
+ try {
1071
+ (parser || JSON.parse)(rawValue);
1072
+ return utils$1.trim(rawValue);
1073
+ } catch (e) {
1074
+ if (e.name !== "SyntaxError") {
1075
+ throw e;
1076
+ }
1077
+ }
1078
+ }
1079
+ return (0, JSON.stringify)(rawValue);
1080
+ }
1081
+ const defaults = {
1082
+ transitional: transitionalDefaults,
1083
+ adapter: ["xhr", "http", "fetch"],
1084
+ transformRequest: [function transformRequest(data, headers) {
1085
+ const contentType = headers.getContentType() || "";
1086
+ const hasJSONContentType = contentType.indexOf("application/json") > -1;
1087
+ const isObjectPayload = utils$1.isObject(data);
1088
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1089
+ data = new FormData(data);
1090
+ }
1091
+ const isFormData2 = utils$1.isFormData(data);
1092
+ if (isFormData2) {
1093
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1094
+ }
1095
+ if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
1096
+ return data;
1097
+ }
1098
+ if (utils$1.isArrayBufferView(data)) {
1099
+ return data.buffer;
1100
+ }
1101
+ if (utils$1.isURLSearchParams(data)) {
1102
+ headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
1103
+ return data.toString();
1104
+ }
1105
+ let isFileList2;
1106
+ if (isObjectPayload) {
1107
+ if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
1108
+ return toURLEncodedForm(data, this.formSerializer).toString();
1109
+ }
1110
+ if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
1111
+ const _FormData = this.env && this.env.FormData;
1112
+ return toFormData(
1113
+ isFileList2 ? { "files[]": data } : data,
1114
+ _FormData && new _FormData(),
1115
+ this.formSerializer
1116
+ );
1117
+ }
1118
+ }
1119
+ if (isObjectPayload || hasJSONContentType) {
1120
+ headers.setContentType("application/json", false);
1121
+ return stringifySafely(data);
1122
+ }
1123
+ return data;
1124
+ }],
1125
+ transformResponse: [function transformResponse(data) {
1126
+ const transitional = this.transitional || defaults.transitional;
1127
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1128
+ const JSONRequested = this.responseType === "json";
1129
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1130
+ return data;
1131
+ }
1132
+ if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
1133
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
1134
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1135
+ try {
1136
+ return JSON.parse(data);
1137
+ } catch (e) {
1138
+ if (strictJSONParsing) {
1139
+ if (e.name === "SyntaxError") {
1140
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
1141
+ }
1142
+ throw e;
1143
+ }
1144
+ }
1145
+ }
1146
+ return data;
1147
+ }],
1148
+ /**
1149
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1150
+ * timeout is not created.
1151
+ */
1152
+ timeout: 0,
1153
+ xsrfCookieName: "XSRF-TOKEN",
1154
+ xsrfHeaderName: "X-XSRF-TOKEN",
1155
+ maxContentLength: -1,
1156
+ maxBodyLength: -1,
1157
+ env: {
1158
+ FormData: platform.classes.FormData,
1159
+ Blob: platform.classes.Blob
1160
+ },
1161
+ validateStatus: function validateStatus(status) {
1162
+ return status >= 200 && status < 300;
1163
+ },
1164
+ headers: {
1165
+ common: {
1166
+ "Accept": "application/json, text/plain, */*",
1167
+ "Content-Type": void 0
1168
+ }
1169
+ }
1170
+ };
1171
+ utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
1172
+ defaults.headers[method] = {};
1173
+ });
1174
+ const ignoreDuplicateOf = utils$1.toObjectSet([
1175
+ "age",
1176
+ "authorization",
1177
+ "content-length",
1178
+ "content-type",
1179
+ "etag",
1180
+ "expires",
1181
+ "from",
1182
+ "host",
1183
+ "if-modified-since",
1184
+ "if-unmodified-since",
1185
+ "last-modified",
1186
+ "location",
1187
+ "max-forwards",
1188
+ "proxy-authorization",
1189
+ "referer",
1190
+ "retry-after",
1191
+ "user-agent"
1192
+ ]);
1193
+ const parseHeaders = (rawHeaders) => {
1194
+ const parsed = {};
1195
+ let key;
1196
+ let val;
1197
+ let i;
1198
+ rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1199
+ i = line.indexOf(":");
1200
+ key = line.substring(0, i).trim().toLowerCase();
1201
+ val = line.substring(i + 1).trim();
1202
+ if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1203
+ return;
1204
+ }
1205
+ if (key === "set-cookie") {
1206
+ if (parsed[key]) {
1207
+ parsed[key].push(val);
1208
+ } else {
1209
+ parsed[key] = [val];
1210
+ }
1211
+ } else {
1212
+ parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1213
+ }
1214
+ });
1215
+ return parsed;
1216
+ };
1217
+ const $internals = Symbol("internals");
1218
+ function normalizeHeader(header) {
1219
+ return header && String(header).trim().toLowerCase();
1220
+ }
1221
+ function normalizeValue(value) {
1222
+ if (value === false || value == null) {
1223
+ return value;
1224
+ }
1225
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1226
+ }
1227
+ function parseTokens(str) {
1228
+ const tokens = /* @__PURE__ */ Object.create(null);
1229
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1230
+ let match;
1231
+ while (match = tokensRE.exec(str)) {
1232
+ tokens[match[1]] = match[2];
1233
+ }
1234
+ return tokens;
1235
+ }
1236
+ const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1237
+ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1238
+ if (utils$1.isFunction(filter)) {
1239
+ return filter.call(this, value, header);
1240
+ }
1241
+ if (isHeaderNameFilter) {
1242
+ value = header;
1243
+ }
1244
+ if (!utils$1.isString(value)) return;
1245
+ if (utils$1.isString(filter)) {
1246
+ return value.indexOf(filter) !== -1;
1247
+ }
1248
+ if (utils$1.isRegExp(filter)) {
1249
+ return filter.test(value);
1250
+ }
1251
+ }
1252
+ function formatHeader(header) {
1253
+ return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1254
+ return char.toUpperCase() + str;
1255
+ });
1256
+ }
1257
+ function buildAccessors(obj, header) {
1258
+ const accessorName = utils$1.toCamelCase(" " + header);
1259
+ ["get", "set", "has"].forEach((methodName) => {
1260
+ Object.defineProperty(obj, methodName + accessorName, {
1261
+ value: function(arg1, arg2, arg3) {
1262
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1263
+ },
1264
+ configurable: true
1265
+ });
1266
+ });
1267
+ }
1268
+ class AxiosHeaders {
1269
+ constructor(headers) {
1270
+ headers && this.set(headers);
1271
+ }
1272
+ set(header, valueOrRewrite, rewrite) {
1273
+ const self2 = this;
1274
+ function setHeader(_value, _header, _rewrite) {
1275
+ const lHeader = normalizeHeader(_header);
1276
+ if (!lHeader) {
1277
+ throw new Error("header name must be a non-empty string");
1278
+ }
1279
+ const key = utils$1.findKey(self2, lHeader);
1280
+ if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1281
+ self2[key || _header] = normalizeValue(_value);
1282
+ }
1283
+ }
1284
+ const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1285
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1286
+ setHeaders(header, valueOrRewrite);
1287
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1288
+ setHeaders(parseHeaders(header), valueOrRewrite);
1289
+ } else if (utils$1.isHeaders(header)) {
1290
+ for (const [key, value] of header.entries()) {
1291
+ setHeader(value, key, rewrite);
1292
+ }
1293
+ } else {
1294
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1295
+ }
1296
+ return this;
1297
+ }
1298
+ get(header, parser) {
1299
+ header = normalizeHeader(header);
1300
+ if (header) {
1301
+ const key = utils$1.findKey(this, header);
1302
+ if (key) {
1303
+ const value = this[key];
1304
+ if (!parser) {
1305
+ return value;
1306
+ }
1307
+ if (parser === true) {
1308
+ return parseTokens(value);
1309
+ }
1310
+ if (utils$1.isFunction(parser)) {
1311
+ return parser.call(this, value, key);
1312
+ }
1313
+ if (utils$1.isRegExp(parser)) {
1314
+ return parser.exec(value);
1315
+ }
1316
+ throw new TypeError("parser must be boolean|regexp|function");
1317
+ }
1318
+ }
1319
+ }
1320
+ has(header, matcher) {
1321
+ header = normalizeHeader(header);
1322
+ if (header) {
1323
+ const key = utils$1.findKey(this, header);
1324
+ return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1325
+ }
1326
+ return false;
1327
+ }
1328
+ delete(header, matcher) {
1329
+ const self2 = this;
1330
+ let deleted = false;
1331
+ function deleteHeader(_header) {
1332
+ _header = normalizeHeader(_header);
1333
+ if (_header) {
1334
+ const key = utils$1.findKey(self2, _header);
1335
+ if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1336
+ delete self2[key];
1337
+ deleted = true;
1338
+ }
1339
+ }
1340
+ }
1341
+ if (utils$1.isArray(header)) {
1342
+ header.forEach(deleteHeader);
1343
+ } else {
1344
+ deleteHeader(header);
1345
+ }
1346
+ return deleted;
1347
+ }
1348
+ clear(matcher) {
1349
+ const keys = Object.keys(this);
1350
+ let i = keys.length;
1351
+ let deleted = false;
1352
+ while (i--) {
1353
+ const key = keys[i];
1354
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1355
+ delete this[key];
1356
+ deleted = true;
1357
+ }
1358
+ }
1359
+ return deleted;
1360
+ }
1361
+ normalize(format) {
1362
+ const self2 = this;
1363
+ const headers = {};
1364
+ utils$1.forEach(this, (value, header) => {
1365
+ const key = utils$1.findKey(headers, header);
1366
+ if (key) {
1367
+ self2[key] = normalizeValue(value);
1368
+ delete self2[header];
1369
+ return;
1370
+ }
1371
+ const normalized = format ? formatHeader(header) : String(header).trim();
1372
+ if (normalized !== header) {
1373
+ delete self2[header];
1374
+ }
1375
+ self2[normalized] = normalizeValue(value);
1376
+ headers[normalized] = true;
1377
+ });
1378
+ return this;
1379
+ }
1380
+ concat(...targets) {
1381
+ return this.constructor.concat(this, ...targets);
1382
+ }
1383
+ toJSON(asStrings) {
1384
+ const obj = /* @__PURE__ */ Object.create(null);
1385
+ utils$1.forEach(this, (value, header) => {
1386
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
1387
+ });
1388
+ return obj;
1389
+ }
1390
+ [Symbol.iterator]() {
1391
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1392
+ }
1393
+ toString() {
1394
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
1395
+ }
1396
+ get [Symbol.toStringTag]() {
1397
+ return "AxiosHeaders";
1398
+ }
1399
+ static from(thing) {
1400
+ return thing instanceof this ? thing : new this(thing);
1401
+ }
1402
+ static concat(first, ...targets) {
1403
+ const computed = new this(first);
1404
+ targets.forEach((target) => computed.set(target));
1405
+ return computed;
1406
+ }
1407
+ static accessor(header) {
1408
+ const internals = this[$internals] = this[$internals] = {
1409
+ accessors: {}
1410
+ };
1411
+ const accessors = internals.accessors;
1412
+ const prototype2 = this.prototype;
1413
+ function defineAccessor(_header) {
1414
+ const lHeader = normalizeHeader(_header);
1415
+ if (!accessors[lHeader]) {
1416
+ buildAccessors(prototype2, _header);
1417
+ accessors[lHeader] = true;
1418
+ }
1419
+ }
1420
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1421
+ return this;
1422
+ }
1423
+ }
1424
+ AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
1425
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
1426
+ let mapped = key[0].toUpperCase() + key.slice(1);
1427
+ return {
1428
+ get: () => value,
1429
+ set(headerValue) {
1430
+ this[mapped] = headerValue;
1431
+ }
1432
+ };
1433
+ });
1434
+ utils$1.freezeMethods(AxiosHeaders);
1435
+ function transformData(fns, response) {
1436
+ const config = this || defaults;
1437
+ const context = response || config;
1438
+ const headers = AxiosHeaders.from(context.headers);
1439
+ let data = context.data;
1440
+ utils$1.forEach(fns, function transform(fn) {
1441
+ data = fn.call(config, data, headers.normalize(), response ? response.status : void 0);
1442
+ });
1443
+ headers.normalize();
1444
+ return data;
1445
+ }
1446
+ function isCancel(value) {
1447
+ return !!(value && value.__CANCEL__);
1448
+ }
1449
+ function CanceledError(message, config, request) {
1450
+ AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request);
1451
+ this.name = "CanceledError";
1452
+ }
1453
+ utils$1.inherits(CanceledError, AxiosError, {
1454
+ __CANCEL__: true
1455
+ });
1456
+ function settle(resolve, reject, response) {
1457
+ const validateStatus = response.config.validateStatus;
1458
+ if (!response.status || !validateStatus || validateStatus(response.status)) {
1459
+ resolve(response);
1460
+ } else {
1461
+ reject(new AxiosError(
1462
+ "Request failed with status code " + response.status,
1463
+ [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1464
+ response.config,
1465
+ response.request,
1466
+ response
1467
+ ));
1468
+ }
1469
+ }
1470
+ function parseProtocol(url) {
1471
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1472
+ return match && match[1] || "";
1473
+ }
1474
+ function speedometer(samplesCount, min) {
1475
+ samplesCount = samplesCount || 10;
1476
+ const bytes = new Array(samplesCount);
1477
+ const timestamps = new Array(samplesCount);
1478
+ let head = 0;
1479
+ let tail = 0;
1480
+ let firstSampleTS;
1481
+ min = min !== void 0 ? min : 1e3;
1482
+ return function push(chunkLength) {
1483
+ const now = Date.now();
1484
+ const startedAt = timestamps[tail];
1485
+ if (!firstSampleTS) {
1486
+ firstSampleTS = now;
1487
+ }
1488
+ bytes[head] = chunkLength;
1489
+ timestamps[head] = now;
1490
+ let i = tail;
1491
+ let bytesCount = 0;
1492
+ while (i !== head) {
1493
+ bytesCount += bytes[i++];
1494
+ i = i % samplesCount;
1495
+ }
1496
+ head = (head + 1) % samplesCount;
1497
+ if (head === tail) {
1498
+ tail = (tail + 1) % samplesCount;
1499
+ }
1500
+ if (now - firstSampleTS < min) {
1501
+ return;
1502
+ }
1503
+ const passed = startedAt && now - startedAt;
1504
+ return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
1505
+ };
1506
+ }
1507
+ function throttle(fn, freq) {
1508
+ let timestamp = 0;
1509
+ let threshold = 1e3 / freq;
1510
+ let lastArgs;
1511
+ let timer;
1512
+ const invoke = (args, now = Date.now()) => {
1513
+ timestamp = now;
1514
+ lastArgs = null;
1515
+ if (timer) {
1516
+ clearTimeout(timer);
1517
+ timer = null;
1518
+ }
1519
+ fn.apply(null, args);
1520
+ };
1521
+ const throttled = (...args) => {
1522
+ const now = Date.now();
1523
+ const passed = now - timestamp;
1524
+ if (passed >= threshold) {
1525
+ invoke(args, now);
1526
+ } else {
1527
+ lastArgs = args;
1528
+ if (!timer) {
1529
+ timer = setTimeout(() => {
1530
+ timer = null;
1531
+ invoke(lastArgs);
1532
+ }, threshold - passed);
1533
+ }
1534
+ }
1535
+ };
1536
+ const flush = () => lastArgs && invoke(lastArgs);
1537
+ return [throttled, flush];
1538
+ }
1539
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1540
+ let bytesNotified = 0;
1541
+ const _speedometer = speedometer(50, 250);
1542
+ return throttle((e) => {
1543
+ const loaded = e.loaded;
1544
+ const total = e.lengthComputable ? e.total : void 0;
1545
+ const progressBytes = loaded - bytesNotified;
1546
+ const rate = _speedometer(progressBytes);
1547
+ const inRange = loaded <= total;
1548
+ bytesNotified = loaded;
1549
+ const data = {
1550
+ loaded,
1551
+ total,
1552
+ progress: total ? loaded / total : void 0,
1553
+ bytes: progressBytes,
1554
+ rate: rate ? rate : void 0,
1555
+ estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
1556
+ event: e,
1557
+ lengthComputable: total != null,
1558
+ [isDownloadStream ? "download" : "upload"]: true
1559
+ };
1560
+ listener(data);
1561
+ }, freq);
1562
+ };
1563
+ const progressEventDecorator = (total, throttled) => {
1564
+ const lengthComputable = total != null;
1565
+ return [(loaded) => throttled[0]({
1566
+ lengthComputable,
1567
+ total,
1568
+ loaded
1569
+ }), throttled[1]];
1570
+ };
1571
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
1572
+ const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
1573
+ url = new URL(url, platform.origin);
1574
+ return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
1575
+ })(
1576
+ new URL(platform.origin),
1577
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
1578
+ ) : () => true;
1579
+ const cookies = platform.hasStandardBrowserEnv ? (
1580
+ // Standard browser envs support document.cookie
1581
+ {
1582
+ write(name, value, expires, path, domain, secure) {
1583
+ const cookie = [name + "=" + encodeURIComponent(value)];
1584
+ utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
1585
+ utils$1.isString(path) && cookie.push("path=" + path);
1586
+ utils$1.isString(domain) && cookie.push("domain=" + domain);
1587
+ secure === true && cookie.push("secure");
1588
+ document.cookie = cookie.join("; ");
1589
+ },
1590
+ read(name) {
1591
+ const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
1592
+ return match ? decodeURIComponent(match[3]) : null;
1593
+ },
1594
+ remove(name) {
1595
+ this.write(name, "", Date.now() - 864e5);
1596
+ }
1597
+ }
1598
+ ) : (
1599
+ // Non-standard browser env (web workers, react-native) lack needed support.
1600
+ {
1601
+ write() {
1602
+ },
1603
+ read() {
1604
+ return null;
1605
+ },
1606
+ remove() {
1607
+ }
1608
+ }
1609
+ );
1610
+ function isAbsoluteURL(url) {
1611
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1612
+ }
1613
+ function combineURLs(baseURL, relativeURL) {
1614
+ return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
1615
+ }
1616
+ function buildFullPath(baseURL, requestedURL) {
1617
+ if (baseURL && !isAbsoluteURL(requestedURL)) {
1618
+ return combineURLs(baseURL, requestedURL);
1619
+ }
1620
+ return requestedURL;
1621
+ }
1622
+ const headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;
1623
+ function mergeConfig(config1, config2) {
1624
+ config2 = config2 || {};
1625
+ const config = {};
1626
+ function getMergedValue(target, source, prop, caseless) {
1627
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
1628
+ return utils$1.merge.call({ caseless }, target, source);
1629
+ } else if (utils$1.isPlainObject(source)) {
1630
+ return utils$1.merge({}, source);
1631
+ } else if (utils$1.isArray(source)) {
1632
+ return source.slice();
1633
+ }
1634
+ return source;
1635
+ }
1636
+ function mergeDeepProperties(a, b, prop, caseless) {
1637
+ if (!utils$1.isUndefined(b)) {
1638
+ return getMergedValue(a, b, prop, caseless);
1639
+ } else if (!utils$1.isUndefined(a)) {
1640
+ return getMergedValue(void 0, a, prop, caseless);
1641
+ }
1642
+ }
1643
+ function valueFromConfig2(a, b) {
1644
+ if (!utils$1.isUndefined(b)) {
1645
+ return getMergedValue(void 0, b);
1646
+ }
1647
+ }
1648
+ function defaultToConfig2(a, b) {
1649
+ if (!utils$1.isUndefined(b)) {
1650
+ return getMergedValue(void 0, b);
1651
+ } else if (!utils$1.isUndefined(a)) {
1652
+ return getMergedValue(void 0, a);
1653
+ }
1654
+ }
1655
+ function mergeDirectKeys(a, b, prop) {
1656
+ if (prop in config2) {
1657
+ return getMergedValue(a, b);
1658
+ } else if (prop in config1) {
1659
+ return getMergedValue(void 0, a);
1660
+ }
1661
+ }
1662
+ const mergeMap = {
1663
+ url: valueFromConfig2,
1664
+ method: valueFromConfig2,
1665
+ data: valueFromConfig2,
1666
+ baseURL: defaultToConfig2,
1667
+ transformRequest: defaultToConfig2,
1668
+ transformResponse: defaultToConfig2,
1669
+ paramsSerializer: defaultToConfig2,
1670
+ timeout: defaultToConfig2,
1671
+ timeoutMessage: defaultToConfig2,
1672
+ withCredentials: defaultToConfig2,
1673
+ withXSRFToken: defaultToConfig2,
1674
+ adapter: defaultToConfig2,
1675
+ responseType: defaultToConfig2,
1676
+ xsrfCookieName: defaultToConfig2,
1677
+ xsrfHeaderName: defaultToConfig2,
1678
+ onUploadProgress: defaultToConfig2,
1679
+ onDownloadProgress: defaultToConfig2,
1680
+ decompress: defaultToConfig2,
1681
+ maxContentLength: defaultToConfig2,
1682
+ maxBodyLength: defaultToConfig2,
1683
+ beforeRedirect: defaultToConfig2,
1684
+ transport: defaultToConfig2,
1685
+ httpAgent: defaultToConfig2,
1686
+ httpsAgent: defaultToConfig2,
1687
+ cancelToken: defaultToConfig2,
1688
+ socketPath: defaultToConfig2,
1689
+ responseEncoding: defaultToConfig2,
1690
+ validateStatus: mergeDirectKeys,
1691
+ headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
1692
+ };
1693
+ utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
1694
+ const merge2 = mergeMap[prop] || mergeDeepProperties;
1695
+ const configValue = merge2(config1[prop], config2[prop], prop);
1696
+ utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
1697
+ });
1698
+ return config;
1699
+ }
1700
+ const resolveConfig = (config) => {
1701
+ const newConfig = mergeConfig({}, config);
1702
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1703
+ newConfig.headers = headers = AxiosHeaders.from(headers);
1704
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
1705
+ if (auth) {
1706
+ headers.set(
1707
+ "Authorization",
1708
+ "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
1709
+ );
1710
+ }
1711
+ let contentType;
1712
+ if (utils$1.isFormData(data)) {
1713
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
1714
+ headers.setContentType(void 0);
1715
+ } else if ((contentType = headers.getContentType()) !== false) {
1716
+ const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : [];
1717
+ headers.setContentType([type || "multipart/form-data", ...tokens].join("; "));
1718
+ }
1719
+ }
1720
+ if (platform.hasStandardBrowserEnv) {
1721
+ withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
1722
+ if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
1723
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
1724
+ if (xsrfValue) {
1725
+ headers.set(xsrfHeaderName, xsrfValue);
1726
+ }
1727
+ }
1728
+ }
1729
+ return newConfig;
1730
+ };
1731
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
1732
+ const xhrAdapter = isXHRAdapterSupported && function(config) {
1733
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
1734
+ const _config = resolveConfig(config);
1735
+ let requestData = _config.data;
1736
+ const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
1737
+ let { responseType, onUploadProgress, onDownloadProgress } = _config;
1738
+ let onCanceled;
1739
+ let uploadThrottled, downloadThrottled;
1740
+ let flushUpload, flushDownload;
1741
+ function done() {
1742
+ flushUpload && flushUpload();
1743
+ flushDownload && flushDownload();
1744
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
1745
+ _config.signal && _config.signal.removeEventListener("abort", onCanceled);
1746
+ }
1747
+ let request = new XMLHttpRequest();
1748
+ request.open(_config.method.toUpperCase(), _config.url, true);
1749
+ request.timeout = _config.timeout;
1750
+ function onloadend() {
1751
+ if (!request) {
1752
+ return;
1753
+ }
1754
+ const responseHeaders = AxiosHeaders.from(
1755
+ "getAllResponseHeaders" in request && request.getAllResponseHeaders()
1756
+ );
1757
+ const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
1758
+ const response = {
1759
+ data: responseData,
1760
+ status: request.status,
1761
+ statusText: request.statusText,
1762
+ headers: responseHeaders,
1763
+ config,
1764
+ request
1765
+ };
1766
+ settle(function _resolve(value) {
1767
+ resolve(value);
1768
+ done();
1769
+ }, function _reject(err) {
1770
+ reject(err);
1771
+ done();
1772
+ }, response);
1773
+ request = null;
1774
+ }
1775
+ if ("onloadend" in request) {
1776
+ request.onloadend = onloadend;
1777
+ } else {
1778
+ request.onreadystatechange = function handleLoad() {
1779
+ if (!request || request.readyState !== 4) {
1780
+ return;
1781
+ }
1782
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
1783
+ return;
1784
+ }
1785
+ setTimeout(onloadend);
1786
+ };
1787
+ }
1788
+ request.onabort = function handleAbort() {
1789
+ if (!request) {
1790
+ return;
1791
+ }
1792
+ reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request));
1793
+ request = null;
1794
+ };
1795
+ request.onerror = function handleError() {
1796
+ reject(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request));
1797
+ request = null;
1798
+ };
1799
+ request.ontimeout = function handleTimeout() {
1800
+ let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
1801
+ const transitional = _config.transitional || transitionalDefaults;
1802
+ if (_config.timeoutErrorMessage) {
1803
+ timeoutErrorMessage = _config.timeoutErrorMessage;
1804
+ }
1805
+ reject(new AxiosError(
1806
+ timeoutErrorMessage,
1807
+ transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
1808
+ config,
1809
+ request
1810
+ ));
1811
+ request = null;
1812
+ };
1813
+ requestData === void 0 && requestHeaders.setContentType(null);
1814
+ if ("setRequestHeader" in request) {
1815
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
1816
+ request.setRequestHeader(key, val);
1817
+ });
1818
+ }
1819
+ if (!utils$1.isUndefined(_config.withCredentials)) {
1820
+ request.withCredentials = !!_config.withCredentials;
1821
+ }
1822
+ if (responseType && responseType !== "json") {
1823
+ request.responseType = _config.responseType;
1824
+ }
1825
+ if (onDownloadProgress) {
1826
+ [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
1827
+ request.addEventListener("progress", downloadThrottled);
1828
+ }
1829
+ if (onUploadProgress && request.upload) {
1830
+ [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
1831
+ request.upload.addEventListener("progress", uploadThrottled);
1832
+ request.upload.addEventListener("loadend", flushUpload);
1833
+ }
1834
+ if (_config.cancelToken || _config.signal) {
1835
+ onCanceled = (cancel) => {
1836
+ if (!request) {
1837
+ return;
1838
+ }
1839
+ reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
1840
+ request.abort();
1841
+ request = null;
1842
+ };
1843
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
1844
+ if (_config.signal) {
1845
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
1846
+ }
1847
+ }
1848
+ const protocol = parseProtocol(_config.url);
1849
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
1850
+ reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config));
1851
+ return;
1852
+ }
1853
+ request.send(requestData || null);
1854
+ });
1855
+ };
1856
+ const composeSignals = (signals, timeout) => {
1857
+ const { length } = signals = signals ? signals.filter(Boolean) : [];
1858
+ if (timeout || length) {
1859
+ let controller = new AbortController();
1860
+ let aborted;
1861
+ const onabort = function(reason) {
1862
+ if (!aborted) {
1863
+ aborted = true;
1864
+ unsubscribe();
1865
+ const err = reason instanceof Error ? reason : this.reason;
1866
+ controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
1867
+ }
1868
+ };
1869
+ let timer = timeout && setTimeout(() => {
1870
+ timer = null;
1871
+ onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
1872
+ }, timeout);
1873
+ const unsubscribe = () => {
1874
+ if (signals) {
1875
+ timer && clearTimeout(timer);
1876
+ timer = null;
1877
+ signals.forEach((signal2) => {
1878
+ signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
1879
+ });
1880
+ signals = null;
1881
+ }
1882
+ };
1883
+ signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
1884
+ const { signal } = controller;
1885
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
1886
+ return signal;
1887
+ }
1888
+ };
1889
+ const streamChunk = function* (chunk, chunkSize) {
1890
+ let len = chunk.byteLength;
1891
+ if (len < chunkSize) {
1892
+ yield chunk;
1893
+ return;
1894
+ }
1895
+ let pos = 0;
1896
+ let end;
1897
+ while (pos < len) {
1898
+ end = pos + chunkSize;
1899
+ yield chunk.slice(pos, end);
1900
+ pos = end;
1901
+ }
1902
+ };
1903
+ const readBytes = async function* (iterable, chunkSize) {
1904
+ for await (const chunk of readStream(iterable)) {
1905
+ yield* streamChunk(chunk, chunkSize);
1906
+ }
1907
+ };
1908
+ const readStream = async function* (stream) {
1909
+ if (stream[Symbol.asyncIterator]) {
1910
+ yield* stream;
1911
+ return;
1912
+ }
1913
+ const reader = stream.getReader();
1914
+ try {
1915
+ for (; ; ) {
1916
+ const { done, value } = await reader.read();
1917
+ if (done) {
1918
+ break;
1919
+ }
1920
+ yield value;
1921
+ }
1922
+ } finally {
1923
+ await reader.cancel();
1924
+ }
1925
+ };
1926
+ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
1927
+ const iterator = readBytes(stream, chunkSize);
1928
+ let bytes = 0;
1929
+ let done;
1930
+ let _onFinish = (e) => {
1931
+ if (!done) {
1932
+ done = true;
1933
+ onFinish && onFinish(e);
1934
+ }
1935
+ };
1936
+ return new ReadableStream({
1937
+ async pull(controller) {
1938
+ try {
1939
+ const { done: done2, value } = await iterator.next();
1940
+ if (done2) {
1941
+ _onFinish();
1942
+ controller.close();
1943
+ return;
1944
+ }
1945
+ let len = value.byteLength;
1946
+ if (onProgress) {
1947
+ let loadedBytes = bytes += len;
1948
+ onProgress(loadedBytes);
1949
+ }
1950
+ controller.enqueue(new Uint8Array(value));
1951
+ } catch (err) {
1952
+ _onFinish(err);
1953
+ throw err;
1954
+ }
1955
+ },
1956
+ cancel(reason) {
1957
+ _onFinish(reason);
1958
+ return iterator.return();
1959
+ }
1960
+ }, {
1961
+ highWaterMark: 2
1962
+ });
1963
+ };
1964
+ const isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function";
1965
+ const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function";
1966
+ const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer()));
1967
+ const test = (fn, ...args) => {
1968
+ try {
1969
+ return !!fn(...args);
1970
+ } catch (e) {
1971
+ return false;
1972
+ }
1973
+ };
1974
+ const supportsRequestStream = isReadableStreamSupported && test(() => {
1975
+ let duplexAccessed = false;
1976
+ const hasContentType = new Request(platform.origin, {
1977
+ body: new ReadableStream(),
1978
+ method: "POST",
1979
+ get duplex() {
1980
+ duplexAccessed = true;
1981
+ return "half";
1982
+ }
1983
+ }).headers.has("Content-Type");
1984
+ return duplexAccessed && !hasContentType;
1985
+ });
1986
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
1987
+ const supportsResponseStream = isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
1988
+ const resolvers = {
1989
+ stream: supportsResponseStream && ((res) => res.body)
1990
+ };
1991
+ isFetchSupported && ((res) => {
1992
+ ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
1993
+ !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res2) => res2[type]() : (_, config) => {
1994
+ throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
1995
+ });
1996
+ });
1997
+ })(new Response());
1998
+ const getBodyLength = async (body) => {
1999
+ if (body == null) {
2000
+ return 0;
2001
+ }
2002
+ if (utils$1.isBlob(body)) {
2003
+ return body.size;
2004
+ }
2005
+ if (utils$1.isSpecCompliantForm(body)) {
2006
+ const _request = new Request(platform.origin, {
2007
+ method: "POST",
2008
+ body
2009
+ });
2010
+ return (await _request.arrayBuffer()).byteLength;
2011
+ }
2012
+ if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2013
+ return body.byteLength;
2014
+ }
2015
+ if (utils$1.isURLSearchParams(body)) {
2016
+ body = body + "";
2017
+ }
2018
+ if (utils$1.isString(body)) {
2019
+ return (await encodeText(body)).byteLength;
2020
+ }
2021
+ };
2022
+ const resolveBodyLength = async (headers, body) => {
2023
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
2024
+ return length == null ? getBodyLength(body) : length;
2025
+ };
2026
+ const fetchAdapter = isFetchSupported && (async (config) => {
2027
+ let {
2028
+ url,
2029
+ method,
2030
+ data,
2031
+ signal,
2032
+ cancelToken,
2033
+ timeout,
2034
+ onDownloadProgress,
2035
+ onUploadProgress,
2036
+ responseType,
2037
+ headers,
2038
+ withCredentials = "same-origin",
2039
+ fetchOptions
2040
+ } = resolveConfig(config);
2041
+ responseType = responseType ? (responseType + "").toLowerCase() : "text";
2042
+ let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2043
+ let request;
2044
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2045
+ composedSignal.unsubscribe();
2046
+ });
2047
+ let requestContentLength;
2048
+ try {
2049
+ if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
2050
+ let _request = new Request(url, {
2051
+ method: "POST",
2052
+ body: data,
2053
+ duplex: "half"
2054
+ });
2055
+ let contentTypeHeader;
2056
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
2057
+ headers.setContentType(contentTypeHeader);
2058
+ }
2059
+ if (_request.body) {
2060
+ const [onProgress, flush] = progressEventDecorator(
2061
+ requestContentLength,
2062
+ progressEventReducer(asyncDecorator(onUploadProgress))
2063
+ );
2064
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2065
+ }
2066
+ }
2067
+ if (!utils$1.isString(withCredentials)) {
2068
+ withCredentials = withCredentials ? "include" : "omit";
2069
+ }
2070
+ const isCredentialsSupported = "credentials" in Request.prototype;
2071
+ request = new Request(url, {
2072
+ ...fetchOptions,
2073
+ signal: composedSignal,
2074
+ method: method.toUpperCase(),
2075
+ headers: headers.normalize().toJSON(),
2076
+ body: data,
2077
+ duplex: "half",
2078
+ credentials: isCredentialsSupported ? withCredentials : void 0
2079
+ });
2080
+ let response = await fetch(request);
2081
+ const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2082
+ if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
2083
+ const options = {};
2084
+ ["status", "statusText", "headers"].forEach((prop) => {
2085
+ options[prop] = response[prop];
2086
+ });
2087
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
2088
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2089
+ responseContentLength,
2090
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
2091
+ ) || [];
2092
+ response = new Response(
2093
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2094
+ flush && flush();
2095
+ unsubscribe && unsubscribe();
2096
+ }),
2097
+ options
2098
+ );
2099
+ }
2100
+ responseType = responseType || "text";
2101
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](response, config);
2102
+ !isStreamResponse && unsubscribe && unsubscribe();
2103
+ return await new Promise((resolve, reject) => {
2104
+ settle(resolve, reject, {
2105
+ data: responseData,
2106
+ headers: AxiosHeaders.from(response.headers),
2107
+ status: response.status,
2108
+ statusText: response.statusText,
2109
+ config,
2110
+ request
2111
+ });
2112
+ });
2113
+ } catch (err) {
2114
+ unsubscribe && unsubscribe();
2115
+ if (err && err.name === "TypeError" && /fetch/i.test(err.message)) {
2116
+ throw Object.assign(
2117
+ new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request),
2118
+ {
2119
+ cause: err.cause || err
2120
+ }
2121
+ );
2122
+ }
2123
+ throw AxiosError.from(err, err && err.code, config, request);
2124
+ }
2125
+ });
2126
+ const knownAdapters = {
2127
+ http: httpAdapter,
2128
+ xhr: xhrAdapter,
2129
+ fetch: fetchAdapter
2130
+ };
2131
+ utils$1.forEach(knownAdapters, (fn, value) => {
2132
+ if (fn) {
2133
+ try {
2134
+ Object.defineProperty(fn, "name", { value });
2135
+ } catch (e) {
2136
+ }
2137
+ Object.defineProperty(fn, "adapterName", { value });
2138
+ }
2139
+ });
2140
+ const renderReason = (reason) => `- ${reason}`;
2141
+ const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
2142
+ const adapters = {
2143
+ getAdapter: (adapters2) => {
2144
+ adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
2145
+ const { length } = adapters2;
2146
+ let nameOrAdapter;
2147
+ let adapter;
2148
+ const rejectedReasons = {};
2149
+ for (let i = 0; i < length; i++) {
2150
+ nameOrAdapter = adapters2[i];
2151
+ let id;
2152
+ adapter = nameOrAdapter;
2153
+ if (!isResolvedHandle(nameOrAdapter)) {
2154
+ adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2155
+ if (adapter === void 0) {
2156
+ throw new AxiosError(`Unknown adapter '${id}'`);
2157
+ }
2158
+ }
2159
+ if (adapter) {
2160
+ break;
2161
+ }
2162
+ rejectedReasons[id || "#" + i] = adapter;
2163
+ }
2164
+ if (!adapter) {
2165
+ const reasons = Object.entries(rejectedReasons).map(
2166
+ ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
2167
+ );
2168
+ let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
2169
+ throw new AxiosError(
2170
+ `There is no suitable adapter to dispatch the request ` + s,
2171
+ "ERR_NOT_SUPPORT"
2172
+ );
2173
+ }
2174
+ return adapter;
2175
+ },
2176
+ adapters: knownAdapters
2177
+ };
2178
+ function throwIfCancellationRequested(config) {
2179
+ if (config.cancelToken) {
2180
+ config.cancelToken.throwIfRequested();
2181
+ }
2182
+ if (config.signal && config.signal.aborted) {
2183
+ throw new CanceledError(null, config);
2184
+ }
2185
+ }
2186
+ function dispatchRequest(config) {
2187
+ throwIfCancellationRequested(config);
2188
+ config.headers = AxiosHeaders.from(config.headers);
2189
+ config.data = transformData.call(
2190
+ config,
2191
+ config.transformRequest
2192
+ );
2193
+ if (["post", "put", "patch"].indexOf(config.method) !== -1) {
2194
+ config.headers.setContentType("application/x-www-form-urlencoded", false);
2195
+ }
2196
+ const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
2197
+ return adapter(config).then(function onAdapterResolution(response) {
2198
+ throwIfCancellationRequested(config);
2199
+ response.data = transformData.call(
2200
+ config,
2201
+ config.transformResponse,
2202
+ response
2203
+ );
2204
+ response.headers = AxiosHeaders.from(response.headers);
2205
+ return response;
2206
+ }, function onAdapterRejection(reason) {
2207
+ if (!isCancel(reason)) {
2208
+ throwIfCancellationRequested(config);
2209
+ if (reason && reason.response) {
2210
+ reason.response.data = transformData.call(
2211
+ config,
2212
+ config.transformResponse,
2213
+ reason.response
2214
+ );
2215
+ reason.response.headers = AxiosHeaders.from(reason.response.headers);
2216
+ }
2217
+ }
2218
+ return Promise.reject(reason);
2219
+ });
2220
+ }
2221
+ const VERSION = "1.7.9";
2222
+ const validators$1 = {};
2223
+ ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
2224
+ validators$1[type] = function validator2(thing) {
2225
+ return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
2226
+ };
2227
+ });
2228
+ const deprecatedWarnings = {};
2229
+ validators$1.transitional = function transitional(validator2, version, message) {
2230
+ function formatMessage(opt, desc) {
2231
+ return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
2232
+ }
2233
+ return (value, opt, opts) => {
2234
+ if (validator2 === false) {
2235
+ throw new AxiosError(
2236
+ formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
2237
+ AxiosError.ERR_DEPRECATED
2238
+ );
2239
+ }
2240
+ if (version && !deprecatedWarnings[opt]) {
2241
+ deprecatedWarnings[opt] = true;
2242
+ console.warn(
2243
+ formatMessage(
2244
+ opt,
2245
+ " has been deprecated since v" + version + " and will be removed in the near future"
2246
+ )
2247
+ );
2248
+ }
2249
+ return validator2 ? validator2(value, opt, opts) : true;
2250
+ };
2251
+ };
2252
+ validators$1.spelling = function spelling(correctSpelling) {
2253
+ return (value, opt) => {
2254
+ console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
2255
+ return true;
2256
+ };
2257
+ };
2258
+ function assertOptions(options, schema, allowUnknown) {
2259
+ if (typeof options !== "object") {
2260
+ throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE);
2261
+ }
2262
+ const keys = Object.keys(options);
2263
+ let i = keys.length;
2264
+ while (i-- > 0) {
2265
+ const opt = keys[i];
2266
+ const validator2 = schema[opt];
2267
+ if (validator2) {
2268
+ const value = options[opt];
2269
+ const result = value === void 0 || validator2(value, opt, options);
2270
+ if (result !== true) {
2271
+ throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE);
2272
+ }
2273
+ continue;
2274
+ }
2275
+ if (allowUnknown !== true) {
2276
+ throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION);
2277
+ }
2278
+ }
2279
+ }
2280
+ const validator = {
2281
+ assertOptions,
2282
+ validators: validators$1
2283
+ };
2284
+ const validators = validator.validators;
2285
+ class Axios {
2286
+ constructor(instanceConfig) {
2287
+ this.defaults = instanceConfig;
2288
+ this.interceptors = {
2289
+ request: new InterceptorManager(),
2290
+ response: new InterceptorManager()
2291
+ };
2292
+ }
2293
+ /**
2294
+ * Dispatch a request
2295
+ *
2296
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
2297
+ * @param {?Object} config
2298
+ *
2299
+ * @returns {Promise} The Promise to be fulfilled
2300
+ */
2301
+ async request(configOrUrl, config) {
2302
+ try {
2303
+ return await this._request(configOrUrl, config);
2304
+ } catch (err) {
2305
+ if (err instanceof Error) {
2306
+ let dummy = {};
2307
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
2308
+ const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
2309
+ try {
2310
+ if (!err.stack) {
2311
+ err.stack = stack;
2312
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
2313
+ err.stack += "\n" + stack;
2314
+ }
2315
+ } catch (e) {
2316
+ }
2317
+ }
2318
+ throw err;
2319
+ }
2320
+ }
2321
+ _request(configOrUrl, config) {
2322
+ if (typeof configOrUrl === "string") {
2323
+ config = config || {};
2324
+ config.url = configOrUrl;
2325
+ } else {
2326
+ config = configOrUrl || {};
2327
+ }
2328
+ config = mergeConfig(this.defaults, config);
2329
+ const { transitional, paramsSerializer, headers } = config;
2330
+ if (transitional !== void 0) {
2331
+ validator.assertOptions(transitional, {
2332
+ silentJSONParsing: validators.transitional(validators.boolean),
2333
+ forcedJSONParsing: validators.transitional(validators.boolean),
2334
+ clarifyTimeoutError: validators.transitional(validators.boolean)
2335
+ }, false);
2336
+ }
2337
+ if (paramsSerializer != null) {
2338
+ if (utils$1.isFunction(paramsSerializer)) {
2339
+ config.paramsSerializer = {
2340
+ serialize: paramsSerializer
2341
+ };
2342
+ } else {
2343
+ validator.assertOptions(paramsSerializer, {
2344
+ encode: validators.function,
2345
+ serialize: validators.function
2346
+ }, true);
2347
+ }
2348
+ }
2349
+ validator.assertOptions(config, {
2350
+ baseUrl: validators.spelling("baseURL"),
2351
+ withXsrfToken: validators.spelling("withXSRFToken")
2352
+ }, true);
2353
+ config.method = (config.method || this.defaults.method || "get").toLowerCase();
2354
+ let contextHeaders = headers && utils$1.merge(
2355
+ headers.common,
2356
+ headers[config.method]
2357
+ );
2358
+ headers && utils$1.forEach(
2359
+ ["delete", "get", "head", "post", "put", "patch", "common"],
2360
+ (method) => {
2361
+ delete headers[method];
2362
+ }
2363
+ );
2364
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
2365
+ const requestInterceptorChain = [];
2366
+ let synchronousRequestInterceptors = true;
2367
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
2368
+ if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
2369
+ return;
2370
+ }
2371
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2372
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2373
+ });
2374
+ const responseInterceptorChain = [];
2375
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
2376
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2377
+ });
2378
+ let promise;
2379
+ let i = 0;
2380
+ let len;
2381
+ if (!synchronousRequestInterceptors) {
2382
+ const chain = [dispatchRequest.bind(this), void 0];
2383
+ chain.unshift.apply(chain, requestInterceptorChain);
2384
+ chain.push.apply(chain, responseInterceptorChain);
2385
+ len = chain.length;
2386
+ promise = Promise.resolve(config);
2387
+ while (i < len) {
2388
+ promise = promise.then(chain[i++], chain[i++]);
2389
+ }
2390
+ return promise;
2391
+ }
2392
+ len = requestInterceptorChain.length;
2393
+ let newConfig = config;
2394
+ i = 0;
2395
+ while (i < len) {
2396
+ const onFulfilled = requestInterceptorChain[i++];
2397
+ const onRejected = requestInterceptorChain[i++];
2398
+ try {
2399
+ newConfig = onFulfilled(newConfig);
2400
+ } catch (error) {
2401
+ onRejected.call(this, error);
2402
+ break;
2403
+ }
2404
+ }
2405
+ try {
2406
+ promise = dispatchRequest.call(this, newConfig);
2407
+ } catch (error) {
2408
+ return Promise.reject(error);
2409
+ }
2410
+ i = 0;
2411
+ len = responseInterceptorChain.length;
2412
+ while (i < len) {
2413
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2414
+ }
2415
+ return promise;
2416
+ }
2417
+ getUri(config) {
2418
+ config = mergeConfig(this.defaults, config);
2419
+ const fullPath = buildFullPath(config.baseURL, config.url);
2420
+ return buildURL(fullPath, config.params, config.paramsSerializer);
2421
+ }
2422
+ }
2423
+ utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
2424
+ Axios.prototype[method] = function(url, config) {
2425
+ return this.request(mergeConfig(config || {}, {
2426
+ method,
2427
+ url,
2428
+ data: (config || {}).data
2429
+ }));
2430
+ };
2431
+ });
2432
+ utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
2433
+ function generateHTTPMethod(isForm) {
2434
+ return function httpMethod(url, data, config) {
2435
+ return this.request(mergeConfig(config || {}, {
2436
+ method,
2437
+ headers: isForm ? {
2438
+ "Content-Type": "multipart/form-data"
2439
+ } : {},
2440
+ url,
2441
+ data
2442
+ }));
2443
+ };
2444
+ }
2445
+ Axios.prototype[method] = generateHTTPMethod();
2446
+ Axios.prototype[method + "Form"] = generateHTTPMethod(true);
2447
+ });
2448
+ class CancelToken {
2449
+ constructor(executor) {
2450
+ if (typeof executor !== "function") {
2451
+ throw new TypeError("executor must be a function.");
2452
+ }
2453
+ let resolvePromise;
2454
+ this.promise = new Promise(function promiseExecutor(resolve) {
2455
+ resolvePromise = resolve;
2456
+ });
2457
+ const token = this;
2458
+ this.promise.then((cancel) => {
2459
+ if (!token._listeners) return;
2460
+ let i = token._listeners.length;
2461
+ while (i-- > 0) {
2462
+ token._listeners[i](cancel);
2463
+ }
2464
+ token._listeners = null;
2465
+ });
2466
+ this.promise.then = (onfulfilled) => {
2467
+ let _resolve;
2468
+ const promise = new Promise((resolve) => {
2469
+ token.subscribe(resolve);
2470
+ _resolve = resolve;
2471
+ }).then(onfulfilled);
2472
+ promise.cancel = function reject() {
2473
+ token.unsubscribe(_resolve);
2474
+ };
2475
+ return promise;
2476
+ };
2477
+ executor(function cancel(message, config, request) {
2478
+ if (token.reason) {
2479
+ return;
2480
+ }
2481
+ token.reason = new CanceledError(message, config, request);
2482
+ resolvePromise(token.reason);
2483
+ });
2484
+ }
2485
+ /**
2486
+ * Throws a `CanceledError` if cancellation has been requested.
2487
+ */
2488
+ throwIfRequested() {
2489
+ if (this.reason) {
2490
+ throw this.reason;
2491
+ }
2492
+ }
2493
+ /**
2494
+ * Subscribe to the cancel signal
2495
+ */
2496
+ subscribe(listener) {
2497
+ if (this.reason) {
2498
+ listener(this.reason);
2499
+ return;
2500
+ }
2501
+ if (this._listeners) {
2502
+ this._listeners.push(listener);
2503
+ } else {
2504
+ this._listeners = [listener];
2505
+ }
2506
+ }
2507
+ /**
2508
+ * Unsubscribe from the cancel signal
2509
+ */
2510
+ unsubscribe(listener) {
2511
+ if (!this._listeners) {
2512
+ return;
2513
+ }
2514
+ const index = this._listeners.indexOf(listener);
2515
+ if (index !== -1) {
2516
+ this._listeners.splice(index, 1);
2517
+ }
2518
+ }
2519
+ toAbortSignal() {
2520
+ const controller = new AbortController();
2521
+ const abort = (err) => {
2522
+ controller.abort(err);
2523
+ };
2524
+ this.subscribe(abort);
2525
+ controller.signal.unsubscribe = () => this.unsubscribe(abort);
2526
+ return controller.signal;
2527
+ }
2528
+ /**
2529
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
2530
+ * cancels the `CancelToken`.
2531
+ */
2532
+ static source() {
2533
+ let cancel;
2534
+ const token = new CancelToken(function executor(c) {
2535
+ cancel = c;
2536
+ });
2537
+ return {
2538
+ token,
2539
+ cancel
2540
+ };
2541
+ }
2542
+ }
2543
+ function spread(callback) {
2544
+ return function wrap(arr) {
2545
+ return callback.apply(null, arr);
2546
+ };
2547
+ }
2548
+ function isAxiosError(payload) {
2549
+ return utils$1.isObject(payload) && payload.isAxiosError === true;
2550
+ }
2551
+ const HttpStatusCode = {
2552
+ Continue: 100,
2553
+ SwitchingProtocols: 101,
2554
+ Processing: 102,
2555
+ EarlyHints: 103,
2556
+ Ok: 200,
2557
+ Created: 201,
2558
+ Accepted: 202,
2559
+ NonAuthoritativeInformation: 203,
2560
+ NoContent: 204,
2561
+ ResetContent: 205,
2562
+ PartialContent: 206,
2563
+ MultiStatus: 207,
2564
+ AlreadyReported: 208,
2565
+ ImUsed: 226,
2566
+ MultipleChoices: 300,
2567
+ MovedPermanently: 301,
2568
+ Found: 302,
2569
+ SeeOther: 303,
2570
+ NotModified: 304,
2571
+ UseProxy: 305,
2572
+ Unused: 306,
2573
+ TemporaryRedirect: 307,
2574
+ PermanentRedirect: 308,
2575
+ BadRequest: 400,
2576
+ Unauthorized: 401,
2577
+ PaymentRequired: 402,
2578
+ Forbidden: 403,
2579
+ NotFound: 404,
2580
+ MethodNotAllowed: 405,
2581
+ NotAcceptable: 406,
2582
+ ProxyAuthenticationRequired: 407,
2583
+ RequestTimeout: 408,
2584
+ Conflict: 409,
2585
+ Gone: 410,
2586
+ LengthRequired: 411,
2587
+ PreconditionFailed: 412,
2588
+ PayloadTooLarge: 413,
2589
+ UriTooLong: 414,
2590
+ UnsupportedMediaType: 415,
2591
+ RangeNotSatisfiable: 416,
2592
+ ExpectationFailed: 417,
2593
+ ImATeapot: 418,
2594
+ MisdirectedRequest: 421,
2595
+ UnprocessableEntity: 422,
2596
+ Locked: 423,
2597
+ FailedDependency: 424,
2598
+ TooEarly: 425,
2599
+ UpgradeRequired: 426,
2600
+ PreconditionRequired: 428,
2601
+ TooManyRequests: 429,
2602
+ RequestHeaderFieldsTooLarge: 431,
2603
+ UnavailableForLegalReasons: 451,
2604
+ InternalServerError: 500,
2605
+ NotImplemented: 501,
2606
+ BadGateway: 502,
2607
+ ServiceUnavailable: 503,
2608
+ GatewayTimeout: 504,
2609
+ HttpVersionNotSupported: 505,
2610
+ VariantAlsoNegotiates: 506,
2611
+ InsufficientStorage: 507,
2612
+ LoopDetected: 508,
2613
+ NotExtended: 510,
2614
+ NetworkAuthenticationRequired: 511
2615
+ };
2616
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
2617
+ HttpStatusCode[value] = key;
2618
+ });
2619
+ function createInstance(defaultConfig) {
2620
+ const context = new Axios(defaultConfig);
2621
+ const instance = bind(Axios.prototype.request, context);
2622
+ utils$1.extend(instance, Axios.prototype, context, { allOwnKeys: true });
2623
+ utils$1.extend(instance, context, null, { allOwnKeys: true });
2624
+ instance.create = function create(instanceConfig) {
2625
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
2626
+ };
2627
+ return instance;
2628
+ }
2629
+ const axios = createInstance(defaults);
2630
+ axios.Axios = Axios;
2631
+ axios.CanceledError = CanceledError;
2632
+ axios.CancelToken = CancelToken;
2633
+ axios.isCancel = isCancel;
2634
+ axios.VERSION = VERSION;
2635
+ axios.toFormData = toFormData;
2636
+ axios.AxiosError = AxiosError;
2637
+ axios.Cancel = axios.CanceledError;
2638
+ axios.all = function all(promises) {
2639
+ return Promise.all(promises);
2640
+ };
2641
+ axios.spread = spread;
2642
+ axios.isAxiosError = isAxiosError;
2643
+ axios.mergeConfig = mergeConfig;
2644
+ axios.AxiosHeaders = AxiosHeaders;
2645
+ axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
2646
+ axios.getAdapter = adapters.getAdapter;
2647
+ axios.HttpStatusCode = HttpStatusCode;
2648
+ axios.default = axios;
2649
+ class MemoryCache {
2650
+ constructor(ttl) {
2651
+ __publicField(this, "cache", {});
2652
+ __publicField(this, "ttl");
2653
+ this.ttl = ttl;
2654
+ }
2655
+ async get(key) {
2656
+ const cacheRecord = this.cache;
2657
+ return new Promise((resolve, reject) => {
2658
+ try {
2659
+ const cacheItem = cacheRecord[key];
2660
+ if (!cacheItem) {
2661
+ return resolve({ error: "[MemoryCache]未找到缓存,将执行请求", data: null });
2662
+ }
2663
+ const { data, exp } = cacheItem;
2664
+ if (exp < Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3)) {
2665
+ this.delete(key);
2666
+ return resolve({ error: "[MemoryCache]缓存已过期,将执行请求", data: null });
2667
+ }
2668
+ resolve({ error: null, data });
2669
+ } catch (error) {
2670
+ reject({ error, data: null });
2671
+ }
2672
+ });
2673
+ }
2674
+ async set(key, value) {
2675
+ return new Promise((resolve, reject) => {
2676
+ try {
2677
+ this.cache[key] = {
2678
+ data: value,
2679
+ exp: Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + this.ttl
2680
+ };
2681
+ resolve({ error: null, data: true });
2682
+ } catch (error) {
2683
+ reject({ error, data: null });
2684
+ }
2685
+ });
2686
+ }
2687
+ async delete(key) {
2688
+ return new Promise((resolve, reject) => {
2689
+ try {
2690
+ delete this.cache[key];
2691
+ resolve({ error: null, data: true });
2692
+ } catch (error) {
2693
+ reject({ error, data: null });
2694
+ }
2695
+ });
2696
+ }
2697
+ }
2698
+ class LocalStorageCache {
2699
+ constructor(ttl) {
2700
+ __publicField(this, "ttl");
2701
+ this.ttl = ttl;
2702
+ }
2703
+ async get(key) {
2704
+ return new Promise((resolve, reject) => {
2705
+ try {
2706
+ const cacheItem = localStorage.getItem(key);
2707
+ if (!cacheItem) {
2708
+ return resolve({ error: `未找到${key}的缓存`, data: null });
2709
+ }
2710
+ const { data, exp } = JSON.parse(cacheItem);
2711
+ if (exp < Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3)) {
2712
+ this.delete(key);
2713
+ return resolve({ error: `${key}的缓存已过期`, data: null });
2714
+ }
2715
+ resolve({ error: null, data });
2716
+ } catch (error) {
2717
+ reject({ error, data: null });
2718
+ }
2719
+ });
2720
+ }
2721
+ async set(key, value) {
2722
+ return new Promise((resolve, reject) => {
2723
+ try {
2724
+ localStorage.setItem(
2725
+ key,
2726
+ JSON.stringify({
2727
+ data: value,
2728
+ exp: Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + this.ttl
2729
+ })
2730
+ );
2731
+ resolve({ error: null, data: true });
2732
+ } catch (error) {
2733
+ reject({ error, data: null });
2734
+ }
2735
+ });
2736
+ }
2737
+ async delete(key) {
2738
+ return new Promise((resolve, reject) => {
2739
+ try {
2740
+ localStorage.removeItem(key);
2741
+ resolve({ error: null, data: true });
2742
+ } catch (error) {
2743
+ reject({ error, data: null });
2744
+ }
2745
+ });
2746
+ }
2747
+ }
2748
+ const INDEXDB_DATABASE_NAME = "SNAIL_CACHE";
2749
+ const INDEXDB_VERSION = 3;
2750
+ const INDEXDB_OBJECT_STORE_NAME = "SNAIL_CACHE_OBJECT";
2751
+ const INDEXDB_INDEX_NAME = "SNAIL_CACHE_INDEX";
2752
+ class IndexDBCache {
2753
+ constructor(ttl) {
2754
+ __publicField(this, "ttl");
2755
+ __publicField(this, "db", null);
2756
+ this.ttl = ttl;
2757
+ }
2758
+ async init() {
2759
+ this.db = await this.openDB();
2760
+ }
2761
+ async openDB() {
2762
+ return new Promise((resolve, reject) => {
2763
+ const request = indexedDB.open(INDEXDB_DATABASE_NAME, INDEXDB_VERSION);
2764
+ request.onupgradeneeded = function(event) {
2765
+ const db = event.target.result;
2766
+ const objectStore = db.createObjectStore(INDEXDB_OBJECT_STORE_NAME, {
2767
+ keyPath: "key"
2768
+ });
2769
+ objectStore.createIndex(INDEXDB_INDEX_NAME, "key", {
2770
+ unique: false
2771
+ });
2772
+ };
2773
+ request.onsuccess = function(event) {
2774
+ const db = event.target.result;
2775
+ resolve(db);
2776
+ };
2777
+ request.onerror = (event) => {
2778
+ console.error(`[indexDB]连接数据库错误:${event.target}`);
2779
+ reject(null);
2780
+ };
2781
+ });
2782
+ }
2783
+ async get(key) {
2784
+ return new Promise((resolve, reject) => {
2785
+ if (this.db === null) {
2786
+ return reject({ error: new Error("数据库未初始化"), data: null });
2787
+ }
2788
+ const select = this.db.transaction(INDEXDB_OBJECT_STORE_NAME, "readonly").objectStore(INDEXDB_OBJECT_STORE_NAME).get(key);
2789
+ select.onsuccess = () => {
2790
+ const result = select.result;
2791
+ if (!result || result.exp < Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3)) {
2792
+ this.delete(key);
2793
+ return resolve({ error: new Error("缓存已过期"), data: null });
2794
+ }
2795
+ resolve({ error: null, data: result.data });
2796
+ };
2797
+ select.onerror = (event) => {
2798
+ reject({
2799
+ error: new Error(`查询数据错误:${event.target}`),
2800
+ data: null
2801
+ });
2802
+ };
2803
+ });
2804
+ }
2805
+ async set(key, value) {
2806
+ return new Promise((resolve, reject) => {
2807
+ if (this.db === null) {
2808
+ return reject({ error: new Error("数据库未初始化"), data: null });
2809
+ }
2810
+ const select = this.db.transaction(INDEXDB_OBJECT_STORE_NAME, "readwrite").objectStore(INDEXDB_OBJECT_STORE_NAME).put(
2811
+ {
2812
+ data: value,
2813
+ exp: Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + this.ttl,
2814
+ key
2815
+ }
2816
+ );
2817
+ select.onsuccess = () => {
2818
+ resolve({ error: null, data: true });
2819
+ };
2820
+ select.onerror = (event) => {
2821
+ reject({
2822
+ error: new Error(`插入数据错误:${event.target}`),
2823
+ data: null
2824
+ });
2825
+ };
2826
+ });
2827
+ }
2828
+ async delete(key) {
2829
+ return new Promise((resolve, reject) => {
2830
+ if (this.db === null) {
2831
+ return reject({ error: new Error("数据库未初始化"), data: null });
2832
+ }
2833
+ const select = this.db.transaction(INDEXDB_OBJECT_STORE_NAME, "readwrite").objectStore(INDEXDB_OBJECT_STORE_NAME).delete(key);
2834
+ select.onsuccess = () => {
2835
+ resolve({ error: null, data: true });
2836
+ };
2837
+ select.onerror = (event) => {
2838
+ reject({
2839
+ error: new Error(`删除数据错误:${event.target}`),
2840
+ data: null
2841
+ });
2842
+ };
2843
+ });
2844
+ }
2845
+ }
2846
+ function createCache(type, ttl) {
2847
+ if (type === CacheType.Memory) {
2848
+ return new MemoryCache(ttl);
2849
+ }
2850
+ if (type === CacheType.LocalStorage) {
2851
+ return new LocalStorageCache(ttl);
2852
+ }
2853
+ if (type === CacheType.IndexDB) {
2854
+ const db = new IndexDBCache(ttl);
2855
+ db.init();
2856
+ return db;
2857
+ }
2858
+ return void 0;
2859
+ }
2860
+ const DEFAULT_CONFIG = {
2861
+ timeout: 5e3,
2862
+ // 默认开启内存缓存
2863
+ CacheManage: {
2864
+ type: CacheType.Memory,
2865
+ // 默认缓存时间为5分钟(单位秒)
2866
+ ttl: 300
2867
+ }
2868
+ };
2869
+ class Snail {
2870
+ constructor(options) {
2871
+ __publicField(this, "axiosInstance");
2872
+ __publicField(this, "baseURL", "");
2873
+ __publicField(this, "versioning");
2874
+ __publicField(this, "options");
2875
+ __publicField(this, "cacheStorage");
2876
+ __publicField(this, "cacheSource");
2877
+ const instance = this;
2878
+ const SnailOptions = {
2879
+ ...DEFAULT_CONFIG,
2880
+ ...options
2881
+ };
2882
+ this.baseURL = SnailOptions.baseURL || "";
2883
+ this.versioning = SnailOptions.Versioning;
2884
+ this.options = SnailOptions;
2885
+ instance.axiosInstance = axios.create({
2886
+ baseURL: instance.baseURL,
2887
+ timeout: instance.options.timeout || 5e3
2888
+ });
2889
+ if (SnailOptions.requestInterceptors) {
2890
+ instance.axiosInstance.interceptors.request.use(
2891
+ (config) => {
2892
+ var _a, _b;
2893
+ const result = (_b = (_a = SnailOptions.requestInterceptors) == null ? void 0 : _a.onFulfilled) == null ? void 0 : _b.call(_a, config);
2894
+ return result ? result : config;
2895
+ },
2896
+ SnailOptions.requestInterceptors.onRejected,
2897
+ SnailOptions.requestInterceptors.options
2898
+ );
2899
+ }
2900
+ if (SnailOptions.responseInterceptors) {
2901
+ instance.axiosInstance.interceptors.response.use(
2902
+ (response) => {
2903
+ var _a, _b;
2904
+ const result = (_b = (_a = SnailOptions.responseInterceptors) == null ? void 0 : _a.onFulfilled) == null ? void 0 : _b.call(_a, response);
2905
+ return result ? result : response;
2906
+ },
2907
+ (error) => {
2908
+ var _a, _b;
2909
+ const result = (_b = (_a = SnailOptions.responseInterceptors) == null ? void 0 : _a.onRejected) == null ? void 0 : _b.call(_a, error);
2910
+ return Promise.reject(result || error);
2911
+ }
2912
+ );
2913
+ }
2914
+ if (instance.options.CacheManage) {
2915
+ const { type, ttl } = instance.options.CacheManage;
2916
+ instance.cacheStorage = createCache(type, ttl || 300);
2917
+ }
2918
+ }
2919
+ Get(url, options) {
2920
+ return new Api(RequestMethod.GET, url, this, options);
2921
+ }
2922
+ Post(url, options) {
2923
+ return new Api(RequestMethod.POST, url, this, options);
2924
+ }
2925
+ Put(url, options) {
2926
+ return new Api(RequestMethod.PUT, url, this, options);
2927
+ }
2928
+ Delete(url, options) {
2929
+ return new Api(RequestMethod.DELETE, url, this, options);
2930
+ }
2931
+ Patch(url, options) {
2932
+ return new Api(RequestMethod.PATCH, url, this, options);
2933
+ }
2934
+ Head(url, options) {
2935
+ return new Api(RequestMethod.HEAD, url, this, options);
2936
+ }
2937
+ Options(url, options) {
2938
+ return new Api(RequestMethod.OPTIONS, url, this, options);
2939
+ }
2940
+ }
2941
+ const createSnail = (option) => {
2942
+ return new Snail(option);
2943
+ };
2944
+ exports2.Api = Api;
2945
+ exports2.CacheType = CacheType;
2946
+ exports2.RequestMethod = RequestMethod;
2947
+ exports2.Snail = Snail;
2948
+ exports2.VersioningType = VersioningType;
2949
+ exports2.apiKey = apiKey;
2950
+ exports2.createSnail = createSnail;
2951
+ exports2.deepCopy = deepCopy;
2952
+ exports2.getResponseDataFromCache = getResponseDataFromCache;
2953
+ exports2.recordToString = recordToString;
2954
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
2955
+ });