@seaverse/payment-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5058 @@
1
+ /**
2
+ * Create a bound version of a function with a specified `this` context
3
+ *
4
+ * @param {Function} fn - The function to bind
5
+ * @param {*} thisArg - The value to be passed as the `this` parameter
6
+ * @returns {Function} A new function that will call the original function with the specified `this` context
7
+ */
8
+ function bind(fn, thisArg) {
9
+ return function wrap() {
10
+ return fn.apply(thisArg, arguments);
11
+ };
12
+ }
13
+
14
+ // utils is a library of generic helper functions non-specific to axios
15
+
16
+ const {toString} = Object.prototype;
17
+ const {getPrototypeOf} = Object;
18
+ const {iterator, toStringTag} = Symbol;
19
+
20
+ const kindOf = (cache => thing => {
21
+ const str = toString.call(thing);
22
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
23
+ })(Object.create(null));
24
+
25
+ const kindOfTest = (type) => {
26
+ type = type.toLowerCase();
27
+ return (thing) => kindOf(thing) === type
28
+ };
29
+
30
+ const typeOfTest = type => thing => typeof thing === type;
31
+
32
+ /**
33
+ * Determine if a value is an Array
34
+ *
35
+ * @param {Object} val The value to test
36
+ *
37
+ * @returns {boolean} True if value is an Array, otherwise false
38
+ */
39
+ const {isArray} = Array;
40
+
41
+ /**
42
+ * Determine if a value is undefined
43
+ *
44
+ * @param {*} val The value to test
45
+ *
46
+ * @returns {boolean} True if the value is undefined, otherwise false
47
+ */
48
+ const isUndefined = typeOfTest('undefined');
49
+
50
+ /**
51
+ * Determine if a value is a Buffer
52
+ *
53
+ * @param {*} val The value to test
54
+ *
55
+ * @returns {boolean} True if value is a Buffer, otherwise false
56
+ */
57
+ function isBuffer(val) {
58
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
59
+ && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
60
+ }
61
+
62
+ /**
63
+ * Determine if a value is an ArrayBuffer
64
+ *
65
+ * @param {*} val The value to test
66
+ *
67
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
68
+ */
69
+ const isArrayBuffer = kindOfTest('ArrayBuffer');
70
+
71
+
72
+ /**
73
+ * Determine if a value is a view on an ArrayBuffer
74
+ *
75
+ * @param {*} val The value to test
76
+ *
77
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
78
+ */
79
+ function isArrayBufferView(val) {
80
+ let result;
81
+ if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
82
+ result = ArrayBuffer.isView(val);
83
+ } else {
84
+ result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
85
+ }
86
+ return result;
87
+ }
88
+
89
+ /**
90
+ * Determine if a value is a String
91
+ *
92
+ * @param {*} val The value to test
93
+ *
94
+ * @returns {boolean} True if value is a String, otherwise false
95
+ */
96
+ const isString = typeOfTest('string');
97
+
98
+ /**
99
+ * Determine if a value is a Function
100
+ *
101
+ * @param {*} val The value to test
102
+ * @returns {boolean} True if value is a Function, otherwise false
103
+ */
104
+ const isFunction$1 = typeOfTest('function');
105
+
106
+ /**
107
+ * Determine if a value is a Number
108
+ *
109
+ * @param {*} val The value to test
110
+ *
111
+ * @returns {boolean} True if value is a Number, otherwise false
112
+ */
113
+ const isNumber = typeOfTest('number');
114
+
115
+ /**
116
+ * Determine if a value is an Object
117
+ *
118
+ * @param {*} thing The value to test
119
+ *
120
+ * @returns {boolean} True if value is an Object, otherwise false
121
+ */
122
+ const isObject = (thing) => thing !== null && typeof thing === 'object';
123
+
124
+ /**
125
+ * Determine if a value is a Boolean
126
+ *
127
+ * @param {*} thing The value to test
128
+ * @returns {boolean} True if value is a Boolean, otherwise false
129
+ */
130
+ const isBoolean = thing => thing === true || thing === false;
131
+
132
+ /**
133
+ * Determine if a value is a plain Object
134
+ *
135
+ * @param {*} val The value to test
136
+ *
137
+ * @returns {boolean} True if value is a plain Object, otherwise false
138
+ */
139
+ const isPlainObject = (val) => {
140
+ if (kindOf(val) !== 'object') {
141
+ return false;
142
+ }
143
+
144
+ const prototype = getPrototypeOf(val);
145
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val);
146
+ };
147
+
148
+ /**
149
+ * Determine if a value is an empty object (safely handles Buffers)
150
+ *
151
+ * @param {*} val The value to test
152
+ *
153
+ * @returns {boolean} True if value is an empty object, otherwise false
154
+ */
155
+ const isEmptyObject = (val) => {
156
+ // Early return for non-objects or Buffers to prevent RangeError
157
+ if (!isObject(val) || isBuffer(val)) {
158
+ return false;
159
+ }
160
+
161
+ try {
162
+ return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
163
+ } catch (e) {
164
+ // Fallback for any other objects that might cause RangeError with Object.keys()
165
+ return false;
166
+ }
167
+ };
168
+
169
+ /**
170
+ * Determine if a value is a Date
171
+ *
172
+ * @param {*} val The value to test
173
+ *
174
+ * @returns {boolean} True if value is a Date, otherwise false
175
+ */
176
+ const isDate = kindOfTest('Date');
177
+
178
+ /**
179
+ * Determine if a value is a File
180
+ *
181
+ * @param {*} val The value to test
182
+ *
183
+ * @returns {boolean} True if value is a File, otherwise false
184
+ */
185
+ const isFile = kindOfTest('File');
186
+
187
+ /**
188
+ * Determine if a value is a Blob
189
+ *
190
+ * @param {*} val The value to test
191
+ *
192
+ * @returns {boolean} True if value is a Blob, otherwise false
193
+ */
194
+ const isBlob = kindOfTest('Blob');
195
+
196
+ /**
197
+ * Determine if a value is a FileList
198
+ *
199
+ * @param {*} val The value to test
200
+ *
201
+ * @returns {boolean} True if value is a File, otherwise false
202
+ */
203
+ const isFileList = kindOfTest('FileList');
204
+
205
+ /**
206
+ * Determine if a value is a Stream
207
+ *
208
+ * @param {*} val The value to test
209
+ *
210
+ * @returns {boolean} True if value is a Stream, otherwise false
211
+ */
212
+ const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
213
+
214
+ /**
215
+ * Determine if a value is a FormData
216
+ *
217
+ * @param {*} thing The value to test
218
+ *
219
+ * @returns {boolean} True if value is an FormData, otherwise false
220
+ */
221
+ const isFormData = (thing) => {
222
+ let kind;
223
+ return thing && (
224
+ (typeof FormData === 'function' && thing instanceof FormData) || (
225
+ isFunction$1(thing.append) && (
226
+ (kind = kindOf(thing)) === 'formdata' ||
227
+ // detect form-data instance
228
+ (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
229
+ )
230
+ )
231
+ )
232
+ };
233
+
234
+ /**
235
+ * Determine if a value is a URLSearchParams object
236
+ *
237
+ * @param {*} val The value to test
238
+ *
239
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
240
+ */
241
+ const isURLSearchParams = kindOfTest('URLSearchParams');
242
+
243
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
244
+
245
+ /**
246
+ * Trim excess whitespace off the beginning and end of a string
247
+ *
248
+ * @param {String} str The String to trim
249
+ *
250
+ * @returns {String} The String freed of excess whitespace
251
+ */
252
+ const trim = (str) => str.trim ?
253
+ str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
254
+
255
+ /**
256
+ * Iterate over an Array or an Object invoking a function for each item.
257
+ *
258
+ * If `obj` is an Array callback will be called passing
259
+ * the value, index, and complete array for each item.
260
+ *
261
+ * If 'obj' is an Object callback will be called passing
262
+ * the value, key, and complete object for each property.
263
+ *
264
+ * @param {Object|Array} obj The object to iterate
265
+ * @param {Function} fn The callback to invoke for each item
266
+ *
267
+ * @param {Boolean} [allOwnKeys = false]
268
+ * @returns {any}
269
+ */
270
+ function forEach(obj, fn, {allOwnKeys = false} = {}) {
271
+ // Don't bother if no value provided
272
+ if (obj === null || typeof obj === 'undefined') {
273
+ return;
274
+ }
275
+
276
+ let i;
277
+ let l;
278
+
279
+ // Force an array if not already something iterable
280
+ if (typeof obj !== 'object') {
281
+ /*eslint no-param-reassign:0*/
282
+ obj = [obj];
283
+ }
284
+
285
+ if (isArray(obj)) {
286
+ // Iterate over array values
287
+ for (i = 0, l = obj.length; i < l; i++) {
288
+ fn.call(null, obj[i], i, obj);
289
+ }
290
+ } else {
291
+ // Buffer check
292
+ if (isBuffer(obj)) {
293
+ return;
294
+ }
295
+
296
+ // Iterate over object keys
297
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
298
+ const len = keys.length;
299
+ let key;
300
+
301
+ for (i = 0; i < len; i++) {
302
+ key = keys[i];
303
+ fn.call(null, obj[key], key, obj);
304
+ }
305
+ }
306
+ }
307
+
308
+ function findKey(obj, key) {
309
+ if (isBuffer(obj)){
310
+ return null;
311
+ }
312
+
313
+ key = key.toLowerCase();
314
+ const keys = Object.keys(obj);
315
+ let i = keys.length;
316
+ let _key;
317
+ while (i-- > 0) {
318
+ _key = keys[i];
319
+ if (key === _key.toLowerCase()) {
320
+ return _key;
321
+ }
322
+ }
323
+ return null;
324
+ }
325
+
326
+ const _global = (() => {
327
+ /*eslint no-undef:0*/
328
+ if (typeof globalThis !== "undefined") return globalThis;
329
+ return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
330
+ })();
331
+
332
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
333
+
334
+ /**
335
+ * Accepts varargs expecting each argument to be an object, then
336
+ * immutably merges the properties of each object and returns result.
337
+ *
338
+ * When multiple objects contain the same key the later object in
339
+ * the arguments list will take precedence.
340
+ *
341
+ * Example:
342
+ *
343
+ * ```js
344
+ * var result = merge({foo: 123}, {foo: 456});
345
+ * console.log(result.foo); // outputs 456
346
+ * ```
347
+ *
348
+ * @param {Object} obj1 Object to merge
349
+ *
350
+ * @returns {Object} Result of all merge properties
351
+ */
352
+ function merge(/* obj1, obj2, obj3, ... */) {
353
+ const {caseless, skipUndefined} = isContextDefined(this) && this || {};
354
+ const result = {};
355
+ const assignValue = (val, key) => {
356
+ const targetKey = caseless && findKey(result, key) || key;
357
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
358
+ result[targetKey] = merge(result[targetKey], val);
359
+ } else if (isPlainObject(val)) {
360
+ result[targetKey] = merge({}, val);
361
+ } else if (isArray(val)) {
362
+ result[targetKey] = val.slice();
363
+ } else if (!skipUndefined || !isUndefined(val)) {
364
+ result[targetKey] = val;
365
+ }
366
+ };
367
+
368
+ for (let i = 0, l = arguments.length; i < l; i++) {
369
+ arguments[i] && forEach(arguments[i], assignValue);
370
+ }
371
+ return result;
372
+ }
373
+
374
+ /**
375
+ * Extends object a by mutably adding to it the properties of object b.
376
+ *
377
+ * @param {Object} a The object to be extended
378
+ * @param {Object} b The object to copy properties from
379
+ * @param {Object} thisArg The object to bind function to
380
+ *
381
+ * @param {Boolean} [allOwnKeys]
382
+ * @returns {Object} The resulting value of object a
383
+ */
384
+ const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
385
+ forEach(b, (val, key) => {
386
+ if (thisArg && isFunction$1(val)) {
387
+ a[key] = bind(val, thisArg);
388
+ } else {
389
+ a[key] = val;
390
+ }
391
+ }, {allOwnKeys});
392
+ return a;
393
+ };
394
+
395
+ /**
396
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
397
+ *
398
+ * @param {string} content with BOM
399
+ *
400
+ * @returns {string} content value without BOM
401
+ */
402
+ const stripBOM = (content) => {
403
+ if (content.charCodeAt(0) === 0xFEFF) {
404
+ content = content.slice(1);
405
+ }
406
+ return content;
407
+ };
408
+
409
+ /**
410
+ * Inherit the prototype methods from one constructor into another
411
+ * @param {function} constructor
412
+ * @param {function} superConstructor
413
+ * @param {object} [props]
414
+ * @param {object} [descriptors]
415
+ *
416
+ * @returns {void}
417
+ */
418
+ const inherits = (constructor, superConstructor, props, descriptors) => {
419
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
420
+ constructor.prototype.constructor = constructor;
421
+ Object.defineProperty(constructor, 'super', {
422
+ value: superConstructor.prototype
423
+ });
424
+ props && Object.assign(constructor.prototype, props);
425
+ };
426
+
427
+ /**
428
+ * Resolve object with deep prototype chain to a flat object
429
+ * @param {Object} sourceObj source object
430
+ * @param {Object} [destObj]
431
+ * @param {Function|Boolean} [filter]
432
+ * @param {Function} [propFilter]
433
+ *
434
+ * @returns {Object}
435
+ */
436
+ const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
437
+ let props;
438
+ let i;
439
+ let prop;
440
+ const merged = {};
441
+
442
+ destObj = destObj || {};
443
+ // eslint-disable-next-line no-eq-null,eqeqeq
444
+ if (sourceObj == null) return destObj;
445
+
446
+ do {
447
+ props = Object.getOwnPropertyNames(sourceObj);
448
+ i = props.length;
449
+ while (i-- > 0) {
450
+ prop = props[i];
451
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
452
+ destObj[prop] = sourceObj[prop];
453
+ merged[prop] = true;
454
+ }
455
+ }
456
+ sourceObj = filter !== false && getPrototypeOf(sourceObj);
457
+ } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
458
+
459
+ return destObj;
460
+ };
461
+
462
+ /**
463
+ * Determines whether a string ends with the characters of a specified string
464
+ *
465
+ * @param {String} str
466
+ * @param {String} searchString
467
+ * @param {Number} [position= 0]
468
+ *
469
+ * @returns {boolean}
470
+ */
471
+ const endsWith = (str, searchString, position) => {
472
+ str = String(str);
473
+ if (position === undefined || position > str.length) {
474
+ position = str.length;
475
+ }
476
+ position -= searchString.length;
477
+ const lastIndex = str.indexOf(searchString, position);
478
+ return lastIndex !== -1 && lastIndex === position;
479
+ };
480
+
481
+
482
+ /**
483
+ * Returns new array from array like object or null if failed
484
+ *
485
+ * @param {*} [thing]
486
+ *
487
+ * @returns {?Array}
488
+ */
489
+ const toArray = (thing) => {
490
+ if (!thing) return null;
491
+ if (isArray(thing)) return thing;
492
+ let i = thing.length;
493
+ if (!isNumber(i)) return null;
494
+ const arr = new Array(i);
495
+ while (i-- > 0) {
496
+ arr[i] = thing[i];
497
+ }
498
+ return arr;
499
+ };
500
+
501
+ /**
502
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
503
+ * thing passed in is an instance of Uint8Array
504
+ *
505
+ * @param {TypedArray}
506
+ *
507
+ * @returns {Array}
508
+ */
509
+ // eslint-disable-next-line func-names
510
+ const isTypedArray = (TypedArray => {
511
+ // eslint-disable-next-line func-names
512
+ return thing => {
513
+ return TypedArray && thing instanceof TypedArray;
514
+ };
515
+ })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
516
+
517
+ /**
518
+ * For each entry in the object, call the function with the key and value.
519
+ *
520
+ * @param {Object<any, any>} obj - The object to iterate over.
521
+ * @param {Function} fn - The function to call for each entry.
522
+ *
523
+ * @returns {void}
524
+ */
525
+ const forEachEntry = (obj, fn) => {
526
+ const generator = obj && obj[iterator];
527
+
528
+ const _iterator = generator.call(obj);
529
+
530
+ let result;
531
+
532
+ while ((result = _iterator.next()) && !result.done) {
533
+ const pair = result.value;
534
+ fn.call(obj, pair[0], pair[1]);
535
+ }
536
+ };
537
+
538
+ /**
539
+ * It takes a regular expression and a string, and returns an array of all the matches
540
+ *
541
+ * @param {string} regExp - The regular expression to match against.
542
+ * @param {string} str - The string to search.
543
+ *
544
+ * @returns {Array<boolean>}
545
+ */
546
+ const matchAll = (regExp, str) => {
547
+ let matches;
548
+ const arr = [];
549
+
550
+ while ((matches = regExp.exec(str)) !== null) {
551
+ arr.push(matches);
552
+ }
553
+
554
+ return arr;
555
+ };
556
+
557
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
558
+ const isHTMLForm = kindOfTest('HTMLFormElement');
559
+
560
+ const toCamelCase = str => {
561
+ return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
562
+ function replacer(m, p1, p2) {
563
+ return p1.toUpperCase() + p2;
564
+ }
565
+ );
566
+ };
567
+
568
+ /* Creating a function that will check if an object has a property. */
569
+ const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
570
+
571
+ /**
572
+ * Determine if a value is a RegExp object
573
+ *
574
+ * @param {*} val The value to test
575
+ *
576
+ * @returns {boolean} True if value is a RegExp object, otherwise false
577
+ */
578
+ const isRegExp = kindOfTest('RegExp');
579
+
580
+ const reduceDescriptors = (obj, reducer) => {
581
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
582
+ const reducedDescriptors = {};
583
+
584
+ forEach(descriptors, (descriptor, name) => {
585
+ let ret;
586
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
587
+ reducedDescriptors[name] = ret || descriptor;
588
+ }
589
+ });
590
+
591
+ Object.defineProperties(obj, reducedDescriptors);
592
+ };
593
+
594
+ /**
595
+ * Makes all methods read-only
596
+ * @param {Object} obj
597
+ */
598
+
599
+ const freezeMethods = (obj) => {
600
+ reduceDescriptors(obj, (descriptor, name) => {
601
+ // skip restricted props in strict mode
602
+ if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
603
+ return false;
604
+ }
605
+
606
+ const value = obj[name];
607
+
608
+ if (!isFunction$1(value)) return;
609
+
610
+ descriptor.enumerable = false;
611
+
612
+ if ('writable' in descriptor) {
613
+ descriptor.writable = false;
614
+ return;
615
+ }
616
+
617
+ if (!descriptor.set) {
618
+ descriptor.set = () => {
619
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
620
+ };
621
+ }
622
+ });
623
+ };
624
+
625
+ const toObjectSet = (arrayOrString, delimiter) => {
626
+ const obj = {};
627
+
628
+ const define = (arr) => {
629
+ arr.forEach(value => {
630
+ obj[value] = true;
631
+ });
632
+ };
633
+
634
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
635
+
636
+ return obj;
637
+ };
638
+
639
+ const noop = () => {};
640
+
641
+ const toFiniteNumber = (value, defaultValue) => {
642
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
643
+ };
644
+
645
+
646
+
647
+ /**
648
+ * If the thing is a FormData object, return true, otherwise return false.
649
+ *
650
+ * @param {unknown} thing - The thing to check.
651
+ *
652
+ * @returns {boolean}
653
+ */
654
+ function isSpecCompliantForm(thing) {
655
+ return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
656
+ }
657
+
658
+ const toJSONObject = (obj) => {
659
+ const stack = new Array(10);
660
+
661
+ const visit = (source, i) => {
662
+
663
+ if (isObject(source)) {
664
+ if (stack.indexOf(source) >= 0) {
665
+ return;
666
+ }
667
+
668
+ //Buffer check
669
+ if (isBuffer(source)) {
670
+ return source;
671
+ }
672
+
673
+ if(!('toJSON' in source)) {
674
+ stack[i] = source;
675
+ const target = isArray(source) ? [] : {};
676
+
677
+ forEach(source, (value, key) => {
678
+ const reducedValue = visit(value, i + 1);
679
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
680
+ });
681
+
682
+ stack[i] = undefined;
683
+
684
+ return target;
685
+ }
686
+ }
687
+
688
+ return source;
689
+ };
690
+
691
+ return visit(obj, 0);
692
+ };
693
+
694
+ const isAsyncFn = kindOfTest('AsyncFunction');
695
+
696
+ const isThenable = (thing) =>
697
+ thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
698
+
699
+ // original code
700
+ // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
701
+
702
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
703
+ if (setImmediateSupported) {
704
+ return setImmediate;
705
+ }
706
+
707
+ return postMessageSupported ? ((token, callbacks) => {
708
+ _global.addEventListener("message", ({source, data}) => {
709
+ if (source === _global && data === token) {
710
+ callbacks.length && callbacks.shift()();
711
+ }
712
+ }, false);
713
+
714
+ return (cb) => {
715
+ callbacks.push(cb);
716
+ _global.postMessage(token, "*");
717
+ }
718
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
719
+ })(
720
+ typeof setImmediate === 'function',
721
+ isFunction$1(_global.postMessage)
722
+ );
723
+
724
+ const asap = typeof queueMicrotask !== 'undefined' ?
725
+ queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
726
+
727
+ // *********************
728
+
729
+
730
+ const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
731
+
732
+
733
+ var utils$1 = {
734
+ isArray,
735
+ isArrayBuffer,
736
+ isBuffer,
737
+ isFormData,
738
+ isArrayBufferView,
739
+ isString,
740
+ isNumber,
741
+ isBoolean,
742
+ isObject,
743
+ isPlainObject,
744
+ isEmptyObject,
745
+ isReadableStream,
746
+ isRequest,
747
+ isResponse,
748
+ isHeaders,
749
+ isUndefined,
750
+ isDate,
751
+ isFile,
752
+ isBlob,
753
+ isRegExp,
754
+ isFunction: isFunction$1,
755
+ isStream,
756
+ isURLSearchParams,
757
+ isTypedArray,
758
+ isFileList,
759
+ forEach,
760
+ merge,
761
+ extend,
762
+ trim,
763
+ stripBOM,
764
+ inherits,
765
+ toFlatObject,
766
+ kindOf,
767
+ kindOfTest,
768
+ endsWith,
769
+ toArray,
770
+ forEachEntry,
771
+ matchAll,
772
+ isHTMLForm,
773
+ hasOwnProperty,
774
+ hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
775
+ reduceDescriptors,
776
+ freezeMethods,
777
+ toObjectSet,
778
+ toCamelCase,
779
+ noop,
780
+ toFiniteNumber,
781
+ findKey,
782
+ global: _global,
783
+ isContextDefined,
784
+ isSpecCompliantForm,
785
+ toJSONObject,
786
+ isAsyncFn,
787
+ isThenable,
788
+ setImmediate: _setImmediate,
789
+ asap,
790
+ isIterable
791
+ };
792
+
793
+ /**
794
+ * Create an Error with the specified message, config, error code, request and response.
795
+ *
796
+ * @param {string} message The error message.
797
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
798
+ * @param {Object} [config] The config.
799
+ * @param {Object} [request] The request.
800
+ * @param {Object} [response] The response.
801
+ *
802
+ * @returns {Error} The created error.
803
+ */
804
+ function AxiosError$1(message, code, config, request, response) {
805
+ Error.call(this);
806
+
807
+ if (Error.captureStackTrace) {
808
+ Error.captureStackTrace(this, this.constructor);
809
+ } else {
810
+ this.stack = (new Error()).stack;
811
+ }
812
+
813
+ this.message = message;
814
+ this.name = 'AxiosError';
815
+ code && (this.code = code);
816
+ config && (this.config = config);
817
+ request && (this.request = request);
818
+ if (response) {
819
+ this.response = response;
820
+ this.status = response.status ? response.status : null;
821
+ }
822
+ }
823
+
824
+ utils$1.inherits(AxiosError$1, Error, {
825
+ toJSON: function toJSON() {
826
+ return {
827
+ // Standard
828
+ message: this.message,
829
+ name: this.name,
830
+ // Microsoft
831
+ description: this.description,
832
+ number: this.number,
833
+ // Mozilla
834
+ fileName: this.fileName,
835
+ lineNumber: this.lineNumber,
836
+ columnNumber: this.columnNumber,
837
+ stack: this.stack,
838
+ // Axios
839
+ config: utils$1.toJSONObject(this.config),
840
+ code: this.code,
841
+ status: this.status
842
+ };
843
+ }
844
+ });
845
+
846
+ const prototype$1 = AxiosError$1.prototype;
847
+ const descriptors = {};
848
+
849
+ [
850
+ 'ERR_BAD_OPTION_VALUE',
851
+ 'ERR_BAD_OPTION',
852
+ 'ECONNABORTED',
853
+ 'ETIMEDOUT',
854
+ 'ERR_NETWORK',
855
+ 'ERR_FR_TOO_MANY_REDIRECTS',
856
+ 'ERR_DEPRECATED',
857
+ 'ERR_BAD_RESPONSE',
858
+ 'ERR_BAD_REQUEST',
859
+ 'ERR_CANCELED',
860
+ 'ERR_NOT_SUPPORT',
861
+ 'ERR_INVALID_URL'
862
+ // eslint-disable-next-line func-names
863
+ ].forEach(code => {
864
+ descriptors[code] = {value: code};
865
+ });
866
+
867
+ Object.defineProperties(AxiosError$1, descriptors);
868
+ Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
869
+
870
+ // eslint-disable-next-line func-names
871
+ AxiosError$1.from = (error, code, config, request, response, customProps) => {
872
+ const axiosError = Object.create(prototype$1);
873
+
874
+ utils$1.toFlatObject(error, axiosError, function filter(obj) {
875
+ return obj !== Error.prototype;
876
+ }, prop => {
877
+ return prop !== 'isAxiosError';
878
+ });
879
+
880
+ const msg = error && error.message ? error.message : 'Error';
881
+
882
+ // Prefer explicit code; otherwise copy the low-level error's code (e.g. ECONNREFUSED)
883
+ const errCode = code == null && error ? error.code : code;
884
+ AxiosError$1.call(axiosError, msg, errCode, config, request, response);
885
+
886
+ // Chain the original error on the standard field; non-enumerable to avoid JSON noise
887
+ if (error && axiosError.cause == null) {
888
+ Object.defineProperty(axiosError, 'cause', { value: error, configurable: true });
889
+ }
890
+
891
+ axiosError.name = (error && error.name) || 'Error';
892
+
893
+ customProps && Object.assign(axiosError, customProps);
894
+
895
+ return axiosError;
896
+ };
897
+
898
+ // eslint-disable-next-line strict
899
+ var httpAdapter = null;
900
+
901
+ /**
902
+ * Determines if the given thing is a array or js object.
903
+ *
904
+ * @param {string} thing - The object or array to be visited.
905
+ *
906
+ * @returns {boolean}
907
+ */
908
+ function isVisitable(thing) {
909
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
910
+ }
911
+
912
+ /**
913
+ * It removes the brackets from the end of a string
914
+ *
915
+ * @param {string} key - The key of the parameter.
916
+ *
917
+ * @returns {string} the key without the brackets.
918
+ */
919
+ function removeBrackets(key) {
920
+ return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
921
+ }
922
+
923
+ /**
924
+ * It takes a path, a key, and a boolean, and returns a string
925
+ *
926
+ * @param {string} path - The path to the current key.
927
+ * @param {string} key - The key of the current object being iterated over.
928
+ * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
929
+ *
930
+ * @returns {string} The path to the current key.
931
+ */
932
+ function renderKey(path, key, dots) {
933
+ if (!path) return key;
934
+ return path.concat(key).map(function each(token, i) {
935
+ // eslint-disable-next-line no-param-reassign
936
+ token = removeBrackets(token);
937
+ return !dots && i ? '[' + token + ']' : token;
938
+ }).join(dots ? '.' : '');
939
+ }
940
+
941
+ /**
942
+ * If the array is an array and none of its elements are visitable, then it's a flat array.
943
+ *
944
+ * @param {Array<any>} arr - The array to check
945
+ *
946
+ * @returns {boolean}
947
+ */
948
+ function isFlatArray(arr) {
949
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
950
+ }
951
+
952
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
953
+ return /^is[A-Z]/.test(prop);
954
+ });
955
+
956
+ /**
957
+ * Convert a data object to FormData
958
+ *
959
+ * @param {Object} obj
960
+ * @param {?Object} [formData]
961
+ * @param {?Object} [options]
962
+ * @param {Function} [options.visitor]
963
+ * @param {Boolean} [options.metaTokens = true]
964
+ * @param {Boolean} [options.dots = false]
965
+ * @param {?Boolean} [options.indexes = false]
966
+ *
967
+ * @returns {Object}
968
+ **/
969
+
970
+ /**
971
+ * It converts an object into a FormData object
972
+ *
973
+ * @param {Object<any, any>} obj - The object to convert to form data.
974
+ * @param {string} formData - The FormData object to append to.
975
+ * @param {Object<string, any>} options
976
+ *
977
+ * @returns
978
+ */
979
+ function toFormData$1(obj, formData, options) {
980
+ if (!utils$1.isObject(obj)) {
981
+ throw new TypeError('target must be an object');
982
+ }
983
+
984
+ // eslint-disable-next-line no-param-reassign
985
+ formData = formData || new (FormData)();
986
+
987
+ // eslint-disable-next-line no-param-reassign
988
+ options = utils$1.toFlatObject(options, {
989
+ metaTokens: true,
990
+ dots: false,
991
+ indexes: false
992
+ }, false, function defined(option, source) {
993
+ // eslint-disable-next-line no-eq-null,eqeqeq
994
+ return !utils$1.isUndefined(source[option]);
995
+ });
996
+
997
+ const metaTokens = options.metaTokens;
998
+ // eslint-disable-next-line no-use-before-define
999
+ const visitor = options.visitor || defaultVisitor;
1000
+ const dots = options.dots;
1001
+ const indexes = options.indexes;
1002
+ const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1003
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1004
+
1005
+ if (!utils$1.isFunction(visitor)) {
1006
+ throw new TypeError('visitor must be a function');
1007
+ }
1008
+
1009
+ function convertValue(value) {
1010
+ if (value === null) return '';
1011
+
1012
+ if (utils$1.isDate(value)) {
1013
+ return value.toISOString();
1014
+ }
1015
+
1016
+ if (utils$1.isBoolean(value)) {
1017
+ return value.toString();
1018
+ }
1019
+
1020
+ if (!useBlob && utils$1.isBlob(value)) {
1021
+ throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
1022
+ }
1023
+
1024
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
1025
+ return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1026
+ }
1027
+
1028
+ return value;
1029
+ }
1030
+
1031
+ /**
1032
+ * Default visitor.
1033
+ *
1034
+ * @param {*} value
1035
+ * @param {String|Number} key
1036
+ * @param {Array<String|Number>} path
1037
+ * @this {FormData}
1038
+ *
1039
+ * @returns {boolean} return true to visit the each prop of the value recursively
1040
+ */
1041
+ function defaultVisitor(value, key, path) {
1042
+ let arr = value;
1043
+
1044
+ if (value && !path && typeof value === 'object') {
1045
+ if (utils$1.endsWith(key, '{}')) {
1046
+ // eslint-disable-next-line no-param-reassign
1047
+ key = metaTokens ? key : key.slice(0, -2);
1048
+ // eslint-disable-next-line no-param-reassign
1049
+ value = JSON.stringify(value);
1050
+ } else if (
1051
+ (utils$1.isArray(value) && isFlatArray(value)) ||
1052
+ ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
1053
+ )) {
1054
+ // eslint-disable-next-line no-param-reassign
1055
+ key = removeBrackets(key);
1056
+
1057
+ arr.forEach(function each(el, index) {
1058
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
1059
+ // eslint-disable-next-line no-nested-ternary
1060
+ indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1061
+ convertValue(el)
1062
+ );
1063
+ });
1064
+ return false;
1065
+ }
1066
+ }
1067
+
1068
+ if (isVisitable(value)) {
1069
+ return true;
1070
+ }
1071
+
1072
+ formData.append(renderKey(path, key, dots), convertValue(value));
1073
+
1074
+ return false;
1075
+ }
1076
+
1077
+ const stack = [];
1078
+
1079
+ const exposedHelpers = Object.assign(predicates, {
1080
+ defaultVisitor,
1081
+ convertValue,
1082
+ isVisitable
1083
+ });
1084
+
1085
+ function build(value, path) {
1086
+ if (utils$1.isUndefined(value)) return;
1087
+
1088
+ if (stack.indexOf(value) !== -1) {
1089
+ throw Error('Circular reference detected in ' + path.join('.'));
1090
+ }
1091
+
1092
+ stack.push(value);
1093
+
1094
+ utils$1.forEach(value, function each(el, key) {
1095
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
1096
+ formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
1097
+ );
1098
+
1099
+ if (result === true) {
1100
+ build(el, path ? path.concat(key) : [key]);
1101
+ }
1102
+ });
1103
+
1104
+ stack.pop();
1105
+ }
1106
+
1107
+ if (!utils$1.isObject(obj)) {
1108
+ throw new TypeError('data must be an object');
1109
+ }
1110
+
1111
+ build(obj);
1112
+
1113
+ return formData;
1114
+ }
1115
+
1116
+ /**
1117
+ * It encodes a string by replacing all characters that are not in the unreserved set with
1118
+ * their percent-encoded equivalents
1119
+ *
1120
+ * @param {string} str - The string to encode.
1121
+ *
1122
+ * @returns {string} The encoded string.
1123
+ */
1124
+ function encode$1(str) {
1125
+ const charMap = {
1126
+ '!': '%21',
1127
+ "'": '%27',
1128
+ '(': '%28',
1129
+ ')': '%29',
1130
+ '~': '%7E',
1131
+ '%20': '+',
1132
+ '%00': '\x00'
1133
+ };
1134
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1135
+ return charMap[match];
1136
+ });
1137
+ }
1138
+
1139
+ /**
1140
+ * It takes a params object and converts it to a FormData object
1141
+ *
1142
+ * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1143
+ * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1144
+ *
1145
+ * @returns {void}
1146
+ */
1147
+ function AxiosURLSearchParams(params, options) {
1148
+ this._pairs = [];
1149
+
1150
+ params && toFormData$1(params, this, options);
1151
+ }
1152
+
1153
+ const prototype = AxiosURLSearchParams.prototype;
1154
+
1155
+ prototype.append = function append(name, value) {
1156
+ this._pairs.push([name, value]);
1157
+ };
1158
+
1159
+ prototype.toString = function toString(encoder) {
1160
+ const _encode = encoder ? function(value) {
1161
+ return encoder.call(this, value, encode$1);
1162
+ } : encode$1;
1163
+
1164
+ return this._pairs.map(function each(pair) {
1165
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
1166
+ }, '').join('&');
1167
+ };
1168
+
1169
+ /**
1170
+ * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1171
+ * URI encoded counterparts
1172
+ *
1173
+ * @param {string} val The value to be encoded.
1174
+ *
1175
+ * @returns {string} The encoded value.
1176
+ */
1177
+ function encode(val) {
1178
+ return encodeURIComponent(val).
1179
+ replace(/%3A/gi, ':').
1180
+ replace(/%24/g, '$').
1181
+ replace(/%2C/gi, ',').
1182
+ replace(/%20/g, '+');
1183
+ }
1184
+
1185
+ /**
1186
+ * Build a URL by appending params to the end
1187
+ *
1188
+ * @param {string} url The base of the url (e.g., http://www.google.com)
1189
+ * @param {object} [params] The params to be appended
1190
+ * @param {?(object|Function)} options
1191
+ *
1192
+ * @returns {string} The formatted url
1193
+ */
1194
+ function buildURL(url, params, options) {
1195
+ /*eslint no-param-reassign:0*/
1196
+ if (!params) {
1197
+ return url;
1198
+ }
1199
+
1200
+ const _encode = options && options.encode || encode;
1201
+
1202
+ if (utils$1.isFunction(options)) {
1203
+ options = {
1204
+ serialize: options
1205
+ };
1206
+ }
1207
+
1208
+ const serializeFn = options && options.serialize;
1209
+
1210
+ let serializedParams;
1211
+
1212
+ if (serializeFn) {
1213
+ serializedParams = serializeFn(params, options);
1214
+ } else {
1215
+ serializedParams = utils$1.isURLSearchParams(params) ?
1216
+ params.toString() :
1217
+ new AxiosURLSearchParams(params, options).toString(_encode);
1218
+ }
1219
+
1220
+ if (serializedParams) {
1221
+ const hashmarkIndex = url.indexOf("#");
1222
+
1223
+ if (hashmarkIndex !== -1) {
1224
+ url = url.slice(0, hashmarkIndex);
1225
+ }
1226
+ url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1227
+ }
1228
+
1229
+ return url;
1230
+ }
1231
+
1232
+ class InterceptorManager {
1233
+ constructor() {
1234
+ this.handlers = [];
1235
+ }
1236
+
1237
+ /**
1238
+ * Add a new interceptor to the stack
1239
+ *
1240
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
1241
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
1242
+ *
1243
+ * @return {Number} An ID used to remove interceptor later
1244
+ */
1245
+ use(fulfilled, rejected, options) {
1246
+ this.handlers.push({
1247
+ fulfilled,
1248
+ rejected,
1249
+ synchronous: options ? options.synchronous : false,
1250
+ runWhen: options ? options.runWhen : null
1251
+ });
1252
+ return this.handlers.length - 1;
1253
+ }
1254
+
1255
+ /**
1256
+ * Remove an interceptor from the stack
1257
+ *
1258
+ * @param {Number} id The ID that was returned by `use`
1259
+ *
1260
+ * @returns {void}
1261
+ */
1262
+ eject(id) {
1263
+ if (this.handlers[id]) {
1264
+ this.handlers[id] = null;
1265
+ }
1266
+ }
1267
+
1268
+ /**
1269
+ * Clear all interceptors from the stack
1270
+ *
1271
+ * @returns {void}
1272
+ */
1273
+ clear() {
1274
+ if (this.handlers) {
1275
+ this.handlers = [];
1276
+ }
1277
+ }
1278
+
1279
+ /**
1280
+ * Iterate over all the registered interceptors
1281
+ *
1282
+ * This method is particularly useful for skipping over any
1283
+ * interceptors that may have become `null` calling `eject`.
1284
+ *
1285
+ * @param {Function} fn The function to call for each interceptor
1286
+ *
1287
+ * @returns {void}
1288
+ */
1289
+ forEach(fn) {
1290
+ utils$1.forEach(this.handlers, function forEachHandler(h) {
1291
+ if (h !== null) {
1292
+ fn(h);
1293
+ }
1294
+ });
1295
+ }
1296
+ }
1297
+
1298
+ var transitionalDefaults = {
1299
+ silentJSONParsing: true,
1300
+ forcedJSONParsing: true,
1301
+ clarifyTimeoutError: false
1302
+ };
1303
+
1304
+ var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1305
+
1306
+ var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
1307
+
1308
+ var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
1309
+
1310
+ var platform$1 = {
1311
+ isBrowser: true,
1312
+ classes: {
1313
+ URLSearchParams: URLSearchParams$1,
1314
+ FormData: FormData$1,
1315
+ Blob: Blob$1
1316
+ },
1317
+ protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1318
+ };
1319
+
1320
+ const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
1321
+
1322
+ const _navigator = typeof navigator === 'object' && navigator || undefined;
1323
+
1324
+ /**
1325
+ * Determine if we're running in a standard browser environment
1326
+ *
1327
+ * This allows axios to run in a web worker, and react-native.
1328
+ * Both environments support XMLHttpRequest, but not fully standard globals.
1329
+ *
1330
+ * web workers:
1331
+ * typeof window -> undefined
1332
+ * typeof document -> undefined
1333
+ *
1334
+ * react-native:
1335
+ * navigator.product -> 'ReactNative'
1336
+ * nativescript
1337
+ * navigator.product -> 'NativeScript' or 'NS'
1338
+ *
1339
+ * @returns {boolean}
1340
+ */
1341
+ const hasStandardBrowserEnv = hasBrowserEnv &&
1342
+ (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
1343
+
1344
+ /**
1345
+ * Determine if we're running in a standard browser webWorker environment
1346
+ *
1347
+ * Although the `isStandardBrowserEnv` method indicates that
1348
+ * `allows axios to run in a web worker`, the WebWorker will still be
1349
+ * filtered out due to its judgment standard
1350
+ * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1351
+ * This leads to a problem when axios post `FormData` in webWorker
1352
+ */
1353
+ const hasStandardBrowserWebWorkerEnv = (() => {
1354
+ return (
1355
+ typeof WorkerGlobalScope !== 'undefined' &&
1356
+ // eslint-disable-next-line no-undef
1357
+ self instanceof WorkerGlobalScope &&
1358
+ typeof self.importScripts === 'function'
1359
+ );
1360
+ })();
1361
+
1362
+ const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1363
+
1364
+ var utils = /*#__PURE__*/Object.freeze({
1365
+ __proto__: null,
1366
+ hasBrowserEnv: hasBrowserEnv,
1367
+ hasStandardBrowserEnv: hasStandardBrowserEnv,
1368
+ hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1369
+ navigator: _navigator,
1370
+ origin: origin
1371
+ });
1372
+
1373
+ var platform = {
1374
+ ...utils,
1375
+ ...platform$1
1376
+ };
1377
+
1378
+ function toURLEncodedForm(data, options) {
1379
+ return toFormData$1(data, new platform.classes.URLSearchParams(), {
1380
+ visitor: function(value, key, path, helpers) {
1381
+ if (platform.isNode && utils$1.isBuffer(value)) {
1382
+ this.append(key, value.toString('base64'));
1383
+ return false;
1384
+ }
1385
+
1386
+ return helpers.defaultVisitor.apply(this, arguments);
1387
+ },
1388
+ ...options
1389
+ });
1390
+ }
1391
+
1392
+ /**
1393
+ * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1394
+ *
1395
+ * @param {string} name - The name of the property to get.
1396
+ *
1397
+ * @returns An array of strings.
1398
+ */
1399
+ function parsePropPath(name) {
1400
+ // foo[x][y][z]
1401
+ // foo.x.y.z
1402
+ // foo-x-y-z
1403
+ // foo x y z
1404
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1405
+ return match[0] === '[]' ? '' : match[1] || match[0];
1406
+ });
1407
+ }
1408
+
1409
+ /**
1410
+ * Convert an array to an object.
1411
+ *
1412
+ * @param {Array<any>} arr - The array to convert to an object.
1413
+ *
1414
+ * @returns An object with the same keys and values as the array.
1415
+ */
1416
+ function arrayToObject(arr) {
1417
+ const obj = {};
1418
+ const keys = Object.keys(arr);
1419
+ let i;
1420
+ const len = keys.length;
1421
+ let key;
1422
+ for (i = 0; i < len; i++) {
1423
+ key = keys[i];
1424
+ obj[key] = arr[key];
1425
+ }
1426
+ return obj;
1427
+ }
1428
+
1429
+ /**
1430
+ * It takes a FormData object and returns a JavaScript object
1431
+ *
1432
+ * @param {string} formData The FormData object to convert to JSON.
1433
+ *
1434
+ * @returns {Object<string, any> | null} The converted object.
1435
+ */
1436
+ function formDataToJSON(formData) {
1437
+ function buildPath(path, value, target, index) {
1438
+ let name = path[index++];
1439
+
1440
+ if (name === '__proto__') return true;
1441
+
1442
+ const isNumericKey = Number.isFinite(+name);
1443
+ const isLast = index >= path.length;
1444
+ name = !name && utils$1.isArray(target) ? target.length : name;
1445
+
1446
+ if (isLast) {
1447
+ if (utils$1.hasOwnProp(target, name)) {
1448
+ target[name] = [target[name], value];
1449
+ } else {
1450
+ target[name] = value;
1451
+ }
1452
+
1453
+ return !isNumericKey;
1454
+ }
1455
+
1456
+ if (!target[name] || !utils$1.isObject(target[name])) {
1457
+ target[name] = [];
1458
+ }
1459
+
1460
+ const result = buildPath(path, value, target[name], index);
1461
+
1462
+ if (result && utils$1.isArray(target[name])) {
1463
+ target[name] = arrayToObject(target[name]);
1464
+ }
1465
+
1466
+ return !isNumericKey;
1467
+ }
1468
+
1469
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1470
+ const obj = {};
1471
+
1472
+ utils$1.forEachEntry(formData, (name, value) => {
1473
+ buildPath(parsePropPath(name), value, obj, 0);
1474
+ });
1475
+
1476
+ return obj;
1477
+ }
1478
+
1479
+ return null;
1480
+ }
1481
+
1482
+ /**
1483
+ * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1484
+ * of the input
1485
+ *
1486
+ * @param {any} rawValue - The value to be stringified.
1487
+ * @param {Function} parser - A function that parses a string into a JavaScript object.
1488
+ * @param {Function} encoder - A function that takes a value and returns a string.
1489
+ *
1490
+ * @returns {string} A stringified version of the rawValue.
1491
+ */
1492
+ function stringifySafely(rawValue, parser, encoder) {
1493
+ if (utils$1.isString(rawValue)) {
1494
+ try {
1495
+ (parser || JSON.parse)(rawValue);
1496
+ return utils$1.trim(rawValue);
1497
+ } catch (e) {
1498
+ if (e.name !== 'SyntaxError') {
1499
+ throw e;
1500
+ }
1501
+ }
1502
+ }
1503
+
1504
+ return (encoder || JSON.stringify)(rawValue);
1505
+ }
1506
+
1507
+ const defaults = {
1508
+
1509
+ transitional: transitionalDefaults,
1510
+
1511
+ adapter: ['xhr', 'http', 'fetch'],
1512
+
1513
+ transformRequest: [function transformRequest(data, headers) {
1514
+ const contentType = headers.getContentType() || '';
1515
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
1516
+ const isObjectPayload = utils$1.isObject(data);
1517
+
1518
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1519
+ data = new FormData(data);
1520
+ }
1521
+
1522
+ const isFormData = utils$1.isFormData(data);
1523
+
1524
+ if (isFormData) {
1525
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1526
+ }
1527
+
1528
+ if (utils$1.isArrayBuffer(data) ||
1529
+ utils$1.isBuffer(data) ||
1530
+ utils$1.isStream(data) ||
1531
+ utils$1.isFile(data) ||
1532
+ utils$1.isBlob(data) ||
1533
+ utils$1.isReadableStream(data)
1534
+ ) {
1535
+ return data;
1536
+ }
1537
+ if (utils$1.isArrayBufferView(data)) {
1538
+ return data.buffer;
1539
+ }
1540
+ if (utils$1.isURLSearchParams(data)) {
1541
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1542
+ return data.toString();
1543
+ }
1544
+
1545
+ let isFileList;
1546
+
1547
+ if (isObjectPayload) {
1548
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1549
+ return toURLEncodedForm(data, this.formSerializer).toString();
1550
+ }
1551
+
1552
+ if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1553
+ const _FormData = this.env && this.env.FormData;
1554
+
1555
+ return toFormData$1(
1556
+ isFileList ? {'files[]': data} : data,
1557
+ _FormData && new _FormData(),
1558
+ this.formSerializer
1559
+ );
1560
+ }
1561
+ }
1562
+
1563
+ if (isObjectPayload || hasJSONContentType ) {
1564
+ headers.setContentType('application/json', false);
1565
+ return stringifySafely(data);
1566
+ }
1567
+
1568
+ return data;
1569
+ }],
1570
+
1571
+ transformResponse: [function transformResponse(data) {
1572
+ const transitional = this.transitional || defaults.transitional;
1573
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1574
+ const JSONRequested = this.responseType === 'json';
1575
+
1576
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1577
+ return data;
1578
+ }
1579
+
1580
+ if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1581
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
1582
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1583
+
1584
+ try {
1585
+ return JSON.parse(data, this.parseReviver);
1586
+ } catch (e) {
1587
+ if (strictJSONParsing) {
1588
+ if (e.name === 'SyntaxError') {
1589
+ throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1590
+ }
1591
+ throw e;
1592
+ }
1593
+ }
1594
+ }
1595
+
1596
+ return data;
1597
+ }],
1598
+
1599
+ /**
1600
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1601
+ * timeout is not created.
1602
+ */
1603
+ timeout: 0,
1604
+
1605
+ xsrfCookieName: 'XSRF-TOKEN',
1606
+ xsrfHeaderName: 'X-XSRF-TOKEN',
1607
+
1608
+ maxContentLength: -1,
1609
+ maxBodyLength: -1,
1610
+
1611
+ env: {
1612
+ FormData: platform.classes.FormData,
1613
+ Blob: platform.classes.Blob
1614
+ },
1615
+
1616
+ validateStatus: function validateStatus(status) {
1617
+ return status >= 200 && status < 300;
1618
+ },
1619
+
1620
+ headers: {
1621
+ common: {
1622
+ 'Accept': 'application/json, text/plain, */*',
1623
+ 'Content-Type': undefined
1624
+ }
1625
+ }
1626
+ };
1627
+
1628
+ utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
1629
+ defaults.headers[method] = {};
1630
+ });
1631
+
1632
+ // RawAxiosHeaders whose duplicates are ignored by node
1633
+ // c.f. https://nodejs.org/api/http.html#http_message_headers
1634
+ const ignoreDuplicateOf = utils$1.toObjectSet([
1635
+ 'age', 'authorization', 'content-length', 'content-type', 'etag',
1636
+ 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1637
+ 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1638
+ 'referer', 'retry-after', 'user-agent'
1639
+ ]);
1640
+
1641
+ /**
1642
+ * Parse headers into an object
1643
+ *
1644
+ * ```
1645
+ * Date: Wed, 27 Aug 2014 08:58:49 GMT
1646
+ * Content-Type: application/json
1647
+ * Connection: keep-alive
1648
+ * Transfer-Encoding: chunked
1649
+ * ```
1650
+ *
1651
+ * @param {String} rawHeaders Headers needing to be parsed
1652
+ *
1653
+ * @returns {Object} Headers parsed into an object
1654
+ */
1655
+ var parseHeaders = rawHeaders => {
1656
+ const parsed = {};
1657
+ let key;
1658
+ let val;
1659
+ let i;
1660
+
1661
+ rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1662
+ i = line.indexOf(':');
1663
+ key = line.substring(0, i).trim().toLowerCase();
1664
+ val = line.substring(i + 1).trim();
1665
+
1666
+ if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1667
+ return;
1668
+ }
1669
+
1670
+ if (key === 'set-cookie') {
1671
+ if (parsed[key]) {
1672
+ parsed[key].push(val);
1673
+ } else {
1674
+ parsed[key] = [val];
1675
+ }
1676
+ } else {
1677
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1678
+ }
1679
+ });
1680
+
1681
+ return parsed;
1682
+ };
1683
+
1684
+ const $internals = Symbol('internals');
1685
+
1686
+ function normalizeHeader(header) {
1687
+ return header && String(header).trim().toLowerCase();
1688
+ }
1689
+
1690
+ function normalizeValue(value) {
1691
+ if (value === false || value == null) {
1692
+ return value;
1693
+ }
1694
+
1695
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1696
+ }
1697
+
1698
+ function parseTokens(str) {
1699
+ const tokens = Object.create(null);
1700
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1701
+ let match;
1702
+
1703
+ while ((match = tokensRE.exec(str))) {
1704
+ tokens[match[1]] = match[2];
1705
+ }
1706
+
1707
+ return tokens;
1708
+ }
1709
+
1710
+ const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1711
+
1712
+ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1713
+ if (utils$1.isFunction(filter)) {
1714
+ return filter.call(this, value, header);
1715
+ }
1716
+
1717
+ if (isHeaderNameFilter) {
1718
+ value = header;
1719
+ }
1720
+
1721
+ if (!utils$1.isString(value)) return;
1722
+
1723
+ if (utils$1.isString(filter)) {
1724
+ return value.indexOf(filter) !== -1;
1725
+ }
1726
+
1727
+ if (utils$1.isRegExp(filter)) {
1728
+ return filter.test(value);
1729
+ }
1730
+ }
1731
+
1732
+ function formatHeader(header) {
1733
+ return header.trim()
1734
+ .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1735
+ return char.toUpperCase() + str;
1736
+ });
1737
+ }
1738
+
1739
+ function buildAccessors(obj, header) {
1740
+ const accessorName = utils$1.toCamelCase(' ' + header);
1741
+
1742
+ ['get', 'set', 'has'].forEach(methodName => {
1743
+ Object.defineProperty(obj, methodName + accessorName, {
1744
+ value: function(arg1, arg2, arg3) {
1745
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1746
+ },
1747
+ configurable: true
1748
+ });
1749
+ });
1750
+ }
1751
+
1752
+ let AxiosHeaders$1 = class AxiosHeaders {
1753
+ constructor(headers) {
1754
+ headers && this.set(headers);
1755
+ }
1756
+
1757
+ set(header, valueOrRewrite, rewrite) {
1758
+ const self = this;
1759
+
1760
+ function setHeader(_value, _header, _rewrite) {
1761
+ const lHeader = normalizeHeader(_header);
1762
+
1763
+ if (!lHeader) {
1764
+ throw new Error('header name must be a non-empty string');
1765
+ }
1766
+
1767
+ const key = utils$1.findKey(self, lHeader);
1768
+
1769
+ if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1770
+ self[key || _header] = normalizeValue(_value);
1771
+ }
1772
+ }
1773
+
1774
+ const setHeaders = (headers, _rewrite) =>
1775
+ utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1776
+
1777
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1778
+ setHeaders(header, valueOrRewrite);
1779
+ } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1780
+ setHeaders(parseHeaders(header), valueOrRewrite);
1781
+ } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1782
+ let obj = {}, dest, key;
1783
+ for (const entry of header) {
1784
+ if (!utils$1.isArray(entry)) {
1785
+ throw TypeError('Object iterator must return a key-value pair');
1786
+ }
1787
+
1788
+ obj[key = entry[0]] = (dest = obj[key]) ?
1789
+ (utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1];
1790
+ }
1791
+
1792
+ setHeaders(obj, valueOrRewrite);
1793
+ } else {
1794
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1795
+ }
1796
+
1797
+ return this;
1798
+ }
1799
+
1800
+ get(header, parser) {
1801
+ header = normalizeHeader(header);
1802
+
1803
+ if (header) {
1804
+ const key = utils$1.findKey(this, header);
1805
+
1806
+ if (key) {
1807
+ const value = this[key];
1808
+
1809
+ if (!parser) {
1810
+ return value;
1811
+ }
1812
+
1813
+ if (parser === true) {
1814
+ return parseTokens(value);
1815
+ }
1816
+
1817
+ if (utils$1.isFunction(parser)) {
1818
+ return parser.call(this, value, key);
1819
+ }
1820
+
1821
+ if (utils$1.isRegExp(parser)) {
1822
+ return parser.exec(value);
1823
+ }
1824
+
1825
+ throw new TypeError('parser must be boolean|regexp|function');
1826
+ }
1827
+ }
1828
+ }
1829
+
1830
+ has(header, matcher) {
1831
+ header = normalizeHeader(header);
1832
+
1833
+ if (header) {
1834
+ const key = utils$1.findKey(this, header);
1835
+
1836
+ return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1837
+ }
1838
+
1839
+ return false;
1840
+ }
1841
+
1842
+ delete(header, matcher) {
1843
+ const self = this;
1844
+ let deleted = false;
1845
+
1846
+ function deleteHeader(_header) {
1847
+ _header = normalizeHeader(_header);
1848
+
1849
+ if (_header) {
1850
+ const key = utils$1.findKey(self, _header);
1851
+
1852
+ if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1853
+ delete self[key];
1854
+
1855
+ deleted = true;
1856
+ }
1857
+ }
1858
+ }
1859
+
1860
+ if (utils$1.isArray(header)) {
1861
+ header.forEach(deleteHeader);
1862
+ } else {
1863
+ deleteHeader(header);
1864
+ }
1865
+
1866
+ return deleted;
1867
+ }
1868
+
1869
+ clear(matcher) {
1870
+ const keys = Object.keys(this);
1871
+ let i = keys.length;
1872
+ let deleted = false;
1873
+
1874
+ while (i--) {
1875
+ const key = keys[i];
1876
+ if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1877
+ delete this[key];
1878
+ deleted = true;
1879
+ }
1880
+ }
1881
+
1882
+ return deleted;
1883
+ }
1884
+
1885
+ normalize(format) {
1886
+ const self = this;
1887
+ const headers = {};
1888
+
1889
+ utils$1.forEach(this, (value, header) => {
1890
+ const key = utils$1.findKey(headers, header);
1891
+
1892
+ if (key) {
1893
+ self[key] = normalizeValue(value);
1894
+ delete self[header];
1895
+ return;
1896
+ }
1897
+
1898
+ const normalized = format ? formatHeader(header) : String(header).trim();
1899
+
1900
+ if (normalized !== header) {
1901
+ delete self[header];
1902
+ }
1903
+
1904
+ self[normalized] = normalizeValue(value);
1905
+
1906
+ headers[normalized] = true;
1907
+ });
1908
+
1909
+ return this;
1910
+ }
1911
+
1912
+ concat(...targets) {
1913
+ return this.constructor.concat(this, ...targets);
1914
+ }
1915
+
1916
+ toJSON(asStrings) {
1917
+ const obj = Object.create(null);
1918
+
1919
+ utils$1.forEach(this, (value, header) => {
1920
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1921
+ });
1922
+
1923
+ return obj;
1924
+ }
1925
+
1926
+ [Symbol.iterator]() {
1927
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1928
+ }
1929
+
1930
+ toString() {
1931
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1932
+ }
1933
+
1934
+ getSetCookie() {
1935
+ return this.get("set-cookie") || [];
1936
+ }
1937
+
1938
+ get [Symbol.toStringTag]() {
1939
+ return 'AxiosHeaders';
1940
+ }
1941
+
1942
+ static from(thing) {
1943
+ return thing instanceof this ? thing : new this(thing);
1944
+ }
1945
+
1946
+ static concat(first, ...targets) {
1947
+ const computed = new this(first);
1948
+
1949
+ targets.forEach((target) => computed.set(target));
1950
+
1951
+ return computed;
1952
+ }
1953
+
1954
+ static accessor(header) {
1955
+ const internals = this[$internals] = (this[$internals] = {
1956
+ accessors: {}
1957
+ });
1958
+
1959
+ const accessors = internals.accessors;
1960
+ const prototype = this.prototype;
1961
+
1962
+ function defineAccessor(_header) {
1963
+ const lHeader = normalizeHeader(_header);
1964
+
1965
+ if (!accessors[lHeader]) {
1966
+ buildAccessors(prototype, _header);
1967
+ accessors[lHeader] = true;
1968
+ }
1969
+ }
1970
+
1971
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1972
+
1973
+ return this;
1974
+ }
1975
+ };
1976
+
1977
+ AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1978
+
1979
+ // reserved names hotfix
1980
+ utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => {
1981
+ let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1982
+ return {
1983
+ get: () => value,
1984
+ set(headerValue) {
1985
+ this[mapped] = headerValue;
1986
+ }
1987
+ }
1988
+ });
1989
+
1990
+ utils$1.freezeMethods(AxiosHeaders$1);
1991
+
1992
+ /**
1993
+ * Transform the data for a request or a response
1994
+ *
1995
+ * @param {Array|Function} fns A single function or Array of functions
1996
+ * @param {?Object} response The response object
1997
+ *
1998
+ * @returns {*} The resulting transformed data
1999
+ */
2000
+ function transformData(fns, response) {
2001
+ const config = this || defaults;
2002
+ const context = response || config;
2003
+ const headers = AxiosHeaders$1.from(context.headers);
2004
+ let data = context.data;
2005
+
2006
+ utils$1.forEach(fns, function transform(fn) {
2007
+ data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
2008
+ });
2009
+
2010
+ headers.normalize();
2011
+
2012
+ return data;
2013
+ }
2014
+
2015
+ function isCancel$1(value) {
2016
+ return !!(value && value.__CANCEL__);
2017
+ }
2018
+
2019
+ /**
2020
+ * A `CanceledError` is an object that is thrown when an operation is canceled.
2021
+ *
2022
+ * @param {string=} message The message.
2023
+ * @param {Object=} config The config.
2024
+ * @param {Object=} request The request.
2025
+ *
2026
+ * @returns {CanceledError} The created error.
2027
+ */
2028
+ function CanceledError$1(message, config, request) {
2029
+ // eslint-disable-next-line no-eq-null,eqeqeq
2030
+ AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
2031
+ this.name = 'CanceledError';
2032
+ }
2033
+
2034
+ utils$1.inherits(CanceledError$1, AxiosError$1, {
2035
+ __CANCEL__: true
2036
+ });
2037
+
2038
+ /**
2039
+ * Resolve or reject a Promise based on response status.
2040
+ *
2041
+ * @param {Function} resolve A function that resolves the promise.
2042
+ * @param {Function} reject A function that rejects the promise.
2043
+ * @param {object} response The response.
2044
+ *
2045
+ * @returns {object} The response.
2046
+ */
2047
+ function settle(resolve, reject, response) {
2048
+ const validateStatus = response.config.validateStatus;
2049
+ if (!response.status || !validateStatus || validateStatus(response.status)) {
2050
+ resolve(response);
2051
+ } else {
2052
+ reject(new AxiosError$1(
2053
+ 'Request failed with status code ' + response.status,
2054
+ [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2055
+ response.config,
2056
+ response.request,
2057
+ response
2058
+ ));
2059
+ }
2060
+ }
2061
+
2062
+ function parseProtocol(url) {
2063
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2064
+ return match && match[1] || '';
2065
+ }
2066
+
2067
+ /**
2068
+ * Calculate data maxRate
2069
+ * @param {Number} [samplesCount= 10]
2070
+ * @param {Number} [min= 1000]
2071
+ * @returns {Function}
2072
+ */
2073
+ function speedometer(samplesCount, min) {
2074
+ samplesCount = samplesCount || 10;
2075
+ const bytes = new Array(samplesCount);
2076
+ const timestamps = new Array(samplesCount);
2077
+ let head = 0;
2078
+ let tail = 0;
2079
+ let firstSampleTS;
2080
+
2081
+ min = min !== undefined ? min : 1000;
2082
+
2083
+ return function push(chunkLength) {
2084
+ const now = Date.now();
2085
+
2086
+ const startedAt = timestamps[tail];
2087
+
2088
+ if (!firstSampleTS) {
2089
+ firstSampleTS = now;
2090
+ }
2091
+
2092
+ bytes[head] = chunkLength;
2093
+ timestamps[head] = now;
2094
+
2095
+ let i = tail;
2096
+ let bytesCount = 0;
2097
+
2098
+ while (i !== head) {
2099
+ bytesCount += bytes[i++];
2100
+ i = i % samplesCount;
2101
+ }
2102
+
2103
+ head = (head + 1) % samplesCount;
2104
+
2105
+ if (head === tail) {
2106
+ tail = (tail + 1) % samplesCount;
2107
+ }
2108
+
2109
+ if (now - firstSampleTS < min) {
2110
+ return;
2111
+ }
2112
+
2113
+ const passed = startedAt && now - startedAt;
2114
+
2115
+ return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2116
+ };
2117
+ }
2118
+
2119
+ /**
2120
+ * Throttle decorator
2121
+ * @param {Function} fn
2122
+ * @param {Number} freq
2123
+ * @return {Function}
2124
+ */
2125
+ function throttle(fn, freq) {
2126
+ let timestamp = 0;
2127
+ let threshold = 1000 / freq;
2128
+ let lastArgs;
2129
+ let timer;
2130
+
2131
+ const invoke = (args, now = Date.now()) => {
2132
+ timestamp = now;
2133
+ lastArgs = null;
2134
+ if (timer) {
2135
+ clearTimeout(timer);
2136
+ timer = null;
2137
+ }
2138
+ fn(...args);
2139
+ };
2140
+
2141
+ const throttled = (...args) => {
2142
+ const now = Date.now();
2143
+ const passed = now - timestamp;
2144
+ if ( passed >= threshold) {
2145
+ invoke(args, now);
2146
+ } else {
2147
+ lastArgs = args;
2148
+ if (!timer) {
2149
+ timer = setTimeout(() => {
2150
+ timer = null;
2151
+ invoke(lastArgs);
2152
+ }, threshold - passed);
2153
+ }
2154
+ }
2155
+ };
2156
+
2157
+ const flush = () => lastArgs && invoke(lastArgs);
2158
+
2159
+ return [throttled, flush];
2160
+ }
2161
+
2162
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2163
+ let bytesNotified = 0;
2164
+ const _speedometer = speedometer(50, 250);
2165
+
2166
+ return throttle(e => {
2167
+ const loaded = e.loaded;
2168
+ const total = e.lengthComputable ? e.total : undefined;
2169
+ const progressBytes = loaded - bytesNotified;
2170
+ const rate = _speedometer(progressBytes);
2171
+ const inRange = loaded <= total;
2172
+
2173
+ bytesNotified = loaded;
2174
+
2175
+ const data = {
2176
+ loaded,
2177
+ total,
2178
+ progress: total ? (loaded / total) : undefined,
2179
+ bytes: progressBytes,
2180
+ rate: rate ? rate : undefined,
2181
+ estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2182
+ event: e,
2183
+ lengthComputable: total != null,
2184
+ [isDownloadStream ? 'download' : 'upload']: true
2185
+ };
2186
+
2187
+ listener(data);
2188
+ }, freq);
2189
+ };
2190
+
2191
+ const progressEventDecorator = (total, throttled) => {
2192
+ const lengthComputable = total != null;
2193
+
2194
+ return [(loaded) => throttled[0]({
2195
+ lengthComputable,
2196
+ total,
2197
+ loaded
2198
+ }), throttled[1]];
2199
+ };
2200
+
2201
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2202
+
2203
+ var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
2204
+ url = new URL(url, platform.origin);
2205
+
2206
+ return (
2207
+ origin.protocol === url.protocol &&
2208
+ origin.host === url.host &&
2209
+ (isMSIE || origin.port === url.port)
2210
+ );
2211
+ })(
2212
+ new URL(platform.origin),
2213
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
2214
+ ) : () => true;
2215
+
2216
+ var cookies = platform.hasStandardBrowserEnv ?
2217
+
2218
+ // Standard browser envs support document.cookie
2219
+ {
2220
+ write(name, value, expires, path, domain, secure, sameSite) {
2221
+ if (typeof document === 'undefined') return;
2222
+
2223
+ const cookie = [`${name}=${encodeURIComponent(value)}`];
2224
+
2225
+ if (utils$1.isNumber(expires)) {
2226
+ cookie.push(`expires=${new Date(expires).toUTCString()}`);
2227
+ }
2228
+ if (utils$1.isString(path)) {
2229
+ cookie.push(`path=${path}`);
2230
+ }
2231
+ if (utils$1.isString(domain)) {
2232
+ cookie.push(`domain=${domain}`);
2233
+ }
2234
+ if (secure === true) {
2235
+ cookie.push('secure');
2236
+ }
2237
+ if (utils$1.isString(sameSite)) {
2238
+ cookie.push(`SameSite=${sameSite}`);
2239
+ }
2240
+
2241
+ document.cookie = cookie.join('; ');
2242
+ },
2243
+
2244
+ read(name) {
2245
+ if (typeof document === 'undefined') return null;
2246
+ const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
2247
+ return match ? decodeURIComponent(match[1]) : null;
2248
+ },
2249
+
2250
+ remove(name) {
2251
+ this.write(name, '', Date.now() - 86400000, '/');
2252
+ }
2253
+ }
2254
+
2255
+ :
2256
+
2257
+ // Non-standard browser env (web workers, react-native) lack needed support.
2258
+ {
2259
+ write() {},
2260
+ read() {
2261
+ return null;
2262
+ },
2263
+ remove() {}
2264
+ };
2265
+
2266
+ /**
2267
+ * Determines whether the specified URL is absolute
2268
+ *
2269
+ * @param {string} url The URL to test
2270
+ *
2271
+ * @returns {boolean} True if the specified URL is absolute, otherwise false
2272
+ */
2273
+ function isAbsoluteURL(url) {
2274
+ // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2275
+ // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2276
+ // by any combination of letters, digits, plus, period, or hyphen.
2277
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2278
+ }
2279
+
2280
+ /**
2281
+ * Creates a new URL by combining the specified URLs
2282
+ *
2283
+ * @param {string} baseURL The base URL
2284
+ * @param {string} relativeURL The relative URL
2285
+ *
2286
+ * @returns {string} The combined URL
2287
+ */
2288
+ function combineURLs(baseURL, relativeURL) {
2289
+ return relativeURL
2290
+ ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2291
+ : baseURL;
2292
+ }
2293
+
2294
+ /**
2295
+ * Creates a new URL by combining the baseURL with the requestedURL,
2296
+ * only when the requestedURL is not already an absolute URL.
2297
+ * If the requestURL is absolute, this function returns the requestedURL untouched.
2298
+ *
2299
+ * @param {string} baseURL The base URL
2300
+ * @param {string} requestedURL Absolute or relative URL to combine
2301
+ *
2302
+ * @returns {string} The combined full path
2303
+ */
2304
+ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2305
+ let isRelativeUrl = !isAbsoluteURL(requestedURL);
2306
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2307
+ return combineURLs(baseURL, requestedURL);
2308
+ }
2309
+ return requestedURL;
2310
+ }
2311
+
2312
+ const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
2313
+
2314
+ /**
2315
+ * Config-specific merge-function which creates a new config-object
2316
+ * by merging two configuration objects together.
2317
+ *
2318
+ * @param {Object} config1
2319
+ * @param {Object} config2
2320
+ *
2321
+ * @returns {Object} New object resulting from merging config2 to config1
2322
+ */
2323
+ function mergeConfig$1(config1, config2) {
2324
+ // eslint-disable-next-line no-param-reassign
2325
+ config2 = config2 || {};
2326
+ const config = {};
2327
+
2328
+ function getMergedValue(target, source, prop, caseless) {
2329
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
2330
+ return utils$1.merge.call({caseless}, target, source);
2331
+ } else if (utils$1.isPlainObject(source)) {
2332
+ return utils$1.merge({}, source);
2333
+ } else if (utils$1.isArray(source)) {
2334
+ return source.slice();
2335
+ }
2336
+ return source;
2337
+ }
2338
+
2339
+ // eslint-disable-next-line consistent-return
2340
+ function mergeDeepProperties(a, b, prop, caseless) {
2341
+ if (!utils$1.isUndefined(b)) {
2342
+ return getMergedValue(a, b, prop, caseless);
2343
+ } else if (!utils$1.isUndefined(a)) {
2344
+ return getMergedValue(undefined, a, prop, caseless);
2345
+ }
2346
+ }
2347
+
2348
+ // eslint-disable-next-line consistent-return
2349
+ function valueFromConfig2(a, b) {
2350
+ if (!utils$1.isUndefined(b)) {
2351
+ return getMergedValue(undefined, b);
2352
+ }
2353
+ }
2354
+
2355
+ // eslint-disable-next-line consistent-return
2356
+ function defaultToConfig2(a, b) {
2357
+ if (!utils$1.isUndefined(b)) {
2358
+ return getMergedValue(undefined, b);
2359
+ } else if (!utils$1.isUndefined(a)) {
2360
+ return getMergedValue(undefined, a);
2361
+ }
2362
+ }
2363
+
2364
+ // eslint-disable-next-line consistent-return
2365
+ function mergeDirectKeys(a, b, prop) {
2366
+ if (prop in config2) {
2367
+ return getMergedValue(a, b);
2368
+ } else if (prop in config1) {
2369
+ return getMergedValue(undefined, a);
2370
+ }
2371
+ }
2372
+
2373
+ const mergeMap = {
2374
+ url: valueFromConfig2,
2375
+ method: valueFromConfig2,
2376
+ data: valueFromConfig2,
2377
+ baseURL: defaultToConfig2,
2378
+ transformRequest: defaultToConfig2,
2379
+ transformResponse: defaultToConfig2,
2380
+ paramsSerializer: defaultToConfig2,
2381
+ timeout: defaultToConfig2,
2382
+ timeoutMessage: defaultToConfig2,
2383
+ withCredentials: defaultToConfig2,
2384
+ withXSRFToken: defaultToConfig2,
2385
+ adapter: defaultToConfig2,
2386
+ responseType: defaultToConfig2,
2387
+ xsrfCookieName: defaultToConfig2,
2388
+ xsrfHeaderName: defaultToConfig2,
2389
+ onUploadProgress: defaultToConfig2,
2390
+ onDownloadProgress: defaultToConfig2,
2391
+ decompress: defaultToConfig2,
2392
+ maxContentLength: defaultToConfig2,
2393
+ maxBodyLength: defaultToConfig2,
2394
+ beforeRedirect: defaultToConfig2,
2395
+ transport: defaultToConfig2,
2396
+ httpAgent: defaultToConfig2,
2397
+ httpsAgent: defaultToConfig2,
2398
+ cancelToken: defaultToConfig2,
2399
+ socketPath: defaultToConfig2,
2400
+ responseEncoding: defaultToConfig2,
2401
+ validateStatus: mergeDirectKeys,
2402
+ headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
2403
+ };
2404
+
2405
+ utils$1.forEach(Object.keys({...config1, ...config2}), function computeConfigValue(prop) {
2406
+ const merge = mergeMap[prop] || mergeDeepProperties;
2407
+ const configValue = merge(config1[prop], config2[prop], prop);
2408
+ (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2409
+ });
2410
+
2411
+ return config;
2412
+ }
2413
+
2414
+ var resolveConfig = (config) => {
2415
+ const newConfig = mergeConfig$1({}, config);
2416
+
2417
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
2418
+
2419
+ newConfig.headers = headers = AxiosHeaders$1.from(headers);
2420
+
2421
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
2422
+
2423
+ // HTTP basic authentication
2424
+ if (auth) {
2425
+ headers.set('Authorization', 'Basic ' +
2426
+ btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
2427
+ );
2428
+ }
2429
+
2430
+ if (utils$1.isFormData(data)) {
2431
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2432
+ headers.setContentType(undefined); // browser handles it
2433
+ } else if (utils$1.isFunction(data.getHeaders)) {
2434
+ // Node.js FormData (like form-data package)
2435
+ const formHeaders = data.getHeaders();
2436
+ // Only set safe headers to avoid overwriting security headers
2437
+ const allowedHeaders = ['content-type', 'content-length'];
2438
+ Object.entries(formHeaders).forEach(([key, val]) => {
2439
+ if (allowedHeaders.includes(key.toLowerCase())) {
2440
+ headers.set(key, val);
2441
+ }
2442
+ });
2443
+ }
2444
+ }
2445
+
2446
+ // Add xsrf header
2447
+ // This is only done if running in a standard browser environment.
2448
+ // Specifically not if we're in a web worker, or react-native.
2449
+
2450
+ if (platform.hasStandardBrowserEnv) {
2451
+ withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
2452
+
2453
+ if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
2454
+ // Add xsrf header
2455
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
2456
+
2457
+ if (xsrfValue) {
2458
+ headers.set(xsrfHeaderName, xsrfValue);
2459
+ }
2460
+ }
2461
+ }
2462
+
2463
+ return newConfig;
2464
+ };
2465
+
2466
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
2467
+
2468
+ var xhrAdapter = isXHRAdapterSupported && function (config) {
2469
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
2470
+ const _config = resolveConfig(config);
2471
+ let requestData = _config.data;
2472
+ const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
2473
+ let {responseType, onUploadProgress, onDownloadProgress} = _config;
2474
+ let onCanceled;
2475
+ let uploadThrottled, downloadThrottled;
2476
+ let flushUpload, flushDownload;
2477
+
2478
+ function done() {
2479
+ flushUpload && flushUpload(); // flush events
2480
+ flushDownload && flushDownload(); // flush events
2481
+
2482
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
2483
+
2484
+ _config.signal && _config.signal.removeEventListener('abort', onCanceled);
2485
+ }
2486
+
2487
+ let request = new XMLHttpRequest();
2488
+
2489
+ request.open(_config.method.toUpperCase(), _config.url, true);
2490
+
2491
+ // Set the request timeout in MS
2492
+ request.timeout = _config.timeout;
2493
+
2494
+ function onloadend() {
2495
+ if (!request) {
2496
+ return;
2497
+ }
2498
+ // Prepare the response
2499
+ const responseHeaders = AxiosHeaders$1.from(
2500
+ 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2501
+ );
2502
+ const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2503
+ request.responseText : request.response;
2504
+ const response = {
2505
+ data: responseData,
2506
+ status: request.status,
2507
+ statusText: request.statusText,
2508
+ headers: responseHeaders,
2509
+ config,
2510
+ request
2511
+ };
2512
+
2513
+ settle(function _resolve(value) {
2514
+ resolve(value);
2515
+ done();
2516
+ }, function _reject(err) {
2517
+ reject(err);
2518
+ done();
2519
+ }, response);
2520
+
2521
+ // Clean up request
2522
+ request = null;
2523
+ }
2524
+
2525
+ if ('onloadend' in request) {
2526
+ // Use onloadend if available
2527
+ request.onloadend = onloadend;
2528
+ } else {
2529
+ // Listen for ready state to emulate onloadend
2530
+ request.onreadystatechange = function handleLoad() {
2531
+ if (!request || request.readyState !== 4) {
2532
+ return;
2533
+ }
2534
+
2535
+ // The request errored out and we didn't get a response, this will be
2536
+ // handled by onerror instead
2537
+ // With one exception: request that using file: protocol, most browsers
2538
+ // will return status as 0 even though it's a successful request
2539
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2540
+ return;
2541
+ }
2542
+ // readystate handler is calling before onerror or ontimeout handlers,
2543
+ // so we should call onloadend on the next 'tick'
2544
+ setTimeout(onloadend);
2545
+ };
2546
+ }
2547
+
2548
+ // Handle browser request cancellation (as opposed to a manual cancellation)
2549
+ request.onabort = function handleAbort() {
2550
+ if (!request) {
2551
+ return;
2552
+ }
2553
+
2554
+ reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
2555
+
2556
+ // Clean up request
2557
+ request = null;
2558
+ };
2559
+
2560
+ // Handle low level network errors
2561
+ request.onerror = function handleError(event) {
2562
+ // Browsers deliver a ProgressEvent in XHR onerror
2563
+ // (message may be empty; when present, surface it)
2564
+ // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
2565
+ const msg = event && event.message ? event.message : 'Network Error';
2566
+ const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request);
2567
+ // attach the underlying event for consumers who want details
2568
+ err.event = event || null;
2569
+ reject(err);
2570
+ request = null;
2571
+ };
2572
+
2573
+ // Handle timeout
2574
+ request.ontimeout = function handleTimeout() {
2575
+ let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
2576
+ const transitional = _config.transitional || transitionalDefaults;
2577
+ if (_config.timeoutErrorMessage) {
2578
+ timeoutErrorMessage = _config.timeoutErrorMessage;
2579
+ }
2580
+ reject(new AxiosError$1(
2581
+ timeoutErrorMessage,
2582
+ transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
2583
+ config,
2584
+ request));
2585
+
2586
+ // Clean up request
2587
+ request = null;
2588
+ };
2589
+
2590
+ // Remove Content-Type if data is undefined
2591
+ requestData === undefined && requestHeaders.setContentType(null);
2592
+
2593
+ // Add headers to the request
2594
+ if ('setRequestHeader' in request) {
2595
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2596
+ request.setRequestHeader(key, val);
2597
+ });
2598
+ }
2599
+
2600
+ // Add withCredentials to request if needed
2601
+ if (!utils$1.isUndefined(_config.withCredentials)) {
2602
+ request.withCredentials = !!_config.withCredentials;
2603
+ }
2604
+
2605
+ // Add responseType to request if needed
2606
+ if (responseType && responseType !== 'json') {
2607
+ request.responseType = _config.responseType;
2608
+ }
2609
+
2610
+ // Handle progress if needed
2611
+ if (onDownloadProgress) {
2612
+ ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
2613
+ request.addEventListener('progress', downloadThrottled);
2614
+ }
2615
+
2616
+ // Not all browsers support upload events
2617
+ if (onUploadProgress && request.upload) {
2618
+ ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
2619
+
2620
+ request.upload.addEventListener('progress', uploadThrottled);
2621
+
2622
+ request.upload.addEventListener('loadend', flushUpload);
2623
+ }
2624
+
2625
+ if (_config.cancelToken || _config.signal) {
2626
+ // Handle cancellation
2627
+ // eslint-disable-next-line func-names
2628
+ onCanceled = cancel => {
2629
+ if (!request) {
2630
+ return;
2631
+ }
2632
+ reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
2633
+ request.abort();
2634
+ request = null;
2635
+ };
2636
+
2637
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
2638
+ if (_config.signal) {
2639
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
2640
+ }
2641
+ }
2642
+
2643
+ const protocol = parseProtocol(_config.url);
2644
+
2645
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
2646
+ reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
2647
+ return;
2648
+ }
2649
+
2650
+
2651
+ // Send the request
2652
+ request.send(requestData || null);
2653
+ });
2654
+ };
2655
+
2656
+ const composeSignals = (signals, timeout) => {
2657
+ const {length} = (signals = signals ? signals.filter(Boolean) : []);
2658
+
2659
+ if (timeout || length) {
2660
+ let controller = new AbortController();
2661
+
2662
+ let aborted;
2663
+
2664
+ const onabort = function (reason) {
2665
+ if (!aborted) {
2666
+ aborted = true;
2667
+ unsubscribe();
2668
+ const err = reason instanceof Error ? reason : this.reason;
2669
+ controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
2670
+ }
2671
+ };
2672
+
2673
+ let timer = timeout && setTimeout(() => {
2674
+ timer = null;
2675
+ onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
2676
+ }, timeout);
2677
+
2678
+ const unsubscribe = () => {
2679
+ if (signals) {
2680
+ timer && clearTimeout(timer);
2681
+ timer = null;
2682
+ signals.forEach(signal => {
2683
+ signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
2684
+ });
2685
+ signals = null;
2686
+ }
2687
+ };
2688
+
2689
+ signals.forEach((signal) => signal.addEventListener('abort', onabort));
2690
+
2691
+ const {signal} = controller;
2692
+
2693
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
2694
+
2695
+ return signal;
2696
+ }
2697
+ };
2698
+
2699
+ const streamChunk = function* (chunk, chunkSize) {
2700
+ let len = chunk.byteLength;
2701
+
2702
+ if (len < chunkSize) {
2703
+ yield chunk;
2704
+ return;
2705
+ }
2706
+
2707
+ let pos = 0;
2708
+ let end;
2709
+
2710
+ while (pos < len) {
2711
+ end = pos + chunkSize;
2712
+ yield chunk.slice(pos, end);
2713
+ pos = end;
2714
+ }
2715
+ };
2716
+
2717
+ const readBytes = async function* (iterable, chunkSize) {
2718
+ for await (const chunk of readStream(iterable)) {
2719
+ yield* streamChunk(chunk, chunkSize);
2720
+ }
2721
+ };
2722
+
2723
+ const readStream = async function* (stream) {
2724
+ if (stream[Symbol.asyncIterator]) {
2725
+ yield* stream;
2726
+ return;
2727
+ }
2728
+
2729
+ const reader = stream.getReader();
2730
+ try {
2731
+ for (;;) {
2732
+ const {done, value} = await reader.read();
2733
+ if (done) {
2734
+ break;
2735
+ }
2736
+ yield value;
2737
+ }
2738
+ } finally {
2739
+ await reader.cancel();
2740
+ }
2741
+ };
2742
+
2743
+ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
2744
+ const iterator = readBytes(stream, chunkSize);
2745
+
2746
+ let bytes = 0;
2747
+ let done;
2748
+ let _onFinish = (e) => {
2749
+ if (!done) {
2750
+ done = true;
2751
+ onFinish && onFinish(e);
2752
+ }
2753
+ };
2754
+
2755
+ return new ReadableStream({
2756
+ async pull(controller) {
2757
+ try {
2758
+ const {done, value} = await iterator.next();
2759
+
2760
+ if (done) {
2761
+ _onFinish();
2762
+ controller.close();
2763
+ return;
2764
+ }
2765
+
2766
+ let len = value.byteLength;
2767
+ if (onProgress) {
2768
+ let loadedBytes = bytes += len;
2769
+ onProgress(loadedBytes);
2770
+ }
2771
+ controller.enqueue(new Uint8Array(value));
2772
+ } catch (err) {
2773
+ _onFinish(err);
2774
+ throw err;
2775
+ }
2776
+ },
2777
+ cancel(reason) {
2778
+ _onFinish(reason);
2779
+ return iterator.return();
2780
+ }
2781
+ }, {
2782
+ highWaterMark: 2
2783
+ })
2784
+ };
2785
+
2786
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
2787
+
2788
+ const {isFunction} = utils$1;
2789
+
2790
+ const globalFetchAPI = (({Request, Response}) => ({
2791
+ Request, Response
2792
+ }))(utils$1.global);
2793
+
2794
+ const {
2795
+ ReadableStream: ReadableStream$1, TextEncoder
2796
+ } = utils$1.global;
2797
+
2798
+
2799
+ const test = (fn, ...args) => {
2800
+ try {
2801
+ return !!fn(...args);
2802
+ } catch (e) {
2803
+ return false
2804
+ }
2805
+ };
2806
+
2807
+ const factory = (env) => {
2808
+ env = utils$1.merge.call({
2809
+ skipUndefined: true
2810
+ }, globalFetchAPI, env);
2811
+
2812
+ const {fetch: envFetch, Request, Response} = env;
2813
+ const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
2814
+ const isRequestSupported = isFunction(Request);
2815
+ const isResponseSupported = isFunction(Response);
2816
+
2817
+ if (!isFetchSupported) {
2818
+ return false;
2819
+ }
2820
+
2821
+ const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
2822
+
2823
+ const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
2824
+ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
2825
+ async (str) => new Uint8Array(await new Request(str).arrayBuffer())
2826
+ );
2827
+
2828
+ const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
2829
+ let duplexAccessed = false;
2830
+
2831
+ const hasContentType = new Request(platform.origin, {
2832
+ body: new ReadableStream$1(),
2833
+ method: 'POST',
2834
+ get duplex() {
2835
+ duplexAccessed = true;
2836
+ return 'half';
2837
+ },
2838
+ }).headers.has('Content-Type');
2839
+
2840
+ return duplexAccessed && !hasContentType;
2841
+ });
2842
+
2843
+ const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
2844
+ test(() => utils$1.isReadableStream(new Response('').body));
2845
+
2846
+ const resolvers = {
2847
+ stream: supportsResponseStream && ((res) => res.body)
2848
+ };
2849
+
2850
+ isFetchSupported && ((() => {
2851
+ ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
2852
+ !resolvers[type] && (resolvers[type] = (res, config) => {
2853
+ let method = res && res[type];
2854
+
2855
+ if (method) {
2856
+ return method.call(res);
2857
+ }
2858
+
2859
+ throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
2860
+ });
2861
+ });
2862
+ })());
2863
+
2864
+ const getBodyLength = async (body) => {
2865
+ if (body == null) {
2866
+ return 0;
2867
+ }
2868
+
2869
+ if (utils$1.isBlob(body)) {
2870
+ return body.size;
2871
+ }
2872
+
2873
+ if (utils$1.isSpecCompliantForm(body)) {
2874
+ const _request = new Request(platform.origin, {
2875
+ method: 'POST',
2876
+ body,
2877
+ });
2878
+ return (await _request.arrayBuffer()).byteLength;
2879
+ }
2880
+
2881
+ if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2882
+ return body.byteLength;
2883
+ }
2884
+
2885
+ if (utils$1.isURLSearchParams(body)) {
2886
+ body = body + '';
2887
+ }
2888
+
2889
+ if (utils$1.isString(body)) {
2890
+ return (await encodeText(body)).byteLength;
2891
+ }
2892
+ };
2893
+
2894
+ const resolveBodyLength = async (headers, body) => {
2895
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
2896
+
2897
+ return length == null ? getBodyLength(body) : length;
2898
+ };
2899
+
2900
+ return async (config) => {
2901
+ let {
2902
+ url,
2903
+ method,
2904
+ data,
2905
+ signal,
2906
+ cancelToken,
2907
+ timeout,
2908
+ onDownloadProgress,
2909
+ onUploadProgress,
2910
+ responseType,
2911
+ headers,
2912
+ withCredentials = 'same-origin',
2913
+ fetchOptions
2914
+ } = resolveConfig(config);
2915
+
2916
+ let _fetch = envFetch || fetch;
2917
+
2918
+ responseType = responseType ? (responseType + '').toLowerCase() : 'text';
2919
+
2920
+ let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2921
+
2922
+ let request = null;
2923
+
2924
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2925
+ composedSignal.unsubscribe();
2926
+ });
2927
+
2928
+ let requestContentLength;
2929
+
2930
+ try {
2931
+ if (
2932
+ onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
2933
+ (requestContentLength = await resolveBodyLength(headers, data)) !== 0
2934
+ ) {
2935
+ let _request = new Request(url, {
2936
+ method: 'POST',
2937
+ body: data,
2938
+ duplex: "half"
2939
+ });
2940
+
2941
+ let contentTypeHeader;
2942
+
2943
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
2944
+ headers.setContentType(contentTypeHeader);
2945
+ }
2946
+
2947
+ if (_request.body) {
2948
+ const [onProgress, flush] = progressEventDecorator(
2949
+ requestContentLength,
2950
+ progressEventReducer(asyncDecorator(onUploadProgress))
2951
+ );
2952
+
2953
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2954
+ }
2955
+ }
2956
+
2957
+ if (!utils$1.isString(withCredentials)) {
2958
+ withCredentials = withCredentials ? 'include' : 'omit';
2959
+ }
2960
+
2961
+ // Cloudflare Workers throws when credentials are defined
2962
+ // see https://github.com/cloudflare/workerd/issues/902
2963
+ const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
2964
+
2965
+ const resolvedOptions = {
2966
+ ...fetchOptions,
2967
+ signal: composedSignal,
2968
+ method: method.toUpperCase(),
2969
+ headers: headers.normalize().toJSON(),
2970
+ body: data,
2971
+ duplex: "half",
2972
+ credentials: isCredentialsSupported ? withCredentials : undefined
2973
+ };
2974
+
2975
+ request = isRequestSupported && new Request(url, resolvedOptions);
2976
+
2977
+ let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
2978
+
2979
+ const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
2980
+
2981
+ if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
2982
+ const options = {};
2983
+
2984
+ ['status', 'statusText', 'headers'].forEach(prop => {
2985
+ options[prop] = response[prop];
2986
+ });
2987
+
2988
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
2989
+
2990
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2991
+ responseContentLength,
2992
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
2993
+ ) || [];
2994
+
2995
+ response = new Response(
2996
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2997
+ flush && flush();
2998
+ unsubscribe && unsubscribe();
2999
+ }),
3000
+ options
3001
+ );
3002
+ }
3003
+
3004
+ responseType = responseType || 'text';
3005
+
3006
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
3007
+
3008
+ !isStreamResponse && unsubscribe && unsubscribe();
3009
+
3010
+ return await new Promise((resolve, reject) => {
3011
+ settle(resolve, reject, {
3012
+ data: responseData,
3013
+ headers: AxiosHeaders$1.from(response.headers),
3014
+ status: response.status,
3015
+ statusText: response.statusText,
3016
+ config,
3017
+ request
3018
+ });
3019
+ })
3020
+ } catch (err) {
3021
+ unsubscribe && unsubscribe();
3022
+
3023
+ if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
3024
+ throw Object.assign(
3025
+ new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request),
3026
+ {
3027
+ cause: err.cause || err
3028
+ }
3029
+ )
3030
+ }
3031
+
3032
+ throw AxiosError$1.from(err, err && err.code, config, request);
3033
+ }
3034
+ }
3035
+ };
3036
+
3037
+ const seedCache = new Map();
3038
+
3039
+ const getFetch = (config) => {
3040
+ let env = (config && config.env) || {};
3041
+ const {fetch, Request, Response} = env;
3042
+ const seeds = [
3043
+ Request, Response, fetch
3044
+ ];
3045
+
3046
+ let len = seeds.length, i = len,
3047
+ seed, target, map = seedCache;
3048
+
3049
+ while (i--) {
3050
+ seed = seeds[i];
3051
+ target = map.get(seed);
3052
+
3053
+ target === undefined && map.set(seed, target = (i ? new Map() : factory(env)));
3054
+
3055
+ map = target;
3056
+ }
3057
+
3058
+ return target;
3059
+ };
3060
+
3061
+ getFetch();
3062
+
3063
+ /**
3064
+ * Known adapters mapping.
3065
+ * Provides environment-specific adapters for Axios:
3066
+ * - `http` for Node.js
3067
+ * - `xhr` for browsers
3068
+ * - `fetch` for fetch API-based requests
3069
+ *
3070
+ * @type {Object<string, Function|Object>}
3071
+ */
3072
+ const knownAdapters = {
3073
+ http: httpAdapter,
3074
+ xhr: xhrAdapter,
3075
+ fetch: {
3076
+ get: getFetch,
3077
+ }
3078
+ };
3079
+
3080
+ // Assign adapter names for easier debugging and identification
3081
+ utils$1.forEach(knownAdapters, (fn, value) => {
3082
+ if (fn) {
3083
+ try {
3084
+ Object.defineProperty(fn, 'name', { value });
3085
+ } catch (e) {
3086
+ // eslint-disable-next-line no-empty
3087
+ }
3088
+ Object.defineProperty(fn, 'adapterName', { value });
3089
+ }
3090
+ });
3091
+
3092
+ /**
3093
+ * Render a rejection reason string for unknown or unsupported adapters
3094
+ *
3095
+ * @param {string} reason
3096
+ * @returns {string}
3097
+ */
3098
+ const renderReason = (reason) => `- ${reason}`;
3099
+
3100
+ /**
3101
+ * Check if the adapter is resolved (function, null, or false)
3102
+ *
3103
+ * @param {Function|null|false} adapter
3104
+ * @returns {boolean}
3105
+ */
3106
+ const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
3107
+
3108
+ /**
3109
+ * Get the first suitable adapter from the provided list.
3110
+ * Tries each adapter in order until a supported one is found.
3111
+ * Throws an AxiosError if no adapter is suitable.
3112
+ *
3113
+ * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
3114
+ * @param {Object} config - Axios request configuration
3115
+ * @throws {AxiosError} If no suitable adapter is available
3116
+ * @returns {Function} The resolved adapter function
3117
+ */
3118
+ function getAdapter$1(adapters, config) {
3119
+ adapters = utils$1.isArray(adapters) ? adapters : [adapters];
3120
+
3121
+ const { length } = adapters;
3122
+ let nameOrAdapter;
3123
+ let adapter;
3124
+
3125
+ const rejectedReasons = {};
3126
+
3127
+ for (let i = 0; i < length; i++) {
3128
+ nameOrAdapter = adapters[i];
3129
+ let id;
3130
+
3131
+ adapter = nameOrAdapter;
3132
+
3133
+ if (!isResolvedHandle(nameOrAdapter)) {
3134
+ adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
3135
+
3136
+ if (adapter === undefined) {
3137
+ throw new AxiosError$1(`Unknown adapter '${id}'`);
3138
+ }
3139
+ }
3140
+
3141
+ if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
3142
+ break;
3143
+ }
3144
+
3145
+ rejectedReasons[id || '#' + i] = adapter;
3146
+ }
3147
+
3148
+ if (!adapter) {
3149
+ const reasons = Object.entries(rejectedReasons)
3150
+ .map(([id, state]) => `adapter ${id} ` +
3151
+ (state === false ? 'is not supported by the environment' : 'is not available in the build')
3152
+ );
3153
+
3154
+ let s = length ?
3155
+ (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
3156
+ 'as no adapter specified';
3157
+
3158
+ throw new AxiosError$1(
3159
+ `There is no suitable adapter to dispatch the request ` + s,
3160
+ 'ERR_NOT_SUPPORT'
3161
+ );
3162
+ }
3163
+
3164
+ return adapter;
3165
+ }
3166
+
3167
+ /**
3168
+ * Exports Axios adapters and utility to resolve an adapter
3169
+ */
3170
+ var adapters = {
3171
+ /**
3172
+ * Resolve an adapter from a list of adapter names or functions.
3173
+ * @type {Function}
3174
+ */
3175
+ getAdapter: getAdapter$1,
3176
+
3177
+ /**
3178
+ * Exposes all known adapters
3179
+ * @type {Object<string, Function|Object>}
3180
+ */
3181
+ adapters: knownAdapters
3182
+ };
3183
+
3184
+ /**
3185
+ * Throws a `CanceledError` if cancellation has been requested.
3186
+ *
3187
+ * @param {Object} config The config that is to be used for the request
3188
+ *
3189
+ * @returns {void}
3190
+ */
3191
+ function throwIfCancellationRequested(config) {
3192
+ if (config.cancelToken) {
3193
+ config.cancelToken.throwIfRequested();
3194
+ }
3195
+
3196
+ if (config.signal && config.signal.aborted) {
3197
+ throw new CanceledError$1(null, config);
3198
+ }
3199
+ }
3200
+
3201
+ /**
3202
+ * Dispatch a request to the server using the configured adapter.
3203
+ *
3204
+ * @param {object} config The config that is to be used for the request
3205
+ *
3206
+ * @returns {Promise} The Promise to be fulfilled
3207
+ */
3208
+ function dispatchRequest(config) {
3209
+ throwIfCancellationRequested(config);
3210
+
3211
+ config.headers = AxiosHeaders$1.from(config.headers);
3212
+
3213
+ // Transform request data
3214
+ config.data = transformData.call(
3215
+ config,
3216
+ config.transformRequest
3217
+ );
3218
+
3219
+ if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
3220
+ config.headers.setContentType('application/x-www-form-urlencoded', false);
3221
+ }
3222
+
3223
+ const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
3224
+
3225
+ return adapter(config).then(function onAdapterResolution(response) {
3226
+ throwIfCancellationRequested(config);
3227
+
3228
+ // Transform response data
3229
+ response.data = transformData.call(
3230
+ config,
3231
+ config.transformResponse,
3232
+ response
3233
+ );
3234
+
3235
+ response.headers = AxiosHeaders$1.from(response.headers);
3236
+
3237
+ return response;
3238
+ }, function onAdapterRejection(reason) {
3239
+ if (!isCancel$1(reason)) {
3240
+ throwIfCancellationRequested(config);
3241
+
3242
+ // Transform response data
3243
+ if (reason && reason.response) {
3244
+ reason.response.data = transformData.call(
3245
+ config,
3246
+ config.transformResponse,
3247
+ reason.response
3248
+ );
3249
+ reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
3250
+ }
3251
+ }
3252
+
3253
+ return Promise.reject(reason);
3254
+ });
3255
+ }
3256
+
3257
+ const VERSION$2 = "1.13.2";
3258
+
3259
+ const validators$1 = {};
3260
+
3261
+ // eslint-disable-next-line func-names
3262
+ ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
3263
+ validators$1[type] = function validator(thing) {
3264
+ return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
3265
+ };
3266
+ });
3267
+
3268
+ const deprecatedWarnings = {};
3269
+
3270
+ /**
3271
+ * Transitional option validator
3272
+ *
3273
+ * @param {function|boolean?} validator - set to false if the transitional option has been removed
3274
+ * @param {string?} version - deprecated version / removed since version
3275
+ * @param {string?} message - some message with additional info
3276
+ *
3277
+ * @returns {function}
3278
+ */
3279
+ validators$1.transitional = function transitional(validator, version, message) {
3280
+ function formatMessage(opt, desc) {
3281
+ return '[Axios v' + VERSION$2 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
3282
+ }
3283
+
3284
+ // eslint-disable-next-line func-names
3285
+ return (value, opt, opts) => {
3286
+ if (validator === false) {
3287
+ throw new AxiosError$1(
3288
+ formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
3289
+ AxiosError$1.ERR_DEPRECATED
3290
+ );
3291
+ }
3292
+
3293
+ if (version && !deprecatedWarnings[opt]) {
3294
+ deprecatedWarnings[opt] = true;
3295
+ // eslint-disable-next-line no-console
3296
+ console.warn(
3297
+ formatMessage(
3298
+ opt,
3299
+ ' has been deprecated since v' + version + ' and will be removed in the near future'
3300
+ )
3301
+ );
3302
+ }
3303
+
3304
+ return validator ? validator(value, opt, opts) : true;
3305
+ };
3306
+ };
3307
+
3308
+ validators$1.spelling = function spelling(correctSpelling) {
3309
+ return (value, opt) => {
3310
+ // eslint-disable-next-line no-console
3311
+ console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
3312
+ return true;
3313
+ }
3314
+ };
3315
+
3316
+ /**
3317
+ * Assert object's properties type
3318
+ *
3319
+ * @param {object} options
3320
+ * @param {object} schema
3321
+ * @param {boolean?} allowUnknown
3322
+ *
3323
+ * @returns {object}
3324
+ */
3325
+
3326
+ function assertOptions(options, schema, allowUnknown) {
3327
+ if (typeof options !== 'object') {
3328
+ throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
3329
+ }
3330
+ const keys = Object.keys(options);
3331
+ let i = keys.length;
3332
+ while (i-- > 0) {
3333
+ const opt = keys[i];
3334
+ const validator = schema[opt];
3335
+ if (validator) {
3336
+ const value = options[opt];
3337
+ const result = value === undefined || validator(value, opt, options);
3338
+ if (result !== true) {
3339
+ throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
3340
+ }
3341
+ continue;
3342
+ }
3343
+ if (allowUnknown !== true) {
3344
+ throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
3345
+ }
3346
+ }
3347
+ }
3348
+
3349
+ var validator = {
3350
+ assertOptions,
3351
+ validators: validators$1
3352
+ };
3353
+
3354
+ const validators = validator.validators;
3355
+
3356
+ /**
3357
+ * Create a new instance of Axios
3358
+ *
3359
+ * @param {Object} instanceConfig The default config for the instance
3360
+ *
3361
+ * @return {Axios} A new instance of Axios
3362
+ */
3363
+ let Axios$1 = class Axios {
3364
+ constructor(instanceConfig) {
3365
+ this.defaults = instanceConfig || {};
3366
+ this.interceptors = {
3367
+ request: new InterceptorManager(),
3368
+ response: new InterceptorManager()
3369
+ };
3370
+ }
3371
+
3372
+ /**
3373
+ * Dispatch a request
3374
+ *
3375
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3376
+ * @param {?Object} config
3377
+ *
3378
+ * @returns {Promise} The Promise to be fulfilled
3379
+ */
3380
+ async request(configOrUrl, config) {
3381
+ try {
3382
+ return await this._request(configOrUrl, config);
3383
+ } catch (err) {
3384
+ if (err instanceof Error) {
3385
+ let dummy = {};
3386
+
3387
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
3388
+
3389
+ // slice off the Error: ... line
3390
+ const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
3391
+ try {
3392
+ if (!err.stack) {
3393
+ err.stack = stack;
3394
+ // match without the 2 top stack lines
3395
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
3396
+ err.stack += '\n' + stack;
3397
+ }
3398
+ } catch (e) {
3399
+ // ignore the case where "stack" is an un-writable property
3400
+ }
3401
+ }
3402
+
3403
+ throw err;
3404
+ }
3405
+ }
3406
+
3407
+ _request(configOrUrl, config) {
3408
+ /*eslint no-param-reassign:0*/
3409
+ // Allow for axios('example/url'[, config]) a la fetch API
3410
+ if (typeof configOrUrl === 'string') {
3411
+ config = config || {};
3412
+ config.url = configOrUrl;
3413
+ } else {
3414
+ config = configOrUrl || {};
3415
+ }
3416
+
3417
+ config = mergeConfig$1(this.defaults, config);
3418
+
3419
+ const {transitional, paramsSerializer, headers} = config;
3420
+
3421
+ if (transitional !== undefined) {
3422
+ validator.assertOptions(transitional, {
3423
+ silentJSONParsing: validators.transitional(validators.boolean),
3424
+ forcedJSONParsing: validators.transitional(validators.boolean),
3425
+ clarifyTimeoutError: validators.transitional(validators.boolean)
3426
+ }, false);
3427
+ }
3428
+
3429
+ if (paramsSerializer != null) {
3430
+ if (utils$1.isFunction(paramsSerializer)) {
3431
+ config.paramsSerializer = {
3432
+ serialize: paramsSerializer
3433
+ };
3434
+ } else {
3435
+ validator.assertOptions(paramsSerializer, {
3436
+ encode: validators.function,
3437
+ serialize: validators.function
3438
+ }, true);
3439
+ }
3440
+ }
3441
+
3442
+ // Set config.allowAbsoluteUrls
3443
+ if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
3444
+ config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
3445
+ } else {
3446
+ config.allowAbsoluteUrls = true;
3447
+ }
3448
+
3449
+ validator.assertOptions(config, {
3450
+ baseUrl: validators.spelling('baseURL'),
3451
+ withXsrfToken: validators.spelling('withXSRFToken')
3452
+ }, true);
3453
+
3454
+ // Set config.method
3455
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3456
+
3457
+ // Flatten headers
3458
+ let contextHeaders = headers && utils$1.merge(
3459
+ headers.common,
3460
+ headers[config.method]
3461
+ );
3462
+
3463
+ headers && utils$1.forEach(
3464
+ ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
3465
+ (method) => {
3466
+ delete headers[method];
3467
+ }
3468
+ );
3469
+
3470
+ config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
3471
+
3472
+ // filter out skipped interceptors
3473
+ const requestInterceptorChain = [];
3474
+ let synchronousRequestInterceptors = true;
3475
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3476
+ if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
3477
+ return;
3478
+ }
3479
+
3480
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3481
+
3482
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3483
+ });
3484
+
3485
+ const responseInterceptorChain = [];
3486
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3487
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3488
+ });
3489
+
3490
+ let promise;
3491
+ let i = 0;
3492
+ let len;
3493
+
3494
+ if (!synchronousRequestInterceptors) {
3495
+ const chain = [dispatchRequest.bind(this), undefined];
3496
+ chain.unshift(...requestInterceptorChain);
3497
+ chain.push(...responseInterceptorChain);
3498
+ len = chain.length;
3499
+
3500
+ promise = Promise.resolve(config);
3501
+
3502
+ while (i < len) {
3503
+ promise = promise.then(chain[i++], chain[i++]);
3504
+ }
3505
+
3506
+ return promise;
3507
+ }
3508
+
3509
+ len = requestInterceptorChain.length;
3510
+
3511
+ let newConfig = config;
3512
+
3513
+ while (i < len) {
3514
+ const onFulfilled = requestInterceptorChain[i++];
3515
+ const onRejected = requestInterceptorChain[i++];
3516
+ try {
3517
+ newConfig = onFulfilled(newConfig);
3518
+ } catch (error) {
3519
+ onRejected.call(this, error);
3520
+ break;
3521
+ }
3522
+ }
3523
+
3524
+ try {
3525
+ promise = dispatchRequest.call(this, newConfig);
3526
+ } catch (error) {
3527
+ return Promise.reject(error);
3528
+ }
3529
+
3530
+ i = 0;
3531
+ len = responseInterceptorChain.length;
3532
+
3533
+ while (i < len) {
3534
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3535
+ }
3536
+
3537
+ return promise;
3538
+ }
3539
+
3540
+ getUri(config) {
3541
+ config = mergeConfig$1(this.defaults, config);
3542
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
3543
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3544
+ }
3545
+ };
3546
+
3547
+ // Provide aliases for supported request methods
3548
+ utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
3549
+ /*eslint func-names:0*/
3550
+ Axios$1.prototype[method] = function(url, config) {
3551
+ return this.request(mergeConfig$1(config || {}, {
3552
+ method,
3553
+ url,
3554
+ data: (config || {}).data
3555
+ }));
3556
+ };
3557
+ });
3558
+
3559
+ utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
3560
+ /*eslint func-names:0*/
3561
+
3562
+ function generateHTTPMethod(isForm) {
3563
+ return function httpMethod(url, data, config) {
3564
+ return this.request(mergeConfig$1(config || {}, {
3565
+ method,
3566
+ headers: isForm ? {
3567
+ 'Content-Type': 'multipart/form-data'
3568
+ } : {},
3569
+ url,
3570
+ data
3571
+ }));
3572
+ };
3573
+ }
3574
+
3575
+ Axios$1.prototype[method] = generateHTTPMethod();
3576
+
3577
+ Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true);
3578
+ });
3579
+
3580
+ /**
3581
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3582
+ *
3583
+ * @param {Function} executor The executor function.
3584
+ *
3585
+ * @returns {CancelToken}
3586
+ */
3587
+ let CancelToken$1 = class CancelToken {
3588
+ constructor(executor) {
3589
+ if (typeof executor !== 'function') {
3590
+ throw new TypeError('executor must be a function.');
3591
+ }
3592
+
3593
+ let resolvePromise;
3594
+
3595
+ this.promise = new Promise(function promiseExecutor(resolve) {
3596
+ resolvePromise = resolve;
3597
+ });
3598
+
3599
+ const token = this;
3600
+
3601
+ // eslint-disable-next-line func-names
3602
+ this.promise.then(cancel => {
3603
+ if (!token._listeners) return;
3604
+
3605
+ let i = token._listeners.length;
3606
+
3607
+ while (i-- > 0) {
3608
+ token._listeners[i](cancel);
3609
+ }
3610
+ token._listeners = null;
3611
+ });
3612
+
3613
+ // eslint-disable-next-line func-names
3614
+ this.promise.then = onfulfilled => {
3615
+ let _resolve;
3616
+ // eslint-disable-next-line func-names
3617
+ const promise = new Promise(resolve => {
3618
+ token.subscribe(resolve);
3619
+ _resolve = resolve;
3620
+ }).then(onfulfilled);
3621
+
3622
+ promise.cancel = function reject() {
3623
+ token.unsubscribe(_resolve);
3624
+ };
3625
+
3626
+ return promise;
3627
+ };
3628
+
3629
+ executor(function cancel(message, config, request) {
3630
+ if (token.reason) {
3631
+ // Cancellation has already been requested
3632
+ return;
3633
+ }
3634
+
3635
+ token.reason = new CanceledError$1(message, config, request);
3636
+ resolvePromise(token.reason);
3637
+ });
3638
+ }
3639
+
3640
+ /**
3641
+ * Throws a `CanceledError` if cancellation has been requested.
3642
+ */
3643
+ throwIfRequested() {
3644
+ if (this.reason) {
3645
+ throw this.reason;
3646
+ }
3647
+ }
3648
+
3649
+ /**
3650
+ * Subscribe to the cancel signal
3651
+ */
3652
+
3653
+ subscribe(listener) {
3654
+ if (this.reason) {
3655
+ listener(this.reason);
3656
+ return;
3657
+ }
3658
+
3659
+ if (this._listeners) {
3660
+ this._listeners.push(listener);
3661
+ } else {
3662
+ this._listeners = [listener];
3663
+ }
3664
+ }
3665
+
3666
+ /**
3667
+ * Unsubscribe from the cancel signal
3668
+ */
3669
+
3670
+ unsubscribe(listener) {
3671
+ if (!this._listeners) {
3672
+ return;
3673
+ }
3674
+ const index = this._listeners.indexOf(listener);
3675
+ if (index !== -1) {
3676
+ this._listeners.splice(index, 1);
3677
+ }
3678
+ }
3679
+
3680
+ toAbortSignal() {
3681
+ const controller = new AbortController();
3682
+
3683
+ const abort = (err) => {
3684
+ controller.abort(err);
3685
+ };
3686
+
3687
+ this.subscribe(abort);
3688
+
3689
+ controller.signal.unsubscribe = () => this.unsubscribe(abort);
3690
+
3691
+ return controller.signal;
3692
+ }
3693
+
3694
+ /**
3695
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3696
+ * cancels the `CancelToken`.
3697
+ */
3698
+ static source() {
3699
+ let cancel;
3700
+ const token = new CancelToken(function executor(c) {
3701
+ cancel = c;
3702
+ });
3703
+ return {
3704
+ token,
3705
+ cancel
3706
+ };
3707
+ }
3708
+ };
3709
+
3710
+ /**
3711
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3712
+ *
3713
+ * Common use case would be to use `Function.prototype.apply`.
3714
+ *
3715
+ * ```js
3716
+ * function f(x, y, z) {}
3717
+ * var args = [1, 2, 3];
3718
+ * f.apply(null, args);
3719
+ * ```
3720
+ *
3721
+ * With `spread` this example can be re-written.
3722
+ *
3723
+ * ```js
3724
+ * spread(function(x, y, z) {})([1, 2, 3]);
3725
+ * ```
3726
+ *
3727
+ * @param {Function} callback
3728
+ *
3729
+ * @returns {Function}
3730
+ */
3731
+ function spread$1(callback) {
3732
+ return function wrap(arr) {
3733
+ return callback.apply(null, arr);
3734
+ };
3735
+ }
3736
+
3737
+ /**
3738
+ * Determines whether the payload is an error thrown by Axios
3739
+ *
3740
+ * @param {*} payload The value to test
3741
+ *
3742
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3743
+ */
3744
+ function isAxiosError$1(payload) {
3745
+ return utils$1.isObject(payload) && (payload.isAxiosError === true);
3746
+ }
3747
+
3748
+ const HttpStatusCode$1 = {
3749
+ Continue: 100,
3750
+ SwitchingProtocols: 101,
3751
+ Processing: 102,
3752
+ EarlyHints: 103,
3753
+ Ok: 200,
3754
+ Created: 201,
3755
+ Accepted: 202,
3756
+ NonAuthoritativeInformation: 203,
3757
+ NoContent: 204,
3758
+ ResetContent: 205,
3759
+ PartialContent: 206,
3760
+ MultiStatus: 207,
3761
+ AlreadyReported: 208,
3762
+ ImUsed: 226,
3763
+ MultipleChoices: 300,
3764
+ MovedPermanently: 301,
3765
+ Found: 302,
3766
+ SeeOther: 303,
3767
+ NotModified: 304,
3768
+ UseProxy: 305,
3769
+ Unused: 306,
3770
+ TemporaryRedirect: 307,
3771
+ PermanentRedirect: 308,
3772
+ BadRequest: 400,
3773
+ Unauthorized: 401,
3774
+ PaymentRequired: 402,
3775
+ Forbidden: 403,
3776
+ NotFound: 404,
3777
+ MethodNotAllowed: 405,
3778
+ NotAcceptable: 406,
3779
+ ProxyAuthenticationRequired: 407,
3780
+ RequestTimeout: 408,
3781
+ Conflict: 409,
3782
+ Gone: 410,
3783
+ LengthRequired: 411,
3784
+ PreconditionFailed: 412,
3785
+ PayloadTooLarge: 413,
3786
+ UriTooLong: 414,
3787
+ UnsupportedMediaType: 415,
3788
+ RangeNotSatisfiable: 416,
3789
+ ExpectationFailed: 417,
3790
+ ImATeapot: 418,
3791
+ MisdirectedRequest: 421,
3792
+ UnprocessableEntity: 422,
3793
+ Locked: 423,
3794
+ FailedDependency: 424,
3795
+ TooEarly: 425,
3796
+ UpgradeRequired: 426,
3797
+ PreconditionRequired: 428,
3798
+ TooManyRequests: 429,
3799
+ RequestHeaderFieldsTooLarge: 431,
3800
+ UnavailableForLegalReasons: 451,
3801
+ InternalServerError: 500,
3802
+ NotImplemented: 501,
3803
+ BadGateway: 502,
3804
+ ServiceUnavailable: 503,
3805
+ GatewayTimeout: 504,
3806
+ HttpVersionNotSupported: 505,
3807
+ VariantAlsoNegotiates: 506,
3808
+ InsufficientStorage: 507,
3809
+ LoopDetected: 508,
3810
+ NotExtended: 510,
3811
+ NetworkAuthenticationRequired: 511,
3812
+ WebServerIsDown: 521,
3813
+ ConnectionTimedOut: 522,
3814
+ OriginIsUnreachable: 523,
3815
+ TimeoutOccurred: 524,
3816
+ SslHandshakeFailed: 525,
3817
+ InvalidSslCertificate: 526,
3818
+ };
3819
+
3820
+ Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
3821
+ HttpStatusCode$1[value] = key;
3822
+ });
3823
+
3824
+ /**
3825
+ * Create an instance of Axios
3826
+ *
3827
+ * @param {Object} defaultConfig The default config for the instance
3828
+ *
3829
+ * @returns {Axios} A new instance of Axios
3830
+ */
3831
+ function createInstance(defaultConfig) {
3832
+ const context = new Axios$1(defaultConfig);
3833
+ const instance = bind(Axios$1.prototype.request, context);
3834
+
3835
+ // Copy axios.prototype to instance
3836
+ utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
3837
+
3838
+ // Copy context to instance
3839
+ utils$1.extend(instance, context, null, {allOwnKeys: true});
3840
+
3841
+ // Factory for creating new instances
3842
+ instance.create = function create(instanceConfig) {
3843
+ return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
3844
+ };
3845
+
3846
+ return instance;
3847
+ }
3848
+
3849
+ // Create the default instance to be exported
3850
+ const axios = createInstance(defaults);
3851
+
3852
+ // Expose Axios class to allow class inheritance
3853
+ axios.Axios = Axios$1;
3854
+
3855
+ // Expose Cancel & CancelToken
3856
+ axios.CanceledError = CanceledError$1;
3857
+ axios.CancelToken = CancelToken$1;
3858
+ axios.isCancel = isCancel$1;
3859
+ axios.VERSION = VERSION$2;
3860
+ axios.toFormData = toFormData$1;
3861
+
3862
+ // Expose AxiosError class
3863
+ axios.AxiosError = AxiosError$1;
3864
+
3865
+ // alias for CanceledError for backward compatibility
3866
+ axios.Cancel = axios.CanceledError;
3867
+
3868
+ // Expose all/spread
3869
+ axios.all = function all(promises) {
3870
+ return Promise.all(promises);
3871
+ };
3872
+
3873
+ axios.spread = spread$1;
3874
+
3875
+ // Expose isAxiosError
3876
+ axios.isAxiosError = isAxiosError$1;
3877
+
3878
+ // Expose mergeConfig
3879
+ axios.mergeConfig = mergeConfig$1;
3880
+
3881
+ axios.AxiosHeaders = AxiosHeaders$1;
3882
+
3883
+ axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
3884
+
3885
+ axios.getAdapter = adapters.getAdapter;
3886
+
3887
+ axios.HttpStatusCode = HttpStatusCode$1;
3888
+
3889
+ axios.default = axios;
3890
+
3891
+ // This module is intended to unwrap Axios default export as named.
3892
+ // Keep top-level export same with static properties
3893
+ // so that it can keep same with es module or cjs
3894
+ const {
3895
+ Axios,
3896
+ AxiosError,
3897
+ CanceledError,
3898
+ isCancel,
3899
+ CancelToken,
3900
+ VERSION: VERSION$1,
3901
+ all,
3902
+ Cancel,
3903
+ isAxiosError,
3904
+ spread,
3905
+ toFormData,
3906
+ AxiosHeaders,
3907
+ HttpStatusCode,
3908
+ formToJSON,
3909
+ getAdapter,
3910
+ mergeConfig
3911
+ } = axios;
3912
+
3913
+ /**
3914
+ * Payment API error
3915
+ */
3916
+ class PaymentAPIError extends Error {
3917
+ constructor(message, code, response) {
3918
+ super(message);
3919
+ this.code = code;
3920
+ this.response = response;
3921
+ this.name = 'PaymentAPIError';
3922
+ }
3923
+ }
3924
+ /**
3925
+ * SeaVerse Payment API Client
3926
+ *
3927
+ * Provides query capabilities for user credit accounts and transactions with multi-tenant support.
3928
+ * All methods are read-only - credit spending/granting is handled by platform backend.
3929
+ *
3930
+ * ## Multi-tenant Architecture
3931
+ * - Each app has isolated credit accounts using `app_id`
3932
+ * - Same user can have different credit accounts in different apps
3933
+ * - Use `appId` to specify which app's credit pool to access
3934
+ *
3935
+ * @example
3936
+ * ```typescript
3937
+ * // SeaVerse platform usage
3938
+ * const client = new PaymentClient({
3939
+ * appId: 'seaverse',
3940
+ * token: 'your-bearer-token'
3941
+ * });
3942
+ *
3943
+ * // Third-party app usage
3944
+ * const gameClient = new PaymentClient({
3945
+ * appId: 'game-abc123',
3946
+ * token: 'your-bearer-token'
3947
+ * });
3948
+ *
3949
+ * // Get credit account
3950
+ * const account = await client.getCreditAccount();
3951
+ * console.log(`Balance: ${account.balance} credits`);
3952
+ *
3953
+ * // List recent transactions
3954
+ * const transactions = await client.listTransactions({ page_size: 10 });
3955
+ * ```
3956
+ */
3957
+ class PaymentClient {
3958
+ constructor(options) {
3959
+ this.axios = axios.create({
3960
+ baseURL: options.baseURL || 'https://payment.sg.seaverse.dev',
3961
+ timeout: options.timeout || 30000,
3962
+ headers: {
3963
+ 'Content-Type': 'application/json',
3964
+ 'X-App-ID': options.appId,
3965
+ Authorization: `Bearer ${options.token}`,
3966
+ },
3967
+ });
3968
+ // Add response interceptor for error handling
3969
+ this.axios.interceptors.response.use((response) => response, (error) => {
3970
+ if (error.response) {
3971
+ const data = error.response.data;
3972
+ throw new PaymentAPIError(data.message || error.message, data.code || error.response.status, data);
3973
+ }
3974
+ throw new PaymentAPIError(error.message, error.code === 'ECONNABORTED' ? 408 : 500);
3975
+ });
3976
+ }
3977
+ /**
3978
+ * Get credit detail with 4-pool system information
3979
+ *
3980
+ * Returns detailed credit information across 4 pools (daily/event/monthly/permanent)
3981
+ * with expiration timestamps. This is the recommended method for displaying user credits.
3982
+ *
3983
+ * **Credit Pool Types:**
3984
+ * - `daily`: Daily credits (expires at next day 00:00 UTC)
3985
+ * - `event`: Event credits (expires at event deadline)
3986
+ * - `monthly`: Monthly credits (expires 30 days after last grant)
3987
+ * - `permanent`: Permanent credits (never expires)
3988
+ *
3989
+ * **Consumption Priority:**
3990
+ * Daily → Event → Monthly → Permanent
3991
+ *
3992
+ * **Response Features:**
3993
+ * - Only returns pools with balance > 0
3994
+ * - `expires_at` is millisecond timestamp (0 means permanent)
3995
+ * - Frontend can calculate remaining time from timestamp
3996
+ *
3997
+ * **Recommended Refresh Rate:** 30 seconds
3998
+ *
3999
+ * @returns Credit detail with pool breakdown
4000
+ * @throws {PaymentAPIError} If request fails
4001
+ *
4002
+ * @example
4003
+ * ```typescript
4004
+ * const detail = await client.getCreditDetail();
4005
+ * console.log(`Total Balance: ${detail.total_balance}`);
4006
+ *
4007
+ * detail.pools.forEach(pool => {
4008
+ * const label = pool.expires_at === 0
4009
+ * ? 'Permanent'
4010
+ * : `Expires in ${Math.floor((pool.expires_at - Date.now()) / 86400000)} days`;
4011
+ * console.log(`${pool.type}: ${pool.balance} (${label})`);
4012
+ * });
4013
+ * ```
4014
+ */
4015
+ async getCreditDetail() {
4016
+ const response = await this.axios.get('/sdk/v1/credits/detail');
4017
+ return response.data.data;
4018
+ }
4019
+ /**
4020
+ * Get authenticated user's credit account information
4021
+ *
4022
+ * Returns current balance, total earned/spent, frozen balance, and account status.
4023
+ *
4024
+ * @deprecated Use getCreditDetail() instead for the new 4-pool credit system
4025
+ * @returns Credit account information
4026
+ * @throws {PaymentAPIError} If request fails
4027
+ *
4028
+ * @example
4029
+ * ```typescript
4030
+ * const account = await client.getCreditAccount();
4031
+ * console.log(`Balance: ${account.balance}`);
4032
+ * console.log(`Status: ${account.status}`);
4033
+ * ```
4034
+ */
4035
+ async getCreditAccount() {
4036
+ const response = await this.axios.get('/sdk/v1/credits/account');
4037
+ return response.data.data;
4038
+ }
4039
+ /**
4040
+ * List credit transactions with filters and pagination
4041
+ *
4042
+ * Query user's transaction history with optional filters for type, source, status, and date range.
4043
+ * Supports pagination with max 50 items per page.
4044
+ *
4045
+ * @param request - List transactions request parameters
4046
+ * @returns Paginated transaction list with has_more flag
4047
+ * @throws {PaymentAPIError} If request fails
4048
+ *
4049
+ * @example
4050
+ * ```typescript
4051
+ * // Get recent transactions
4052
+ * const result = await client.listTransactions({ page_size: 20 });
4053
+ *
4054
+ * // Filter by type
4055
+ * const spending = await client.listTransactions({
4056
+ * type: 'spend',
4057
+ * page: 1,
4058
+ * page_size: 10
4059
+ * });
4060
+ *
4061
+ * // Filter by date range
4062
+ * const recentTransactions = await client.listTransactions({
4063
+ * start_date: '2024-01-01T00:00:00Z',
4064
+ * end_date: '2024-12-31T23:59:59Z',
4065
+ * status: 'completed'
4066
+ * });
4067
+ * ```
4068
+ */
4069
+ async listTransactions(request = {}) {
4070
+ const params = {};
4071
+ if (request.type)
4072
+ params.type = request.type;
4073
+ if (request.source)
4074
+ params.source = request.source;
4075
+ if (request.status)
4076
+ params.status = request.status;
4077
+ if (request.start_date)
4078
+ params.start_date = request.start_date;
4079
+ if (request.end_date)
4080
+ params.end_date = request.end_date;
4081
+ if (request.page)
4082
+ params.page = request.page;
4083
+ if (request.page_size)
4084
+ params.page_size = request.page_size;
4085
+ const response = await this.axios.get('/sdk/v1/credits/transactions', { params });
4086
+ return response.data.data;
4087
+ }
4088
+ /**
4089
+ * Update the bearer token for authentication
4090
+ *
4091
+ * Use this method to update the token when it expires or needs to be refreshed.
4092
+ *
4093
+ * @param token - New bearer token
4094
+ *
4095
+ * @example
4096
+ * ```typescript
4097
+ * client.setToken('new-bearer-token');
4098
+ * ```
4099
+ */
4100
+ setToken(token) {
4101
+ this.axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
4102
+ }
4103
+ /**
4104
+ * Update the base URL for the API
4105
+ *
4106
+ * Use this method to switch between different environments (dev/staging/prod).
4107
+ *
4108
+ * @param baseURL - New base URL
4109
+ *
4110
+ * @example
4111
+ * ```typescript
4112
+ * client.setBaseURL('https://payment.sg.seaverse.dev');
4113
+ * ```
4114
+ */
4115
+ setBaseURL(baseURL) {
4116
+ this.axios.defaults.baseURL = baseURL;
4117
+ }
4118
+ /**
4119
+ * Update the app ID for multi-tenant isolation
4120
+ *
4121
+ * Use this method to switch between different apps at runtime.
4122
+ *
4123
+ * @param appId - New app ID
4124
+ *
4125
+ * @example
4126
+ * ```typescript
4127
+ * // Switch to SeaVerse platform
4128
+ * client.setAppId('seaverse');
4129
+ *
4130
+ * // Switch to third-party app
4131
+ * client.setAppId('game-abc123');
4132
+ * ```
4133
+ */
4134
+ setAppId(appId) {
4135
+ this.axios.defaults.headers.common['X-App-ID'] = appId;
4136
+ }
4137
+ }
4138
+
4139
+ /**
4140
+ * SeaVerse Payment SDK - 常量配置
4141
+ */
4142
+ /**
4143
+ * 环境配置
4144
+ */
4145
+ const ENV_CONFIG = {
4146
+ develop: {
4147
+ apiHost: 'https://aiart-openresty.dev.seaart.dev',
4148
+ iframeUrl: 'https://aiart-payment-page.dev.seaart.dev',
4149
+ },
4150
+ release: {
4151
+ apiHost: 'https://www.seaart.ai',
4152
+ iframeUrl: 'https://pay.seaart.ai',
4153
+ },
4154
+ };
4155
+ /**
4156
+ * SDK CDN 地址
4157
+ */
4158
+ const SDK_CDN_URL = 'https://image.cdn2.seaart.me/seaart-payment-sdk/1.0.2/seaart-pay-sdk-umd.min.js';
4159
+ /**
4160
+ * SDK 加载超时时间(毫秒)
4161
+ */
4162
+ const SDK_LOAD_TIMEOUT = 15000;
4163
+ /**
4164
+ * SDK 全局对象名称
4165
+ */
4166
+ const SDK_GLOBAL_NAME = 'SeaArtPay';
4167
+ /**
4168
+ * API 端点
4169
+ */
4170
+ const API_ENDPOINTS = {
4171
+ /** SDK 结账接口 */
4172
+ SDK_CHECKOUT: '/api/v1/payment/sdk/checkout',
4173
+ };
4174
+ /**
4175
+ * 默认配置
4176
+ */
4177
+ const DEFAULT_CHECKOUT_CONFIG = {
4178
+ environment: 'develop',
4179
+ debug: false,
4180
+ language: 'en',
4181
+ sdkTimeout: SDK_LOAD_TIMEOUT,
4182
+ };
4183
+ /**
4184
+ * HTTP 状态码
4185
+ */
4186
+ const HTTP_STATUS = {
4187
+ OK: 200,
4188
+ BAD_REQUEST: 400,
4189
+ UNAUTHORIZED: 401,
4190
+ FORBIDDEN: 403,
4191
+ NOT_FOUND: 404,
4192
+ INTERNAL_ERROR: 500,
4193
+ };
4194
+ /**
4195
+ * 业务状态码
4196
+ */
4197
+ const BIZ_CODE = {
4198
+ SUCCESS: 0,
4199
+ BAD_REQUEST: 400,
4200
+ UNAUTHORIZED: 401,
4201
+ SERVER_ERROR: 500,
4202
+ };
4203
+
4204
+ /**
4205
+ * SeaArtPay SDK 加载器
4206
+ * 负责从 CDN 动态加载 SeaArt 支付 SDK
4207
+ */
4208
+ /**
4209
+ * SDK 加载器类
4210
+ */
4211
+ class SeaArtPayLoader {
4212
+ constructor(config = {}) {
4213
+ this.status = 'idle';
4214
+ this.sdk = null;
4215
+ this.loadPromise = null;
4216
+ this.config = {
4217
+ cdnUrl: config.cdnUrl ?? SDK_CDN_URL,
4218
+ timeout: config.timeout ?? SDK_LOAD_TIMEOUT,
4219
+ debug: config.debug ?? false,
4220
+ environment: config.environment ?? 'develop',
4221
+ };
4222
+ }
4223
+ /**
4224
+ * 获取当前加载状态
4225
+ */
4226
+ getStatus() {
4227
+ return this.status;
4228
+ }
4229
+ /**
4230
+ * 检查 SDK 是否已加载
4231
+ */
4232
+ isLoaded() {
4233
+ return this.status === 'loaded' && this.sdk !== null;
4234
+ }
4235
+ /**
4236
+ * 获取 SDK 实例
4237
+ */
4238
+ getSDK() {
4239
+ return this.sdk;
4240
+ }
4241
+ /**
4242
+ * 加载 SDK
4243
+ */
4244
+ async load() {
4245
+ // 如果已加载,直接返回
4246
+ if (this.sdk) {
4247
+ return this.sdk;
4248
+ }
4249
+ // 如果正在加载,返回现有的 Promise
4250
+ if (this.loadPromise) {
4251
+ return this.loadPromise;
4252
+ }
4253
+ this.status = 'loading';
4254
+ this.log('开始加载 SeaArtPay SDK...');
4255
+ this.loadPromise = this.loadSDKFromSources();
4256
+ try {
4257
+ this.sdk = await this.loadPromise;
4258
+ this.status = 'loaded';
4259
+ this.initializeSDK();
4260
+ this.log('SDK 加载成功');
4261
+ return this.sdk;
4262
+ }
4263
+ catch (error) {
4264
+ this.status = 'error';
4265
+ this.loadPromise = null;
4266
+ throw error;
4267
+ }
4268
+ }
4269
+ /**
4270
+ * 从多个源尝试加载 SDK
4271
+ */
4272
+ async loadSDKFromSources() {
4273
+ const sources = [
4274
+ { name: 'CDN', url: this.config.cdnUrl },
4275
+ ];
4276
+ for (const source of sources) {
4277
+ this.log(`尝试从 ${source.name} 加载: ${source.url}`);
4278
+ try {
4279
+ await this.loadScript(source.url);
4280
+ const sdk = this.extractSDKInstance();
4281
+ if (sdk) {
4282
+ this.log(`成功从 ${source.name} 加载 SDK`);
4283
+ return sdk;
4284
+ }
4285
+ this.log(`${source.name} 加载的脚本无效`);
4286
+ }
4287
+ catch (error) {
4288
+ this.log(`从 ${source.name} 加载失败: ${error}`);
4289
+ }
4290
+ }
4291
+ throw new Error('所有 SDK 源加载失败');
4292
+ }
4293
+ /**
4294
+ * 动态加载脚本
4295
+ */
4296
+ loadScript(url) {
4297
+ return new Promise((resolve, reject) => {
4298
+ // 检查是否在浏览器环境
4299
+ if (typeof document === 'undefined') {
4300
+ reject(new Error('非浏览器环境,无法加载脚本'));
4301
+ return;
4302
+ }
4303
+ // 检查是否已加载
4304
+ const existingScript = document.querySelector(`script[src="${url}"]`);
4305
+ if (existingScript) {
4306
+ resolve();
4307
+ return;
4308
+ }
4309
+ const script = document.createElement('script');
4310
+ script.src = url;
4311
+ script.async = true;
4312
+ script.setAttribute('data-sdk', 'seaart-payment');
4313
+ const timer = setTimeout(() => {
4314
+ cleanup();
4315
+ reject(new Error(`脚本加载超时: ${url}`));
4316
+ }, this.config.timeout);
4317
+ const cleanup = () => {
4318
+ clearTimeout(timer);
4319
+ script.onload = null;
4320
+ script.onerror = null;
4321
+ };
4322
+ script.onload = () => {
4323
+ cleanup();
4324
+ resolve();
4325
+ };
4326
+ script.onerror = () => {
4327
+ cleanup();
4328
+ document.head.removeChild(script);
4329
+ reject(new Error(`脚本加载失败: ${url}`));
4330
+ };
4331
+ document.head.appendChild(script);
4332
+ });
4333
+ }
4334
+ /**
4335
+ * 提取 SDK 实例
4336
+ * 处理 UMD 包装对象的情况
4337
+ */
4338
+ extractSDKInstance() {
4339
+ if (typeof window === 'undefined') {
4340
+ return null;
4341
+ }
4342
+ const globalObj = window.SeaArtPay;
4343
+ if (!globalObj) {
4344
+ return null;
4345
+ }
4346
+ // 检查是否是实际的 SDK 实例(有 show 方法)
4347
+ if (this.isValidSDK(globalObj)) {
4348
+ return globalObj;
4349
+ }
4350
+ // 检查是否是 UMD 包装对象
4351
+ const wrapped = globalObj;
4352
+ if (wrapped.SeaArtPay && this.isValidSDK(wrapped.SeaArtPay)) {
4353
+ // 修复全局引用
4354
+ window.SeaArtPay = wrapped.SeaArtPay;
4355
+ return wrapped.SeaArtPay;
4356
+ }
4357
+ return null;
4358
+ }
4359
+ /**
4360
+ * 验证 SDK 实例是否有效
4361
+ */
4362
+ isValidSDK(sdk) {
4363
+ return (typeof sdk === 'object' &&
4364
+ sdk !== null &&
4365
+ typeof sdk.show === 'function');
4366
+ }
4367
+ /**
4368
+ * 初始化 SDK
4369
+ */
4370
+ initializeSDK() {
4371
+ if (!this.sdk)
4372
+ return;
4373
+ const envConfig = ENV_CONFIG[this.config.environment];
4374
+ if (typeof this.sdk.init === 'function') {
4375
+ this.sdk.init({
4376
+ debug: this.config.debug,
4377
+ iframeUrl: envConfig.iframeUrl,
4378
+ });
4379
+ this.log(`SDK 已初始化,环境: ${this.config.environment}`);
4380
+ }
4381
+ }
4382
+ /**
4383
+ * 日志输出
4384
+ */
4385
+ log(message) {
4386
+ if (this.config.debug) {
4387
+ console.log(`[SeaArtPayLoader] ${message}`);
4388
+ }
4389
+ }
4390
+ /**
4391
+ * 重置加载器
4392
+ */
4393
+ reset() {
4394
+ this.status = 'idle';
4395
+ this.sdk = null;
4396
+ this.loadPromise = null;
4397
+ }
4398
+ }
4399
+ /**
4400
+ * 创建全局单例加载器
4401
+ */
4402
+ let globalLoader = null;
4403
+ /**
4404
+ * 获取或创建全局加载器
4405
+ */
4406
+ function getGlobalLoader(config) {
4407
+ if (!globalLoader) {
4408
+ globalLoader = new SeaArtPayLoader(config);
4409
+ }
4410
+ return globalLoader;
4411
+ }
4412
+ /**
4413
+ * 重置全局加载器
4414
+ */
4415
+ function resetGlobalLoader() {
4416
+ globalLoader?.reset();
4417
+ globalLoader = null;
4418
+ }
4419
+
4420
+ /**
4421
+ * 结账 API 模块
4422
+ * 实现 /api/v1/payment/sdk/checkout 接口调用
4423
+ */
4424
+ /**
4425
+ * 结账 API 客户端
4426
+ */
4427
+ class CheckoutAPI {
4428
+ constructor(config) {
4429
+ this.config = config;
4430
+ }
4431
+ /**
4432
+ * 创建一次性购买订单
4433
+ */
4434
+ async createOneTimeCheckout(params) {
4435
+ return this.createCheckout({
4436
+ product_id: params.productId,
4437
+ product_name: params.productName,
4438
+ price: params.price,
4439
+ purchase_type: 1,
4440
+ extra: params.extra,
4441
+ });
4442
+ }
4443
+ /**
4444
+ * 创建订阅订单
4445
+ */
4446
+ async createSubscriptionCheckout(params) {
4447
+ return this.createCheckout({
4448
+ product_id: params.productId,
4449
+ product_name: params.productName,
4450
+ price: params.price,
4451
+ purchase_type: 2,
4452
+ subscription: params.subscription,
4453
+ extra: params.extra,
4454
+ });
4455
+ }
4456
+ /**
4457
+ * 创建结账订单
4458
+ */
4459
+ async createCheckout(request) {
4460
+ this.validateRequest(request);
4461
+ const url = `${this.config.apiHost}${API_ENDPOINTS.SDK_CHECKOUT}`;
4462
+ const token = await this.config.getAuthToken();
4463
+ if (!token) {
4464
+ throw this.createError('UNAUTHORIZED', '未授权:缺少 JWT Token');
4465
+ }
4466
+ this.log('发起结账请求:', { url, request });
4467
+ try {
4468
+ const response = await fetch(url, {
4469
+ method: 'POST',
4470
+ headers: {
4471
+ 'Content-Type': 'application/json',
4472
+ Authorization: `Bearer ${token}`,
4473
+ },
4474
+ body: JSON.stringify(request),
4475
+ });
4476
+ const data = await response.json();
4477
+ this.log('结账响应:', data);
4478
+ if (data.code !== BIZ_CODE.SUCCESS) {
4479
+ throw this.createError(this.mapErrorCode(data.code), data.msg || '结账失败');
4480
+ }
4481
+ if (!data.data) {
4482
+ throw this.createError('CHECKOUT_FAILED', '结账响应数据为空');
4483
+ }
4484
+ return this.transformResponse(data.data);
4485
+ }
4486
+ catch (error) {
4487
+ if (this.isPaymentError(error)) {
4488
+ throw error;
4489
+ }
4490
+ if (error instanceof TypeError) {
4491
+ throw this.createError('NETWORK_ERROR', '网络请求失败', error);
4492
+ }
4493
+ throw this.createError('UNKNOWN_ERROR', '未知错误', error);
4494
+ }
4495
+ }
4496
+ /**
4497
+ * 验证请求参数
4498
+ */
4499
+ validateRequest(request) {
4500
+ // 必须提供 productId 或 (productName + price)
4501
+ const hasProductId = !!request.product_id;
4502
+ const hasManualProduct = !!request.product_name && request.price != null;
4503
+ if (!hasProductId && !hasManualProduct) {
4504
+ throw this.createError('INVALID_PARAMS', '必须提供 productId 或 (productName + price)');
4505
+ }
4506
+ // 订阅类型必须提供订阅参数
4507
+ if (request.purchase_type === 2 && !request.subscription) {
4508
+ throw this.createError('INVALID_PARAMS', '订阅类型必须提供 subscription 参数');
4509
+ }
4510
+ // 验证订阅参数
4511
+ if (request.subscription) {
4512
+ if (!request.subscription.period) {
4513
+ throw this.createError('INVALID_PARAMS', '订阅参数缺少 period');
4514
+ }
4515
+ if (request.subscription.periodAmount == null) {
4516
+ throw this.createError('INVALID_PARAMS', '订阅参数缺少 periodAmount');
4517
+ }
4518
+ }
4519
+ }
4520
+ /**
4521
+ * 转换响应数据
4522
+ */
4523
+ transformResponse(response) {
4524
+ return {
4525
+ orderId: response.order_id,
4526
+ transactionId: response.transaction_id,
4527
+ price: response.price,
4528
+ currency: response.currency,
4529
+ sdkConfig: {
4530
+ appId: response.sdk_config.app_id,
4531
+ apiHost: response.sdk_config.api_host,
4532
+ environment: response.sdk_config.environment,
4533
+ },
4534
+ };
4535
+ }
4536
+ /**
4537
+ * 映射错误代码
4538
+ */
4539
+ mapErrorCode(code) {
4540
+ switch (code) {
4541
+ case BIZ_CODE.BAD_REQUEST:
4542
+ return 'INVALID_PARAMS';
4543
+ case BIZ_CODE.UNAUTHORIZED:
4544
+ return 'UNAUTHORIZED';
4545
+ case BIZ_CODE.SERVER_ERROR:
4546
+ return 'API_ERROR';
4547
+ default:
4548
+ return 'CHECKOUT_FAILED';
4549
+ }
4550
+ }
4551
+ /**
4552
+ * 创建支付错误
4553
+ */
4554
+ createError(code, message, cause) {
4555
+ return { code, message, cause };
4556
+ }
4557
+ /**
4558
+ * 检查是否是支付错误
4559
+ */
4560
+ isPaymentError(error) {
4561
+ return (typeof error === 'object' &&
4562
+ error !== null &&
4563
+ 'code' in error &&
4564
+ 'message' in error);
4565
+ }
4566
+ /**
4567
+ * 日志输出
4568
+ */
4569
+ log(message, data) {
4570
+ if (this.config.debug) {
4571
+ console.log(`[CheckoutAPI] ${message}`, data ?? '');
4572
+ }
4573
+ }
4574
+ }
4575
+
4576
+ /**
4577
+ * PaymentCheckoutClient - 支付弹窗客户端
4578
+ * 提供支付弹窗的初始化、结账和订阅功能
4579
+ */
4580
+ /**
4581
+ * 支付弹窗客户端类
4582
+ *
4583
+ * 提供一次性购买和订阅购买功能,自动处理:
4584
+ * - SeaArtPay SDK 的动态加载
4585
+ * - 创建结账订单
4586
+ * - 显示支付弹窗
4587
+ * - 支付结果回调
4588
+ *
4589
+ * @example
4590
+ * ```typescript
4591
+ * // 创建客户端
4592
+ * const checkoutClient = new PaymentCheckoutClient({
4593
+ * apiHost: 'https://payment.sg.seaverse.dev',
4594
+ * authToken: 'your-jwt-token',
4595
+ * environment: 'develop',
4596
+ * debug: true,
4597
+ * });
4598
+ *
4599
+ * // 初始化
4600
+ * await checkoutClient.init();
4601
+ *
4602
+ * // 发起购买
4603
+ * const result = await checkoutClient.checkout({
4604
+ * productId: 'pkg_starter',
4605
+ * onSuccess: (res) => console.log('支付成功:', res),
4606
+ * onError: (err) => console.error('支付失败:', err),
4607
+ * });
4608
+ * ```
4609
+ */
4610
+ class PaymentCheckoutClient {
4611
+ constructor(config) {
4612
+ this.status = 'idle';
4613
+ this.initPromise = null;
4614
+ // 验证必须提供 authToken 或 getAuthToken 其中之一
4615
+ if (!config.authToken && !config.getAuthToken) {
4616
+ throw new Error('必须提供 authToken 或 getAuthToken 其中之一');
4617
+ }
4618
+ this.config = {
4619
+ ...config,
4620
+ environment: config.environment ?? DEFAULT_CHECKOUT_CONFIG.environment,
4621
+ debug: config.debug ?? DEFAULT_CHECKOUT_CONFIG.debug,
4622
+ };
4623
+ // 创建 SDK 加载器
4624
+ this.loader = new SeaArtPayLoader({
4625
+ cdnUrl: config.sdkCdnUrl,
4626
+ timeout: config.sdkTimeout ?? DEFAULT_CHECKOUT_CONFIG.sdkTimeout,
4627
+ debug: this.config.debug,
4628
+ environment: this.config.environment,
4629
+ });
4630
+ // 创建获取 Token 的函数(支持静态 token 和动态获取)
4631
+ const getAuthToken = config.authToken
4632
+ ? () => config.authToken
4633
+ : config.getAuthToken;
4634
+ // 创建结账 API 客户端
4635
+ this.checkoutAPI = new CheckoutAPI({
4636
+ apiHost: this.config.apiHost,
4637
+ getAuthToken,
4638
+ debug: this.config.debug,
4639
+ });
4640
+ }
4641
+ /**
4642
+ * 获取客户端状态
4643
+ */
4644
+ getStatus() {
4645
+ return this.status;
4646
+ }
4647
+ /**
4648
+ * 检查是否已初始化
4649
+ */
4650
+ isReady() {
4651
+ return this.status === 'ready';
4652
+ }
4653
+ /**
4654
+ * 初始化客户端
4655
+ * 加载 SeaArtPay SDK
4656
+ */
4657
+ async init() {
4658
+ if (this.status === 'ready') {
4659
+ return;
4660
+ }
4661
+ if (this.initPromise) {
4662
+ return this.initPromise;
4663
+ }
4664
+ this.status = 'initializing';
4665
+ this.log('初始化支付弹窗客户端...');
4666
+ this.initPromise = this.doInit();
4667
+ try {
4668
+ await this.initPromise;
4669
+ this.status = 'ready';
4670
+ this.log('支付弹窗客户端初始化完成');
4671
+ }
4672
+ catch (error) {
4673
+ this.status = 'error';
4674
+ this.initPromise = null;
4675
+ throw error;
4676
+ }
4677
+ }
4678
+ async doInit() {
4679
+ try {
4680
+ await this.loader.load();
4681
+ }
4682
+ catch (error) {
4683
+ throw this.createError('SDK_LOAD_FAILED', 'SeaArt 支付 SDK 加载失败', error);
4684
+ }
4685
+ }
4686
+ /**
4687
+ * 一次性购买
4688
+ * @param options 购买选项
4689
+ * @returns 结账结果(包含 transactionId)
4690
+ */
4691
+ async checkout(options) {
4692
+ await this.ensureReady();
4693
+ this.log('发起一次性购买:', options);
4694
+ // 调用结账 API
4695
+ const result = await this.checkoutAPI.createOneTimeCheckout({
4696
+ productId: options.productId,
4697
+ productName: options.productName,
4698
+ price: options.price,
4699
+ extra: options.extra,
4700
+ });
4701
+ // 自动打开支付弹窗
4702
+ this.showPaymentModal({
4703
+ transactionId: result.transactionId,
4704
+ language: options.language,
4705
+ userName: options.userName,
4706
+ productName: options.productName,
4707
+ onSuccess: options.onSuccess,
4708
+ onUnsuccess: (unsuccessResult) => {
4709
+ if (unsuccessResult.reason === 'cancel') {
4710
+ options.onClose?.();
4711
+ }
4712
+ else {
4713
+ options.onError?.({
4714
+ code: 'PAYMENT_FAILED',
4715
+ message: unsuccessResult.message,
4716
+ });
4717
+ }
4718
+ },
4719
+ });
4720
+ return result;
4721
+ }
4722
+ /**
4723
+ * 订阅购买
4724
+ * @param options 订阅选项
4725
+ * @returns 结账结果(包含 transactionId)
4726
+ */
4727
+ async subscribe(options) {
4728
+ await this.ensureReady();
4729
+ this.log('发起订阅购买:', options);
4730
+ // 调用结账 API
4731
+ const result = await this.checkoutAPI.createSubscriptionCheckout({
4732
+ productId: options.productId,
4733
+ productName: options.productName,
4734
+ price: options.price,
4735
+ subscription: {
4736
+ period: options.period,
4737
+ periodAmount: options.periodAmount,
4738
+ firstDays: options.firstDays ?? 0,
4739
+ },
4740
+ extra: options.extra,
4741
+ });
4742
+ // 自动打开支付弹窗
4743
+ this.showPaymentModal({
4744
+ transactionId: result.transactionId,
4745
+ language: options.language,
4746
+ userName: options.userName,
4747
+ productName: options.productName,
4748
+ onSuccess: options.onSuccess,
4749
+ onUnsuccess: (unsuccessResult) => {
4750
+ if (unsuccessResult.reason === 'cancel') {
4751
+ options.onClose?.();
4752
+ }
4753
+ else {
4754
+ options.onError?.({
4755
+ code: 'PAYMENT_FAILED',
4756
+ message: unsuccessResult.message,
4757
+ });
4758
+ }
4759
+ },
4760
+ });
4761
+ return result;
4762
+ }
4763
+ /**
4764
+ * 直接打开支付弹窗
4765
+ * 使用已有的 transactionId
4766
+ */
4767
+ showPayment(options) {
4768
+ if (!this.isReady()) {
4769
+ throw this.createError('SDK_NOT_READY', '支付 SDK 未初始化');
4770
+ }
4771
+ this.showPaymentModal(options);
4772
+ }
4773
+ /**
4774
+ * 关闭支付弹窗
4775
+ */
4776
+ close() {
4777
+ const sdk = this.getSDK();
4778
+ if (sdk && typeof sdk.close === 'function') {
4779
+ sdk.close();
4780
+ this.log('支付弹窗已关闭');
4781
+ }
4782
+ }
4783
+ /**
4784
+ * 获取环境配置
4785
+ */
4786
+ getEnvironmentConfig() {
4787
+ return ENV_CONFIG[this.config.environment];
4788
+ }
4789
+ // ==================== 私有方法 ====================
4790
+ /**
4791
+ * 确保客户端已就绪
4792
+ */
4793
+ async ensureReady() {
4794
+ if (this.status === 'ready') {
4795
+ return;
4796
+ }
4797
+ if (this.status === 'initializing' && this.initPromise) {
4798
+ await this.initPromise;
4799
+ return;
4800
+ }
4801
+ await this.init();
4802
+ }
4803
+ /**
4804
+ * 获取 SDK 实例
4805
+ */
4806
+ getSDK() {
4807
+ return this.loader.getSDK();
4808
+ }
4809
+ /**
4810
+ * 显示支付弹窗
4811
+ */
4812
+ showPaymentModal(options) {
4813
+ const sdk = this.getSDK();
4814
+ if (!sdk) {
4815
+ throw this.createError('SDK_NOT_READY', '支付 SDK 未加载');
4816
+ }
4817
+ this.log('打开支付弹窗:', options.transactionId);
4818
+ sdk.show({
4819
+ transactionId: options.transactionId,
4820
+ language: options.language ?? DEFAULT_CHECKOUT_CONFIG.language,
4821
+ userName: options.userName,
4822
+ productName: options.productName,
4823
+ from: options.from,
4824
+ onSuccess: (result) => {
4825
+ this.log('支付成功:', result);
4826
+ options.onSuccess?.({
4827
+ transactionId: options.transactionId,
4828
+ status: 'success',
4829
+ data: result,
4830
+ });
4831
+ },
4832
+ onUnsuccess: (result) => {
4833
+ this.log('支付未成功:', result);
4834
+ const unsuccessResult = result;
4835
+ options.onUnsuccess?.({
4836
+ reason: unsuccessResult.reason ?? 'error',
4837
+ message: unsuccessResult.message ?? '支付未完成',
4838
+ transactionId: options.transactionId,
4839
+ });
4840
+ },
4841
+ });
4842
+ }
4843
+ /**
4844
+ * 创建支付错误
4845
+ */
4846
+ createError(code, message, cause) {
4847
+ return { code, message, cause };
4848
+ }
4849
+ /**
4850
+ * 日志输出
4851
+ */
4852
+ log(message, data) {
4853
+ if (this.config.debug) {
4854
+ console.log(`[PaymentCheckoutClient] ${message}`, data ?? '');
4855
+ }
4856
+ }
4857
+ }
4858
+
4859
+ /**
4860
+ * 工具函数模块
4861
+ */
4862
+ /**
4863
+ * 生成唯一的订单引用号
4864
+ * @param prefix 前缀
4865
+ * @returns 唯一引用号
4866
+ */
4867
+ function generateOrderReference(prefix = 'sv') {
4868
+ const timestamp = Date.now();
4869
+ const random = Math.random().toString(36).substring(2, 8);
4870
+ return `${prefix}-${timestamp}-${random}`;
4871
+ }
4872
+ /**
4873
+ * 将美元金额转换为分
4874
+ * @param dollars 美元金额
4875
+ * @returns 分
4876
+ */
4877
+ function dollarsToCents(dollars) {
4878
+ return Math.round(dollars * 100);
4879
+ }
4880
+ /**
4881
+ * 将分转换为美元
4882
+ * @param cents 分
4883
+ * @returns 美元金额
4884
+ */
4885
+ function centsToDollars(cents) {
4886
+ return cents / 100;
4887
+ }
4888
+ /**
4889
+ * 格式化价格显示
4890
+ * @param amount 金额(美元)
4891
+ * @param currency 货币代码
4892
+ * @returns 格式化的价格字符串
4893
+ */
4894
+ function formatPrice(amount, currency = 'USD') {
4895
+ const symbols = {
4896
+ USD: '$',
4897
+ CNY: '¥',
4898
+ EUR: '€',
4899
+ GBP: '£',
4900
+ JPY: '¥',
4901
+ KRW: '₩',
4902
+ };
4903
+ const symbol = symbols[currency] || currency + ' ';
4904
+ return `${symbol}${amount.toFixed(2)}`;
4905
+ }
4906
+ /**
4907
+ * 创建支付错误对象
4908
+ * @param code 错误代码
4909
+ * @param message 错误消息
4910
+ * @param cause 原始错误
4911
+ * @returns 支付错误对象
4912
+ */
4913
+ function createCheckoutPaymentError(code, message, cause) {
4914
+ return { code, message, cause };
4915
+ }
4916
+ /**
4917
+ * 检查是否是支付错误
4918
+ * @param error 错误对象
4919
+ * @returns 是否是支付错误
4920
+ */
4921
+ function isCheckoutPaymentError(error) {
4922
+ return (typeof error === 'object' &&
4923
+ error !== null &&
4924
+ 'code' in error &&
4925
+ 'message' in error);
4926
+ }
4927
+ /**
4928
+ * 延迟函数
4929
+ * @param ms 毫秒
4930
+ * @returns Promise
4931
+ */
4932
+ function delay(ms) {
4933
+ return new Promise((resolve) => setTimeout(resolve, ms));
4934
+ }
4935
+ /**
4936
+ * 带超时的 Promise
4937
+ * @param promise 原始 Promise
4938
+ * @param ms 超时毫秒数
4939
+ * @param errorMessage 超时错误消息
4940
+ * @returns 带超时的 Promise
4941
+ */
4942
+ function withTimeout(promise, ms, errorMessage = 'Operation timed out') {
4943
+ return Promise.race([
4944
+ promise,
4945
+ new Promise((_, reject) => {
4946
+ setTimeout(() => reject(new Error(errorMessage)), ms);
4947
+ }),
4948
+ ]);
4949
+ }
4950
+ /**
4951
+ * 安全的 JSON 解析
4952
+ * @param json JSON 字符串
4953
+ * @param defaultValue 默认值
4954
+ * @returns 解析结果或默认值
4955
+ */
4956
+ function safeJsonParse(json, defaultValue) {
4957
+ try {
4958
+ return JSON.parse(json);
4959
+ }
4960
+ catch {
4961
+ return defaultValue;
4962
+ }
4963
+ }
4964
+ /**
4965
+ * 检查是否在浏览器环境
4966
+ */
4967
+ function isBrowser() {
4968
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
4969
+ }
4970
+ /**
4971
+ * 获取当前页面 URL
4972
+ */
4973
+ function getCurrentUrl() {
4974
+ if (!isBrowser())
4975
+ return '';
4976
+ return window.location.href;
4977
+ }
4978
+ /**
4979
+ * Locale 映射(项目语言到 SDK 语言)
4980
+ */
4981
+ const LOCALE_MAP = {
4982
+ 'zh-CN': 'zh-CN',
4983
+ 'zh-TW': 'zh-TW',
4984
+ zh: 'zh-CN',
4985
+ en: 'en-US',
4986
+ 'en-US': 'en-US',
4987
+ ko: 'ko-KR',
4988
+ 'ko-KR': 'ko-KR',
4989
+ ja: 'ja-JP',
4990
+ 'ja-JP': 'ja-JP',
4991
+ es: 'es-ES',
4992
+ fr: 'fr-FR',
4993
+ de: 'de-DE',
4994
+ };
4995
+ /**
4996
+ * 获取 SDK 支持的 locale
4997
+ * @param locale 项目 locale
4998
+ * @returns SDK locale
4999
+ */
5000
+ function getSDKLocale(locale) {
5001
+ return LOCALE_MAP[locale] || LOCALE_MAP['en'];
5002
+ }
5003
+
5004
+ /**
5005
+ * @seaverse/payment-sdk
5006
+ *
5007
+ * SeaVerse Payment SDK - Credit management and payment checkout
5008
+ *
5009
+ * This SDK provides two main features:
5010
+ *
5011
+ * ## 1. Credit Query (PaymentClient)
5012
+ * Query user credit accounts and transaction history.
5013
+ *
5014
+ * ```typescript
5015
+ * import { PaymentClient } from '@seaverse/payment-sdk';
5016
+ *
5017
+ * const client = new PaymentClient({
5018
+ * appId: 'seaverse',
5019
+ * token: 'your-bearer-token',
5020
+ * });
5021
+ *
5022
+ * const detail = await client.getCreditDetail();
5023
+ * console.log(`Total Balance: ${detail.total_balance}`);
5024
+ * ```
5025
+ *
5026
+ * ## 2. Payment Checkout (PaymentCheckoutClient)
5027
+ * Show payment modal for one-time purchases and subscriptions.
5028
+ *
5029
+ * ```typescript
5030
+ * import { PaymentCheckoutClient } from '@seaverse/payment-sdk';
5031
+ *
5032
+ * const checkoutClient = new PaymentCheckoutClient({
5033
+ * apiHost: 'https://payment.sg.seaverse.dev',
5034
+ * authToken: 'your-jwt-token',
5035
+ * environment: 'develop',
5036
+ * });
5037
+ *
5038
+ * await checkoutClient.init();
5039
+ *
5040
+ * await checkoutClient.checkout({
5041
+ * productId: 'pkg_starter',
5042
+ * onSuccess: (res) => console.log('Payment success:', res),
5043
+ * });
5044
+ * ```
5045
+ */
5046
+ // ============================================================================
5047
+ // Credit Query API (PaymentClient)
5048
+ // ============================================================================
5049
+ // ============================================================================
5050
+ // Version
5051
+ // ============================================================================
5052
+ /**
5053
+ * SDK version
5054
+ */
5055
+ const VERSION = '0.1.0';
5056
+
5057
+ export { API_ENDPOINTS, BIZ_CODE, CheckoutAPI, DEFAULT_CHECKOUT_CONFIG, ENV_CONFIG, HTTP_STATUS, PaymentAPIError, PaymentCheckoutClient, PaymentClient, SDK_CDN_URL, SDK_GLOBAL_NAME, SDK_LOAD_TIMEOUT, SeaArtPayLoader, VERSION, centsToDollars, createCheckoutPaymentError, delay, dollarsToCents, formatPrice, generateOrderReference, getCurrentUrl, getGlobalLoader, getSDKLocale, isBrowser, isCheckoutPaymentError, resetGlobalLoader, safeJsonParse, withTimeout };
5058
+ //# sourceMappingURL=index.browser.js.map