@seaverse/data-service-sdk 0.2.0 → 0.4.0

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