react-unified-auth 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4262 @@
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('react/jsx-runtime');
4
+ var React = require('react');
5
+
6
+ const AuthContext = React.createContext(undefined);
7
+ function AuthProvider({ config, children }) {
8
+ return (jsxRuntime.jsx(AuthContext.Provider, { value: { config }, children: children }));
9
+ }
10
+ function useAuthConfig() {
11
+ const context = React.useContext(AuthContext);
12
+ if (!context) {
13
+ throw new Error('useAuthConfig must be used within an AuthProvider');
14
+ }
15
+ return context.config;
16
+ }
17
+
18
+ /**
19
+ * Create a bound version of a function with a specified `this` context
20
+ *
21
+ * @param {Function} fn - The function to bind
22
+ * @param {*} thisArg - The value to be passed as the `this` parameter
23
+ * @returns {Function} A new function that will call the original function with the specified `this` context
24
+ */
25
+ function bind(fn, thisArg) {
26
+ return function wrap() {
27
+ return fn.apply(thisArg, arguments);
28
+ };
29
+ }
30
+
31
+ // utils is a library of generic helper functions non-specific to axios
32
+
33
+ const {toString} = Object.prototype;
34
+ const {getPrototypeOf} = Object;
35
+ const {iterator, toStringTag} = Symbol;
36
+
37
+ const kindOf = (cache => thing => {
38
+ const str = toString.call(thing);
39
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
40
+ })(Object.create(null));
41
+
42
+ const kindOfTest = (type) => {
43
+ type = type.toLowerCase();
44
+ return (thing) => kindOf(thing) === type
45
+ };
46
+
47
+ const typeOfTest = type => thing => typeof thing === type;
48
+
49
+ /**
50
+ * Determine if a value is an Array
51
+ *
52
+ * @param {Object} val The value to test
53
+ *
54
+ * @returns {boolean} True if value is an Array, otherwise false
55
+ */
56
+ const {isArray} = Array;
57
+
58
+ /**
59
+ * Determine if a value is undefined
60
+ *
61
+ * @param {*} val The value to test
62
+ *
63
+ * @returns {boolean} True if the value is undefined, otherwise false
64
+ */
65
+ const isUndefined = typeOfTest('undefined');
66
+
67
+ /**
68
+ * Determine if a value is a Buffer
69
+ *
70
+ * @param {*} val The value to test
71
+ *
72
+ * @returns {boolean} True if value is a Buffer, otherwise false
73
+ */
74
+ function isBuffer(val) {
75
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
76
+ && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
77
+ }
78
+
79
+ /**
80
+ * Determine if a value is an ArrayBuffer
81
+ *
82
+ * @param {*} val The value to test
83
+ *
84
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
85
+ */
86
+ const isArrayBuffer = kindOfTest('ArrayBuffer');
87
+
88
+
89
+ /**
90
+ * Determine if a value is a view on an ArrayBuffer
91
+ *
92
+ * @param {*} val The value to test
93
+ *
94
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
95
+ */
96
+ function isArrayBufferView(val) {
97
+ let result;
98
+ if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
99
+ result = ArrayBuffer.isView(val);
100
+ } else {
101
+ result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
102
+ }
103
+ return result;
104
+ }
105
+
106
+ /**
107
+ * Determine if a value is a String
108
+ *
109
+ * @param {*} val The value to test
110
+ *
111
+ * @returns {boolean} True if value is a String, otherwise false
112
+ */
113
+ const isString = typeOfTest('string');
114
+
115
+ /**
116
+ * Determine if a value is a Function
117
+ *
118
+ * @param {*} val The value to test
119
+ * @returns {boolean} True if value is a Function, otherwise false
120
+ */
121
+ const isFunction$1 = typeOfTest('function');
122
+
123
+ /**
124
+ * Determine if a value is a Number
125
+ *
126
+ * @param {*} val The value to test
127
+ *
128
+ * @returns {boolean} True if value is a Number, otherwise false
129
+ */
130
+ const isNumber = typeOfTest('number');
131
+
132
+ /**
133
+ * Determine if a value is an Object
134
+ *
135
+ * @param {*} thing The value to test
136
+ *
137
+ * @returns {boolean} True if value is an Object, otherwise false
138
+ */
139
+ const isObject = (thing) => thing !== null && typeof thing === 'object';
140
+
141
+ /**
142
+ * Determine if a value is a Boolean
143
+ *
144
+ * @param {*} thing The value to test
145
+ * @returns {boolean} True if value is a Boolean, otherwise false
146
+ */
147
+ const isBoolean = thing => thing === true || thing === false;
148
+
149
+ /**
150
+ * Determine if a value is a plain Object
151
+ *
152
+ * @param {*} val The value to test
153
+ *
154
+ * @returns {boolean} True if value is a plain Object, otherwise false
155
+ */
156
+ const isPlainObject = (val) => {
157
+ if (kindOf(val) !== 'object') {
158
+ return false;
159
+ }
160
+
161
+ const prototype = getPrototypeOf(val);
162
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val);
163
+ };
164
+
165
+ /**
166
+ * Determine if a value is an empty object (safely handles Buffers)
167
+ *
168
+ * @param {*} val The value to test
169
+ *
170
+ * @returns {boolean} True if value is an empty object, otherwise false
171
+ */
172
+ const isEmptyObject = (val) => {
173
+ // Early return for non-objects or Buffers to prevent RangeError
174
+ if (!isObject(val) || isBuffer(val)) {
175
+ return false;
176
+ }
177
+
178
+ try {
179
+ return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
180
+ } catch (e) {
181
+ // Fallback for any other objects that might cause RangeError with Object.keys()
182
+ return false;
183
+ }
184
+ };
185
+
186
+ /**
187
+ * Determine if a value is a Date
188
+ *
189
+ * @param {*} val The value to test
190
+ *
191
+ * @returns {boolean} True if value is a Date, otherwise false
192
+ */
193
+ const isDate = kindOfTest('Date');
194
+
195
+ /**
196
+ * Determine if a value is a File
197
+ *
198
+ * @param {*} val The value to test
199
+ *
200
+ * @returns {boolean} True if value is a File, otherwise false
201
+ */
202
+ const isFile = kindOfTest('File');
203
+
204
+ /**
205
+ * Determine if a value is a Blob
206
+ *
207
+ * @param {*} val The value to test
208
+ *
209
+ * @returns {boolean} True if value is a Blob, otherwise false
210
+ */
211
+ const isBlob = kindOfTest('Blob');
212
+
213
+ /**
214
+ * Determine if a value is a FileList
215
+ *
216
+ * @param {*} val The value to test
217
+ *
218
+ * @returns {boolean} True if value is a File, otherwise false
219
+ */
220
+ const isFileList = kindOfTest('FileList');
221
+
222
+ /**
223
+ * Determine if a value is a Stream
224
+ *
225
+ * @param {*} val The value to test
226
+ *
227
+ * @returns {boolean} True if value is a Stream, otherwise false
228
+ */
229
+ const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
230
+
231
+ /**
232
+ * Determine if a value is a FormData
233
+ *
234
+ * @param {*} thing The value to test
235
+ *
236
+ * @returns {boolean} True if value is an FormData, otherwise false
237
+ */
238
+ const isFormData = (thing) => {
239
+ let kind;
240
+ return thing && (
241
+ (typeof FormData === 'function' && thing instanceof FormData) || (
242
+ isFunction$1(thing.append) && (
243
+ (kind = kindOf(thing)) === 'formdata' ||
244
+ // detect form-data instance
245
+ (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
246
+ )
247
+ )
248
+ )
249
+ };
250
+
251
+ /**
252
+ * Determine if a value is a URLSearchParams object
253
+ *
254
+ * @param {*} val The value to test
255
+ *
256
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
257
+ */
258
+ const isURLSearchParams = kindOfTest('URLSearchParams');
259
+
260
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
261
+
262
+ /**
263
+ * Trim excess whitespace off the beginning and end of a string
264
+ *
265
+ * @param {String} str The String to trim
266
+ *
267
+ * @returns {String} The String freed of excess whitespace
268
+ */
269
+ const trim = (str) => str.trim ?
270
+ str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
271
+
272
+ /**
273
+ * Iterate over an Array or an Object invoking a function for each item.
274
+ *
275
+ * If `obj` is an Array callback will be called passing
276
+ * the value, index, and complete array for each item.
277
+ *
278
+ * If 'obj' is an Object callback will be called passing
279
+ * the value, key, and complete object for each property.
280
+ *
281
+ * @param {Object|Array} obj The object to iterate
282
+ * @param {Function} fn The callback to invoke for each item
283
+ *
284
+ * @param {Boolean} [allOwnKeys = false]
285
+ * @returns {any}
286
+ */
287
+ function forEach(obj, fn, {allOwnKeys = false} = {}) {
288
+ // Don't bother if no value provided
289
+ if (obj === null || typeof obj === 'undefined') {
290
+ return;
291
+ }
292
+
293
+ let i;
294
+ let l;
295
+
296
+ // Force an array if not already something iterable
297
+ if (typeof obj !== 'object') {
298
+ /*eslint no-param-reassign:0*/
299
+ obj = [obj];
300
+ }
301
+
302
+ if (isArray(obj)) {
303
+ // Iterate over array values
304
+ for (i = 0, l = obj.length; i < l; i++) {
305
+ fn.call(null, obj[i], i, obj);
306
+ }
307
+ } else {
308
+ // Buffer check
309
+ if (isBuffer(obj)) {
310
+ return;
311
+ }
312
+
313
+ // Iterate over object keys
314
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
315
+ const len = keys.length;
316
+ let key;
317
+
318
+ for (i = 0; i < len; i++) {
319
+ key = keys[i];
320
+ fn.call(null, obj[key], key, obj);
321
+ }
322
+ }
323
+ }
324
+
325
+ function findKey(obj, key) {
326
+ if (isBuffer(obj)){
327
+ return null;
328
+ }
329
+
330
+ key = key.toLowerCase();
331
+ const keys = Object.keys(obj);
332
+ let i = keys.length;
333
+ let _key;
334
+ while (i-- > 0) {
335
+ _key = keys[i];
336
+ if (key === _key.toLowerCase()) {
337
+ return _key;
338
+ }
339
+ }
340
+ return null;
341
+ }
342
+
343
+ const _global = (() => {
344
+ /*eslint no-undef:0*/
345
+ if (typeof globalThis !== "undefined") return globalThis;
346
+ return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
347
+ })();
348
+
349
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
350
+
351
+ /**
352
+ * Accepts varargs expecting each argument to be an object, then
353
+ * immutably merges the properties of each object and returns result.
354
+ *
355
+ * When multiple objects contain the same key the later object in
356
+ * the arguments list will take precedence.
357
+ *
358
+ * Example:
359
+ *
360
+ * ```js
361
+ * var result = merge({foo: 123}, {foo: 456});
362
+ * console.log(result.foo); // outputs 456
363
+ * ```
364
+ *
365
+ * @param {Object} obj1 Object to merge
366
+ *
367
+ * @returns {Object} Result of all merge properties
368
+ */
369
+ function merge(/* obj1, obj2, obj3, ... */) {
370
+ const {caseless, skipUndefined} = isContextDefined(this) && this || {};
371
+ const result = {};
372
+ const assignValue = (val, key) => {
373
+ const targetKey = caseless && findKey(result, key) || key;
374
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
375
+ result[targetKey] = merge(result[targetKey], val);
376
+ } else if (isPlainObject(val)) {
377
+ result[targetKey] = merge({}, val);
378
+ } else if (isArray(val)) {
379
+ result[targetKey] = val.slice();
380
+ } else if (!skipUndefined || !isUndefined(val)) {
381
+ result[targetKey] = val;
382
+ }
383
+ };
384
+
385
+ for (let i = 0, l = arguments.length; i < l; i++) {
386
+ arguments[i] && forEach(arguments[i], assignValue);
387
+ }
388
+ return result;
389
+ }
390
+
391
+ /**
392
+ * Extends object a by mutably adding to it the properties of object b.
393
+ *
394
+ * @param {Object} a The object to be extended
395
+ * @param {Object} b The object to copy properties from
396
+ * @param {Object} thisArg The object to bind function to
397
+ *
398
+ * @param {Boolean} [allOwnKeys]
399
+ * @returns {Object} The resulting value of object a
400
+ */
401
+ const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
402
+ forEach(b, (val, key) => {
403
+ if (thisArg && isFunction$1(val)) {
404
+ a[key] = bind(val, thisArg);
405
+ } else {
406
+ a[key] = val;
407
+ }
408
+ }, {allOwnKeys});
409
+ return a;
410
+ };
411
+
412
+ /**
413
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
414
+ *
415
+ * @param {string} content with BOM
416
+ *
417
+ * @returns {string} content value without BOM
418
+ */
419
+ const stripBOM = (content) => {
420
+ if (content.charCodeAt(0) === 0xFEFF) {
421
+ content = content.slice(1);
422
+ }
423
+ return content;
424
+ };
425
+
426
+ /**
427
+ * Inherit the prototype methods from one constructor into another
428
+ * @param {function} constructor
429
+ * @param {function} superConstructor
430
+ * @param {object} [props]
431
+ * @param {object} [descriptors]
432
+ *
433
+ * @returns {void}
434
+ */
435
+ const inherits = (constructor, superConstructor, props, descriptors) => {
436
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
437
+ constructor.prototype.constructor = constructor;
438
+ Object.defineProperty(constructor, 'super', {
439
+ value: superConstructor.prototype
440
+ });
441
+ props && Object.assign(constructor.prototype, props);
442
+ };
443
+
444
+ /**
445
+ * Resolve object with deep prototype chain to a flat object
446
+ * @param {Object} sourceObj source object
447
+ * @param {Object} [destObj]
448
+ * @param {Function|Boolean} [filter]
449
+ * @param {Function} [propFilter]
450
+ *
451
+ * @returns {Object}
452
+ */
453
+ const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
454
+ let props;
455
+ let i;
456
+ let prop;
457
+ const merged = {};
458
+
459
+ destObj = destObj || {};
460
+ // eslint-disable-next-line no-eq-null,eqeqeq
461
+ if (sourceObj == null) return destObj;
462
+
463
+ do {
464
+ props = Object.getOwnPropertyNames(sourceObj);
465
+ i = props.length;
466
+ while (i-- > 0) {
467
+ prop = props[i];
468
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
469
+ destObj[prop] = sourceObj[prop];
470
+ merged[prop] = true;
471
+ }
472
+ }
473
+ sourceObj = filter !== false && getPrototypeOf(sourceObj);
474
+ } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
475
+
476
+ return destObj;
477
+ };
478
+
479
+ /**
480
+ * Determines whether a string ends with the characters of a specified string
481
+ *
482
+ * @param {String} str
483
+ * @param {String} searchString
484
+ * @param {Number} [position= 0]
485
+ *
486
+ * @returns {boolean}
487
+ */
488
+ const endsWith = (str, searchString, position) => {
489
+ str = String(str);
490
+ if (position === undefined || position > str.length) {
491
+ position = str.length;
492
+ }
493
+ position -= searchString.length;
494
+ const lastIndex = str.indexOf(searchString, position);
495
+ return lastIndex !== -1 && lastIndex === position;
496
+ };
497
+
498
+
499
+ /**
500
+ * Returns new array from array like object or null if failed
501
+ *
502
+ * @param {*} [thing]
503
+ *
504
+ * @returns {?Array}
505
+ */
506
+ const toArray = (thing) => {
507
+ if (!thing) return null;
508
+ if (isArray(thing)) return thing;
509
+ let i = thing.length;
510
+ if (!isNumber(i)) return null;
511
+ const arr = new Array(i);
512
+ while (i-- > 0) {
513
+ arr[i] = thing[i];
514
+ }
515
+ return arr;
516
+ };
517
+
518
+ /**
519
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
520
+ * thing passed in is an instance of Uint8Array
521
+ *
522
+ * @param {TypedArray}
523
+ *
524
+ * @returns {Array}
525
+ */
526
+ // eslint-disable-next-line func-names
527
+ const isTypedArray = (TypedArray => {
528
+ // eslint-disable-next-line func-names
529
+ return thing => {
530
+ return TypedArray && thing instanceof TypedArray;
531
+ };
532
+ })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
533
+
534
+ /**
535
+ * For each entry in the object, call the function with the key and value.
536
+ *
537
+ * @param {Object<any, any>} obj - The object to iterate over.
538
+ * @param {Function} fn - The function to call for each entry.
539
+ *
540
+ * @returns {void}
541
+ */
542
+ const forEachEntry = (obj, fn) => {
543
+ const generator = obj && obj[iterator];
544
+
545
+ const _iterator = generator.call(obj);
546
+
547
+ let result;
548
+
549
+ while ((result = _iterator.next()) && !result.done) {
550
+ const pair = result.value;
551
+ fn.call(obj, pair[0], pair[1]);
552
+ }
553
+ };
554
+
555
+ /**
556
+ * It takes a regular expression and a string, and returns an array of all the matches
557
+ *
558
+ * @param {string} regExp - The regular expression to match against.
559
+ * @param {string} str - The string to search.
560
+ *
561
+ * @returns {Array<boolean>}
562
+ */
563
+ const matchAll = (regExp, str) => {
564
+ let matches;
565
+ const arr = [];
566
+
567
+ while ((matches = regExp.exec(str)) !== null) {
568
+ arr.push(matches);
569
+ }
570
+
571
+ return arr;
572
+ };
573
+
574
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
575
+ const isHTMLForm = kindOfTest('HTMLFormElement');
576
+
577
+ const toCamelCase = str => {
578
+ return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
579
+ function replacer(m, p1, p2) {
580
+ return p1.toUpperCase() + p2;
581
+ }
582
+ );
583
+ };
584
+
585
+ /* Creating a function that will check if an object has a property. */
586
+ const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
587
+
588
+ /**
589
+ * Determine if a value is a RegExp object
590
+ *
591
+ * @param {*} val The value to test
592
+ *
593
+ * @returns {boolean} True if value is a RegExp object, otherwise false
594
+ */
595
+ const isRegExp = kindOfTest('RegExp');
596
+
597
+ const reduceDescriptors = (obj, reducer) => {
598
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
599
+ const reducedDescriptors = {};
600
+
601
+ forEach(descriptors, (descriptor, name) => {
602
+ let ret;
603
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
604
+ reducedDescriptors[name] = ret || descriptor;
605
+ }
606
+ });
607
+
608
+ Object.defineProperties(obj, reducedDescriptors);
609
+ };
610
+
611
+ /**
612
+ * Makes all methods read-only
613
+ * @param {Object} obj
614
+ */
615
+
616
+ const freezeMethods = (obj) => {
617
+ reduceDescriptors(obj, (descriptor, name) => {
618
+ // skip restricted props in strict mode
619
+ if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
620
+ return false;
621
+ }
622
+
623
+ const value = obj[name];
624
+
625
+ if (!isFunction$1(value)) return;
626
+
627
+ descriptor.enumerable = false;
628
+
629
+ if ('writable' in descriptor) {
630
+ descriptor.writable = false;
631
+ return;
632
+ }
633
+
634
+ if (!descriptor.set) {
635
+ descriptor.set = () => {
636
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
637
+ };
638
+ }
639
+ });
640
+ };
641
+
642
+ const toObjectSet = (arrayOrString, delimiter) => {
643
+ const obj = {};
644
+
645
+ const define = (arr) => {
646
+ arr.forEach(value => {
647
+ obj[value] = true;
648
+ });
649
+ };
650
+
651
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
652
+
653
+ return obj;
654
+ };
655
+
656
+ const noop = () => {};
657
+
658
+ const toFiniteNumber = (value, defaultValue) => {
659
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
660
+ };
661
+
662
+
663
+
664
+ /**
665
+ * If the thing is a FormData object, return true, otherwise return false.
666
+ *
667
+ * @param {unknown} thing - The thing to check.
668
+ *
669
+ * @returns {boolean}
670
+ */
671
+ function isSpecCompliantForm(thing) {
672
+ return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
673
+ }
674
+
675
+ const toJSONObject = (obj) => {
676
+ const stack = new Array(10);
677
+
678
+ const visit = (source, i) => {
679
+
680
+ if (isObject(source)) {
681
+ if (stack.indexOf(source) >= 0) {
682
+ return;
683
+ }
684
+
685
+ //Buffer check
686
+ if (isBuffer(source)) {
687
+ return source;
688
+ }
689
+
690
+ if(!('toJSON' in source)) {
691
+ stack[i] = source;
692
+ const target = isArray(source) ? [] : {};
693
+
694
+ forEach(source, (value, key) => {
695
+ const reducedValue = visit(value, i + 1);
696
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
697
+ });
698
+
699
+ stack[i] = undefined;
700
+
701
+ return target;
702
+ }
703
+ }
704
+
705
+ return source;
706
+ };
707
+
708
+ return visit(obj, 0);
709
+ };
710
+
711
+ const isAsyncFn = kindOfTest('AsyncFunction');
712
+
713
+ const isThenable = (thing) =>
714
+ thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
715
+
716
+ // original code
717
+ // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
718
+
719
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
720
+ if (setImmediateSupported) {
721
+ return setImmediate;
722
+ }
723
+
724
+ return postMessageSupported ? ((token, callbacks) => {
725
+ _global.addEventListener("message", ({source, data}) => {
726
+ if (source === _global && data === token) {
727
+ callbacks.length && callbacks.shift()();
728
+ }
729
+ }, false);
730
+
731
+ return (cb) => {
732
+ callbacks.push(cb);
733
+ _global.postMessage(token, "*");
734
+ }
735
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
736
+ })(
737
+ typeof setImmediate === 'function',
738
+ isFunction$1(_global.postMessage)
739
+ );
740
+
741
+ const asap = typeof queueMicrotask !== 'undefined' ?
742
+ queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
743
+
744
+ // *********************
745
+
746
+
747
+ const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
748
+
749
+
750
+ var utils$1 = {
751
+ isArray,
752
+ isArrayBuffer,
753
+ isBuffer,
754
+ isFormData,
755
+ isArrayBufferView,
756
+ isString,
757
+ isNumber,
758
+ isBoolean,
759
+ isObject,
760
+ isPlainObject,
761
+ isEmptyObject,
762
+ isReadableStream,
763
+ isRequest,
764
+ isResponse,
765
+ isHeaders,
766
+ isUndefined,
767
+ isDate,
768
+ isFile,
769
+ isBlob,
770
+ isRegExp,
771
+ isFunction: isFunction$1,
772
+ isStream,
773
+ isURLSearchParams,
774
+ isTypedArray,
775
+ isFileList,
776
+ forEach,
777
+ merge,
778
+ extend,
779
+ trim,
780
+ stripBOM,
781
+ inherits,
782
+ toFlatObject,
783
+ kindOf,
784
+ kindOfTest,
785
+ endsWith,
786
+ toArray,
787
+ forEachEntry,
788
+ matchAll,
789
+ isHTMLForm,
790
+ hasOwnProperty,
791
+ hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
792
+ reduceDescriptors,
793
+ freezeMethods,
794
+ toObjectSet,
795
+ toCamelCase,
796
+ noop,
797
+ toFiniteNumber,
798
+ findKey,
799
+ global: _global,
800
+ isContextDefined,
801
+ isSpecCompliantForm,
802
+ toJSONObject,
803
+ isAsyncFn,
804
+ isThenable,
805
+ setImmediate: _setImmediate,
806
+ asap,
807
+ isIterable
808
+ };
809
+
810
+ /**
811
+ * Create an Error with the specified message, config, error code, request and response.
812
+ *
813
+ * @param {string} message The error message.
814
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
815
+ * @param {Object} [config] The config.
816
+ * @param {Object} [request] The request.
817
+ * @param {Object} [response] The response.
818
+ *
819
+ * @returns {Error} The created error.
820
+ */
821
+ function AxiosError(message, code, config, request, response) {
822
+ Error.call(this);
823
+
824
+ if (Error.captureStackTrace) {
825
+ Error.captureStackTrace(this, this.constructor);
826
+ } else {
827
+ this.stack = (new Error()).stack;
828
+ }
829
+
830
+ this.message = message;
831
+ this.name = 'AxiosError';
832
+ code && (this.code = code);
833
+ config && (this.config = config);
834
+ request && (this.request = request);
835
+ if (response) {
836
+ this.response = response;
837
+ this.status = response.status ? response.status : null;
838
+ }
839
+ }
840
+
841
+ utils$1.inherits(AxiosError, Error, {
842
+ toJSON: function toJSON() {
843
+ return {
844
+ // Standard
845
+ message: this.message,
846
+ name: this.name,
847
+ // Microsoft
848
+ description: this.description,
849
+ number: this.number,
850
+ // Mozilla
851
+ fileName: this.fileName,
852
+ lineNumber: this.lineNumber,
853
+ columnNumber: this.columnNumber,
854
+ stack: this.stack,
855
+ // Axios
856
+ config: utils$1.toJSONObject(this.config),
857
+ code: this.code,
858
+ status: this.status
859
+ };
860
+ }
861
+ });
862
+
863
+ const prototype$1 = AxiosError.prototype;
864
+ const descriptors = {};
865
+
866
+ [
867
+ 'ERR_BAD_OPTION_VALUE',
868
+ 'ERR_BAD_OPTION',
869
+ 'ECONNABORTED',
870
+ 'ETIMEDOUT',
871
+ 'ERR_NETWORK',
872
+ 'ERR_FR_TOO_MANY_REDIRECTS',
873
+ 'ERR_DEPRECATED',
874
+ 'ERR_BAD_RESPONSE',
875
+ 'ERR_BAD_REQUEST',
876
+ 'ERR_CANCELED',
877
+ 'ERR_NOT_SUPPORT',
878
+ 'ERR_INVALID_URL'
879
+ // eslint-disable-next-line func-names
880
+ ].forEach(code => {
881
+ descriptors[code] = {value: code};
882
+ });
883
+
884
+ Object.defineProperties(AxiosError, descriptors);
885
+ Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
886
+
887
+ // eslint-disable-next-line func-names
888
+ AxiosError.from = (error, code, config, request, response, customProps) => {
889
+ const axiosError = Object.create(prototype$1);
890
+
891
+ utils$1.toFlatObject(error, axiosError, function filter(obj) {
892
+ return obj !== Error.prototype;
893
+ }, prop => {
894
+ return prop !== 'isAxiosError';
895
+ });
896
+
897
+ const msg = error && error.message ? error.message : 'Error';
898
+
899
+ // Prefer explicit code; otherwise copy the low-level error's code (e.g. ECONNREFUSED)
900
+ const errCode = code == null && error ? error.code : code;
901
+ AxiosError.call(axiosError, msg, errCode, config, request, response);
902
+
903
+ // Chain the original error on the standard field; non-enumerable to avoid JSON noise
904
+ if (error && axiosError.cause == null) {
905
+ Object.defineProperty(axiosError, 'cause', { value: error, configurable: true });
906
+ }
907
+
908
+ axiosError.name = (error && error.name) || 'Error';
909
+
910
+ customProps && Object.assign(axiosError, customProps);
911
+
912
+ return axiosError;
913
+ };
914
+
915
+ // eslint-disable-next-line strict
916
+ var httpAdapter = null;
917
+
918
+ /**
919
+ * Determines if the given thing is a array or js object.
920
+ *
921
+ * @param {string} thing - The object or array to be visited.
922
+ *
923
+ * @returns {boolean}
924
+ */
925
+ function isVisitable(thing) {
926
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
927
+ }
928
+
929
+ /**
930
+ * It removes the brackets from the end of a string
931
+ *
932
+ * @param {string} key - The key of the parameter.
933
+ *
934
+ * @returns {string} the key without the brackets.
935
+ */
936
+ function removeBrackets(key) {
937
+ return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
938
+ }
939
+
940
+ /**
941
+ * It takes a path, a key, and a boolean, and returns a string
942
+ *
943
+ * @param {string} path - The path to the current key.
944
+ * @param {string} key - The key of the current object being iterated over.
945
+ * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
946
+ *
947
+ * @returns {string} The path to the current key.
948
+ */
949
+ function renderKey(path, key, dots) {
950
+ if (!path) return key;
951
+ return path.concat(key).map(function each(token, i) {
952
+ // eslint-disable-next-line no-param-reassign
953
+ token = removeBrackets(token);
954
+ return !dots && i ? '[' + token + ']' : token;
955
+ }).join(dots ? '.' : '');
956
+ }
957
+
958
+ /**
959
+ * If the array is an array and none of its elements are visitable, then it's a flat array.
960
+ *
961
+ * @param {Array<any>} arr - The array to check
962
+ *
963
+ * @returns {boolean}
964
+ */
965
+ function isFlatArray(arr) {
966
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
967
+ }
968
+
969
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
970
+ return /^is[A-Z]/.test(prop);
971
+ });
972
+
973
+ /**
974
+ * Convert a data object to FormData
975
+ *
976
+ * @param {Object} obj
977
+ * @param {?Object} [formData]
978
+ * @param {?Object} [options]
979
+ * @param {Function} [options.visitor]
980
+ * @param {Boolean} [options.metaTokens = true]
981
+ * @param {Boolean} [options.dots = false]
982
+ * @param {?Boolean} [options.indexes = false]
983
+ *
984
+ * @returns {Object}
985
+ **/
986
+
987
+ /**
988
+ * It converts an object into a FormData object
989
+ *
990
+ * @param {Object<any, any>} obj - The object to convert to form data.
991
+ * @param {string} formData - The FormData object to append to.
992
+ * @param {Object<string, any>} options
993
+ *
994
+ * @returns
995
+ */
996
+ function toFormData(obj, formData, options) {
997
+ if (!utils$1.isObject(obj)) {
998
+ throw new TypeError('target must be an object');
999
+ }
1000
+
1001
+ // eslint-disable-next-line no-param-reassign
1002
+ formData = formData || new (FormData)();
1003
+
1004
+ // eslint-disable-next-line no-param-reassign
1005
+ options = utils$1.toFlatObject(options, {
1006
+ metaTokens: true,
1007
+ dots: false,
1008
+ indexes: false
1009
+ }, false, function defined(option, source) {
1010
+ // eslint-disable-next-line no-eq-null,eqeqeq
1011
+ return !utils$1.isUndefined(source[option]);
1012
+ });
1013
+
1014
+ const metaTokens = options.metaTokens;
1015
+ // eslint-disable-next-line no-use-before-define
1016
+ const visitor = options.visitor || defaultVisitor;
1017
+ const dots = options.dots;
1018
+ const indexes = options.indexes;
1019
+ const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1020
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1021
+
1022
+ if (!utils$1.isFunction(visitor)) {
1023
+ throw new TypeError('visitor must be a function');
1024
+ }
1025
+
1026
+ function convertValue(value) {
1027
+ if (value === null) return '';
1028
+
1029
+ if (utils$1.isDate(value)) {
1030
+ return value.toISOString();
1031
+ }
1032
+
1033
+ if (utils$1.isBoolean(value)) {
1034
+ return value.toString();
1035
+ }
1036
+
1037
+ if (!useBlob && utils$1.isBlob(value)) {
1038
+ throw new AxiosError('Blob is not supported. Use a Buffer instead.');
1039
+ }
1040
+
1041
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
1042
+ return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1043
+ }
1044
+
1045
+ return value;
1046
+ }
1047
+
1048
+ /**
1049
+ * Default visitor.
1050
+ *
1051
+ * @param {*} value
1052
+ * @param {String|Number} key
1053
+ * @param {Array<String|Number>} path
1054
+ * @this {FormData}
1055
+ *
1056
+ * @returns {boolean} return true to visit the each prop of the value recursively
1057
+ */
1058
+ function defaultVisitor(value, key, path) {
1059
+ let arr = value;
1060
+
1061
+ if (value && !path && typeof value === 'object') {
1062
+ if (utils$1.endsWith(key, '{}')) {
1063
+ // eslint-disable-next-line no-param-reassign
1064
+ key = metaTokens ? key : key.slice(0, -2);
1065
+ // eslint-disable-next-line no-param-reassign
1066
+ value = JSON.stringify(value);
1067
+ } else if (
1068
+ (utils$1.isArray(value) && isFlatArray(value)) ||
1069
+ ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
1070
+ )) {
1071
+ // eslint-disable-next-line no-param-reassign
1072
+ key = removeBrackets(key);
1073
+
1074
+ arr.forEach(function each(el, index) {
1075
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
1076
+ // eslint-disable-next-line no-nested-ternary
1077
+ indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1078
+ convertValue(el)
1079
+ );
1080
+ });
1081
+ return false;
1082
+ }
1083
+ }
1084
+
1085
+ if (isVisitable(value)) {
1086
+ return true;
1087
+ }
1088
+
1089
+ formData.append(renderKey(path, key, dots), convertValue(value));
1090
+
1091
+ return false;
1092
+ }
1093
+
1094
+ const stack = [];
1095
+
1096
+ const exposedHelpers = Object.assign(predicates, {
1097
+ defaultVisitor,
1098
+ convertValue,
1099
+ isVisitable
1100
+ });
1101
+
1102
+ function build(value, path) {
1103
+ if (utils$1.isUndefined(value)) return;
1104
+
1105
+ if (stack.indexOf(value) !== -1) {
1106
+ throw Error('Circular reference detected in ' + path.join('.'));
1107
+ }
1108
+
1109
+ stack.push(value);
1110
+
1111
+ utils$1.forEach(value, function each(el, key) {
1112
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
1113
+ formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
1114
+ );
1115
+
1116
+ if (result === true) {
1117
+ build(el, path ? path.concat(key) : [key]);
1118
+ }
1119
+ });
1120
+
1121
+ stack.pop();
1122
+ }
1123
+
1124
+ if (!utils$1.isObject(obj)) {
1125
+ throw new TypeError('data must be an object');
1126
+ }
1127
+
1128
+ build(obj);
1129
+
1130
+ return formData;
1131
+ }
1132
+
1133
+ /**
1134
+ * It encodes a string by replacing all characters that are not in the unreserved set with
1135
+ * their percent-encoded equivalents
1136
+ *
1137
+ * @param {string} str - The string to encode.
1138
+ *
1139
+ * @returns {string} The encoded string.
1140
+ */
1141
+ function encode$1(str) {
1142
+ const charMap = {
1143
+ '!': '%21',
1144
+ "'": '%27',
1145
+ '(': '%28',
1146
+ ')': '%29',
1147
+ '~': '%7E',
1148
+ '%20': '+',
1149
+ '%00': '\x00'
1150
+ };
1151
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1152
+ return charMap[match];
1153
+ });
1154
+ }
1155
+
1156
+ /**
1157
+ * It takes a params object and converts it to a FormData object
1158
+ *
1159
+ * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1160
+ * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1161
+ *
1162
+ * @returns {void}
1163
+ */
1164
+ function AxiosURLSearchParams(params, options) {
1165
+ this._pairs = [];
1166
+
1167
+ params && toFormData(params, this, options);
1168
+ }
1169
+
1170
+ const prototype = AxiosURLSearchParams.prototype;
1171
+
1172
+ prototype.append = function append(name, value) {
1173
+ this._pairs.push([name, value]);
1174
+ };
1175
+
1176
+ prototype.toString = function toString(encoder) {
1177
+ const _encode = encoder ? function(value) {
1178
+ return encoder.call(this, value, encode$1);
1179
+ } : encode$1;
1180
+
1181
+ return this._pairs.map(function each(pair) {
1182
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
1183
+ }, '').join('&');
1184
+ };
1185
+
1186
+ /**
1187
+ * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1188
+ * URI encoded counterparts
1189
+ *
1190
+ * @param {string} val The value to be encoded.
1191
+ *
1192
+ * @returns {string} The encoded value.
1193
+ */
1194
+ function encode(val) {
1195
+ return encodeURIComponent(val).
1196
+ replace(/%3A/gi, ':').
1197
+ replace(/%24/g, '$').
1198
+ replace(/%2C/gi, ',').
1199
+ replace(/%20/g, '+');
1200
+ }
1201
+
1202
+ /**
1203
+ * Build a URL by appending params to the end
1204
+ *
1205
+ * @param {string} url The base of the url (e.g., http://www.google.com)
1206
+ * @param {object} [params] The params to be appended
1207
+ * @param {?(object|Function)} options
1208
+ *
1209
+ * @returns {string} The formatted url
1210
+ */
1211
+ function buildURL(url, params, options) {
1212
+ /*eslint no-param-reassign:0*/
1213
+ if (!params) {
1214
+ return url;
1215
+ }
1216
+
1217
+ const _encode = options && options.encode || encode;
1218
+
1219
+ if (utils$1.isFunction(options)) {
1220
+ options = {
1221
+ serialize: options
1222
+ };
1223
+ }
1224
+
1225
+ const serializeFn = options && options.serialize;
1226
+
1227
+ let serializedParams;
1228
+
1229
+ if (serializeFn) {
1230
+ serializedParams = serializeFn(params, options);
1231
+ } else {
1232
+ serializedParams = utils$1.isURLSearchParams(params) ?
1233
+ params.toString() :
1234
+ new AxiosURLSearchParams(params, options).toString(_encode);
1235
+ }
1236
+
1237
+ if (serializedParams) {
1238
+ const hashmarkIndex = url.indexOf("#");
1239
+
1240
+ if (hashmarkIndex !== -1) {
1241
+ url = url.slice(0, hashmarkIndex);
1242
+ }
1243
+ url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1244
+ }
1245
+
1246
+ return url;
1247
+ }
1248
+
1249
+ class InterceptorManager {
1250
+ constructor() {
1251
+ this.handlers = [];
1252
+ }
1253
+
1254
+ /**
1255
+ * Add a new interceptor to the stack
1256
+ *
1257
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
1258
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
1259
+ *
1260
+ * @return {Number} An ID used to remove interceptor later
1261
+ */
1262
+ use(fulfilled, rejected, options) {
1263
+ this.handlers.push({
1264
+ fulfilled,
1265
+ rejected,
1266
+ synchronous: options ? options.synchronous : false,
1267
+ runWhen: options ? options.runWhen : null
1268
+ });
1269
+ return this.handlers.length - 1;
1270
+ }
1271
+
1272
+ /**
1273
+ * Remove an interceptor from the stack
1274
+ *
1275
+ * @param {Number} id The ID that was returned by `use`
1276
+ *
1277
+ * @returns {void}
1278
+ */
1279
+ eject(id) {
1280
+ if (this.handlers[id]) {
1281
+ this.handlers[id] = null;
1282
+ }
1283
+ }
1284
+
1285
+ /**
1286
+ * Clear all interceptors from the stack
1287
+ *
1288
+ * @returns {void}
1289
+ */
1290
+ clear() {
1291
+ if (this.handlers) {
1292
+ this.handlers = [];
1293
+ }
1294
+ }
1295
+
1296
+ /**
1297
+ * Iterate over all the registered interceptors
1298
+ *
1299
+ * This method is particularly useful for skipping over any
1300
+ * interceptors that may have become `null` calling `eject`.
1301
+ *
1302
+ * @param {Function} fn The function to call for each interceptor
1303
+ *
1304
+ * @returns {void}
1305
+ */
1306
+ forEach(fn) {
1307
+ utils$1.forEach(this.handlers, function forEachHandler(h) {
1308
+ if (h !== null) {
1309
+ fn(h);
1310
+ }
1311
+ });
1312
+ }
1313
+ }
1314
+
1315
+ var InterceptorManager$1 = InterceptorManager;
1316
+
1317
+ var transitionalDefaults = {
1318
+ silentJSONParsing: true,
1319
+ forcedJSONParsing: true,
1320
+ clarifyTimeoutError: false
1321
+ };
1322
+
1323
+ var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1324
+
1325
+ var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
1326
+
1327
+ var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
1328
+
1329
+ var platform$1 = {
1330
+ isBrowser: true,
1331
+ classes: {
1332
+ URLSearchParams: URLSearchParams$1,
1333
+ FormData: FormData$1,
1334
+ Blob: Blob$1
1335
+ },
1336
+ protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1337
+ };
1338
+
1339
+ const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
1340
+
1341
+ const _navigator = typeof navigator === 'object' && navigator || undefined;
1342
+
1343
+ /**
1344
+ * Determine if we're running in a standard browser environment
1345
+ *
1346
+ * This allows axios to run in a web worker, and react-native.
1347
+ * Both environments support XMLHttpRequest, but not fully standard globals.
1348
+ *
1349
+ * web workers:
1350
+ * typeof window -> undefined
1351
+ * typeof document -> undefined
1352
+ *
1353
+ * react-native:
1354
+ * navigator.product -> 'ReactNative'
1355
+ * nativescript
1356
+ * navigator.product -> 'NativeScript' or 'NS'
1357
+ *
1358
+ * @returns {boolean}
1359
+ */
1360
+ const hasStandardBrowserEnv = hasBrowserEnv &&
1361
+ (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
1362
+
1363
+ /**
1364
+ * Determine if we're running in a standard browser webWorker environment
1365
+ *
1366
+ * Although the `isStandardBrowserEnv` method indicates that
1367
+ * `allows axios to run in a web worker`, the WebWorker will still be
1368
+ * filtered out due to its judgment standard
1369
+ * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1370
+ * This leads to a problem when axios post `FormData` in webWorker
1371
+ */
1372
+ const hasStandardBrowserWebWorkerEnv = (() => {
1373
+ return (
1374
+ typeof WorkerGlobalScope !== 'undefined' &&
1375
+ // eslint-disable-next-line no-undef
1376
+ self instanceof WorkerGlobalScope &&
1377
+ typeof self.importScripts === 'function'
1378
+ );
1379
+ })();
1380
+
1381
+ const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1382
+
1383
+ var utils = /*#__PURE__*/Object.freeze({
1384
+ __proto__: null,
1385
+ hasBrowserEnv: hasBrowserEnv,
1386
+ hasStandardBrowserEnv: hasStandardBrowserEnv,
1387
+ hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1388
+ navigator: _navigator,
1389
+ origin: origin
1390
+ });
1391
+
1392
+ var platform = {
1393
+ ...utils,
1394
+ ...platform$1
1395
+ };
1396
+
1397
+ function toURLEncodedForm(data, options) {
1398
+ return toFormData(data, new platform.classes.URLSearchParams(), {
1399
+ visitor: function(value, key, path, helpers) {
1400
+ if (platform.isNode && utils$1.isBuffer(value)) {
1401
+ this.append(key, value.toString('base64'));
1402
+ return false;
1403
+ }
1404
+
1405
+ return helpers.defaultVisitor.apply(this, arguments);
1406
+ },
1407
+ ...options
1408
+ });
1409
+ }
1410
+
1411
+ /**
1412
+ * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1413
+ *
1414
+ * @param {string} name - The name of the property to get.
1415
+ *
1416
+ * @returns An array of strings.
1417
+ */
1418
+ function parsePropPath(name) {
1419
+ // foo[x][y][z]
1420
+ // foo.x.y.z
1421
+ // foo-x-y-z
1422
+ // foo x y z
1423
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1424
+ return match[0] === '[]' ? '' : match[1] || match[0];
1425
+ });
1426
+ }
1427
+
1428
+ /**
1429
+ * Convert an array to an object.
1430
+ *
1431
+ * @param {Array<any>} arr - The array to convert to an object.
1432
+ *
1433
+ * @returns An object with the same keys and values as the array.
1434
+ */
1435
+ function arrayToObject(arr) {
1436
+ const obj = {};
1437
+ const keys = Object.keys(arr);
1438
+ let i;
1439
+ const len = keys.length;
1440
+ let key;
1441
+ for (i = 0; i < len; i++) {
1442
+ key = keys[i];
1443
+ obj[key] = arr[key];
1444
+ }
1445
+ return obj;
1446
+ }
1447
+
1448
+ /**
1449
+ * It takes a FormData object and returns a JavaScript object
1450
+ *
1451
+ * @param {string} formData The FormData object to convert to JSON.
1452
+ *
1453
+ * @returns {Object<string, any> | null} The converted object.
1454
+ */
1455
+ function formDataToJSON(formData) {
1456
+ function buildPath(path, value, target, index) {
1457
+ let name = path[index++];
1458
+
1459
+ if (name === '__proto__') return true;
1460
+
1461
+ const isNumericKey = Number.isFinite(+name);
1462
+ const isLast = index >= path.length;
1463
+ name = !name && utils$1.isArray(target) ? target.length : name;
1464
+
1465
+ if (isLast) {
1466
+ if (utils$1.hasOwnProp(target, name)) {
1467
+ target[name] = [target[name], value];
1468
+ } else {
1469
+ target[name] = value;
1470
+ }
1471
+
1472
+ return !isNumericKey;
1473
+ }
1474
+
1475
+ if (!target[name] || !utils$1.isObject(target[name])) {
1476
+ target[name] = [];
1477
+ }
1478
+
1479
+ const result = buildPath(path, value, target[name], index);
1480
+
1481
+ if (result && utils$1.isArray(target[name])) {
1482
+ target[name] = arrayToObject(target[name]);
1483
+ }
1484
+
1485
+ return !isNumericKey;
1486
+ }
1487
+
1488
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1489
+ const obj = {};
1490
+
1491
+ utils$1.forEachEntry(formData, (name, value) => {
1492
+ buildPath(parsePropPath(name), value, obj, 0);
1493
+ });
1494
+
1495
+ return obj;
1496
+ }
1497
+
1498
+ return null;
1499
+ }
1500
+
1501
+ /**
1502
+ * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1503
+ * of the input
1504
+ *
1505
+ * @param {any} rawValue - The value to be stringified.
1506
+ * @param {Function} parser - A function that parses a string into a JavaScript object.
1507
+ * @param {Function} encoder - A function that takes a value and returns a string.
1508
+ *
1509
+ * @returns {string} A stringified version of the rawValue.
1510
+ */
1511
+ function stringifySafely(rawValue, parser, encoder) {
1512
+ if (utils$1.isString(rawValue)) {
1513
+ try {
1514
+ (parser || JSON.parse)(rawValue);
1515
+ return utils$1.trim(rawValue);
1516
+ } catch (e) {
1517
+ if (e.name !== 'SyntaxError') {
1518
+ throw e;
1519
+ }
1520
+ }
1521
+ }
1522
+
1523
+ return (encoder || JSON.stringify)(rawValue);
1524
+ }
1525
+
1526
+ const defaults = {
1527
+
1528
+ transitional: transitionalDefaults,
1529
+
1530
+ adapter: ['xhr', 'http', 'fetch'],
1531
+
1532
+ transformRequest: [function transformRequest(data, headers) {
1533
+ const contentType = headers.getContentType() || '';
1534
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
1535
+ const isObjectPayload = utils$1.isObject(data);
1536
+
1537
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1538
+ data = new FormData(data);
1539
+ }
1540
+
1541
+ const isFormData = utils$1.isFormData(data);
1542
+
1543
+ if (isFormData) {
1544
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1545
+ }
1546
+
1547
+ if (utils$1.isArrayBuffer(data) ||
1548
+ utils$1.isBuffer(data) ||
1549
+ utils$1.isStream(data) ||
1550
+ utils$1.isFile(data) ||
1551
+ utils$1.isBlob(data) ||
1552
+ utils$1.isReadableStream(data)
1553
+ ) {
1554
+ return data;
1555
+ }
1556
+ if (utils$1.isArrayBufferView(data)) {
1557
+ return data.buffer;
1558
+ }
1559
+ if (utils$1.isURLSearchParams(data)) {
1560
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1561
+ return data.toString();
1562
+ }
1563
+
1564
+ let isFileList;
1565
+
1566
+ if (isObjectPayload) {
1567
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1568
+ return toURLEncodedForm(data, this.formSerializer).toString();
1569
+ }
1570
+
1571
+ if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1572
+ const _FormData = this.env && this.env.FormData;
1573
+
1574
+ return toFormData(
1575
+ isFileList ? {'files[]': data} : data,
1576
+ _FormData && new _FormData(),
1577
+ this.formSerializer
1578
+ );
1579
+ }
1580
+ }
1581
+
1582
+ if (isObjectPayload || hasJSONContentType ) {
1583
+ headers.setContentType('application/json', false);
1584
+ return stringifySafely(data);
1585
+ }
1586
+
1587
+ return data;
1588
+ }],
1589
+
1590
+ transformResponse: [function transformResponse(data) {
1591
+ const transitional = this.transitional || defaults.transitional;
1592
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1593
+ const JSONRequested = this.responseType === 'json';
1594
+
1595
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1596
+ return data;
1597
+ }
1598
+
1599
+ if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1600
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
1601
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1602
+
1603
+ try {
1604
+ return JSON.parse(data, this.parseReviver);
1605
+ } catch (e) {
1606
+ if (strictJSONParsing) {
1607
+ if (e.name === 'SyntaxError') {
1608
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
1609
+ }
1610
+ throw e;
1611
+ }
1612
+ }
1613
+ }
1614
+
1615
+ return data;
1616
+ }],
1617
+
1618
+ /**
1619
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1620
+ * timeout is not created.
1621
+ */
1622
+ timeout: 0,
1623
+
1624
+ xsrfCookieName: 'XSRF-TOKEN',
1625
+ xsrfHeaderName: 'X-XSRF-TOKEN',
1626
+
1627
+ maxContentLength: -1,
1628
+ maxBodyLength: -1,
1629
+
1630
+ env: {
1631
+ FormData: platform.classes.FormData,
1632
+ Blob: platform.classes.Blob
1633
+ },
1634
+
1635
+ validateStatus: function validateStatus(status) {
1636
+ return status >= 200 && status < 300;
1637
+ },
1638
+
1639
+ headers: {
1640
+ common: {
1641
+ 'Accept': 'application/json, text/plain, */*',
1642
+ 'Content-Type': undefined
1643
+ }
1644
+ }
1645
+ };
1646
+
1647
+ utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
1648
+ defaults.headers[method] = {};
1649
+ });
1650
+
1651
+ var defaults$1 = defaults;
1652
+
1653
+ // RawAxiosHeaders whose duplicates are ignored by node
1654
+ // c.f. https://nodejs.org/api/http.html#http_message_headers
1655
+ const ignoreDuplicateOf = utils$1.toObjectSet([
1656
+ 'age', 'authorization', 'content-length', 'content-type', 'etag',
1657
+ 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1658
+ 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1659
+ 'referer', 'retry-after', 'user-agent'
1660
+ ]);
1661
+
1662
+ /**
1663
+ * Parse headers into an object
1664
+ *
1665
+ * ```
1666
+ * Date: Wed, 27 Aug 2014 08:58:49 GMT
1667
+ * Content-Type: application/json
1668
+ * Connection: keep-alive
1669
+ * Transfer-Encoding: chunked
1670
+ * ```
1671
+ *
1672
+ * @param {String} rawHeaders Headers needing to be parsed
1673
+ *
1674
+ * @returns {Object} Headers parsed into an object
1675
+ */
1676
+ var parseHeaders = rawHeaders => {
1677
+ const parsed = {};
1678
+ let key;
1679
+ let val;
1680
+ let i;
1681
+
1682
+ rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1683
+ i = line.indexOf(':');
1684
+ key = line.substring(0, i).trim().toLowerCase();
1685
+ val = line.substring(i + 1).trim();
1686
+
1687
+ if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1688
+ return;
1689
+ }
1690
+
1691
+ if (key === 'set-cookie') {
1692
+ if (parsed[key]) {
1693
+ parsed[key].push(val);
1694
+ } else {
1695
+ parsed[key] = [val];
1696
+ }
1697
+ } else {
1698
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1699
+ }
1700
+ });
1701
+
1702
+ return parsed;
1703
+ };
1704
+
1705
+ const $internals = Symbol('internals');
1706
+
1707
+ function normalizeHeader(header) {
1708
+ return header && String(header).trim().toLowerCase();
1709
+ }
1710
+
1711
+ function normalizeValue(value) {
1712
+ if (value === false || value == null) {
1713
+ return value;
1714
+ }
1715
+
1716
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1717
+ }
1718
+
1719
+ function parseTokens(str) {
1720
+ const tokens = Object.create(null);
1721
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1722
+ let match;
1723
+
1724
+ while ((match = tokensRE.exec(str))) {
1725
+ tokens[match[1]] = match[2];
1726
+ }
1727
+
1728
+ return tokens;
1729
+ }
1730
+
1731
+ const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1732
+
1733
+ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1734
+ if (utils$1.isFunction(filter)) {
1735
+ return filter.call(this, value, header);
1736
+ }
1737
+
1738
+ if (isHeaderNameFilter) {
1739
+ value = header;
1740
+ }
1741
+
1742
+ if (!utils$1.isString(value)) return;
1743
+
1744
+ if (utils$1.isString(filter)) {
1745
+ return value.indexOf(filter) !== -1;
1746
+ }
1747
+
1748
+ if (utils$1.isRegExp(filter)) {
1749
+ return filter.test(value);
1750
+ }
1751
+ }
1752
+
1753
+ function formatHeader(header) {
1754
+ return header.trim()
1755
+ .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1756
+ return char.toUpperCase() + str;
1757
+ });
1758
+ }
1759
+
1760
+ function buildAccessors(obj, header) {
1761
+ const accessorName = utils$1.toCamelCase(' ' + header);
1762
+
1763
+ ['get', 'set', 'has'].forEach(methodName => {
1764
+ Object.defineProperty(obj, methodName + accessorName, {
1765
+ value: function(arg1, arg2, arg3) {
1766
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1767
+ },
1768
+ configurable: true
1769
+ });
1770
+ });
1771
+ }
1772
+
1773
+ class AxiosHeaders {
1774
+ constructor(headers) {
1775
+ headers && this.set(headers);
1776
+ }
1777
+
1778
+ set(header, valueOrRewrite, rewrite) {
1779
+ const self = this;
1780
+
1781
+ function setHeader(_value, _header, _rewrite) {
1782
+ const lHeader = normalizeHeader(_header);
1783
+
1784
+ if (!lHeader) {
1785
+ throw new Error('header name must be a non-empty string');
1786
+ }
1787
+
1788
+ const key = utils$1.findKey(self, lHeader);
1789
+
1790
+ if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1791
+ self[key || _header] = normalizeValue(_value);
1792
+ }
1793
+ }
1794
+
1795
+ const setHeaders = (headers, _rewrite) =>
1796
+ utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1797
+
1798
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1799
+ setHeaders(header, valueOrRewrite);
1800
+ } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1801
+ setHeaders(parseHeaders(header), valueOrRewrite);
1802
+ } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1803
+ let obj = {}, dest, key;
1804
+ for (const entry of header) {
1805
+ if (!utils$1.isArray(entry)) {
1806
+ throw TypeError('Object iterator must return a key-value pair');
1807
+ }
1808
+
1809
+ obj[key = entry[0]] = (dest = obj[key]) ?
1810
+ (utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1];
1811
+ }
1812
+
1813
+ setHeaders(obj, valueOrRewrite);
1814
+ } else {
1815
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1816
+ }
1817
+
1818
+ return this;
1819
+ }
1820
+
1821
+ get(header, parser) {
1822
+ header = normalizeHeader(header);
1823
+
1824
+ if (header) {
1825
+ const key = utils$1.findKey(this, header);
1826
+
1827
+ if (key) {
1828
+ const value = this[key];
1829
+
1830
+ if (!parser) {
1831
+ return value;
1832
+ }
1833
+
1834
+ if (parser === true) {
1835
+ return parseTokens(value);
1836
+ }
1837
+
1838
+ if (utils$1.isFunction(parser)) {
1839
+ return parser.call(this, value, key);
1840
+ }
1841
+
1842
+ if (utils$1.isRegExp(parser)) {
1843
+ return parser.exec(value);
1844
+ }
1845
+
1846
+ throw new TypeError('parser must be boolean|regexp|function');
1847
+ }
1848
+ }
1849
+ }
1850
+
1851
+ has(header, matcher) {
1852
+ header = normalizeHeader(header);
1853
+
1854
+ if (header) {
1855
+ const key = utils$1.findKey(this, header);
1856
+
1857
+ return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1858
+ }
1859
+
1860
+ return false;
1861
+ }
1862
+
1863
+ delete(header, matcher) {
1864
+ const self = this;
1865
+ let deleted = false;
1866
+
1867
+ function deleteHeader(_header) {
1868
+ _header = normalizeHeader(_header);
1869
+
1870
+ if (_header) {
1871
+ const key = utils$1.findKey(self, _header);
1872
+
1873
+ if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1874
+ delete self[key];
1875
+
1876
+ deleted = true;
1877
+ }
1878
+ }
1879
+ }
1880
+
1881
+ if (utils$1.isArray(header)) {
1882
+ header.forEach(deleteHeader);
1883
+ } else {
1884
+ deleteHeader(header);
1885
+ }
1886
+
1887
+ return deleted;
1888
+ }
1889
+
1890
+ clear(matcher) {
1891
+ const keys = Object.keys(this);
1892
+ let i = keys.length;
1893
+ let deleted = false;
1894
+
1895
+ while (i--) {
1896
+ const key = keys[i];
1897
+ if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1898
+ delete this[key];
1899
+ deleted = true;
1900
+ }
1901
+ }
1902
+
1903
+ return deleted;
1904
+ }
1905
+
1906
+ normalize(format) {
1907
+ const self = this;
1908
+ const headers = {};
1909
+
1910
+ utils$1.forEach(this, (value, header) => {
1911
+ const key = utils$1.findKey(headers, header);
1912
+
1913
+ if (key) {
1914
+ self[key] = normalizeValue(value);
1915
+ delete self[header];
1916
+ return;
1917
+ }
1918
+
1919
+ const normalized = format ? formatHeader(header) : String(header).trim();
1920
+
1921
+ if (normalized !== header) {
1922
+ delete self[header];
1923
+ }
1924
+
1925
+ self[normalized] = normalizeValue(value);
1926
+
1927
+ headers[normalized] = true;
1928
+ });
1929
+
1930
+ return this;
1931
+ }
1932
+
1933
+ concat(...targets) {
1934
+ return this.constructor.concat(this, ...targets);
1935
+ }
1936
+
1937
+ toJSON(asStrings) {
1938
+ const obj = Object.create(null);
1939
+
1940
+ utils$1.forEach(this, (value, header) => {
1941
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1942
+ });
1943
+
1944
+ return obj;
1945
+ }
1946
+
1947
+ [Symbol.iterator]() {
1948
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1949
+ }
1950
+
1951
+ toString() {
1952
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1953
+ }
1954
+
1955
+ getSetCookie() {
1956
+ return this.get("set-cookie") || [];
1957
+ }
1958
+
1959
+ get [Symbol.toStringTag]() {
1960
+ return 'AxiosHeaders';
1961
+ }
1962
+
1963
+ static from(thing) {
1964
+ return thing instanceof this ? thing : new this(thing);
1965
+ }
1966
+
1967
+ static concat(first, ...targets) {
1968
+ const computed = new this(first);
1969
+
1970
+ targets.forEach((target) => computed.set(target));
1971
+
1972
+ return computed;
1973
+ }
1974
+
1975
+ static accessor(header) {
1976
+ const internals = this[$internals] = (this[$internals] = {
1977
+ accessors: {}
1978
+ });
1979
+
1980
+ const accessors = internals.accessors;
1981
+ const prototype = this.prototype;
1982
+
1983
+ function defineAccessor(_header) {
1984
+ const lHeader = normalizeHeader(_header);
1985
+
1986
+ if (!accessors[lHeader]) {
1987
+ buildAccessors(prototype, _header);
1988
+ accessors[lHeader] = true;
1989
+ }
1990
+ }
1991
+
1992
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1993
+
1994
+ return this;
1995
+ }
1996
+ }
1997
+
1998
+ AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1999
+
2000
+ // reserved names hotfix
2001
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
2002
+ let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
2003
+ return {
2004
+ get: () => value,
2005
+ set(headerValue) {
2006
+ this[mapped] = headerValue;
2007
+ }
2008
+ }
2009
+ });
2010
+
2011
+ utils$1.freezeMethods(AxiosHeaders);
2012
+
2013
+ var AxiosHeaders$1 = AxiosHeaders;
2014
+
2015
+ /**
2016
+ * Transform the data for a request or a response
2017
+ *
2018
+ * @param {Array|Function} fns A single function or Array of functions
2019
+ * @param {?Object} response The response object
2020
+ *
2021
+ * @returns {*} The resulting transformed data
2022
+ */
2023
+ function transformData(fns, response) {
2024
+ const config = this || defaults$1;
2025
+ const context = response || config;
2026
+ const headers = AxiosHeaders$1.from(context.headers);
2027
+ let data = context.data;
2028
+
2029
+ utils$1.forEach(fns, function transform(fn) {
2030
+ data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
2031
+ });
2032
+
2033
+ headers.normalize();
2034
+
2035
+ return data;
2036
+ }
2037
+
2038
+ function isCancel(value) {
2039
+ return !!(value && value.__CANCEL__);
2040
+ }
2041
+
2042
+ /**
2043
+ * A `CanceledError` is an object that is thrown when an operation is canceled.
2044
+ *
2045
+ * @param {string=} message The message.
2046
+ * @param {Object=} config The config.
2047
+ * @param {Object=} request The request.
2048
+ *
2049
+ * @returns {CanceledError} The created error.
2050
+ */
2051
+ function CanceledError(message, config, request) {
2052
+ // eslint-disable-next-line no-eq-null,eqeqeq
2053
+ AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
2054
+ this.name = 'CanceledError';
2055
+ }
2056
+
2057
+ utils$1.inherits(CanceledError, AxiosError, {
2058
+ __CANCEL__: true
2059
+ });
2060
+
2061
+ /**
2062
+ * Resolve or reject a Promise based on response status.
2063
+ *
2064
+ * @param {Function} resolve A function that resolves the promise.
2065
+ * @param {Function} reject A function that rejects the promise.
2066
+ * @param {object} response The response.
2067
+ *
2068
+ * @returns {object} The response.
2069
+ */
2070
+ function settle(resolve, reject, response) {
2071
+ const validateStatus = response.config.validateStatus;
2072
+ if (!response.status || !validateStatus || validateStatus(response.status)) {
2073
+ resolve(response);
2074
+ } else {
2075
+ reject(new AxiosError(
2076
+ 'Request failed with status code ' + response.status,
2077
+ [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2078
+ response.config,
2079
+ response.request,
2080
+ response
2081
+ ));
2082
+ }
2083
+ }
2084
+
2085
+ function parseProtocol(url) {
2086
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2087
+ return match && match[1] || '';
2088
+ }
2089
+
2090
+ /**
2091
+ * Calculate data maxRate
2092
+ * @param {Number} [samplesCount= 10]
2093
+ * @param {Number} [min= 1000]
2094
+ * @returns {Function}
2095
+ */
2096
+ function speedometer(samplesCount, min) {
2097
+ samplesCount = samplesCount || 10;
2098
+ const bytes = new Array(samplesCount);
2099
+ const timestamps = new Array(samplesCount);
2100
+ let head = 0;
2101
+ let tail = 0;
2102
+ let firstSampleTS;
2103
+
2104
+ min = min !== undefined ? min : 1000;
2105
+
2106
+ return function push(chunkLength) {
2107
+ const now = Date.now();
2108
+
2109
+ const startedAt = timestamps[tail];
2110
+
2111
+ if (!firstSampleTS) {
2112
+ firstSampleTS = now;
2113
+ }
2114
+
2115
+ bytes[head] = chunkLength;
2116
+ timestamps[head] = now;
2117
+
2118
+ let i = tail;
2119
+ let bytesCount = 0;
2120
+
2121
+ while (i !== head) {
2122
+ bytesCount += bytes[i++];
2123
+ i = i % samplesCount;
2124
+ }
2125
+
2126
+ head = (head + 1) % samplesCount;
2127
+
2128
+ if (head === tail) {
2129
+ tail = (tail + 1) % samplesCount;
2130
+ }
2131
+
2132
+ if (now - firstSampleTS < min) {
2133
+ return;
2134
+ }
2135
+
2136
+ const passed = startedAt && now - startedAt;
2137
+
2138
+ return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2139
+ };
2140
+ }
2141
+
2142
+ /**
2143
+ * Throttle decorator
2144
+ * @param {Function} fn
2145
+ * @param {Number} freq
2146
+ * @return {Function}
2147
+ */
2148
+ function throttle(fn, freq) {
2149
+ let timestamp = 0;
2150
+ let threshold = 1000 / freq;
2151
+ let lastArgs;
2152
+ let timer;
2153
+
2154
+ const invoke = (args, now = Date.now()) => {
2155
+ timestamp = now;
2156
+ lastArgs = null;
2157
+ if (timer) {
2158
+ clearTimeout(timer);
2159
+ timer = null;
2160
+ }
2161
+ fn(...args);
2162
+ };
2163
+
2164
+ const throttled = (...args) => {
2165
+ const now = Date.now();
2166
+ const passed = now - timestamp;
2167
+ if ( passed >= threshold) {
2168
+ invoke(args, now);
2169
+ } else {
2170
+ lastArgs = args;
2171
+ if (!timer) {
2172
+ timer = setTimeout(() => {
2173
+ timer = null;
2174
+ invoke(lastArgs);
2175
+ }, threshold - passed);
2176
+ }
2177
+ }
2178
+ };
2179
+
2180
+ const flush = () => lastArgs && invoke(lastArgs);
2181
+
2182
+ return [throttled, flush];
2183
+ }
2184
+
2185
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2186
+ let bytesNotified = 0;
2187
+ const _speedometer = speedometer(50, 250);
2188
+
2189
+ return throttle(e => {
2190
+ const loaded = e.loaded;
2191
+ const total = e.lengthComputable ? e.total : undefined;
2192
+ const progressBytes = loaded - bytesNotified;
2193
+ const rate = _speedometer(progressBytes);
2194
+ const inRange = loaded <= total;
2195
+
2196
+ bytesNotified = loaded;
2197
+
2198
+ const data = {
2199
+ loaded,
2200
+ total,
2201
+ progress: total ? (loaded / total) : undefined,
2202
+ bytes: progressBytes,
2203
+ rate: rate ? rate : undefined,
2204
+ estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2205
+ event: e,
2206
+ lengthComputable: total != null,
2207
+ [isDownloadStream ? 'download' : 'upload']: true
2208
+ };
2209
+
2210
+ listener(data);
2211
+ }, freq);
2212
+ };
2213
+
2214
+ const progressEventDecorator = (total, throttled) => {
2215
+ const lengthComputable = total != null;
2216
+
2217
+ return [(loaded) => throttled[0]({
2218
+ lengthComputable,
2219
+ total,
2220
+ loaded
2221
+ }), throttled[1]];
2222
+ };
2223
+
2224
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2225
+
2226
+ var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
2227
+ url = new URL(url, platform.origin);
2228
+
2229
+ return (
2230
+ origin.protocol === url.protocol &&
2231
+ origin.host === url.host &&
2232
+ (isMSIE || origin.port === url.port)
2233
+ );
2234
+ })(
2235
+ new URL(platform.origin),
2236
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
2237
+ ) : () => true;
2238
+
2239
+ var cookies = platform.hasStandardBrowserEnv ?
2240
+
2241
+ // Standard browser envs support document.cookie
2242
+ {
2243
+ write(name, value, expires, path, domain, secure, sameSite) {
2244
+ if (typeof document === 'undefined') return;
2245
+
2246
+ const cookie = [`${name}=${encodeURIComponent(value)}`];
2247
+
2248
+ if (utils$1.isNumber(expires)) {
2249
+ cookie.push(`expires=${new Date(expires).toUTCString()}`);
2250
+ }
2251
+ if (utils$1.isString(path)) {
2252
+ cookie.push(`path=${path}`);
2253
+ }
2254
+ if (utils$1.isString(domain)) {
2255
+ cookie.push(`domain=${domain}`);
2256
+ }
2257
+ if (secure === true) {
2258
+ cookie.push('secure');
2259
+ }
2260
+ if (utils$1.isString(sameSite)) {
2261
+ cookie.push(`SameSite=${sameSite}`);
2262
+ }
2263
+
2264
+ document.cookie = cookie.join('; ');
2265
+ },
2266
+
2267
+ read(name) {
2268
+ if (typeof document === 'undefined') return null;
2269
+ const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
2270
+ return match ? decodeURIComponent(match[1]) : null;
2271
+ },
2272
+
2273
+ remove(name) {
2274
+ this.write(name, '', Date.now() - 86400000, '/');
2275
+ }
2276
+ }
2277
+
2278
+ :
2279
+
2280
+ // Non-standard browser env (web workers, react-native) lack needed support.
2281
+ {
2282
+ write() {},
2283
+ read() {
2284
+ return null;
2285
+ },
2286
+ remove() {}
2287
+ };
2288
+
2289
+ /**
2290
+ * Determines whether the specified URL is absolute
2291
+ *
2292
+ * @param {string} url The URL to test
2293
+ *
2294
+ * @returns {boolean} True if the specified URL is absolute, otherwise false
2295
+ */
2296
+ function isAbsoluteURL(url) {
2297
+ // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2298
+ // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2299
+ // by any combination of letters, digits, plus, period, or hyphen.
2300
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2301
+ }
2302
+
2303
+ /**
2304
+ * Creates a new URL by combining the specified URLs
2305
+ *
2306
+ * @param {string} baseURL The base URL
2307
+ * @param {string} relativeURL The relative URL
2308
+ *
2309
+ * @returns {string} The combined URL
2310
+ */
2311
+ function combineURLs(baseURL, relativeURL) {
2312
+ return relativeURL
2313
+ ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2314
+ : baseURL;
2315
+ }
2316
+
2317
+ /**
2318
+ * Creates a new URL by combining the baseURL with the requestedURL,
2319
+ * only when the requestedURL is not already an absolute URL.
2320
+ * If the requestURL is absolute, this function returns the requestedURL untouched.
2321
+ *
2322
+ * @param {string} baseURL The base URL
2323
+ * @param {string} requestedURL Absolute or relative URL to combine
2324
+ *
2325
+ * @returns {string} The combined full path
2326
+ */
2327
+ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2328
+ let isRelativeUrl = !isAbsoluteURL(requestedURL);
2329
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2330
+ return combineURLs(baseURL, requestedURL);
2331
+ }
2332
+ return requestedURL;
2333
+ }
2334
+
2335
+ const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
2336
+
2337
+ /**
2338
+ * Config-specific merge-function which creates a new config-object
2339
+ * by merging two configuration objects together.
2340
+ *
2341
+ * @param {Object} config1
2342
+ * @param {Object} config2
2343
+ *
2344
+ * @returns {Object} New object resulting from merging config2 to config1
2345
+ */
2346
+ function mergeConfig(config1, config2) {
2347
+ // eslint-disable-next-line no-param-reassign
2348
+ config2 = config2 || {};
2349
+ const config = {};
2350
+
2351
+ function getMergedValue(target, source, prop, caseless) {
2352
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
2353
+ return utils$1.merge.call({caseless}, target, source);
2354
+ } else if (utils$1.isPlainObject(source)) {
2355
+ return utils$1.merge({}, source);
2356
+ } else if (utils$1.isArray(source)) {
2357
+ return source.slice();
2358
+ }
2359
+ return source;
2360
+ }
2361
+
2362
+ // eslint-disable-next-line consistent-return
2363
+ function mergeDeepProperties(a, b, prop, caseless) {
2364
+ if (!utils$1.isUndefined(b)) {
2365
+ return getMergedValue(a, b, prop, caseless);
2366
+ } else if (!utils$1.isUndefined(a)) {
2367
+ return getMergedValue(undefined, a, prop, caseless);
2368
+ }
2369
+ }
2370
+
2371
+ // eslint-disable-next-line consistent-return
2372
+ function valueFromConfig2(a, b) {
2373
+ if (!utils$1.isUndefined(b)) {
2374
+ return getMergedValue(undefined, b);
2375
+ }
2376
+ }
2377
+
2378
+ // eslint-disable-next-line consistent-return
2379
+ function defaultToConfig2(a, b) {
2380
+ if (!utils$1.isUndefined(b)) {
2381
+ return getMergedValue(undefined, b);
2382
+ } else if (!utils$1.isUndefined(a)) {
2383
+ return getMergedValue(undefined, a);
2384
+ }
2385
+ }
2386
+
2387
+ // eslint-disable-next-line consistent-return
2388
+ function mergeDirectKeys(a, b, prop) {
2389
+ if (prop in config2) {
2390
+ return getMergedValue(a, b);
2391
+ } else if (prop in config1) {
2392
+ return getMergedValue(undefined, a);
2393
+ }
2394
+ }
2395
+
2396
+ const mergeMap = {
2397
+ url: valueFromConfig2,
2398
+ method: valueFromConfig2,
2399
+ data: valueFromConfig2,
2400
+ baseURL: defaultToConfig2,
2401
+ transformRequest: defaultToConfig2,
2402
+ transformResponse: defaultToConfig2,
2403
+ paramsSerializer: defaultToConfig2,
2404
+ timeout: defaultToConfig2,
2405
+ timeoutMessage: defaultToConfig2,
2406
+ withCredentials: defaultToConfig2,
2407
+ withXSRFToken: defaultToConfig2,
2408
+ adapter: defaultToConfig2,
2409
+ responseType: defaultToConfig2,
2410
+ xsrfCookieName: defaultToConfig2,
2411
+ xsrfHeaderName: defaultToConfig2,
2412
+ onUploadProgress: defaultToConfig2,
2413
+ onDownloadProgress: defaultToConfig2,
2414
+ decompress: defaultToConfig2,
2415
+ maxContentLength: defaultToConfig2,
2416
+ maxBodyLength: defaultToConfig2,
2417
+ beforeRedirect: defaultToConfig2,
2418
+ transport: defaultToConfig2,
2419
+ httpAgent: defaultToConfig2,
2420
+ httpsAgent: defaultToConfig2,
2421
+ cancelToken: defaultToConfig2,
2422
+ socketPath: defaultToConfig2,
2423
+ responseEncoding: defaultToConfig2,
2424
+ validateStatus: mergeDirectKeys,
2425
+ headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
2426
+ };
2427
+
2428
+ utils$1.forEach(Object.keys({...config1, ...config2}), function computeConfigValue(prop) {
2429
+ const merge = mergeMap[prop] || mergeDeepProperties;
2430
+ const configValue = merge(config1[prop], config2[prop], prop);
2431
+ (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2432
+ });
2433
+
2434
+ return config;
2435
+ }
2436
+
2437
+ var resolveConfig = (config) => {
2438
+ const newConfig = mergeConfig({}, config);
2439
+
2440
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
2441
+
2442
+ newConfig.headers = headers = AxiosHeaders$1.from(headers);
2443
+
2444
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
2445
+
2446
+ // HTTP basic authentication
2447
+ if (auth) {
2448
+ headers.set('Authorization', 'Basic ' +
2449
+ btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
2450
+ );
2451
+ }
2452
+
2453
+ if (utils$1.isFormData(data)) {
2454
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2455
+ headers.setContentType(undefined); // browser handles it
2456
+ } else if (utils$1.isFunction(data.getHeaders)) {
2457
+ // Node.js FormData (like form-data package)
2458
+ const formHeaders = data.getHeaders();
2459
+ // Only set safe headers to avoid overwriting security headers
2460
+ const allowedHeaders = ['content-type', 'content-length'];
2461
+ Object.entries(formHeaders).forEach(([key, val]) => {
2462
+ if (allowedHeaders.includes(key.toLowerCase())) {
2463
+ headers.set(key, val);
2464
+ }
2465
+ });
2466
+ }
2467
+ }
2468
+
2469
+ // Add xsrf header
2470
+ // This is only done if running in a standard browser environment.
2471
+ // Specifically not if we're in a web worker, or react-native.
2472
+
2473
+ if (platform.hasStandardBrowserEnv) {
2474
+ withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
2475
+
2476
+ if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
2477
+ // Add xsrf header
2478
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
2479
+
2480
+ if (xsrfValue) {
2481
+ headers.set(xsrfHeaderName, xsrfValue);
2482
+ }
2483
+ }
2484
+ }
2485
+
2486
+ return newConfig;
2487
+ };
2488
+
2489
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
2490
+
2491
+ var xhrAdapter = isXHRAdapterSupported && function (config) {
2492
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
2493
+ const _config = resolveConfig(config);
2494
+ let requestData = _config.data;
2495
+ const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
2496
+ let {responseType, onUploadProgress, onDownloadProgress} = _config;
2497
+ let onCanceled;
2498
+ let uploadThrottled, downloadThrottled;
2499
+ let flushUpload, flushDownload;
2500
+
2501
+ function done() {
2502
+ flushUpload && flushUpload(); // flush events
2503
+ flushDownload && flushDownload(); // flush events
2504
+
2505
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
2506
+
2507
+ _config.signal && _config.signal.removeEventListener('abort', onCanceled);
2508
+ }
2509
+
2510
+ let request = new XMLHttpRequest();
2511
+
2512
+ request.open(_config.method.toUpperCase(), _config.url, true);
2513
+
2514
+ // Set the request timeout in MS
2515
+ request.timeout = _config.timeout;
2516
+
2517
+ function onloadend() {
2518
+ if (!request) {
2519
+ return;
2520
+ }
2521
+ // Prepare the response
2522
+ const responseHeaders = AxiosHeaders$1.from(
2523
+ 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2524
+ );
2525
+ const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2526
+ request.responseText : request.response;
2527
+ const response = {
2528
+ data: responseData,
2529
+ status: request.status,
2530
+ statusText: request.statusText,
2531
+ headers: responseHeaders,
2532
+ config,
2533
+ request
2534
+ };
2535
+
2536
+ settle(function _resolve(value) {
2537
+ resolve(value);
2538
+ done();
2539
+ }, function _reject(err) {
2540
+ reject(err);
2541
+ done();
2542
+ }, response);
2543
+
2544
+ // Clean up request
2545
+ request = null;
2546
+ }
2547
+
2548
+ if ('onloadend' in request) {
2549
+ // Use onloadend if available
2550
+ request.onloadend = onloadend;
2551
+ } else {
2552
+ // Listen for ready state to emulate onloadend
2553
+ request.onreadystatechange = function handleLoad() {
2554
+ if (!request || request.readyState !== 4) {
2555
+ return;
2556
+ }
2557
+
2558
+ // The request errored out and we didn't get a response, this will be
2559
+ // handled by onerror instead
2560
+ // With one exception: request that using file: protocol, most browsers
2561
+ // will return status as 0 even though it's a successful request
2562
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2563
+ return;
2564
+ }
2565
+ // readystate handler is calling before onerror or ontimeout handlers,
2566
+ // so we should call onloadend on the next 'tick'
2567
+ setTimeout(onloadend);
2568
+ };
2569
+ }
2570
+
2571
+ // Handle browser request cancellation (as opposed to a manual cancellation)
2572
+ request.onabort = function handleAbort() {
2573
+ if (!request) {
2574
+ return;
2575
+ }
2576
+
2577
+ reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
2578
+
2579
+ // Clean up request
2580
+ request = null;
2581
+ };
2582
+
2583
+ // Handle low level network errors
2584
+ request.onerror = function handleError(event) {
2585
+ // Browsers deliver a ProgressEvent in XHR onerror
2586
+ // (message may be empty; when present, surface it)
2587
+ // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
2588
+ const msg = event && event.message ? event.message : 'Network Error';
2589
+ const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
2590
+ // attach the underlying event for consumers who want details
2591
+ err.event = event || null;
2592
+ reject(err);
2593
+ request = null;
2594
+ };
2595
+
2596
+ // Handle timeout
2597
+ request.ontimeout = function handleTimeout() {
2598
+ let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
2599
+ const transitional = _config.transitional || transitionalDefaults;
2600
+ if (_config.timeoutErrorMessage) {
2601
+ timeoutErrorMessage = _config.timeoutErrorMessage;
2602
+ }
2603
+ reject(new AxiosError(
2604
+ timeoutErrorMessage,
2605
+ transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
2606
+ config,
2607
+ request));
2608
+
2609
+ // Clean up request
2610
+ request = null;
2611
+ };
2612
+
2613
+ // Remove Content-Type if data is undefined
2614
+ requestData === undefined && requestHeaders.setContentType(null);
2615
+
2616
+ // Add headers to the request
2617
+ if ('setRequestHeader' in request) {
2618
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2619
+ request.setRequestHeader(key, val);
2620
+ });
2621
+ }
2622
+
2623
+ // Add withCredentials to request if needed
2624
+ if (!utils$1.isUndefined(_config.withCredentials)) {
2625
+ request.withCredentials = !!_config.withCredentials;
2626
+ }
2627
+
2628
+ // Add responseType to request if needed
2629
+ if (responseType && responseType !== 'json') {
2630
+ request.responseType = _config.responseType;
2631
+ }
2632
+
2633
+ // Handle progress if needed
2634
+ if (onDownloadProgress) {
2635
+ ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
2636
+ request.addEventListener('progress', downloadThrottled);
2637
+ }
2638
+
2639
+ // Not all browsers support upload events
2640
+ if (onUploadProgress && request.upload) {
2641
+ ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
2642
+
2643
+ request.upload.addEventListener('progress', uploadThrottled);
2644
+
2645
+ request.upload.addEventListener('loadend', flushUpload);
2646
+ }
2647
+
2648
+ if (_config.cancelToken || _config.signal) {
2649
+ // Handle cancellation
2650
+ // eslint-disable-next-line func-names
2651
+ onCanceled = cancel => {
2652
+ if (!request) {
2653
+ return;
2654
+ }
2655
+ reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
2656
+ request.abort();
2657
+ request = null;
2658
+ };
2659
+
2660
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
2661
+ if (_config.signal) {
2662
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
2663
+ }
2664
+ }
2665
+
2666
+ const protocol = parseProtocol(_config.url);
2667
+
2668
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
2669
+ reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
2670
+ return;
2671
+ }
2672
+
2673
+
2674
+ // Send the request
2675
+ request.send(requestData || null);
2676
+ });
2677
+ };
2678
+
2679
+ const composeSignals = (signals, timeout) => {
2680
+ const {length} = (signals = signals ? signals.filter(Boolean) : []);
2681
+
2682
+ if (timeout || length) {
2683
+ let controller = new AbortController();
2684
+
2685
+ let aborted;
2686
+
2687
+ const onabort = function (reason) {
2688
+ if (!aborted) {
2689
+ aborted = true;
2690
+ unsubscribe();
2691
+ const err = reason instanceof Error ? reason : this.reason;
2692
+ controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
2693
+ }
2694
+ };
2695
+
2696
+ let timer = timeout && setTimeout(() => {
2697
+ timer = null;
2698
+ onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
2699
+ }, timeout);
2700
+
2701
+ const unsubscribe = () => {
2702
+ if (signals) {
2703
+ timer && clearTimeout(timer);
2704
+ timer = null;
2705
+ signals.forEach(signal => {
2706
+ signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
2707
+ });
2708
+ signals = null;
2709
+ }
2710
+ };
2711
+
2712
+ signals.forEach((signal) => signal.addEventListener('abort', onabort));
2713
+
2714
+ const {signal} = controller;
2715
+
2716
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
2717
+
2718
+ return signal;
2719
+ }
2720
+ };
2721
+
2722
+ var composeSignals$1 = composeSignals;
2723
+
2724
+ const streamChunk = function* (chunk, chunkSize) {
2725
+ let len = chunk.byteLength;
2726
+
2727
+ if (!chunkSize || len < chunkSize) {
2728
+ yield chunk;
2729
+ return;
2730
+ }
2731
+
2732
+ let pos = 0;
2733
+ let end;
2734
+
2735
+ while (pos < len) {
2736
+ end = pos + chunkSize;
2737
+ yield chunk.slice(pos, end);
2738
+ pos = end;
2739
+ }
2740
+ };
2741
+
2742
+ const readBytes = async function* (iterable, chunkSize) {
2743
+ for await (const chunk of readStream(iterable)) {
2744
+ yield* streamChunk(chunk, chunkSize);
2745
+ }
2746
+ };
2747
+
2748
+ const readStream = async function* (stream) {
2749
+ if (stream[Symbol.asyncIterator]) {
2750
+ yield* stream;
2751
+ return;
2752
+ }
2753
+
2754
+ const reader = stream.getReader();
2755
+ try {
2756
+ for (;;) {
2757
+ const {done, value} = await reader.read();
2758
+ if (done) {
2759
+ break;
2760
+ }
2761
+ yield value;
2762
+ }
2763
+ } finally {
2764
+ await reader.cancel();
2765
+ }
2766
+ };
2767
+
2768
+ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
2769
+ const iterator = readBytes(stream, chunkSize);
2770
+
2771
+ let bytes = 0;
2772
+ let done;
2773
+ let _onFinish = (e) => {
2774
+ if (!done) {
2775
+ done = true;
2776
+ onFinish && onFinish(e);
2777
+ }
2778
+ };
2779
+
2780
+ return new ReadableStream({
2781
+ async pull(controller) {
2782
+ try {
2783
+ const {done, value} = await iterator.next();
2784
+
2785
+ if (done) {
2786
+ _onFinish();
2787
+ controller.close();
2788
+ return;
2789
+ }
2790
+
2791
+ let len = value.byteLength;
2792
+ if (onProgress) {
2793
+ let loadedBytes = bytes += len;
2794
+ onProgress(loadedBytes);
2795
+ }
2796
+ controller.enqueue(new Uint8Array(value));
2797
+ } catch (err) {
2798
+ _onFinish(err);
2799
+ throw err;
2800
+ }
2801
+ },
2802
+ cancel(reason) {
2803
+ _onFinish(reason);
2804
+ return iterator.return();
2805
+ }
2806
+ }, {
2807
+ highWaterMark: 2
2808
+ })
2809
+ };
2810
+
2811
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
2812
+
2813
+ const {isFunction} = utils$1;
2814
+
2815
+ const globalFetchAPI = (({Request, Response}) => ({
2816
+ Request, Response
2817
+ }))(utils$1.global);
2818
+
2819
+ const {
2820
+ ReadableStream: ReadableStream$1, TextEncoder
2821
+ } = utils$1.global;
2822
+
2823
+
2824
+ const test = (fn, ...args) => {
2825
+ try {
2826
+ return !!fn(...args);
2827
+ } catch (e) {
2828
+ return false
2829
+ }
2830
+ };
2831
+
2832
+ const factory = (env) => {
2833
+ env = utils$1.merge.call({
2834
+ skipUndefined: true
2835
+ }, globalFetchAPI, env);
2836
+
2837
+ const {fetch: envFetch, Request, Response} = env;
2838
+ const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
2839
+ const isRequestSupported = isFunction(Request);
2840
+ const isResponseSupported = isFunction(Response);
2841
+
2842
+ if (!isFetchSupported) {
2843
+ return false;
2844
+ }
2845
+
2846
+ const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
2847
+
2848
+ const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
2849
+ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
2850
+ async (str) => new Uint8Array(await new Request(str).arrayBuffer())
2851
+ );
2852
+
2853
+ const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
2854
+ let duplexAccessed = false;
2855
+
2856
+ const hasContentType = new Request(platform.origin, {
2857
+ body: new ReadableStream$1(),
2858
+ method: 'POST',
2859
+ get duplex() {
2860
+ duplexAccessed = true;
2861
+ return 'half';
2862
+ },
2863
+ }).headers.has('Content-Type');
2864
+
2865
+ return duplexAccessed && !hasContentType;
2866
+ });
2867
+
2868
+ const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
2869
+ test(() => utils$1.isReadableStream(new Response('').body));
2870
+
2871
+ const resolvers = {
2872
+ stream: supportsResponseStream && ((res) => res.body)
2873
+ };
2874
+
2875
+ isFetchSupported && ((() => {
2876
+ ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
2877
+ !resolvers[type] && (resolvers[type] = (res, config) => {
2878
+ let method = res && res[type];
2879
+
2880
+ if (method) {
2881
+ return method.call(res);
2882
+ }
2883
+
2884
+ throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
2885
+ });
2886
+ });
2887
+ })());
2888
+
2889
+ const getBodyLength = async (body) => {
2890
+ if (body == null) {
2891
+ return 0;
2892
+ }
2893
+
2894
+ if (utils$1.isBlob(body)) {
2895
+ return body.size;
2896
+ }
2897
+
2898
+ if (utils$1.isSpecCompliantForm(body)) {
2899
+ const _request = new Request(platform.origin, {
2900
+ method: 'POST',
2901
+ body,
2902
+ });
2903
+ return (await _request.arrayBuffer()).byteLength;
2904
+ }
2905
+
2906
+ if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2907
+ return body.byteLength;
2908
+ }
2909
+
2910
+ if (utils$1.isURLSearchParams(body)) {
2911
+ body = body + '';
2912
+ }
2913
+
2914
+ if (utils$1.isString(body)) {
2915
+ return (await encodeText(body)).byteLength;
2916
+ }
2917
+ };
2918
+
2919
+ const resolveBodyLength = async (headers, body) => {
2920
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
2921
+
2922
+ return length == null ? getBodyLength(body) : length;
2923
+ };
2924
+
2925
+ return async (config) => {
2926
+ let {
2927
+ url,
2928
+ method,
2929
+ data,
2930
+ signal,
2931
+ cancelToken,
2932
+ timeout,
2933
+ onDownloadProgress,
2934
+ onUploadProgress,
2935
+ responseType,
2936
+ headers,
2937
+ withCredentials = 'same-origin',
2938
+ fetchOptions
2939
+ } = resolveConfig(config);
2940
+
2941
+ let _fetch = envFetch || fetch;
2942
+
2943
+ responseType = responseType ? (responseType + '').toLowerCase() : 'text';
2944
+
2945
+ let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2946
+
2947
+ let request = null;
2948
+
2949
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2950
+ composedSignal.unsubscribe();
2951
+ });
2952
+
2953
+ let requestContentLength;
2954
+
2955
+ try {
2956
+ if (
2957
+ onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
2958
+ (requestContentLength = await resolveBodyLength(headers, data)) !== 0
2959
+ ) {
2960
+ let _request = new Request(url, {
2961
+ method: 'POST',
2962
+ body: data,
2963
+ duplex: "half"
2964
+ });
2965
+
2966
+ let contentTypeHeader;
2967
+
2968
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
2969
+ headers.setContentType(contentTypeHeader);
2970
+ }
2971
+
2972
+ if (_request.body) {
2973
+ const [onProgress, flush] = progressEventDecorator(
2974
+ requestContentLength,
2975
+ progressEventReducer(asyncDecorator(onUploadProgress))
2976
+ );
2977
+
2978
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2979
+ }
2980
+ }
2981
+
2982
+ if (!utils$1.isString(withCredentials)) {
2983
+ withCredentials = withCredentials ? 'include' : 'omit';
2984
+ }
2985
+
2986
+ // Cloudflare Workers throws when credentials are defined
2987
+ // see https://github.com/cloudflare/workerd/issues/902
2988
+ const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
2989
+
2990
+ const resolvedOptions = {
2991
+ ...fetchOptions,
2992
+ signal: composedSignal,
2993
+ method: method.toUpperCase(),
2994
+ headers: headers.normalize().toJSON(),
2995
+ body: data,
2996
+ duplex: "half",
2997
+ credentials: isCredentialsSupported ? withCredentials : undefined
2998
+ };
2999
+
3000
+ request = isRequestSupported && new Request(url, resolvedOptions);
3001
+
3002
+ let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
3003
+
3004
+ const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
3005
+
3006
+ if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
3007
+ const options = {};
3008
+
3009
+ ['status', 'statusText', 'headers'].forEach(prop => {
3010
+ options[prop] = response[prop];
3011
+ });
3012
+
3013
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
3014
+
3015
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
3016
+ responseContentLength,
3017
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
3018
+ ) || [];
3019
+
3020
+ response = new Response(
3021
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3022
+ flush && flush();
3023
+ unsubscribe && unsubscribe();
3024
+ }),
3025
+ options
3026
+ );
3027
+ }
3028
+
3029
+ responseType = responseType || 'text';
3030
+
3031
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
3032
+
3033
+ !isStreamResponse && unsubscribe && unsubscribe();
3034
+
3035
+ return await new Promise((resolve, reject) => {
3036
+ settle(resolve, reject, {
3037
+ data: responseData,
3038
+ headers: AxiosHeaders$1.from(response.headers),
3039
+ status: response.status,
3040
+ statusText: response.statusText,
3041
+ config,
3042
+ request
3043
+ });
3044
+ })
3045
+ } catch (err) {
3046
+ unsubscribe && unsubscribe();
3047
+
3048
+ if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
3049
+ throw Object.assign(
3050
+ new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
3051
+ {
3052
+ cause: err.cause || err
3053
+ }
3054
+ )
3055
+ }
3056
+
3057
+ throw AxiosError.from(err, err && err.code, config, request);
3058
+ }
3059
+ }
3060
+ };
3061
+
3062
+ const seedCache = new Map();
3063
+
3064
+ const getFetch = (config) => {
3065
+ let env = (config && config.env) || {};
3066
+ const {fetch, Request, Response} = env;
3067
+ const seeds = [
3068
+ Request, Response, fetch
3069
+ ];
3070
+
3071
+ let len = seeds.length, i = len,
3072
+ seed, target, map = seedCache;
3073
+
3074
+ while (i--) {
3075
+ seed = seeds[i];
3076
+ target = map.get(seed);
3077
+
3078
+ target === undefined && map.set(seed, target = (i ? new Map() : factory(env)));
3079
+
3080
+ map = target;
3081
+ }
3082
+
3083
+ return target;
3084
+ };
3085
+
3086
+ getFetch();
3087
+
3088
+ /**
3089
+ * Known adapters mapping.
3090
+ * Provides environment-specific adapters for Axios:
3091
+ * - `http` for Node.js
3092
+ * - `xhr` for browsers
3093
+ * - `fetch` for fetch API-based requests
3094
+ *
3095
+ * @type {Object<string, Function|Object>}
3096
+ */
3097
+ const knownAdapters = {
3098
+ http: httpAdapter,
3099
+ xhr: xhrAdapter,
3100
+ fetch: {
3101
+ get: getFetch,
3102
+ }
3103
+ };
3104
+
3105
+ // Assign adapter names for easier debugging and identification
3106
+ utils$1.forEach(knownAdapters, (fn, value) => {
3107
+ if (fn) {
3108
+ try {
3109
+ Object.defineProperty(fn, 'name', { value });
3110
+ } catch (e) {
3111
+ // eslint-disable-next-line no-empty
3112
+ }
3113
+ Object.defineProperty(fn, 'adapterName', { value });
3114
+ }
3115
+ });
3116
+
3117
+ /**
3118
+ * Render a rejection reason string for unknown or unsupported adapters
3119
+ *
3120
+ * @param {string} reason
3121
+ * @returns {string}
3122
+ */
3123
+ const renderReason = (reason) => `- ${reason}`;
3124
+
3125
+ /**
3126
+ * Check if the adapter is resolved (function, null, or false)
3127
+ *
3128
+ * @param {Function|null|false} adapter
3129
+ * @returns {boolean}
3130
+ */
3131
+ const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
3132
+
3133
+ /**
3134
+ * Get the first suitable adapter from the provided list.
3135
+ * Tries each adapter in order until a supported one is found.
3136
+ * Throws an AxiosError if no adapter is suitable.
3137
+ *
3138
+ * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
3139
+ * @param {Object} config - Axios request configuration
3140
+ * @throws {AxiosError} If no suitable adapter is available
3141
+ * @returns {Function} The resolved adapter function
3142
+ */
3143
+ function getAdapter(adapters, config) {
3144
+ adapters = utils$1.isArray(adapters) ? adapters : [adapters];
3145
+
3146
+ const { length } = adapters;
3147
+ let nameOrAdapter;
3148
+ let adapter;
3149
+
3150
+ const rejectedReasons = {};
3151
+
3152
+ for (let i = 0; i < length; i++) {
3153
+ nameOrAdapter = adapters[i];
3154
+ let id;
3155
+
3156
+ adapter = nameOrAdapter;
3157
+
3158
+ if (!isResolvedHandle(nameOrAdapter)) {
3159
+ adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
3160
+
3161
+ if (adapter === undefined) {
3162
+ throw new AxiosError(`Unknown adapter '${id}'`);
3163
+ }
3164
+ }
3165
+
3166
+ if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
3167
+ break;
3168
+ }
3169
+
3170
+ rejectedReasons[id || '#' + i] = adapter;
3171
+ }
3172
+
3173
+ if (!adapter) {
3174
+ const reasons = Object.entries(rejectedReasons)
3175
+ .map(([id, state]) => `adapter ${id} ` +
3176
+ (state === false ? 'is not supported by the environment' : 'is not available in the build')
3177
+ );
3178
+
3179
+ let s = length ?
3180
+ (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
3181
+ 'as no adapter specified';
3182
+
3183
+ throw new AxiosError(
3184
+ `There is no suitable adapter to dispatch the request ` + s,
3185
+ 'ERR_NOT_SUPPORT'
3186
+ );
3187
+ }
3188
+
3189
+ return adapter;
3190
+ }
3191
+
3192
+ /**
3193
+ * Exports Axios adapters and utility to resolve an adapter
3194
+ */
3195
+ var adapters = {
3196
+ /**
3197
+ * Resolve an adapter from a list of adapter names or functions.
3198
+ * @type {Function}
3199
+ */
3200
+ getAdapter,
3201
+
3202
+ /**
3203
+ * Exposes all known adapters
3204
+ * @type {Object<string, Function|Object>}
3205
+ */
3206
+ adapters: knownAdapters
3207
+ };
3208
+
3209
+ /**
3210
+ * Throws a `CanceledError` if cancellation has been requested.
3211
+ *
3212
+ * @param {Object} config The config that is to be used for the request
3213
+ *
3214
+ * @returns {void}
3215
+ */
3216
+ function throwIfCancellationRequested(config) {
3217
+ if (config.cancelToken) {
3218
+ config.cancelToken.throwIfRequested();
3219
+ }
3220
+
3221
+ if (config.signal && config.signal.aborted) {
3222
+ throw new CanceledError(null, config);
3223
+ }
3224
+ }
3225
+
3226
+ /**
3227
+ * Dispatch a request to the server using the configured adapter.
3228
+ *
3229
+ * @param {object} config The config that is to be used for the request
3230
+ *
3231
+ * @returns {Promise} The Promise to be fulfilled
3232
+ */
3233
+ function dispatchRequest(config) {
3234
+ throwIfCancellationRequested(config);
3235
+
3236
+ config.headers = AxiosHeaders$1.from(config.headers);
3237
+
3238
+ // Transform request data
3239
+ config.data = transformData.call(
3240
+ config,
3241
+ config.transformRequest
3242
+ );
3243
+
3244
+ if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
3245
+ config.headers.setContentType('application/x-www-form-urlencoded', false);
3246
+ }
3247
+
3248
+ const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config);
3249
+
3250
+ return adapter(config).then(function onAdapterResolution(response) {
3251
+ throwIfCancellationRequested(config);
3252
+
3253
+ // Transform response data
3254
+ response.data = transformData.call(
3255
+ config,
3256
+ config.transformResponse,
3257
+ response
3258
+ );
3259
+
3260
+ response.headers = AxiosHeaders$1.from(response.headers);
3261
+
3262
+ return response;
3263
+ }, function onAdapterRejection(reason) {
3264
+ if (!isCancel(reason)) {
3265
+ throwIfCancellationRequested(config);
3266
+
3267
+ // Transform response data
3268
+ if (reason && reason.response) {
3269
+ reason.response.data = transformData.call(
3270
+ config,
3271
+ config.transformResponse,
3272
+ reason.response
3273
+ );
3274
+ reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
3275
+ }
3276
+ }
3277
+
3278
+ return Promise.reject(reason);
3279
+ });
3280
+ }
3281
+
3282
+ const VERSION = "1.13.2";
3283
+
3284
+ const validators$1 = {};
3285
+
3286
+ // eslint-disable-next-line func-names
3287
+ ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
3288
+ validators$1[type] = function validator(thing) {
3289
+ return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
3290
+ };
3291
+ });
3292
+
3293
+ const deprecatedWarnings = {};
3294
+
3295
+ /**
3296
+ * Transitional option validator
3297
+ *
3298
+ * @param {function|boolean?} validator - set to false if the transitional option has been removed
3299
+ * @param {string?} version - deprecated version / removed since version
3300
+ * @param {string?} message - some message with additional info
3301
+ *
3302
+ * @returns {function}
3303
+ */
3304
+ validators$1.transitional = function transitional(validator, version, message) {
3305
+ function formatMessage(opt, desc) {
3306
+ return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
3307
+ }
3308
+
3309
+ // eslint-disable-next-line func-names
3310
+ return (value, opt, opts) => {
3311
+ if (validator === false) {
3312
+ throw new AxiosError(
3313
+ formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
3314
+ AxiosError.ERR_DEPRECATED
3315
+ );
3316
+ }
3317
+
3318
+ if (version && !deprecatedWarnings[opt]) {
3319
+ deprecatedWarnings[opt] = true;
3320
+ // eslint-disable-next-line no-console
3321
+ console.warn(
3322
+ formatMessage(
3323
+ opt,
3324
+ ' has been deprecated since v' + version + ' and will be removed in the near future'
3325
+ )
3326
+ );
3327
+ }
3328
+
3329
+ return validator ? validator(value, opt, opts) : true;
3330
+ };
3331
+ };
3332
+
3333
+ validators$1.spelling = function spelling(correctSpelling) {
3334
+ return (value, opt) => {
3335
+ // eslint-disable-next-line no-console
3336
+ console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
3337
+ return true;
3338
+ }
3339
+ };
3340
+
3341
+ /**
3342
+ * Assert object's properties type
3343
+ *
3344
+ * @param {object} options
3345
+ * @param {object} schema
3346
+ * @param {boolean?} allowUnknown
3347
+ *
3348
+ * @returns {object}
3349
+ */
3350
+
3351
+ function assertOptions(options, schema, allowUnknown) {
3352
+ if (typeof options !== 'object') {
3353
+ throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
3354
+ }
3355
+ const keys = Object.keys(options);
3356
+ let i = keys.length;
3357
+ while (i-- > 0) {
3358
+ const opt = keys[i];
3359
+ const validator = schema[opt];
3360
+ if (validator) {
3361
+ const value = options[opt];
3362
+ const result = value === undefined || validator(value, opt, options);
3363
+ if (result !== true) {
3364
+ throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
3365
+ }
3366
+ continue;
3367
+ }
3368
+ if (allowUnknown !== true) {
3369
+ throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
3370
+ }
3371
+ }
3372
+ }
3373
+
3374
+ var validator = {
3375
+ assertOptions,
3376
+ validators: validators$1
3377
+ };
3378
+
3379
+ const validators = validator.validators;
3380
+
3381
+ /**
3382
+ * Create a new instance of Axios
3383
+ *
3384
+ * @param {Object} instanceConfig The default config for the instance
3385
+ *
3386
+ * @return {Axios} A new instance of Axios
3387
+ */
3388
+ class Axios {
3389
+ constructor(instanceConfig) {
3390
+ this.defaults = instanceConfig || {};
3391
+ this.interceptors = {
3392
+ request: new InterceptorManager$1(),
3393
+ response: new InterceptorManager$1()
3394
+ };
3395
+ }
3396
+
3397
+ /**
3398
+ * Dispatch a request
3399
+ *
3400
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3401
+ * @param {?Object} config
3402
+ *
3403
+ * @returns {Promise} The Promise to be fulfilled
3404
+ */
3405
+ async request(configOrUrl, config) {
3406
+ try {
3407
+ return await this._request(configOrUrl, config);
3408
+ } catch (err) {
3409
+ if (err instanceof Error) {
3410
+ let dummy = {};
3411
+
3412
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
3413
+
3414
+ // slice off the Error: ... line
3415
+ const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
3416
+ try {
3417
+ if (!err.stack) {
3418
+ err.stack = stack;
3419
+ // match without the 2 top stack lines
3420
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
3421
+ err.stack += '\n' + stack;
3422
+ }
3423
+ } catch (e) {
3424
+ // ignore the case where "stack" is an un-writable property
3425
+ }
3426
+ }
3427
+
3428
+ throw err;
3429
+ }
3430
+ }
3431
+
3432
+ _request(configOrUrl, config) {
3433
+ /*eslint no-param-reassign:0*/
3434
+ // Allow for axios('example/url'[, config]) a la fetch API
3435
+ if (typeof configOrUrl === 'string') {
3436
+ config = config || {};
3437
+ config.url = configOrUrl;
3438
+ } else {
3439
+ config = configOrUrl || {};
3440
+ }
3441
+
3442
+ config = mergeConfig(this.defaults, config);
3443
+
3444
+ const {transitional, paramsSerializer, headers} = config;
3445
+
3446
+ if (transitional !== undefined) {
3447
+ validator.assertOptions(transitional, {
3448
+ silentJSONParsing: validators.transitional(validators.boolean),
3449
+ forcedJSONParsing: validators.transitional(validators.boolean),
3450
+ clarifyTimeoutError: validators.transitional(validators.boolean)
3451
+ }, false);
3452
+ }
3453
+
3454
+ if (paramsSerializer != null) {
3455
+ if (utils$1.isFunction(paramsSerializer)) {
3456
+ config.paramsSerializer = {
3457
+ serialize: paramsSerializer
3458
+ };
3459
+ } else {
3460
+ validator.assertOptions(paramsSerializer, {
3461
+ encode: validators.function,
3462
+ serialize: validators.function
3463
+ }, true);
3464
+ }
3465
+ }
3466
+
3467
+ // Set config.allowAbsoluteUrls
3468
+ if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
3469
+ config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
3470
+ } else {
3471
+ config.allowAbsoluteUrls = true;
3472
+ }
3473
+
3474
+ validator.assertOptions(config, {
3475
+ baseUrl: validators.spelling('baseURL'),
3476
+ withXsrfToken: validators.spelling('withXSRFToken')
3477
+ }, true);
3478
+
3479
+ // Set config.method
3480
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3481
+
3482
+ // Flatten headers
3483
+ let contextHeaders = headers && utils$1.merge(
3484
+ headers.common,
3485
+ headers[config.method]
3486
+ );
3487
+
3488
+ headers && utils$1.forEach(
3489
+ ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
3490
+ (method) => {
3491
+ delete headers[method];
3492
+ }
3493
+ );
3494
+
3495
+ config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
3496
+
3497
+ // filter out skipped interceptors
3498
+ const requestInterceptorChain = [];
3499
+ let synchronousRequestInterceptors = true;
3500
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3501
+ if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
3502
+ return;
3503
+ }
3504
+
3505
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3506
+
3507
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3508
+ });
3509
+
3510
+ const responseInterceptorChain = [];
3511
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3512
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3513
+ });
3514
+
3515
+ let promise;
3516
+ let i = 0;
3517
+ let len;
3518
+
3519
+ if (!synchronousRequestInterceptors) {
3520
+ const chain = [dispatchRequest.bind(this), undefined];
3521
+ chain.unshift(...requestInterceptorChain);
3522
+ chain.push(...responseInterceptorChain);
3523
+ len = chain.length;
3524
+
3525
+ promise = Promise.resolve(config);
3526
+
3527
+ while (i < len) {
3528
+ promise = promise.then(chain[i++], chain[i++]);
3529
+ }
3530
+
3531
+ return promise;
3532
+ }
3533
+
3534
+ len = requestInterceptorChain.length;
3535
+
3536
+ let newConfig = config;
3537
+
3538
+ while (i < len) {
3539
+ const onFulfilled = requestInterceptorChain[i++];
3540
+ const onRejected = requestInterceptorChain[i++];
3541
+ try {
3542
+ newConfig = onFulfilled(newConfig);
3543
+ } catch (error) {
3544
+ onRejected.call(this, error);
3545
+ break;
3546
+ }
3547
+ }
3548
+
3549
+ try {
3550
+ promise = dispatchRequest.call(this, newConfig);
3551
+ } catch (error) {
3552
+ return Promise.reject(error);
3553
+ }
3554
+
3555
+ i = 0;
3556
+ len = responseInterceptorChain.length;
3557
+
3558
+ while (i < len) {
3559
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3560
+ }
3561
+
3562
+ return promise;
3563
+ }
3564
+
3565
+ getUri(config) {
3566
+ config = mergeConfig(this.defaults, config);
3567
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
3568
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3569
+ }
3570
+ }
3571
+
3572
+ // Provide aliases for supported request methods
3573
+ utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
3574
+ /*eslint func-names:0*/
3575
+ Axios.prototype[method] = function(url, config) {
3576
+ return this.request(mergeConfig(config || {}, {
3577
+ method,
3578
+ url,
3579
+ data: (config || {}).data
3580
+ }));
3581
+ };
3582
+ });
3583
+
3584
+ utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
3585
+ /*eslint func-names:0*/
3586
+
3587
+ function generateHTTPMethod(isForm) {
3588
+ return function httpMethod(url, data, config) {
3589
+ return this.request(mergeConfig(config || {}, {
3590
+ method,
3591
+ headers: isForm ? {
3592
+ 'Content-Type': 'multipart/form-data'
3593
+ } : {},
3594
+ url,
3595
+ data
3596
+ }));
3597
+ };
3598
+ }
3599
+
3600
+ Axios.prototype[method] = generateHTTPMethod();
3601
+
3602
+ Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3603
+ });
3604
+
3605
+ var Axios$1 = Axios;
3606
+
3607
+ /**
3608
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3609
+ *
3610
+ * @param {Function} executor The executor function.
3611
+ *
3612
+ * @returns {CancelToken}
3613
+ */
3614
+ class CancelToken {
3615
+ constructor(executor) {
3616
+ if (typeof executor !== 'function') {
3617
+ throw new TypeError('executor must be a function.');
3618
+ }
3619
+
3620
+ let resolvePromise;
3621
+
3622
+ this.promise = new Promise(function promiseExecutor(resolve) {
3623
+ resolvePromise = resolve;
3624
+ });
3625
+
3626
+ const token = this;
3627
+
3628
+ // eslint-disable-next-line func-names
3629
+ this.promise.then(cancel => {
3630
+ if (!token._listeners) return;
3631
+
3632
+ let i = token._listeners.length;
3633
+
3634
+ while (i-- > 0) {
3635
+ token._listeners[i](cancel);
3636
+ }
3637
+ token._listeners = null;
3638
+ });
3639
+
3640
+ // eslint-disable-next-line func-names
3641
+ this.promise.then = onfulfilled => {
3642
+ let _resolve;
3643
+ // eslint-disable-next-line func-names
3644
+ const promise = new Promise(resolve => {
3645
+ token.subscribe(resolve);
3646
+ _resolve = resolve;
3647
+ }).then(onfulfilled);
3648
+
3649
+ promise.cancel = function reject() {
3650
+ token.unsubscribe(_resolve);
3651
+ };
3652
+
3653
+ return promise;
3654
+ };
3655
+
3656
+ executor(function cancel(message, config, request) {
3657
+ if (token.reason) {
3658
+ // Cancellation has already been requested
3659
+ return;
3660
+ }
3661
+
3662
+ token.reason = new CanceledError(message, config, request);
3663
+ resolvePromise(token.reason);
3664
+ });
3665
+ }
3666
+
3667
+ /**
3668
+ * Throws a `CanceledError` if cancellation has been requested.
3669
+ */
3670
+ throwIfRequested() {
3671
+ if (this.reason) {
3672
+ throw this.reason;
3673
+ }
3674
+ }
3675
+
3676
+ /**
3677
+ * Subscribe to the cancel signal
3678
+ */
3679
+
3680
+ subscribe(listener) {
3681
+ if (this.reason) {
3682
+ listener(this.reason);
3683
+ return;
3684
+ }
3685
+
3686
+ if (this._listeners) {
3687
+ this._listeners.push(listener);
3688
+ } else {
3689
+ this._listeners = [listener];
3690
+ }
3691
+ }
3692
+
3693
+ /**
3694
+ * Unsubscribe from the cancel signal
3695
+ */
3696
+
3697
+ unsubscribe(listener) {
3698
+ if (!this._listeners) {
3699
+ return;
3700
+ }
3701
+ const index = this._listeners.indexOf(listener);
3702
+ if (index !== -1) {
3703
+ this._listeners.splice(index, 1);
3704
+ }
3705
+ }
3706
+
3707
+ toAbortSignal() {
3708
+ const controller = new AbortController();
3709
+
3710
+ const abort = (err) => {
3711
+ controller.abort(err);
3712
+ };
3713
+
3714
+ this.subscribe(abort);
3715
+
3716
+ controller.signal.unsubscribe = () => this.unsubscribe(abort);
3717
+
3718
+ return controller.signal;
3719
+ }
3720
+
3721
+ /**
3722
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3723
+ * cancels the `CancelToken`.
3724
+ */
3725
+ static source() {
3726
+ let cancel;
3727
+ const token = new CancelToken(function executor(c) {
3728
+ cancel = c;
3729
+ });
3730
+ return {
3731
+ token,
3732
+ cancel
3733
+ };
3734
+ }
3735
+ }
3736
+
3737
+ var CancelToken$1 = CancelToken;
3738
+
3739
+ /**
3740
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3741
+ *
3742
+ * Common use case would be to use `Function.prototype.apply`.
3743
+ *
3744
+ * ```js
3745
+ * function f(x, y, z) {}
3746
+ * var args = [1, 2, 3];
3747
+ * f.apply(null, args);
3748
+ * ```
3749
+ *
3750
+ * With `spread` this example can be re-written.
3751
+ *
3752
+ * ```js
3753
+ * spread(function(x, y, z) {})([1, 2, 3]);
3754
+ * ```
3755
+ *
3756
+ * @param {Function} callback
3757
+ *
3758
+ * @returns {Function}
3759
+ */
3760
+ function spread(callback) {
3761
+ return function wrap(arr) {
3762
+ return callback.apply(null, arr);
3763
+ };
3764
+ }
3765
+
3766
+ /**
3767
+ * Determines whether the payload is an error thrown by Axios
3768
+ *
3769
+ * @param {*} payload The value to test
3770
+ *
3771
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3772
+ */
3773
+ function isAxiosError(payload) {
3774
+ return utils$1.isObject(payload) && (payload.isAxiosError === true);
3775
+ }
3776
+
3777
+ const HttpStatusCode = {
3778
+ Continue: 100,
3779
+ SwitchingProtocols: 101,
3780
+ Processing: 102,
3781
+ EarlyHints: 103,
3782
+ Ok: 200,
3783
+ Created: 201,
3784
+ Accepted: 202,
3785
+ NonAuthoritativeInformation: 203,
3786
+ NoContent: 204,
3787
+ ResetContent: 205,
3788
+ PartialContent: 206,
3789
+ MultiStatus: 207,
3790
+ AlreadyReported: 208,
3791
+ ImUsed: 226,
3792
+ MultipleChoices: 300,
3793
+ MovedPermanently: 301,
3794
+ Found: 302,
3795
+ SeeOther: 303,
3796
+ NotModified: 304,
3797
+ UseProxy: 305,
3798
+ Unused: 306,
3799
+ TemporaryRedirect: 307,
3800
+ PermanentRedirect: 308,
3801
+ BadRequest: 400,
3802
+ Unauthorized: 401,
3803
+ PaymentRequired: 402,
3804
+ Forbidden: 403,
3805
+ NotFound: 404,
3806
+ MethodNotAllowed: 405,
3807
+ NotAcceptable: 406,
3808
+ ProxyAuthenticationRequired: 407,
3809
+ RequestTimeout: 408,
3810
+ Conflict: 409,
3811
+ Gone: 410,
3812
+ LengthRequired: 411,
3813
+ PreconditionFailed: 412,
3814
+ PayloadTooLarge: 413,
3815
+ UriTooLong: 414,
3816
+ UnsupportedMediaType: 415,
3817
+ RangeNotSatisfiable: 416,
3818
+ ExpectationFailed: 417,
3819
+ ImATeapot: 418,
3820
+ MisdirectedRequest: 421,
3821
+ UnprocessableEntity: 422,
3822
+ Locked: 423,
3823
+ FailedDependency: 424,
3824
+ TooEarly: 425,
3825
+ UpgradeRequired: 426,
3826
+ PreconditionRequired: 428,
3827
+ TooManyRequests: 429,
3828
+ RequestHeaderFieldsTooLarge: 431,
3829
+ UnavailableForLegalReasons: 451,
3830
+ InternalServerError: 500,
3831
+ NotImplemented: 501,
3832
+ BadGateway: 502,
3833
+ ServiceUnavailable: 503,
3834
+ GatewayTimeout: 504,
3835
+ HttpVersionNotSupported: 505,
3836
+ VariantAlsoNegotiates: 506,
3837
+ InsufficientStorage: 507,
3838
+ LoopDetected: 508,
3839
+ NotExtended: 510,
3840
+ NetworkAuthenticationRequired: 511,
3841
+ WebServerIsDown: 521,
3842
+ ConnectionTimedOut: 522,
3843
+ OriginIsUnreachable: 523,
3844
+ TimeoutOccurred: 524,
3845
+ SslHandshakeFailed: 525,
3846
+ InvalidSslCertificate: 526,
3847
+ };
3848
+
3849
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
3850
+ HttpStatusCode[value] = key;
3851
+ });
3852
+
3853
+ var HttpStatusCode$1 = HttpStatusCode;
3854
+
3855
+ /**
3856
+ * Create an instance of Axios
3857
+ *
3858
+ * @param {Object} defaultConfig The default config for the instance
3859
+ *
3860
+ * @returns {Axios} A new instance of Axios
3861
+ */
3862
+ function createInstance(defaultConfig) {
3863
+ const context = new Axios$1(defaultConfig);
3864
+ const instance = bind(Axios$1.prototype.request, context);
3865
+
3866
+ // Copy axios.prototype to instance
3867
+ utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
3868
+
3869
+ // Copy context to instance
3870
+ utils$1.extend(instance, context, null, {allOwnKeys: true});
3871
+
3872
+ // Factory for creating new instances
3873
+ instance.create = function create(instanceConfig) {
3874
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
3875
+ };
3876
+
3877
+ return instance;
3878
+ }
3879
+
3880
+ // Create the default instance to be exported
3881
+ const axios = createInstance(defaults$1);
3882
+
3883
+ // Expose Axios class to allow class inheritance
3884
+ axios.Axios = Axios$1;
3885
+
3886
+ // Expose Cancel & CancelToken
3887
+ axios.CanceledError = CanceledError;
3888
+ axios.CancelToken = CancelToken$1;
3889
+ axios.isCancel = isCancel;
3890
+ axios.VERSION = VERSION;
3891
+ axios.toFormData = toFormData;
3892
+
3893
+ // Expose AxiosError class
3894
+ axios.AxiosError = AxiosError;
3895
+
3896
+ // alias for CanceledError for backward compatibility
3897
+ axios.Cancel = axios.CanceledError;
3898
+
3899
+ // Expose all/spread
3900
+ axios.all = function all(promises) {
3901
+ return Promise.all(promises);
3902
+ };
3903
+
3904
+ axios.spread = spread;
3905
+
3906
+ // Expose isAxiosError
3907
+ axios.isAxiosError = isAxiosError;
3908
+
3909
+ // Expose mergeConfig
3910
+ axios.mergeConfig = mergeConfig;
3911
+
3912
+ axios.AxiosHeaders = AxiosHeaders$1;
3913
+
3914
+ axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
3915
+
3916
+ axios.getAdapter = adapters.getAdapter;
3917
+
3918
+ axios.HttpStatusCode = HttpStatusCode$1;
3919
+
3920
+ axios.default = axios;
3921
+
3922
+ // this module should only have a default export
3923
+ var axios$1 = axios;
3924
+
3925
+ class ApiClient {
3926
+ constructor(config) {
3927
+ this.client = axios$1.create({
3928
+ baseURL: config.baseURL,
3929
+ timeout: config.timeout || 10000,
3930
+ headers: {
3931
+ 'Content-Type': 'application/json',
3932
+ ...config.headers,
3933
+ },
3934
+ });
3935
+ }
3936
+ async get(url, config) {
3937
+ const response = await this.client.get(url, config);
3938
+ return response.data;
3939
+ }
3940
+ async post(url, data, config) {
3941
+ const response = await this.client.post(url, data, config);
3942
+ return response.data;
3943
+ }
3944
+ async put(url, data, config) {
3945
+ const response = await this.client.put(url, data, config);
3946
+ return response.data;
3947
+ }
3948
+ async patch(url, data, config) {
3949
+ const response = await this.client.patch(url, data, config);
3950
+ return response.data;
3951
+ }
3952
+ async delete(url, config) {
3953
+ const response = await this.client.delete(url, config);
3954
+ return response.data;
3955
+ }
3956
+ }
3957
+
3958
+ function useAuth() {
3959
+ const config = useAuthConfig();
3960
+ const [user, setUser] = React.useState(null);
3961
+ const [loading, setLoading] = React.useState(false);
3962
+ const [error, setError] = React.useState(null);
3963
+ const login = async (credentials) => {
3964
+ setLoading(true);
3965
+ setError(null);
3966
+ try {
3967
+ const apiClient = new ApiClient({
3968
+ baseURL: config.apiUrl,
3969
+ timeout: config.timeout,
3970
+ headers: config.headers,
3971
+ });
3972
+ const response = await apiClient.post('/auth/login', credentials);
3973
+ if (response.success && response.data?.user) {
3974
+ setUser(response.data.user);
3975
+ }
3976
+ return response;
3977
+ }
3978
+ catch (err) {
3979
+ const errorMessage = err instanceof Error ? err.message : 'Login failed';
3980
+ setError(errorMessage);
3981
+ return { success: false, error: errorMessage };
3982
+ }
3983
+ finally {
3984
+ setLoading(false);
3985
+ }
3986
+ };
3987
+ const logout = async () => {
3988
+ setLoading(true);
3989
+ try {
3990
+ const apiClient = new ApiClient({
3991
+ baseURL: config.apiUrl,
3992
+ timeout: config.timeout,
3993
+ headers: config.headers,
3994
+ });
3995
+ await apiClient.post('/auth/logout', {});
3996
+ setUser(null);
3997
+ }
3998
+ catch (err) {
3999
+ console.error('Logout error:', err);
4000
+ }
4001
+ finally {
4002
+ setLoading(false);
4003
+ }
4004
+ };
4005
+ const getUserInfo = async () => {
4006
+ setLoading(true);
4007
+ try {
4008
+ const apiClient = new ApiClient({
4009
+ baseURL: config.apiUrl,
4010
+ timeout: config.timeout,
4011
+ headers: config.headers,
4012
+ });
4013
+ const response = await apiClient.get('/auth/me');
4014
+ setUser(response.data);
4015
+ return response.data;
4016
+ }
4017
+ catch (err) {
4018
+ console.error('Get user info error:', err);
4019
+ return null;
4020
+ }
4021
+ finally {
4022
+ setLoading(false);
4023
+ }
4024
+ };
4025
+ return {
4026
+ user,
4027
+ loading,
4028
+ error,
4029
+ login,
4030
+ logout,
4031
+ getUserInfo,
4032
+ isAuthenticated: !!user,
4033
+ };
4034
+ }
4035
+
4036
+ function useDynamicForm(formId) {
4037
+ const config = useAuthConfig();
4038
+ const [formConfig, setFormConfig] = React.useState(null);
4039
+ const [loading, setLoading] = React.useState(false);
4040
+ const [error, setError] = React.useState(null);
4041
+ React.useEffect(() => {
4042
+ const fetchFormConfig = async () => {
4043
+ setLoading(true);
4044
+ setError(null);
4045
+ try {
4046
+ const apiClient = new ApiClient({
4047
+ baseURL: config.apiUrl,
4048
+ timeout: config.timeout,
4049
+ headers: config.headers,
4050
+ });
4051
+ const response = await apiClient.get(`/forms/${formId}`);
4052
+ setFormConfig(response.data);
4053
+ }
4054
+ catch (err) {
4055
+ setError(err instanceof Error ? err.message : 'Failed to fetch form configuration');
4056
+ }
4057
+ finally {
4058
+ setLoading(false);
4059
+ }
4060
+ };
4061
+ fetchFormConfig();
4062
+ }, [formId, config]);
4063
+ return { formConfig, loading, error };
4064
+ }
4065
+
4066
+ function Button({ variant = 'primary', size = 'md', loading = false, fullWidth = false, children, disabled, className = '', ...props }) {
4067
+ const baseStyles = 'inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
4068
+ const variantStyles = {
4069
+ primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
4070
+ secondary: 'bg-gray-600 text-white hover:bg-gray-700 focus:ring-gray-500',
4071
+ outline: 'border-2 border-blue-600 text-blue-600 hover:bg-blue-50 focus:ring-blue-500',
4072
+ };
4073
+ const sizeStyles = {
4074
+ sm: 'px-3 py-1.5 text-sm',
4075
+ md: 'px-4 py-2 text-base',
4076
+ lg: 'px-6 py-3 text-lg',
4077
+ };
4078
+ const widthStyles = fullWidth ? 'w-full' : '';
4079
+ return (jsxRuntime.jsxs("button", { className: `${baseStyles} ${variantStyles[variant]} ${sizeStyles[size]} ${widthStyles} ${className}`, disabled: disabled || loading, ...props, children: [loading && (jsxRuntime.jsxs("svg", { className: "animate-spin -ml-1 mr-2 h-4 w-4", xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", children: [jsxRuntime.jsx("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), jsxRuntime.jsx("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] })), children] }));
4080
+ }
4081
+
4082
+ function validateField(field, value) {
4083
+ if (field.required && !value) {
4084
+ return { valid: false, error: `${field.label} is required` };
4085
+ }
4086
+ if (!value) {
4087
+ return { valid: true };
4088
+ }
4089
+ const { validation } = field;
4090
+ if (!validation) {
4091
+ return { valid: true };
4092
+ }
4093
+ if (validation.pattern) {
4094
+ const regex = new RegExp(validation.pattern);
4095
+ if (!regex.test(value)) {
4096
+ return { valid: false, error: `${field.label} format is invalid` };
4097
+ }
4098
+ }
4099
+ if (validation.minLength && value.length < validation.minLength) {
4100
+ return { valid: false, error: `${field.label} must be at least ${validation.minLength} characters` };
4101
+ }
4102
+ if (validation.maxLength && value.length > validation.maxLength) {
4103
+ return { valid: false, error: `${field.label} must not exceed ${validation.maxLength} characters` };
4104
+ }
4105
+ if (field.type === 'number' && validation.min !== undefined && value < validation.min) {
4106
+ return { valid: false, error: `${field.label} must be at least ${validation.min}` };
4107
+ }
4108
+ if (field.type === 'number' && validation.max !== undefined && value > validation.max) {
4109
+ return { valid: false, error: `${field.label} must not exceed ${validation.max}` };
4110
+ }
4111
+ return { valid: true };
4112
+ }
4113
+ function validateForm(fields, values) {
4114
+ const errors = {};
4115
+ let valid = true;
4116
+ fields.forEach((field) => {
4117
+ const result = validateField(field, values[field.name]);
4118
+ if (!result.valid) {
4119
+ errors[field.name] = result.error || '';
4120
+ valid = false;
4121
+ }
4122
+ });
4123
+ return { valid, errors };
4124
+ }
4125
+
4126
+ function DynamicForm({ fields, onSubmit, submitText = 'Submit', submitVariant = 'primary', loading = false, }) {
4127
+ const [values, setValues] = React.useState({});
4128
+ const [errors, setErrors] = React.useState({});
4129
+ const [touched, setTouched] = React.useState({});
4130
+ const handleChange = (name, value) => {
4131
+ setValues((prev) => ({ ...prev, [name]: value }));
4132
+ if (touched[name]) {
4133
+ const field = fields.find((f) => f.name === name);
4134
+ if (field) {
4135
+ const result = validateField(field, value);
4136
+ setErrors((prev) => ({ ...prev, [name]: result.error || '' }));
4137
+ }
4138
+ }
4139
+ };
4140
+ const handleBlur = (name) => {
4141
+ setTouched((prev) => ({ ...prev, [name]: true }));
4142
+ const field = fields.find((f) => f.name === name);
4143
+ if (field) {
4144
+ const result = validateField(field, values[name]);
4145
+ setErrors((prev) => ({ ...prev, [name]: result.error || '' }));
4146
+ }
4147
+ };
4148
+ const handleSubmit = (e) => {
4149
+ e.preventDefault();
4150
+ const newErrors = {};
4151
+ let hasError = false;
4152
+ fields.forEach((field) => {
4153
+ const result = validateField(field, values[field.name]);
4154
+ if (!result.valid) {
4155
+ newErrors[field.name] = result.error || '';
4156
+ hasError = true;
4157
+ }
4158
+ });
4159
+ setErrors(newErrors);
4160
+ setTouched(fields.reduce((acc, field) => ({ ...acc, [field.name]: true }), {}));
4161
+ if (!hasError) {
4162
+ onSubmit(values);
4163
+ }
4164
+ };
4165
+ const renderField = (field) => {
4166
+ const error = touched[field.name] ? errors[field.name] : '';
4167
+ const hasError = !!error;
4168
+ const baseInputStyles = 'w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 transition-colors';
4169
+ const errorStyles = hasError ? 'border-red-500 focus:ring-red-500' : 'border-gray-300 focus:ring-blue-500';
4170
+ switch (field.type) {
4171
+ case 'text':
4172
+ case 'email':
4173
+ case 'password':
4174
+ case 'number':
4175
+ return (jsxRuntime.jsx("input", { type: field.type, name: field.name, value: values[field.name] || '', onChange: (e) => handleChange(field.name, e.target.value), onBlur: () => handleBlur(field.name), placeholder: field.placeholder, className: `${baseInputStyles} ${errorStyles}`, disabled: loading }));
4176
+ case 'textarea':
4177
+ return (jsxRuntime.jsx("textarea", { name: field.name, value: values[field.name] || '', onChange: (e) => handleChange(field.name, e.target.value), onBlur: () => handleBlur(field.name), placeholder: field.placeholder, rows: 4, className: `${baseInputStyles} ${errorStyles}`, disabled: loading }));
4178
+ case 'select':
4179
+ return (jsxRuntime.jsxs("select", { name: field.name, value: values[field.name] || '', onChange: (e) => handleChange(field.name, e.target.value), onBlur: () => handleBlur(field.name), className: `${baseInputStyles} ${errorStyles}`, disabled: loading, children: [jsxRuntime.jsx("option", { value: "", children: "Select an option" }), field.options?.map((option) => (jsxRuntime.jsx("option", { value: option.value, children: option.label }, option.value)))] }));
4180
+ case 'checkbox':
4181
+ return (jsxRuntime.jsx("input", { type: "checkbox", name: field.name, checked: values[field.name] || false, onChange: (e) => handleChange(field.name, e.target.checked), onBlur: () => handleBlur(field.name), className: "w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500", disabled: loading }));
4182
+ case 'radio':
4183
+ return (jsxRuntime.jsx("div", { className: "space-y-2", children: field.options?.map((option) => (jsxRuntime.jsxs("label", { className: "flex items-center space-x-2", children: [jsxRuntime.jsx("input", { type: "radio", name: field.name, value: option.value, checked: values[field.name] === option.value, onChange: (e) => handleChange(field.name, e.target.value), onBlur: () => handleBlur(field.name), className: "w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500", disabled: loading }), jsxRuntime.jsx("span", { children: option.label })] }, option.value))) }));
4184
+ default:
4185
+ return null;
4186
+ }
4187
+ };
4188
+ return (jsxRuntime.jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [fields.map((field) => (jsxRuntime.jsxs("div", { children: [jsxRuntime.jsxs("label", { className: "block text-sm font-medium text-gray-700 mb-1", children: [field.label, field.required && jsxRuntime.jsx("span", { className: "text-red-500 ml-1", children: "*" })] }), renderField(field), touched[field.name] && errors[field.name] && (jsxRuntime.jsx("p", { className: "mt-1 text-sm text-red-600", children: errors[field.name] }))] }, field.name))), jsxRuntime.jsx(Button, { type: "submit", variant: submitVariant, loading: loading, fullWidth: true, children: submitText })] }));
4189
+ }
4190
+
4191
+ function LoginForm({ formId, onSuccess, onError }) {
4192
+ const config = useAuthConfig();
4193
+ const { formConfig, loading: formLoading, error: formError } = useDynamicForm(formId);
4194
+ const [submitting, setSubmitting] = React.useState(false);
4195
+ const handleSubmit = async (values) => {
4196
+ if (!formConfig)
4197
+ return;
4198
+ setSubmitting(true);
4199
+ try {
4200
+ const apiClient = new ApiClient({
4201
+ baseURL: config.apiUrl,
4202
+ timeout: config.timeout,
4203
+ headers: config.headers,
4204
+ });
4205
+ const response = await apiClient.post(formConfig.submitUrl, values);
4206
+ if (onSuccess) {
4207
+ onSuccess(response);
4208
+ }
4209
+ }
4210
+ catch (err) {
4211
+ const errorMessage = err instanceof Error ? err.message : 'Login failed';
4212
+ if (onError) {
4213
+ onError(errorMessage);
4214
+ }
4215
+ }
4216
+ finally {
4217
+ setSubmitting(false);
4218
+ }
4219
+ };
4220
+ if (formLoading) {
4221
+ return (jsxRuntime.jsx("div", { className: "flex items-center justify-center p-8", children: jsxRuntime.jsx("div", { className: "animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" }) }));
4222
+ }
4223
+ if (formError) {
4224
+ return (jsxRuntime.jsx("div", { className: "p-4 bg-red-50 border border-red-200 rounded-lg", children: jsxRuntime.jsx("p", { className: "text-red-600", children: formError }) }));
4225
+ }
4226
+ if (!formConfig) {
4227
+ return null;
4228
+ }
4229
+ return (jsxRuntime.jsx("div", { className: "w-full", children: jsxRuntime.jsx(DynamicForm, { fields: formConfig.fields, onSubmit: handleSubmit, submitText: formConfig.submitButton?.text || 'Login', submitVariant: formConfig.submitButton?.variant || 'primary', loading: submitting }) }));
4230
+ }
4231
+
4232
+ function UserInfoBox({ user, onLogout, loading = false, className = '' }) {
4233
+ return (jsxRuntime.jsxs("div", { className: `bg-white rounded-lg shadow-md p-6 ${className}`, children: [jsxRuntime.jsxs("div", { className: "flex items-center space-x-4", children: [user.avatar && (jsxRuntime.jsx("img", { src: user.avatar, alt: user.name, className: "w-16 h-16 rounded-full object-cover" })), jsxRuntime.jsxs("div", { className: "flex-1", children: [jsxRuntime.jsx("h3", { className: "text-lg font-semibold text-gray-900", children: user.name }), user.email && (jsxRuntime.jsx("p", { className: "text-sm text-gray-600", children: user.email }))] })] }), onLogout && (jsxRuntime.jsx("div", { className: "mt-4", children: jsxRuntime.jsx(Button, { variant: "outline", size: "sm", onClick: onLogout, loading: loading, fullWidth: true, children: "Logout" }) }))] }));
4234
+ }
4235
+
4236
+ function SocialLoginButton({ provider, onClick, loading = false, className = '' }) {
4237
+ const handleClick = () => {
4238
+ onClick(provider);
4239
+ };
4240
+ return (jsxRuntime.jsxs(Button, { variant: "outline", onClick: handleClick, loading: loading, fullWidth: true, className: `flex items-center justify-center space-x-2 ${className}`, children: [provider.icon && (jsxRuntime.jsx("img", { src: provider.icon, alt: provider.name, className: "w-5 h-5" })), jsxRuntime.jsxs("span", { children: ["Continue with ", provider.name] })] }));
4241
+ }
4242
+ function SocialLogin({ providers, onLogin, loading = false, className = '' }) {
4243
+ if (providers.length === 0) {
4244
+ return null;
4245
+ }
4246
+ return (jsxRuntime.jsx("div", { className: `space-y-3 ${className}`, children: providers.map((provider) => (jsxRuntime.jsx(SocialLoginButton, { provider: provider, onClick: onLogin, loading: loading }, provider.id))) }));
4247
+ }
4248
+
4249
+ exports.ApiClient = ApiClient;
4250
+ exports.AuthProvider = AuthProvider;
4251
+ exports.Button = Button;
4252
+ exports.DynamicForm = DynamicForm;
4253
+ exports.LoginForm = LoginForm;
4254
+ exports.SocialLogin = SocialLogin;
4255
+ exports.SocialLoginButton = SocialLoginButton;
4256
+ exports.UserInfoBox = UserInfoBox;
4257
+ exports.useAuth = useAuth;
4258
+ exports.useAuthConfig = useAuthConfig;
4259
+ exports.useDynamicForm = useDynamicForm;
4260
+ exports.validateField = validateField;
4261
+ exports.validateForm = validateForm;
4262
+ //# sourceMappingURL=index.js.map