medos-sdk 1.0.3 → 1.1.1

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