denotify-client 1.0.0

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