axios.cjs 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191
  1. // Axios v1.3.4 Copyright (c) 2023 Matt Zabriskie and contributors
  2. 'use strict';
  3. function bind(fn, thisArg) {
  4. return function wrap() {
  5. return fn.apply(thisArg, arguments);
  6. };
  7. }
  8. // utils is a library of generic helper functions non-specific to axios
  9. const {toString} = Object.prototype;
  10. const {getPrototypeOf} = Object;
  11. const kindOf = (cache => thing => {
  12. const str = toString.call(thing);
  13. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  14. })(Object.create(null));
  15. const kindOfTest = (type) => {
  16. type = type.toLowerCase();
  17. return (thing) => kindOf(thing) === type
  18. };
  19. const typeOfTest = type => thing => typeof thing === type;
  20. /**
  21. * Determine if a value is an Array
  22. *
  23. * @param {Object} val The value to test
  24. *
  25. * @returns {boolean} True if value is an Array, otherwise false
  26. */
  27. const {isArray} = Array;
  28. /**
  29. * Determine if a value is undefined
  30. *
  31. * @param {*} val The value to test
  32. *
  33. * @returns {boolean} True if the value is undefined, otherwise false
  34. */
  35. const isUndefined = typeOfTest('undefined');
  36. /**
  37. * Determine if a value is a Buffer
  38. *
  39. * @param {*} val The value to test
  40. *
  41. * @returns {boolean} True if value is a Buffer, otherwise false
  42. */
  43. function isBuffer(val) {
  44. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  45. && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
  46. }
  47. /**
  48. * Determine if a value is an ArrayBuffer
  49. *
  50. * @param {*} val The value to test
  51. *
  52. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  53. */
  54. const isArrayBuffer = kindOfTest('ArrayBuffer');
  55. /**
  56. * Determine if a value is a view on an ArrayBuffer
  57. *
  58. * @param {*} val The value to test
  59. *
  60. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  61. */
  62. function isArrayBufferView(val) {
  63. let result;
  64. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  65. result = ArrayBuffer.isView(val);
  66. } else {
  67. result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  68. }
  69. return result;
  70. }
  71. /**
  72. * Determine if a value is a String
  73. *
  74. * @param {*} val The value to test
  75. *
  76. * @returns {boolean} True if value is a String, otherwise false
  77. */
  78. const isString = typeOfTest('string');
  79. /**
  80. * Determine if a value is a Function
  81. *
  82. * @param {*} val The value to test
  83. * @returns {boolean} True if value is a Function, otherwise false
  84. */
  85. const isFunction = typeOfTest('function');
  86. /**
  87. * Determine if a value is a Number
  88. *
  89. * @param {*} val The value to test
  90. *
  91. * @returns {boolean} True if value is a Number, otherwise false
  92. */
  93. const isNumber = typeOfTest('number');
  94. /**
  95. * Determine if a value is an Object
  96. *
  97. * @param {*} thing The value to test
  98. *
  99. * @returns {boolean} True if value is an Object, otherwise false
  100. */
  101. const isObject = (thing) => thing !== null && typeof thing === 'object';
  102. /**
  103. * Determine if a value is a Boolean
  104. *
  105. * @param {*} thing The value to test
  106. * @returns {boolean} True if value is a Boolean, otherwise false
  107. */
  108. const isBoolean = thing => thing === true || thing === false;
  109. /**
  110. * Determine if a value is a plain Object
  111. *
  112. * @param {*} val The value to test
  113. *
  114. * @returns {boolean} True if value is a plain Object, otherwise false
  115. */
  116. const isPlainObject = (val) => {
  117. if (kindOf(val) !== 'object') {
  118. return false;
  119. }
  120. const prototype = getPrototypeOf(val);
  121. return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
  122. };
  123. /**
  124. * Determine if a value is a Date
  125. *
  126. * @param {*} val The value to test
  127. *
  128. * @returns {boolean} True if value is a Date, otherwise false
  129. */
  130. const isDate = kindOfTest('Date');
  131. /**
  132. * Determine if a value is a File
  133. *
  134. * @param {*} val The value to test
  135. *
  136. * @returns {boolean} True if value is a File, otherwise false
  137. */
  138. const isFile = kindOfTest('File');
  139. /**
  140. * Determine if a value is a Blob
  141. *
  142. * @param {*} val The value to test
  143. *
  144. * @returns {boolean} True if value is a Blob, otherwise false
  145. */
  146. const isBlob = kindOfTest('Blob');
  147. /**
  148. * Determine if a value is a FileList
  149. *
  150. * @param {*} val The value to test
  151. *
  152. * @returns {boolean} True if value is a File, otherwise false
  153. */
  154. const isFileList = kindOfTest('FileList');
  155. /**
  156. * Determine if a value is a Stream
  157. *
  158. * @param {*} val The value to test
  159. *
  160. * @returns {boolean} True if value is a Stream, otherwise false
  161. */
  162. const isStream = (val) => isObject(val) && isFunction(val.pipe);
  163. /**
  164. * Determine if a value is a FormData
  165. *
  166. * @param {*} thing The value to test
  167. *
  168. * @returns {boolean} True if value is an FormData, otherwise false
  169. */
  170. const isFormData = (thing) => {
  171. const pattern = '[object FormData]';
  172. return thing && (
  173. (typeof FormData === 'function' && thing instanceof FormData) ||
  174. toString.call(thing) === pattern ||
  175. (isFunction(thing.toString) && thing.toString() === pattern)
  176. );
  177. };
  178. /**
  179. * Determine if a value is a URLSearchParams object
  180. *
  181. * @param {*} val The value to test
  182. *
  183. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  184. */
  185. const isURLSearchParams = kindOfTest('URLSearchParams');
  186. /**
  187. * Trim excess whitespace off the beginning and end of a string
  188. *
  189. * @param {String} str The String to trim
  190. *
  191. * @returns {String} The String freed of excess whitespace
  192. */
  193. const trim = (str) => str.trim ?
  194. str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  195. /**
  196. * Iterate over an Array or an Object invoking a function for each item.
  197. *
  198. * If `obj` is an Array callback will be called passing
  199. * the value, index, and complete array for each item.
  200. *
  201. * If 'obj' is an Object callback will be called passing
  202. * the value, key, and complete object for each property.
  203. *
  204. * @param {Object|Array} obj The object to iterate
  205. * @param {Function} fn The callback to invoke for each item
  206. *
  207. * @param {Boolean} [allOwnKeys = false]
  208. * @returns {any}
  209. */
  210. function forEach(obj, fn, {allOwnKeys = false} = {}) {
  211. // Don't bother if no value provided
  212. if (obj === null || typeof obj === 'undefined') {
  213. return;
  214. }
  215. let i;
  216. let l;
  217. // Force an array if not already something iterable
  218. if (typeof obj !== 'object') {
  219. /*eslint no-param-reassign:0*/
  220. obj = [obj];
  221. }
  222. if (isArray(obj)) {
  223. // Iterate over array values
  224. for (i = 0, l = obj.length; i < l; i++) {
  225. fn.call(null, obj[i], i, obj);
  226. }
  227. } else {
  228. // Iterate over object keys
  229. const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  230. const len = keys.length;
  231. let key;
  232. for (i = 0; i < len; i++) {
  233. key = keys[i];
  234. fn.call(null, obj[key], key, obj);
  235. }
  236. }
  237. }
  238. function findKey(obj, key) {
  239. key = key.toLowerCase();
  240. const keys = Object.keys(obj);
  241. let i = keys.length;
  242. let _key;
  243. while (i-- > 0) {
  244. _key = keys[i];
  245. if (key === _key.toLowerCase()) {
  246. return _key;
  247. }
  248. }
  249. return null;
  250. }
  251. const _global = (() => {
  252. /*eslint no-undef:0*/
  253. if (typeof globalThis !== "undefined") return globalThis;
  254. return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
  255. })();
  256. const isContextDefined = (context) => !isUndefined(context) && context !== _global;
  257. /**
  258. * Accepts varargs expecting each argument to be an object, then
  259. * immutably merges the properties of each object and returns result.
  260. *
  261. * When multiple objects contain the same key the later object in
  262. * the arguments list will take precedence.
  263. *
  264. * Example:
  265. *
  266. * ```js
  267. * var result = merge({foo: 123}, {foo: 456});
  268. * console.log(result.foo); // outputs 456
  269. * ```
  270. *
  271. * @param {Object} obj1 Object to merge
  272. *
  273. * @returns {Object} Result of all merge properties
  274. */
  275. function merge(/* obj1, obj2, obj3, ... */) {
  276. const {caseless} = isContextDefined(this) && this || {};
  277. const result = {};
  278. const assignValue = (val, key) => {
  279. const targetKey = caseless && findKey(result, key) || key;
  280. if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
  281. result[targetKey] = merge(result[targetKey], val);
  282. } else if (isPlainObject(val)) {
  283. result[targetKey] = merge({}, val);
  284. } else if (isArray(val)) {
  285. result[targetKey] = val.slice();
  286. } else {
  287. result[targetKey] = val;
  288. }
  289. };
  290. for (let i = 0, l = arguments.length; i < l; i++) {
  291. arguments[i] && forEach(arguments[i], assignValue);
  292. }
  293. return result;
  294. }
  295. /**
  296. * Extends object a by mutably adding to it the properties of object b.
  297. *
  298. * @param {Object} a The object to be extended
  299. * @param {Object} b The object to copy properties from
  300. * @param {Object} thisArg The object to bind function to
  301. *
  302. * @param {Boolean} [allOwnKeys]
  303. * @returns {Object} The resulting value of object a
  304. */
  305. const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
  306. forEach(b, (val, key) => {
  307. if (thisArg && isFunction(val)) {
  308. a[key] = bind(val, thisArg);
  309. } else {
  310. a[key] = val;
  311. }
  312. }, {allOwnKeys});
  313. return a;
  314. };
  315. /**
  316. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  317. *
  318. * @param {string} content with BOM
  319. *
  320. * @returns {string} content value without BOM
  321. */
  322. const stripBOM = (content) => {
  323. if (content.charCodeAt(0) === 0xFEFF) {
  324. content = content.slice(1);
  325. }
  326. return content;
  327. };
  328. /**
  329. * Inherit the prototype methods from one constructor into another
  330. * @param {function} constructor
  331. * @param {function} superConstructor
  332. * @param {object} [props]
  333. * @param {object} [descriptors]
  334. *
  335. * @returns {void}
  336. */
  337. const inherits = (constructor, superConstructor, props, descriptors) => {
  338. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  339. constructor.prototype.constructor = constructor;
  340. Object.defineProperty(constructor, 'super', {
  341. value: superConstructor.prototype
  342. });
  343. props && Object.assign(constructor.prototype, props);
  344. };
  345. /**
  346. * Resolve object with deep prototype chain to a flat object
  347. * @param {Object} sourceObj source object
  348. * @param {Object} [destObj]
  349. * @param {Function|Boolean} [filter]
  350. * @param {Function} [propFilter]
  351. *
  352. * @returns {Object}
  353. */
  354. const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  355. let props;
  356. let i;
  357. let prop;
  358. const merged = {};
  359. destObj = destObj || {};
  360. // eslint-disable-next-line no-eq-null,eqeqeq
  361. if (sourceObj == null) return destObj;
  362. do {
  363. props = Object.getOwnPropertyNames(sourceObj);
  364. i = props.length;
  365. while (i-- > 0) {
  366. prop = props[i];
  367. if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
  368. destObj[prop] = sourceObj[prop];
  369. merged[prop] = true;
  370. }
  371. }
  372. sourceObj = filter !== false && getPrototypeOf(sourceObj);
  373. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  374. return destObj;
  375. };
  376. /**
  377. * Determines whether a string ends with the characters of a specified string
  378. *
  379. * @param {String} str
  380. * @param {String} searchString
  381. * @param {Number} [position= 0]
  382. *
  383. * @returns {boolean}
  384. */
  385. const endsWith = (str, searchString, position) => {
  386. str = String(str);
  387. if (position === undefined || position > str.length) {
  388. position = str.length;
  389. }
  390. position -= searchString.length;
  391. const lastIndex = str.indexOf(searchString, position);
  392. return lastIndex !== -1 && lastIndex === position;
  393. };
  394. /**
  395. * Returns new array from array like object or null if failed
  396. *
  397. * @param {*} [thing]
  398. *
  399. * @returns {?Array}
  400. */
  401. const toArray = (thing) => {
  402. if (!thing) return null;
  403. if (isArray(thing)) return thing;
  404. let i = thing.length;
  405. if (!isNumber(i)) return null;
  406. const arr = new Array(i);
  407. while (i-- > 0) {
  408. arr[i] = thing[i];
  409. }
  410. return arr;
  411. };
  412. /**
  413. * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
  414. * thing passed in is an instance of Uint8Array
  415. *
  416. * @param {TypedArray}
  417. *
  418. * @returns {Array}
  419. */
  420. // eslint-disable-next-line func-names
  421. const isTypedArray = (TypedArray => {
  422. // eslint-disable-next-line func-names
  423. return thing => {
  424. return TypedArray && thing instanceof TypedArray;
  425. };
  426. })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
  427. /**
  428. * For each entry in the object, call the function with the key and value.
  429. *
  430. * @param {Object<any, any>} obj - The object to iterate over.
  431. * @param {Function} fn - The function to call for each entry.
  432. *
  433. * @returns {void}
  434. */
  435. const forEachEntry = (obj, fn) => {
  436. const generator = obj && obj[Symbol.iterator];
  437. const iterator = generator.call(obj);
  438. let result;
  439. while ((result = iterator.next()) && !result.done) {
  440. const pair = result.value;
  441. fn.call(obj, pair[0], pair[1]);
  442. }
  443. };
  444. /**
  445. * It takes a regular expression and a string, and returns an array of all the matches
  446. *
  447. * @param {string} regExp - The regular expression to match against.
  448. * @param {string} str - The string to search.
  449. *
  450. * @returns {Array<boolean>}
  451. */
  452. const matchAll = (regExp, str) => {
  453. let matches;
  454. const arr = [];
  455. while ((matches = regExp.exec(str)) !== null) {
  456. arr.push(matches);
  457. }
  458. return arr;
  459. };
  460. /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
  461. const isHTMLForm = kindOfTest('HTMLFormElement');
  462. const toCamelCase = str => {
  463. return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
  464. function replacer(m, p1, p2) {
  465. return p1.toUpperCase() + p2;
  466. }
  467. );
  468. };
  469. /* Creating a function that will check if an object has a property. */
  470. const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
  471. /**
  472. * Determine if a value is a RegExp object
  473. *
  474. * @param {*} val The value to test
  475. *
  476. * @returns {boolean} True if value is a RegExp object, otherwise false
  477. */
  478. const isRegExp = kindOfTest('RegExp');
  479. const reduceDescriptors = (obj, reducer) => {
  480. const descriptors = Object.getOwnPropertyDescriptors(obj);
  481. const reducedDescriptors = {};
  482. forEach(descriptors, (descriptor, name) => {
  483. if (reducer(descriptor, name, obj) !== false) {
  484. reducedDescriptors[name] = descriptor;
  485. }
  486. });
  487. Object.defineProperties(obj, reducedDescriptors);
  488. };
  489. /**
  490. * Makes all methods read-only
  491. * @param {Object} obj
  492. */
  493. const freezeMethods = (obj) => {
  494. reduceDescriptors(obj, (descriptor, name) => {
  495. // skip restricted props in strict mode
  496. if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
  497. return false;
  498. }
  499. const value = obj[name];
  500. if (!isFunction(value)) return;
  501. descriptor.enumerable = false;
  502. if ('writable' in descriptor) {
  503. descriptor.writable = false;
  504. return;
  505. }
  506. if (!descriptor.set) {
  507. descriptor.set = () => {
  508. throw Error('Can not rewrite read-only method \'' + name + '\'');
  509. };
  510. }
  511. });
  512. };
  513. const toObjectSet = (arrayOrString, delimiter) => {
  514. const obj = {};
  515. const define = (arr) => {
  516. arr.forEach(value => {
  517. obj[value] = true;
  518. });
  519. };
  520. isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  521. return obj;
  522. };
  523. const noop = () => {};
  524. const toFiniteNumber = (value, defaultValue) => {
  525. value = +value;
  526. return Number.isFinite(value) ? value : defaultValue;
  527. };
  528. const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
  529. const DIGIT = '0123456789';
  530. const ALPHABET = {
  531. DIGIT,
  532. ALPHA,
  533. ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
  534. };
  535. const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
  536. let str = '';
  537. const {length} = alphabet;
  538. while (size--) {
  539. str += alphabet[Math.random() * length|0];
  540. }
  541. return str;
  542. };
  543. /**
  544. * If the thing is a FormData object, return true, otherwise return false.
  545. *
  546. * @param {unknown} thing - The thing to check.
  547. *
  548. * @returns {boolean}
  549. */
  550. function isSpecCompliantForm(thing) {
  551. return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
  552. }
  553. const toJSONObject = (obj) => {
  554. const stack = new Array(10);
  555. const visit = (source, i) => {
  556. if (isObject(source)) {
  557. if (stack.indexOf(source) >= 0) {
  558. return;
  559. }
  560. if(!('toJSON' in source)) {
  561. stack[i] = source;
  562. const target = isArray(source) ? [] : {};
  563. forEach(source, (value, key) => {
  564. const reducedValue = visit(value, i + 1);
  565. !isUndefined(reducedValue) && (target[key] = reducedValue);
  566. });
  567. stack[i] = undefined;
  568. return target;
  569. }
  570. }
  571. return source;
  572. };
  573. return visit(obj, 0);
  574. };
  575. var utils = {
  576. isArray,
  577. isArrayBuffer,
  578. isBuffer,
  579. isFormData,
  580. isArrayBufferView,
  581. isString,
  582. isNumber,
  583. isBoolean,
  584. isObject,
  585. isPlainObject,
  586. isUndefined,
  587. isDate,
  588. isFile,
  589. isBlob,
  590. isRegExp,
  591. isFunction,
  592. isStream,
  593. isURLSearchParams,
  594. isTypedArray,
  595. isFileList,
  596. forEach,
  597. merge,
  598. extend,
  599. trim,
  600. stripBOM,
  601. inherits,
  602. toFlatObject,
  603. kindOf,
  604. kindOfTest,
  605. endsWith,
  606. toArray,
  607. forEachEntry,
  608. matchAll,
  609. isHTMLForm,
  610. hasOwnProperty,
  611. hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
  612. reduceDescriptors,
  613. freezeMethods,
  614. toObjectSet,
  615. toCamelCase,
  616. noop,
  617. toFiniteNumber,
  618. findKey,
  619. global: _global,
  620. isContextDefined,
  621. ALPHABET,
  622. generateString,
  623. isSpecCompliantForm,
  624. toJSONObject
  625. };
  626. /**
  627. * Create an Error with the specified message, config, error code, request and response.
  628. *
  629. * @param {string} message The error message.
  630. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  631. * @param {Object} [config] The config.
  632. * @param {Object} [request] The request.
  633. * @param {Object} [response] The response.
  634. *
  635. * @returns {Error} The created error.
  636. */
  637. function AxiosError(message, code, config, request, response) {
  638. Error.call(this);
  639. if (Error.captureStackTrace) {
  640. Error.captureStackTrace(this, this.constructor);
  641. } else {
  642. this.stack = (new Error()).stack;
  643. }
  644. this.message = message;
  645. this.name = 'AxiosError';
  646. code && (this.code = code);
  647. config && (this.config = config);
  648. request && (this.request = request);
  649. response && (this.response = response);
  650. }
  651. utils.inherits(AxiosError, Error, {
  652. toJSON: function toJSON() {
  653. return {
  654. // Standard
  655. message: this.message,
  656. name: this.name,
  657. // Microsoft
  658. description: this.description,
  659. number: this.number,
  660. // Mozilla
  661. fileName: this.fileName,
  662. lineNumber: this.lineNumber,
  663. columnNumber: this.columnNumber,
  664. stack: this.stack,
  665. // Axios
  666. config: utils.toJSONObject(this.config),
  667. code: this.code,
  668. status: this.response && this.response.status ? this.response.status : null
  669. };
  670. }
  671. });
  672. const prototype$1 = AxiosError.prototype;
  673. const descriptors = {};
  674. [
  675. 'ERR_BAD_OPTION_VALUE',
  676. 'ERR_BAD_OPTION',
  677. 'ECONNABORTED',
  678. 'ETIMEDOUT',
  679. 'ERR_NETWORK',
  680. 'ERR_FR_TOO_MANY_REDIRECTS',
  681. 'ERR_DEPRECATED',
  682. 'ERR_BAD_RESPONSE',
  683. 'ERR_BAD_REQUEST',
  684. 'ERR_CANCELED',
  685. 'ERR_NOT_SUPPORT',
  686. 'ERR_INVALID_URL'
  687. // eslint-disable-next-line func-names
  688. ].forEach(code => {
  689. descriptors[code] = {value: code};
  690. });
  691. Object.defineProperties(AxiosError, descriptors);
  692. Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
  693. // eslint-disable-next-line func-names
  694. AxiosError.from = (error, code, config, request, response, customProps) => {
  695. const axiosError = Object.create(prototype$1);
  696. utils.toFlatObject(error, axiosError, function filter(obj) {
  697. return obj !== Error.prototype;
  698. }, prop => {
  699. return prop !== 'isAxiosError';
  700. });
  701. AxiosError.call(axiosError, error.message, code, config, request, response);
  702. axiosError.cause = error;
  703. axiosError.name = error.name;
  704. customProps && Object.assign(axiosError, customProps);
  705. return axiosError;
  706. };
  707. // eslint-disable-next-line strict
  708. var httpAdapter = null;
  709. /**
  710. * Determines if the given thing is a array or js object.
  711. *
  712. * @param {string} thing - The object or array to be visited.
  713. *
  714. * @returns {boolean}
  715. */
  716. function isVisitable(thing) {
  717. return utils.isPlainObject(thing) || utils.isArray(thing);
  718. }
  719. /**
  720. * It removes the brackets from the end of a string
  721. *
  722. * @param {string} key - The key of the parameter.
  723. *
  724. * @returns {string} the key without the brackets.
  725. */
  726. function removeBrackets(key) {
  727. return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;
  728. }
  729. /**
  730. * It takes a path, a key, and a boolean, and returns a string
  731. *
  732. * @param {string} path - The path to the current key.
  733. * @param {string} key - The key of the current object being iterated over.
  734. * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
  735. *
  736. * @returns {string} The path to the current key.
  737. */
  738. function renderKey(path, key, dots) {
  739. if (!path) return key;
  740. return path.concat(key).map(function each(token, i) {
  741. // eslint-disable-next-line no-param-reassign
  742. token = removeBrackets(token);
  743. return !dots && i ? '[' + token + ']' : token;
  744. }).join(dots ? '.' : '');
  745. }
  746. /**
  747. * If the array is an array and none of its elements are visitable, then it's a flat array.
  748. *
  749. * @param {Array<any>} arr - The array to check
  750. *
  751. * @returns {boolean}
  752. */
  753. function isFlatArray(arr) {
  754. return utils.isArray(arr) && !arr.some(isVisitable);
  755. }
  756. const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
  757. return /^is[A-Z]/.test(prop);
  758. });
  759. /**
  760. * Convert a data object to FormData
  761. *
  762. * @param {Object} obj
  763. * @param {?Object} [formData]
  764. * @param {?Object} [options]
  765. * @param {Function} [options.visitor]
  766. * @param {Boolean} [options.metaTokens = true]
  767. * @param {Boolean} [options.dots = false]
  768. * @param {?Boolean} [options.indexes = false]
  769. *
  770. * @returns {Object}
  771. **/
  772. /**
  773. * It converts an object into a FormData object
  774. *
  775. * @param {Object<any, any>} obj - The object to convert to form data.
  776. * @param {string} formData - The FormData object to append to.
  777. * @param {Object<string, any>} options
  778. *
  779. * @returns
  780. */
  781. function toFormData(obj, formData, options) {
  782. if (!utils.isObject(obj)) {
  783. throw new TypeError('target must be an object');
  784. }
  785. // eslint-disable-next-line no-param-reassign
  786. formData = formData || new (FormData)();
  787. // eslint-disable-next-line no-param-reassign
  788. options = utils.toFlatObject(options, {
  789. metaTokens: true,
  790. dots: false,
  791. indexes: false
  792. }, false, function defined(option, source) {
  793. // eslint-disable-next-line no-eq-null,eqeqeq
  794. return !utils.isUndefined(source[option]);
  795. });
  796. const metaTokens = options.metaTokens;
  797. // eslint-disable-next-line no-use-before-define
  798. const visitor = options.visitor || defaultVisitor;
  799. const dots = options.dots;
  800. const indexes = options.indexes;
  801. const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  802. const useBlob = _Blob && utils.isSpecCompliantForm(formData);
  803. if (!utils.isFunction(visitor)) {
  804. throw new TypeError('visitor must be a function');
  805. }
  806. function convertValue(value) {
  807. if (value === null) return '';
  808. if (utils.isDate(value)) {
  809. return value.toISOString();
  810. }
  811. if (!useBlob && utils.isBlob(value)) {
  812. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  813. }
  814. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  815. return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  816. }
  817. return value;
  818. }
  819. /**
  820. * Default visitor.
  821. *
  822. * @param {*} value
  823. * @param {String|Number} key
  824. * @param {Array<String|Number>} path
  825. * @this {FormData}
  826. *
  827. * @returns {boolean} return true to visit the each prop of the value recursively
  828. */
  829. function defaultVisitor(value, key, path) {
  830. let arr = value;
  831. if (value && !path && typeof value === 'object') {
  832. if (utils.endsWith(key, '{}')) {
  833. // eslint-disable-next-line no-param-reassign
  834. key = metaTokens ? key : key.slice(0, -2);
  835. // eslint-disable-next-line no-param-reassign
  836. value = JSON.stringify(value);
  837. } else if (
  838. (utils.isArray(value) && isFlatArray(value)) ||
  839. ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))
  840. )) {
  841. // eslint-disable-next-line no-param-reassign
  842. key = removeBrackets(key);
  843. arr.forEach(function each(el, index) {
  844. !(utils.isUndefined(el) || el === null) && formData.append(
  845. // eslint-disable-next-line no-nested-ternary
  846. indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
  847. convertValue(el)
  848. );
  849. });
  850. return false;
  851. }
  852. }
  853. if (isVisitable(value)) {
  854. return true;
  855. }
  856. formData.append(renderKey(path, key, dots), convertValue(value));
  857. return false;
  858. }
  859. const stack = [];
  860. const exposedHelpers = Object.assign(predicates, {
  861. defaultVisitor,
  862. convertValue,
  863. isVisitable
  864. });
  865. function build(value, path) {
  866. if (utils.isUndefined(value)) return;
  867. if (stack.indexOf(value) !== -1) {
  868. throw Error('Circular reference detected in ' + path.join('.'));
  869. }
  870. stack.push(value);
  871. utils.forEach(value, function each(el, key) {
  872. const result = !(utils.isUndefined(el) || el === null) && visitor.call(
  873. formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
  874. );
  875. if (result === true) {
  876. build(el, path ? path.concat(key) : [key]);
  877. }
  878. });
  879. stack.pop();
  880. }
  881. if (!utils.isObject(obj)) {
  882. throw new TypeError('data must be an object');
  883. }
  884. build(obj);
  885. return formData;
  886. }
  887. /**
  888. * It encodes a string by replacing all characters that are not in the unreserved set with
  889. * their percent-encoded equivalents
  890. *
  891. * @param {string} str - The string to encode.
  892. *
  893. * @returns {string} The encoded string.
  894. */
  895. function encode$1(str) {
  896. const charMap = {
  897. '!': '%21',
  898. "'": '%27',
  899. '(': '%28',
  900. ')': '%29',
  901. '~': '%7E',
  902. '%20': '+',
  903. '%00': '\x00'
  904. };
  905. return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
  906. return charMap[match];
  907. });
  908. }
  909. /**
  910. * It takes a params object and converts it to a FormData object
  911. *
  912. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  913. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  914. *
  915. * @returns {void}
  916. */
  917. function AxiosURLSearchParams(params, options) {
  918. this._pairs = [];
  919. params && toFormData(params, this, options);
  920. }
  921. const prototype = AxiosURLSearchParams.prototype;
  922. prototype.append = function append(name, value) {
  923. this._pairs.push([name, value]);
  924. };
  925. prototype.toString = function toString(encoder) {
  926. const _encode = encoder ? function(value) {
  927. return encoder.call(this, value, encode$1);
  928. } : encode$1;
  929. return this._pairs.map(function each(pair) {
  930. return _encode(pair[0]) + '=' + _encode(pair[1]);
  931. }, '').join('&');
  932. };
  933. /**
  934. * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
  935. * URI encoded counterparts
  936. *
  937. * @param {string} val The value to be encoded.
  938. *
  939. * @returns {string} The encoded value.
  940. */
  941. function encode(val) {
  942. return encodeURIComponent(val).
  943. replace(/%3A/gi, ':').
  944. replace(/%24/g, '$').
  945. replace(/%2C/gi, ',').
  946. replace(/%20/g, '+').
  947. replace(/%5B/gi, '[').
  948. replace(/%5D/gi, ']');
  949. }
  950. /**
  951. * Build a URL by appending params to the end
  952. *
  953. * @param {string} url The base of the url (e.g., http://www.google.com)
  954. * @param {object} [params] The params to be appended
  955. * @param {?object} options
  956. *
  957. * @returns {string} The formatted url
  958. */
  959. function buildURL(url, params, options) {
  960. /*eslint no-param-reassign:0*/
  961. if (!params) {
  962. return url;
  963. }
  964. const _encode = options && options.encode || encode;
  965. const serializeFn = options && options.serialize;
  966. let serializedParams;
  967. if (serializeFn) {
  968. serializedParams = serializeFn(params, options);
  969. } else {
  970. serializedParams = utils.isURLSearchParams(params) ?
  971. params.toString() :
  972. new AxiosURLSearchParams(params, options).toString(_encode);
  973. }
  974. if (serializedParams) {
  975. const hashmarkIndex = url.indexOf("#");
  976. if (hashmarkIndex !== -1) {
  977. url = url.slice(0, hashmarkIndex);
  978. }
  979. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  980. }
  981. return url;
  982. }
  983. class InterceptorManager {
  984. constructor() {
  985. this.handlers = [];
  986. }
  987. /**
  988. * Add a new interceptor to the stack
  989. *
  990. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  991. * @param {Function} rejected The function to handle `reject` for a `Promise`
  992. *
  993. * @return {Number} An ID used to remove interceptor later
  994. */
  995. use(fulfilled, rejected, options) {
  996. this.handlers.push({
  997. fulfilled,
  998. rejected,
  999. synchronous: options ? options.synchronous : false,
  1000. runWhen: options ? options.runWhen : null
  1001. });
  1002. return this.handlers.length - 1;
  1003. }
  1004. /**
  1005. * Remove an interceptor from the stack
  1006. *
  1007. * @param {Number} id The ID that was returned by `use`
  1008. *
  1009. * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
  1010. */
  1011. eject(id) {
  1012. if (this.handlers[id]) {
  1013. this.handlers[id] = null;
  1014. }
  1015. }
  1016. /**
  1017. * Clear all interceptors from the stack
  1018. *
  1019. * @returns {void}
  1020. */
  1021. clear() {
  1022. if (this.handlers) {
  1023. this.handlers = [];
  1024. }
  1025. }
  1026. /**
  1027. * Iterate over all the registered interceptors
  1028. *
  1029. * This method is particularly useful for skipping over any
  1030. * interceptors that may have become `null` calling `eject`.
  1031. *
  1032. * @param {Function} fn The function to call for each interceptor
  1033. *
  1034. * @returns {void}
  1035. */
  1036. forEach(fn) {
  1037. utils.forEach(this.handlers, function forEachHandler(h) {
  1038. if (h !== null) {
  1039. fn(h);
  1040. }
  1041. });
  1042. }
  1043. }
  1044. var InterceptorManager$1 = InterceptorManager;
  1045. var transitionalDefaults = {
  1046. silentJSONParsing: true,
  1047. forcedJSONParsing: true,
  1048. clarifyTimeoutError: false
  1049. };
  1050. var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
  1051. var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
  1052. var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
  1053. /**
  1054. * Determine if we're running in a standard browser environment
  1055. *
  1056. * This allows axios to run in a web worker, and react-native.
  1057. * Both environments support XMLHttpRequest, but not fully standard globals.
  1058. *
  1059. * web workers:
  1060. * typeof window -> undefined
  1061. * typeof document -> undefined
  1062. *
  1063. * react-native:
  1064. * navigator.product -> 'ReactNative'
  1065. * nativescript
  1066. * navigator.product -> 'NativeScript' or 'NS'
  1067. *
  1068. * @returns {boolean}
  1069. */
  1070. const isStandardBrowserEnv = (() => {
  1071. let product;
  1072. if (typeof navigator !== 'undefined' && (
  1073. (product = navigator.product) === 'ReactNative' ||
  1074. product === 'NativeScript' ||
  1075. product === 'NS')
  1076. ) {
  1077. return false;
  1078. }
  1079. return typeof window !== 'undefined' && typeof document !== 'undefined';
  1080. })();
  1081. /**
  1082. * Determine if we're running in a standard browser webWorker environment
  1083. *
  1084. * Although the `isStandardBrowserEnv` method indicates that
  1085. * `allows axios to run in a web worker`, the WebWorker will still be
  1086. * filtered out due to its judgment standard
  1087. * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
  1088. * This leads to a problem when axios post `FormData` in webWorker
  1089. */
  1090. const isStandardBrowserWebWorkerEnv = (() => {
  1091. return (
  1092. typeof WorkerGlobalScope !== 'undefined' &&
  1093. // eslint-disable-next-line no-undef
  1094. self instanceof WorkerGlobalScope &&
  1095. typeof self.importScripts === 'function'
  1096. );
  1097. })();
  1098. var platform = {
  1099. isBrowser: true,
  1100. classes: {
  1101. URLSearchParams: URLSearchParams$1,
  1102. FormData: FormData$1,
  1103. Blob: Blob$1
  1104. },
  1105. isStandardBrowserEnv,
  1106. isStandardBrowserWebWorkerEnv,
  1107. protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
  1108. };
  1109. function toURLEncodedForm(data, options) {
  1110. return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
  1111. visitor: function(value, key, path, helpers) {
  1112. if (platform.isNode && utils.isBuffer(value)) {
  1113. this.append(key, value.toString('base64'));
  1114. return false;
  1115. }
  1116. return helpers.defaultVisitor.apply(this, arguments);
  1117. }
  1118. }, options));
  1119. }
  1120. /**
  1121. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  1122. *
  1123. * @param {string} name - The name of the property to get.
  1124. *
  1125. * @returns An array of strings.
  1126. */
  1127. function parsePropPath(name) {
  1128. // foo[x][y][z]
  1129. // foo.x.y.z
  1130. // foo-x-y-z
  1131. // foo x y z
  1132. return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
  1133. return match[0] === '[]' ? '' : match[1] || match[0];
  1134. });
  1135. }
  1136. /**
  1137. * Convert an array to an object.
  1138. *
  1139. * @param {Array<any>} arr - The array to convert to an object.
  1140. *
  1141. * @returns An object with the same keys and values as the array.
  1142. */
  1143. function arrayToObject(arr) {
  1144. const obj = {};
  1145. const keys = Object.keys(arr);
  1146. let i;
  1147. const len = keys.length;
  1148. let key;
  1149. for (i = 0; i < len; i++) {
  1150. key = keys[i];
  1151. obj[key] = arr[key];
  1152. }
  1153. return obj;
  1154. }
  1155. /**
  1156. * It takes a FormData object and returns a JavaScript object
  1157. *
  1158. * @param {string} formData The FormData object to convert to JSON.
  1159. *
  1160. * @returns {Object<string, any> | null} The converted object.
  1161. */
  1162. function formDataToJSON(formData) {
  1163. function buildPath(path, value, target, index) {
  1164. let name = path[index++];
  1165. const isNumericKey = Number.isFinite(+name);
  1166. const isLast = index >= path.length;
  1167. name = !name && utils.isArray(target) ? target.length : name;
  1168. if (isLast) {
  1169. if (utils.hasOwnProp(target, name)) {
  1170. target[name] = [target[name], value];
  1171. } else {
  1172. target[name] = value;
  1173. }
  1174. return !isNumericKey;
  1175. }
  1176. if (!target[name] || !utils.isObject(target[name])) {
  1177. target[name] = [];
  1178. }
  1179. const result = buildPath(path, value, target[name], index);
  1180. if (result && utils.isArray(target[name])) {
  1181. target[name] = arrayToObject(target[name]);
  1182. }
  1183. return !isNumericKey;
  1184. }
  1185. if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
  1186. const obj = {};
  1187. utils.forEachEntry(formData, (name, value) => {
  1188. buildPath(parsePropPath(name), value, obj, 0);
  1189. });
  1190. return obj;
  1191. }
  1192. return null;
  1193. }
  1194. const DEFAULT_CONTENT_TYPE = {
  1195. 'Content-Type': undefined
  1196. };
  1197. /**
  1198. * It takes a string, tries to parse it, and if it fails, it returns the stringified version
  1199. * of the input
  1200. *
  1201. * @param {any} rawValue - The value to be stringified.
  1202. * @param {Function} parser - A function that parses a string into a JavaScript object.
  1203. * @param {Function} encoder - A function that takes a value and returns a string.
  1204. *
  1205. * @returns {string} A stringified version of the rawValue.
  1206. */
  1207. function stringifySafely(rawValue, parser, encoder) {
  1208. if (utils.isString(rawValue)) {
  1209. try {
  1210. (parser || JSON.parse)(rawValue);
  1211. return utils.trim(rawValue);
  1212. } catch (e) {
  1213. if (e.name !== 'SyntaxError') {
  1214. throw e;
  1215. }
  1216. }
  1217. }
  1218. return (encoder || JSON.stringify)(rawValue);
  1219. }
  1220. const defaults = {
  1221. transitional: transitionalDefaults,
  1222. adapter: ['xhr', 'http'],
  1223. transformRequest: [function transformRequest(data, headers) {
  1224. const contentType = headers.getContentType() || '';
  1225. const hasJSONContentType = contentType.indexOf('application/json') > -1;
  1226. const isObjectPayload = utils.isObject(data);
  1227. if (isObjectPayload && utils.isHTMLForm(data)) {
  1228. data = new FormData(data);
  1229. }
  1230. const isFormData = utils.isFormData(data);
  1231. if (isFormData) {
  1232. if (!hasJSONContentType) {
  1233. return data;
  1234. }
  1235. return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
  1236. }
  1237. if (utils.isArrayBuffer(data) ||
  1238. utils.isBuffer(data) ||
  1239. utils.isStream(data) ||
  1240. utils.isFile(data) ||
  1241. utils.isBlob(data)
  1242. ) {
  1243. return data;
  1244. }
  1245. if (utils.isArrayBufferView(data)) {
  1246. return data.buffer;
  1247. }
  1248. if (utils.isURLSearchParams(data)) {
  1249. headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
  1250. return data.toString();
  1251. }
  1252. let isFileList;
  1253. if (isObjectPayload) {
  1254. if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
  1255. return toURLEncodedForm(data, this.formSerializer).toString();
  1256. }
  1257. if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
  1258. const _FormData = this.env && this.env.FormData;
  1259. return toFormData(
  1260. isFileList ? {'files[]': data} : data,
  1261. _FormData && new _FormData(),
  1262. this.formSerializer
  1263. );
  1264. }
  1265. }
  1266. if (isObjectPayload || hasJSONContentType ) {
  1267. headers.setContentType('application/json', false);
  1268. return stringifySafely(data);
  1269. }
  1270. return data;
  1271. }],
  1272. transformResponse: [function transformResponse(data) {
  1273. const transitional = this.transitional || defaults.transitional;
  1274. const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  1275. const JSONRequested = this.responseType === 'json';
  1276. if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
  1277. const silentJSONParsing = transitional && transitional.silentJSONParsing;
  1278. const strictJSONParsing = !silentJSONParsing && JSONRequested;
  1279. try {
  1280. return JSON.parse(data);
  1281. } catch (e) {
  1282. if (strictJSONParsing) {
  1283. if (e.name === 'SyntaxError') {
  1284. throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
  1285. }
  1286. throw e;
  1287. }
  1288. }
  1289. }
  1290. return data;
  1291. }],
  1292. /**
  1293. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  1294. * timeout is not created.
  1295. */
  1296. timeout: 0,
  1297. xsrfCookieName: 'XSRF-TOKEN',
  1298. xsrfHeaderName: 'X-XSRF-TOKEN',
  1299. maxContentLength: -1,
  1300. maxBodyLength: -1,
  1301. env: {
  1302. FormData: platform.classes.FormData,
  1303. Blob: platform.classes.Blob
  1304. },
  1305. validateStatus: function validateStatus(status) {
  1306. return status >= 200 && status < 300;
  1307. },
  1308. headers: {
  1309. common: {
  1310. 'Accept': 'application/json, text/plain, */*'
  1311. }
  1312. }
  1313. };
  1314. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  1315. defaults.headers[method] = {};
  1316. });
  1317. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  1318. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  1319. });
  1320. var defaults$1 = defaults;
  1321. // RawAxiosHeaders whose duplicates are ignored by node
  1322. // c.f. https://nodejs.org/api/http.html#http_message_headers
  1323. const ignoreDuplicateOf = utils.toObjectSet([
  1324. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  1325. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  1326. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  1327. 'referer', 'retry-after', 'user-agent'
  1328. ]);
  1329. /**
  1330. * Parse headers into an object
  1331. *
  1332. * ```
  1333. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  1334. * Content-Type: application/json
  1335. * Connection: keep-alive
  1336. * Transfer-Encoding: chunked
  1337. * ```
  1338. *
  1339. * @param {String} rawHeaders Headers needing to be parsed
  1340. *
  1341. * @returns {Object} Headers parsed into an object
  1342. */
  1343. var parseHeaders = rawHeaders => {
  1344. const parsed = {};
  1345. let key;
  1346. let val;
  1347. let i;
  1348. rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
  1349. i = line.indexOf(':');
  1350. key = line.substring(0, i).trim().toLowerCase();
  1351. val = line.substring(i + 1).trim();
  1352. if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
  1353. return;
  1354. }
  1355. if (key === 'set-cookie') {
  1356. if (parsed[key]) {
  1357. parsed[key].push(val);
  1358. } else {
  1359. parsed[key] = [val];
  1360. }
  1361. } else {
  1362. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  1363. }
  1364. });
  1365. return parsed;
  1366. };
  1367. const $internals = Symbol('internals');
  1368. function normalizeHeader(header) {
  1369. return header && String(header).trim().toLowerCase();
  1370. }
  1371. function normalizeValue(value) {
  1372. if (value === false || value == null) {
  1373. return value;
  1374. }
  1375. return utils.isArray(value) ? value.map(normalizeValue) : String(value);
  1376. }
  1377. function parseTokens(str) {
  1378. const tokens = Object.create(null);
  1379. const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  1380. let match;
  1381. while ((match = tokensRE.exec(str))) {
  1382. tokens[match[1]] = match[2];
  1383. }
  1384. return tokens;
  1385. }
  1386. function isValidHeaderName(str) {
  1387. return /^[-_a-zA-Z]+$/.test(str.trim());
  1388. }
  1389. function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  1390. if (utils.isFunction(filter)) {
  1391. return filter.call(this, value, header);
  1392. }
  1393. if (isHeaderNameFilter) {
  1394. value = header;
  1395. }
  1396. if (!utils.isString(value)) return;
  1397. if (utils.isString(filter)) {
  1398. return value.indexOf(filter) !== -1;
  1399. }
  1400. if (utils.isRegExp(filter)) {
  1401. return filter.test(value);
  1402. }
  1403. }
  1404. function formatHeader(header) {
  1405. return header.trim()
  1406. .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
  1407. return char.toUpperCase() + str;
  1408. });
  1409. }
  1410. function buildAccessors(obj, header) {
  1411. const accessorName = utils.toCamelCase(' ' + header);
  1412. ['get', 'set', 'has'].forEach(methodName => {
  1413. Object.defineProperty(obj, methodName + accessorName, {
  1414. value: function(arg1, arg2, arg3) {
  1415. return this[methodName].call(this, header, arg1, arg2, arg3);
  1416. },
  1417. configurable: true
  1418. });
  1419. });
  1420. }
  1421. class AxiosHeaders {
  1422. constructor(headers) {
  1423. headers && this.set(headers);
  1424. }
  1425. set(header, valueOrRewrite, rewrite) {
  1426. const self = this;
  1427. function setHeader(_value, _header, _rewrite) {
  1428. const lHeader = normalizeHeader(_header);
  1429. if (!lHeader) {
  1430. throw new Error('header name must be a non-empty string');
  1431. }
  1432. const key = utils.findKey(self, lHeader);
  1433. if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
  1434. self[key || _header] = normalizeValue(_value);
  1435. }
  1436. }
  1437. const setHeaders = (headers, _rewrite) =>
  1438. utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
  1439. if (utils.isPlainObject(header) || header instanceof this.constructor) {
  1440. setHeaders(header, valueOrRewrite);
  1441. } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
  1442. setHeaders(parseHeaders(header), valueOrRewrite);
  1443. } else {
  1444. header != null && setHeader(valueOrRewrite, header, rewrite);
  1445. }
  1446. return this;
  1447. }
  1448. get(header, parser) {
  1449. header = normalizeHeader(header);
  1450. if (header) {
  1451. const key = utils.findKey(this, header);
  1452. if (key) {
  1453. const value = this[key];
  1454. if (!parser) {
  1455. return value;
  1456. }
  1457. if (parser === true) {
  1458. return parseTokens(value);
  1459. }
  1460. if (utils.isFunction(parser)) {
  1461. return parser.call(this, value, key);
  1462. }
  1463. if (utils.isRegExp(parser)) {
  1464. return parser.exec(value);
  1465. }
  1466. throw new TypeError('parser must be boolean|regexp|function');
  1467. }
  1468. }
  1469. }
  1470. has(header, matcher) {
  1471. header = normalizeHeader(header);
  1472. if (header) {
  1473. const key = utils.findKey(this, header);
  1474. return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
  1475. }
  1476. return false;
  1477. }
  1478. delete(header, matcher) {
  1479. const self = this;
  1480. let deleted = false;
  1481. function deleteHeader(_header) {
  1482. _header = normalizeHeader(_header);
  1483. if (_header) {
  1484. const key = utils.findKey(self, _header);
  1485. if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
  1486. delete self[key];
  1487. deleted = true;
  1488. }
  1489. }
  1490. }
  1491. if (utils.isArray(header)) {
  1492. header.forEach(deleteHeader);
  1493. } else {
  1494. deleteHeader(header);
  1495. }
  1496. return deleted;
  1497. }
  1498. clear(matcher) {
  1499. const keys = Object.keys(this);
  1500. let i = keys.length;
  1501. let deleted = false;
  1502. while (i--) {
  1503. const key = keys[i];
  1504. if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
  1505. delete this[key];
  1506. deleted = true;
  1507. }
  1508. }
  1509. return deleted;
  1510. }
  1511. normalize(format) {
  1512. const self = this;
  1513. const headers = {};
  1514. utils.forEach(this, (value, header) => {
  1515. const key = utils.findKey(headers, header);
  1516. if (key) {
  1517. self[key] = normalizeValue(value);
  1518. delete self[header];
  1519. return;
  1520. }
  1521. const normalized = format ? formatHeader(header) : String(header).trim();
  1522. if (normalized !== header) {
  1523. delete self[header];
  1524. }
  1525. self[normalized] = normalizeValue(value);
  1526. headers[normalized] = true;
  1527. });
  1528. return this;
  1529. }
  1530. concat(...targets) {
  1531. return this.constructor.concat(this, ...targets);
  1532. }
  1533. toJSON(asStrings) {
  1534. const obj = Object.create(null);
  1535. utils.forEach(this, (value, header) => {
  1536. value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
  1537. });
  1538. return obj;
  1539. }
  1540. [Symbol.iterator]() {
  1541. return Object.entries(this.toJSON())[Symbol.iterator]();
  1542. }
  1543. toString() {
  1544. return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  1545. }
  1546. get [Symbol.toStringTag]() {
  1547. return 'AxiosHeaders';
  1548. }
  1549. static from(thing) {
  1550. return thing instanceof this ? thing : new this(thing);
  1551. }
  1552. static concat(first, ...targets) {
  1553. const computed = new this(first);
  1554. targets.forEach((target) => computed.set(target));
  1555. return computed;
  1556. }
  1557. static accessor(header) {
  1558. const internals = this[$internals] = (this[$internals] = {
  1559. accessors: {}
  1560. });
  1561. const accessors = internals.accessors;
  1562. const prototype = this.prototype;
  1563. function defineAccessor(_header) {
  1564. const lHeader = normalizeHeader(_header);
  1565. if (!accessors[lHeader]) {
  1566. buildAccessors(prototype, _header);
  1567. accessors[lHeader] = true;
  1568. }
  1569. }
  1570. utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
  1571. return this;
  1572. }
  1573. }
  1574. AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
  1575. utils.freezeMethods(AxiosHeaders.prototype);
  1576. utils.freezeMethods(AxiosHeaders);
  1577. var AxiosHeaders$1 = AxiosHeaders;
  1578. /**
  1579. * Transform the data for a request or a response
  1580. *
  1581. * @param {Array|Function} fns A single function or Array of functions
  1582. * @param {?Object} response The response object
  1583. *
  1584. * @returns {*} The resulting transformed data
  1585. */
  1586. function transformData(fns, response) {
  1587. const config = this || defaults$1;
  1588. const context = response || config;
  1589. const headers = AxiosHeaders$1.from(context.headers);
  1590. let data = context.data;
  1591. utils.forEach(fns, function transform(fn) {
  1592. data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  1593. });
  1594. headers.normalize();
  1595. return data;
  1596. }
  1597. function isCancel(value) {
  1598. return !!(value && value.__CANCEL__);
  1599. }
  1600. /**
  1601. * A `CanceledError` is an object that is thrown when an operation is canceled.
  1602. *
  1603. * @param {string=} message The message.
  1604. * @param {Object=} config The config.
  1605. * @param {Object=} request The request.
  1606. *
  1607. * @returns {CanceledError} The created error.
  1608. */
  1609. function CanceledError(message, config, request) {
  1610. // eslint-disable-next-line no-eq-null,eqeqeq
  1611. AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
  1612. this.name = 'CanceledError';
  1613. }
  1614. utils.inherits(CanceledError, AxiosError, {
  1615. __CANCEL__: true
  1616. });
  1617. /**
  1618. * Resolve or reject a Promise based on response status.
  1619. *
  1620. * @param {Function} resolve A function that resolves the promise.
  1621. * @param {Function} reject A function that rejects the promise.
  1622. * @param {object} response The response.
  1623. *
  1624. * @returns {object} The response.
  1625. */
  1626. function settle(resolve, reject, response) {
  1627. const validateStatus = response.config.validateStatus;
  1628. if (!response.status || !validateStatus || validateStatus(response.status)) {
  1629. resolve(response);
  1630. } else {
  1631. reject(new AxiosError(
  1632. 'Request failed with status code ' + response.status,
  1633. [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
  1634. response.config,
  1635. response.request,
  1636. response
  1637. ));
  1638. }
  1639. }
  1640. var cookies = platform.isStandardBrowserEnv ?
  1641. // Standard browser envs support document.cookie
  1642. (function standardBrowserEnv() {
  1643. return {
  1644. write: function write(name, value, expires, path, domain, secure) {
  1645. const cookie = [];
  1646. cookie.push(name + '=' + encodeURIComponent(value));
  1647. if (utils.isNumber(expires)) {
  1648. cookie.push('expires=' + new Date(expires).toGMTString());
  1649. }
  1650. if (utils.isString(path)) {
  1651. cookie.push('path=' + path);
  1652. }
  1653. if (utils.isString(domain)) {
  1654. cookie.push('domain=' + domain);
  1655. }
  1656. if (secure === true) {
  1657. cookie.push('secure');
  1658. }
  1659. document.cookie = cookie.join('; ');
  1660. },
  1661. read: function read(name) {
  1662. const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  1663. return (match ? decodeURIComponent(match[3]) : null);
  1664. },
  1665. remove: function remove(name) {
  1666. this.write(name, '', Date.now() - 86400000);
  1667. }
  1668. };
  1669. })() :
  1670. // Non standard browser env (web workers, react-native) lack needed support.
  1671. (function nonStandardBrowserEnv() {
  1672. return {
  1673. write: function write() {},
  1674. read: function read() { return null; },
  1675. remove: function remove() {}
  1676. };
  1677. })();
  1678. /**
  1679. * Determines whether the specified URL is absolute
  1680. *
  1681. * @param {string} url The URL to test
  1682. *
  1683. * @returns {boolean} True if the specified URL is absolute, otherwise false
  1684. */
  1685. function isAbsoluteURL(url) {
  1686. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  1687. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  1688. // by any combination of letters, digits, plus, period, or hyphen.
  1689. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  1690. }
  1691. /**
  1692. * Creates a new URL by combining the specified URLs
  1693. *
  1694. * @param {string} baseURL The base URL
  1695. * @param {string} relativeURL The relative URL
  1696. *
  1697. * @returns {string} The combined URL
  1698. */
  1699. function combineURLs(baseURL, relativeURL) {
  1700. return relativeURL
  1701. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  1702. : baseURL;
  1703. }
  1704. /**
  1705. * Creates a new URL by combining the baseURL with the requestedURL,
  1706. * only when the requestedURL is not already an absolute URL.
  1707. * If the requestURL is absolute, this function returns the requestedURL untouched.
  1708. *
  1709. * @param {string} baseURL The base URL
  1710. * @param {string} requestedURL Absolute or relative URL to combine
  1711. *
  1712. * @returns {string} The combined full path
  1713. */
  1714. function buildFullPath(baseURL, requestedURL) {
  1715. if (baseURL && !isAbsoluteURL(requestedURL)) {
  1716. return combineURLs(baseURL, requestedURL);
  1717. }
  1718. return requestedURL;
  1719. }
  1720. var isURLSameOrigin = platform.isStandardBrowserEnv ?
  1721. // Standard browser envs have full support of the APIs needed to test
  1722. // whether the request URL is of the same origin as current location.
  1723. (function standardBrowserEnv() {
  1724. const msie = /(msie|trident)/i.test(navigator.userAgent);
  1725. const urlParsingNode = document.createElement('a');
  1726. let originURL;
  1727. /**
  1728. * Parse a URL to discover it's components
  1729. *
  1730. * @param {String} url The URL to be parsed
  1731. * @returns {Object}
  1732. */
  1733. function resolveURL(url) {
  1734. let href = url;
  1735. if (msie) {
  1736. // IE needs attribute set twice to normalize properties
  1737. urlParsingNode.setAttribute('href', href);
  1738. href = urlParsingNode.href;
  1739. }
  1740. urlParsingNode.setAttribute('href', href);
  1741. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  1742. return {
  1743. href: urlParsingNode.href,
  1744. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  1745. host: urlParsingNode.host,
  1746. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  1747. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  1748. hostname: urlParsingNode.hostname,
  1749. port: urlParsingNode.port,
  1750. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  1751. urlParsingNode.pathname :
  1752. '/' + urlParsingNode.pathname
  1753. };
  1754. }
  1755. originURL = resolveURL(window.location.href);
  1756. /**
  1757. * Determine if a URL shares the same origin as the current location
  1758. *
  1759. * @param {String} requestURL The URL to test
  1760. * @returns {boolean} True if URL shares the same origin, otherwise false
  1761. */
  1762. return function isURLSameOrigin(requestURL) {
  1763. const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  1764. return (parsed.protocol === originURL.protocol &&
  1765. parsed.host === originURL.host);
  1766. };
  1767. })() :
  1768. // Non standard browser envs (web workers, react-native) lack needed support.
  1769. (function nonStandardBrowserEnv() {
  1770. return function isURLSameOrigin() {
  1771. return true;
  1772. };
  1773. })();
  1774. function parseProtocol(url) {
  1775. const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  1776. return match && match[1] || '';
  1777. }
  1778. /**
  1779. * Calculate data maxRate
  1780. * @param {Number} [samplesCount= 10]
  1781. * @param {Number} [min= 1000]
  1782. * @returns {Function}
  1783. */
  1784. function speedometer(samplesCount, min) {
  1785. samplesCount = samplesCount || 10;
  1786. const bytes = new Array(samplesCount);
  1787. const timestamps = new Array(samplesCount);
  1788. let head = 0;
  1789. let tail = 0;
  1790. let firstSampleTS;
  1791. min = min !== undefined ? min : 1000;
  1792. return function push(chunkLength) {
  1793. const now = Date.now();
  1794. const startedAt = timestamps[tail];
  1795. if (!firstSampleTS) {
  1796. firstSampleTS = now;
  1797. }
  1798. bytes[head] = chunkLength;
  1799. timestamps[head] = now;
  1800. let i = tail;
  1801. let bytesCount = 0;
  1802. while (i !== head) {
  1803. bytesCount += bytes[i++];
  1804. i = i % samplesCount;
  1805. }
  1806. head = (head + 1) % samplesCount;
  1807. if (head === tail) {
  1808. tail = (tail + 1) % samplesCount;
  1809. }
  1810. if (now - firstSampleTS < min) {
  1811. return;
  1812. }
  1813. const passed = startedAt && now - startedAt;
  1814. return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  1815. };
  1816. }
  1817. function progressEventReducer(listener, isDownloadStream) {
  1818. let bytesNotified = 0;
  1819. const _speedometer = speedometer(50, 250);
  1820. return e => {
  1821. const loaded = e.loaded;
  1822. const total = e.lengthComputable ? e.total : undefined;
  1823. const progressBytes = loaded - bytesNotified;
  1824. const rate = _speedometer(progressBytes);
  1825. const inRange = loaded <= total;
  1826. bytesNotified = loaded;
  1827. const data = {
  1828. loaded,
  1829. total,
  1830. progress: total ? (loaded / total) : undefined,
  1831. bytes: progressBytes,
  1832. rate: rate ? rate : undefined,
  1833. estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
  1834. event: e
  1835. };
  1836. data[isDownloadStream ? 'download' : 'upload'] = true;
  1837. listener(data);
  1838. };
  1839. }
  1840. const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
  1841. var xhrAdapter = isXHRAdapterSupported && function (config) {
  1842. return new Promise(function dispatchXhrRequest(resolve, reject) {
  1843. let requestData = config.data;
  1844. const requestHeaders = AxiosHeaders$1.from(config.headers).normalize();
  1845. const responseType = config.responseType;
  1846. let onCanceled;
  1847. function done() {
  1848. if (config.cancelToken) {
  1849. config.cancelToken.unsubscribe(onCanceled);
  1850. }
  1851. if (config.signal) {
  1852. config.signal.removeEventListener('abort', onCanceled);
  1853. }
  1854. }
  1855. if (utils.isFormData(requestData) && (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv)) {
  1856. requestHeaders.setContentType(false); // Let the browser set it
  1857. }
  1858. let request = new XMLHttpRequest();
  1859. // HTTP basic authentication
  1860. if (config.auth) {
  1861. const username = config.auth.username || '';
  1862. const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  1863. requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
  1864. }
  1865. const fullPath = buildFullPath(config.baseURL, config.url);
  1866. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  1867. // Set the request timeout in MS
  1868. request.timeout = config.timeout;
  1869. function onloadend() {
  1870. if (!request) {
  1871. return;
  1872. }
  1873. // Prepare the response
  1874. const responseHeaders = AxiosHeaders$1.from(
  1875. 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
  1876. );
  1877. const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
  1878. request.responseText : request.response;
  1879. const response = {
  1880. data: responseData,
  1881. status: request.status,
  1882. statusText: request.statusText,
  1883. headers: responseHeaders,
  1884. config,
  1885. request
  1886. };
  1887. settle(function _resolve(value) {
  1888. resolve(value);
  1889. done();
  1890. }, function _reject(err) {
  1891. reject(err);
  1892. done();
  1893. }, response);
  1894. // Clean up request
  1895. request = null;
  1896. }
  1897. if ('onloadend' in request) {
  1898. // Use onloadend if available
  1899. request.onloadend = onloadend;
  1900. } else {
  1901. // Listen for ready state to emulate onloadend
  1902. request.onreadystatechange = function handleLoad() {
  1903. if (!request || request.readyState !== 4) {
  1904. return;
  1905. }
  1906. // The request errored out and we didn't get a response, this will be
  1907. // handled by onerror instead
  1908. // With one exception: request that using file: protocol, most browsers
  1909. // will return status as 0 even though it's a successful request
  1910. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  1911. return;
  1912. }
  1913. // readystate handler is calling before onerror or ontimeout handlers,
  1914. // so we should call onloadend on the next 'tick'
  1915. setTimeout(onloadend);
  1916. };
  1917. }
  1918. // Handle browser request cancellation (as opposed to a manual cancellation)
  1919. request.onabort = function handleAbort() {
  1920. if (!request) {
  1921. return;
  1922. }
  1923. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  1924. // Clean up request
  1925. request = null;
  1926. };
  1927. // Handle low level network errors
  1928. request.onerror = function handleError() {
  1929. // Real errors are hidden from us by the browser
  1930. // onerror should only fire if it's a network error
  1931. reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
  1932. // Clean up request
  1933. request = null;
  1934. };
  1935. // Handle timeout
  1936. request.ontimeout = function handleTimeout() {
  1937. let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
  1938. const transitional = config.transitional || transitionalDefaults;
  1939. if (config.timeoutErrorMessage) {
  1940. timeoutErrorMessage = config.timeoutErrorMessage;
  1941. }
  1942. reject(new AxiosError(
  1943. timeoutErrorMessage,
  1944. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  1945. config,
  1946. request));
  1947. // Clean up request
  1948. request = null;
  1949. };
  1950. // Add xsrf header
  1951. // This is only done if running in a standard browser environment.
  1952. // Specifically not if we're in a web worker, or react-native.
  1953. if (platform.isStandardBrowserEnv) {
  1954. // Add xsrf header
  1955. const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
  1956. && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
  1957. if (xsrfValue) {
  1958. requestHeaders.set(config.xsrfHeaderName, xsrfValue);
  1959. }
  1960. }
  1961. // Remove Content-Type if data is undefined
  1962. requestData === undefined && requestHeaders.setContentType(null);
  1963. // Add headers to the request
  1964. if ('setRequestHeader' in request) {
  1965. utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
  1966. request.setRequestHeader(key, val);
  1967. });
  1968. }
  1969. // Add withCredentials to request if needed
  1970. if (!utils.isUndefined(config.withCredentials)) {
  1971. request.withCredentials = !!config.withCredentials;
  1972. }
  1973. // Add responseType to request if needed
  1974. if (responseType && responseType !== 'json') {
  1975. request.responseType = config.responseType;
  1976. }
  1977. // Handle progress if needed
  1978. if (typeof config.onDownloadProgress === 'function') {
  1979. request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
  1980. }
  1981. // Not all browsers support upload events
  1982. if (typeof config.onUploadProgress === 'function' && request.upload) {
  1983. request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
  1984. }
  1985. if (config.cancelToken || config.signal) {
  1986. // Handle cancellation
  1987. // eslint-disable-next-line func-names
  1988. onCanceled = cancel => {
  1989. if (!request) {
  1990. return;
  1991. }
  1992. reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
  1993. request.abort();
  1994. request = null;
  1995. };
  1996. config.cancelToken && config.cancelToken.subscribe(onCanceled);
  1997. if (config.signal) {
  1998. config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
  1999. }
  2000. }
  2001. const protocol = parseProtocol(fullPath);
  2002. if (protocol && platform.protocols.indexOf(protocol) === -1) {
  2003. reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
  2004. return;
  2005. }
  2006. // Send the request
  2007. request.send(requestData || null);
  2008. });
  2009. };
  2010. const knownAdapters = {
  2011. http: httpAdapter,
  2012. xhr: xhrAdapter
  2013. };
  2014. utils.forEach(knownAdapters, (fn, value) => {
  2015. if(fn) {
  2016. try {
  2017. Object.defineProperty(fn, 'name', {value});
  2018. } catch (e) {
  2019. // eslint-disable-next-line no-empty
  2020. }
  2021. Object.defineProperty(fn, 'adapterName', {value});
  2022. }
  2023. });
  2024. var adapters = {
  2025. getAdapter: (adapters) => {
  2026. adapters = utils.isArray(adapters) ? adapters : [adapters];
  2027. const {length} = adapters;
  2028. let nameOrAdapter;
  2029. let adapter;
  2030. for (let i = 0; i < length; i++) {
  2031. nameOrAdapter = adapters[i];
  2032. if((adapter = utils.isString(nameOrAdapter) ? knownAdapters[nameOrAdapter.toLowerCase()] : nameOrAdapter)) {
  2033. break;
  2034. }
  2035. }
  2036. if (!adapter) {
  2037. if (adapter === false) {
  2038. throw new AxiosError(
  2039. `Adapter ${nameOrAdapter} is not supported by the environment`,
  2040. 'ERR_NOT_SUPPORT'
  2041. );
  2042. }
  2043. throw new Error(
  2044. utils.hasOwnProp(knownAdapters, nameOrAdapter) ?
  2045. `Adapter '${nameOrAdapter}' is not available in the build` :
  2046. `Unknown adapter '${nameOrAdapter}'`
  2047. );
  2048. }
  2049. if (!utils.isFunction(adapter)) {
  2050. throw new TypeError('adapter is not a function');
  2051. }
  2052. return adapter;
  2053. },
  2054. adapters: knownAdapters
  2055. };
  2056. /**
  2057. * Throws a `CanceledError` if cancellation has been requested.
  2058. *
  2059. * @param {Object} config The config that is to be used for the request
  2060. *
  2061. * @returns {void}
  2062. */
  2063. function throwIfCancellationRequested(config) {
  2064. if (config.cancelToken) {
  2065. config.cancelToken.throwIfRequested();
  2066. }
  2067. if (config.signal && config.signal.aborted) {
  2068. throw new CanceledError(null, config);
  2069. }
  2070. }
  2071. /**
  2072. * Dispatch a request to the server using the configured adapter.
  2073. *
  2074. * @param {object} config The config that is to be used for the request
  2075. *
  2076. * @returns {Promise} The Promise to be fulfilled
  2077. */
  2078. function dispatchRequest(config) {
  2079. throwIfCancellationRequested(config);
  2080. config.headers = AxiosHeaders$1.from(config.headers);
  2081. // Transform request data
  2082. config.data = transformData.call(
  2083. config,
  2084. config.transformRequest
  2085. );
  2086. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  2087. config.headers.setContentType('application/x-www-form-urlencoded', false);
  2088. }
  2089. const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
  2090. return adapter(config).then(function onAdapterResolution(response) {
  2091. throwIfCancellationRequested(config);
  2092. // Transform response data
  2093. response.data = transformData.call(
  2094. config,
  2095. config.transformResponse,
  2096. response
  2097. );
  2098. response.headers = AxiosHeaders$1.from(response.headers);
  2099. return response;
  2100. }, function onAdapterRejection(reason) {
  2101. if (!isCancel(reason)) {
  2102. throwIfCancellationRequested(config);
  2103. // Transform response data
  2104. if (reason && reason.response) {
  2105. reason.response.data = transformData.call(
  2106. config,
  2107. config.transformResponse,
  2108. reason.response
  2109. );
  2110. reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
  2111. }
  2112. }
  2113. return Promise.reject(reason);
  2114. });
  2115. }
  2116. const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing;
  2117. /**
  2118. * Config-specific merge-function which creates a new config-object
  2119. * by merging two configuration objects together.
  2120. *
  2121. * @param {Object} config1
  2122. * @param {Object} config2
  2123. *
  2124. * @returns {Object} New object resulting from merging config2 to config1
  2125. */
  2126. function mergeConfig(config1, config2) {
  2127. // eslint-disable-next-line no-param-reassign
  2128. config2 = config2 || {};
  2129. const config = {};
  2130. function getMergedValue(target, source, caseless) {
  2131. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  2132. return utils.merge.call({caseless}, target, source);
  2133. } else if (utils.isPlainObject(source)) {
  2134. return utils.merge({}, source);
  2135. } else if (utils.isArray(source)) {
  2136. return source.slice();
  2137. }
  2138. return source;
  2139. }
  2140. // eslint-disable-next-line consistent-return
  2141. function mergeDeepProperties(a, b, caseless) {
  2142. if (!utils.isUndefined(b)) {
  2143. return getMergedValue(a, b, caseless);
  2144. } else if (!utils.isUndefined(a)) {
  2145. return getMergedValue(undefined, a, caseless);
  2146. }
  2147. }
  2148. // eslint-disable-next-line consistent-return
  2149. function valueFromConfig2(a, b) {
  2150. if (!utils.isUndefined(b)) {
  2151. return getMergedValue(undefined, b);
  2152. }
  2153. }
  2154. // eslint-disable-next-line consistent-return
  2155. function defaultToConfig2(a, b) {
  2156. if (!utils.isUndefined(b)) {
  2157. return getMergedValue(undefined, b);
  2158. } else if (!utils.isUndefined(a)) {
  2159. return getMergedValue(undefined, a);
  2160. }
  2161. }
  2162. // eslint-disable-next-line consistent-return
  2163. function mergeDirectKeys(a, b, prop) {
  2164. if (prop in config2) {
  2165. return getMergedValue(a, b);
  2166. } else if (prop in config1) {
  2167. return getMergedValue(undefined, a);
  2168. }
  2169. }
  2170. const mergeMap = {
  2171. url: valueFromConfig2,
  2172. method: valueFromConfig2,
  2173. data: valueFromConfig2,
  2174. baseURL: defaultToConfig2,
  2175. transformRequest: defaultToConfig2,
  2176. transformResponse: defaultToConfig2,
  2177. paramsSerializer: defaultToConfig2,
  2178. timeout: defaultToConfig2,
  2179. timeoutMessage: defaultToConfig2,
  2180. withCredentials: defaultToConfig2,
  2181. adapter: defaultToConfig2,
  2182. responseType: defaultToConfig2,
  2183. xsrfCookieName: defaultToConfig2,
  2184. xsrfHeaderName: defaultToConfig2,
  2185. onUploadProgress: defaultToConfig2,
  2186. onDownloadProgress: defaultToConfig2,
  2187. decompress: defaultToConfig2,
  2188. maxContentLength: defaultToConfig2,
  2189. maxBodyLength: defaultToConfig2,
  2190. beforeRedirect: defaultToConfig2,
  2191. transport: defaultToConfig2,
  2192. httpAgent: defaultToConfig2,
  2193. httpsAgent: defaultToConfig2,
  2194. cancelToken: defaultToConfig2,
  2195. socketPath: defaultToConfig2,
  2196. responseEncoding: defaultToConfig2,
  2197. validateStatus: mergeDirectKeys,
  2198. headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
  2199. };
  2200. utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
  2201. const merge = mergeMap[prop] || mergeDeepProperties;
  2202. const configValue = merge(config1[prop], config2[prop], prop);
  2203. (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
  2204. });
  2205. return config;
  2206. }
  2207. const VERSION = "1.3.4";
  2208. const validators$1 = {};
  2209. // eslint-disable-next-line func-names
  2210. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  2211. validators$1[type] = function validator(thing) {
  2212. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  2213. };
  2214. });
  2215. const deprecatedWarnings = {};
  2216. /**
  2217. * Transitional option validator
  2218. *
  2219. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  2220. * @param {string?} version - deprecated version / removed since version
  2221. * @param {string?} message - some message with additional info
  2222. *
  2223. * @returns {function}
  2224. */
  2225. validators$1.transitional = function transitional(validator, version, message) {
  2226. function formatMessage(opt, desc) {
  2227. return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
  2228. }
  2229. // eslint-disable-next-line func-names
  2230. return (value, opt, opts) => {
  2231. if (validator === false) {
  2232. throw new AxiosError(
  2233. formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
  2234. AxiosError.ERR_DEPRECATED
  2235. );
  2236. }
  2237. if (version && !deprecatedWarnings[opt]) {
  2238. deprecatedWarnings[opt] = true;
  2239. // eslint-disable-next-line no-console
  2240. console.warn(
  2241. formatMessage(
  2242. opt,
  2243. ' has been deprecated since v' + version + ' and will be removed in the near future'
  2244. )
  2245. );
  2246. }
  2247. return validator ? validator(value, opt, opts) : true;
  2248. };
  2249. };
  2250. /**
  2251. * Assert object's properties type
  2252. *
  2253. * @param {object} options
  2254. * @param {object} schema
  2255. * @param {boolean?} allowUnknown
  2256. *
  2257. * @returns {object}
  2258. */
  2259. function assertOptions(options, schema, allowUnknown) {
  2260. if (typeof options !== 'object') {
  2261. throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  2262. }
  2263. const keys = Object.keys(options);
  2264. let i = keys.length;
  2265. while (i-- > 0) {
  2266. const opt = keys[i];
  2267. const validator = schema[opt];
  2268. if (validator) {
  2269. const value = options[opt];
  2270. const result = value === undefined || validator(value, opt, options);
  2271. if (result !== true) {
  2272. throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
  2273. }
  2274. continue;
  2275. }
  2276. if (allowUnknown !== true) {
  2277. throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
  2278. }
  2279. }
  2280. }
  2281. var validator = {
  2282. assertOptions,
  2283. validators: validators$1
  2284. };
  2285. const validators = validator.validators;
  2286. /**
  2287. * Create a new instance of Axios
  2288. *
  2289. * @param {Object} instanceConfig The default config for the instance
  2290. *
  2291. * @return {Axios} A new instance of Axios
  2292. */
  2293. class Axios {
  2294. constructor(instanceConfig) {
  2295. this.defaults = instanceConfig;
  2296. this.interceptors = {
  2297. request: new InterceptorManager$1(),
  2298. response: new InterceptorManager$1()
  2299. };
  2300. }
  2301. /**
  2302. * Dispatch a request
  2303. *
  2304. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  2305. * @param {?Object} config
  2306. *
  2307. * @returns {Promise} The Promise to be fulfilled
  2308. */
  2309. request(configOrUrl, config) {
  2310. /*eslint no-param-reassign:0*/
  2311. // Allow for axios('example/url'[, config]) a la fetch API
  2312. if (typeof configOrUrl === 'string') {
  2313. config = config || {};
  2314. config.url = configOrUrl;
  2315. } else {
  2316. config = configOrUrl || {};
  2317. }
  2318. config = mergeConfig(this.defaults, config);
  2319. const {transitional, paramsSerializer, headers} = config;
  2320. if (transitional !== undefined) {
  2321. validator.assertOptions(transitional, {
  2322. silentJSONParsing: validators.transitional(validators.boolean),
  2323. forcedJSONParsing: validators.transitional(validators.boolean),
  2324. clarifyTimeoutError: validators.transitional(validators.boolean)
  2325. }, false);
  2326. }
  2327. if (paramsSerializer !== undefined) {
  2328. validator.assertOptions(paramsSerializer, {
  2329. encode: validators.function,
  2330. serialize: validators.function
  2331. }, true);
  2332. }
  2333. // Set config.method
  2334. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  2335. let contextHeaders;
  2336. // Flatten headers
  2337. contextHeaders = headers && utils.merge(
  2338. headers.common,
  2339. headers[config.method]
  2340. );
  2341. contextHeaders && utils.forEach(
  2342. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  2343. (method) => {
  2344. delete headers[method];
  2345. }
  2346. );
  2347. config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
  2348. // filter out skipped interceptors
  2349. const requestInterceptorChain = [];
  2350. let synchronousRequestInterceptors = true;
  2351. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  2352. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  2353. return;
  2354. }
  2355. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  2356. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  2357. });
  2358. const responseInterceptorChain = [];
  2359. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  2360. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  2361. });
  2362. let promise;
  2363. let i = 0;
  2364. let len;
  2365. if (!synchronousRequestInterceptors) {
  2366. const chain = [dispatchRequest.bind(this), undefined];
  2367. chain.unshift.apply(chain, requestInterceptorChain);
  2368. chain.push.apply(chain, responseInterceptorChain);
  2369. len = chain.length;
  2370. promise = Promise.resolve(config);
  2371. while (i < len) {
  2372. promise = promise.then(chain[i++], chain[i++]);
  2373. }
  2374. return promise;
  2375. }
  2376. len = requestInterceptorChain.length;
  2377. let newConfig = config;
  2378. i = 0;
  2379. while (i < len) {
  2380. const onFulfilled = requestInterceptorChain[i++];
  2381. const onRejected = requestInterceptorChain[i++];
  2382. try {
  2383. newConfig = onFulfilled(newConfig);
  2384. } catch (error) {
  2385. onRejected.call(this, error);
  2386. break;
  2387. }
  2388. }
  2389. try {
  2390. promise = dispatchRequest.call(this, newConfig);
  2391. } catch (error) {
  2392. return Promise.reject(error);
  2393. }
  2394. i = 0;
  2395. len = responseInterceptorChain.length;
  2396. while (i < len) {
  2397. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  2398. }
  2399. return promise;
  2400. }
  2401. getUri(config) {
  2402. config = mergeConfig(this.defaults, config);
  2403. const fullPath = buildFullPath(config.baseURL, config.url);
  2404. return buildURL(fullPath, config.params, config.paramsSerializer);
  2405. }
  2406. }
  2407. // Provide aliases for supported request methods
  2408. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  2409. /*eslint func-names:0*/
  2410. Axios.prototype[method] = function(url, config) {
  2411. return this.request(mergeConfig(config || {}, {
  2412. method,
  2413. url,
  2414. data: (config || {}).data
  2415. }));
  2416. };
  2417. });
  2418. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  2419. /*eslint func-names:0*/
  2420. function generateHTTPMethod(isForm) {
  2421. return function httpMethod(url, data, config) {
  2422. return this.request(mergeConfig(config || {}, {
  2423. method,
  2424. headers: isForm ? {
  2425. 'Content-Type': 'multipart/form-data'
  2426. } : {},
  2427. url,
  2428. data
  2429. }));
  2430. };
  2431. }
  2432. Axios.prototype[method] = generateHTTPMethod();
  2433. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  2434. });
  2435. var Axios$1 = Axios;
  2436. /**
  2437. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  2438. *
  2439. * @param {Function} executor The executor function.
  2440. *
  2441. * @returns {CancelToken}
  2442. */
  2443. class CancelToken {
  2444. constructor(executor) {
  2445. if (typeof executor !== 'function') {
  2446. throw new TypeError('executor must be a function.');
  2447. }
  2448. let resolvePromise;
  2449. this.promise = new Promise(function promiseExecutor(resolve) {
  2450. resolvePromise = resolve;
  2451. });
  2452. const token = this;
  2453. // eslint-disable-next-line func-names
  2454. this.promise.then(cancel => {
  2455. if (!token._listeners) return;
  2456. let i = token._listeners.length;
  2457. while (i-- > 0) {
  2458. token._listeners[i](cancel);
  2459. }
  2460. token._listeners = null;
  2461. });
  2462. // eslint-disable-next-line func-names
  2463. this.promise.then = onfulfilled => {
  2464. let _resolve;
  2465. // eslint-disable-next-line func-names
  2466. const promise = new Promise(resolve => {
  2467. token.subscribe(resolve);
  2468. _resolve = resolve;
  2469. }).then(onfulfilled);
  2470. promise.cancel = function reject() {
  2471. token.unsubscribe(_resolve);
  2472. };
  2473. return promise;
  2474. };
  2475. executor(function cancel(message, config, request) {
  2476. if (token.reason) {
  2477. // Cancellation has already been requested
  2478. return;
  2479. }
  2480. token.reason = new CanceledError(message, config, request);
  2481. resolvePromise(token.reason);
  2482. });
  2483. }
  2484. /**
  2485. * Throws a `CanceledError` if cancellation has been requested.
  2486. */
  2487. throwIfRequested() {
  2488. if (this.reason) {
  2489. throw this.reason;
  2490. }
  2491. }
  2492. /**
  2493. * Subscribe to the cancel signal
  2494. */
  2495. subscribe(listener) {
  2496. if (this.reason) {
  2497. listener(this.reason);
  2498. return;
  2499. }
  2500. if (this._listeners) {
  2501. this._listeners.push(listener);
  2502. } else {
  2503. this._listeners = [listener];
  2504. }
  2505. }
  2506. /**
  2507. * Unsubscribe from the cancel signal
  2508. */
  2509. unsubscribe(listener) {
  2510. if (!this._listeners) {
  2511. return;
  2512. }
  2513. const index = this._listeners.indexOf(listener);
  2514. if (index !== -1) {
  2515. this._listeners.splice(index, 1);
  2516. }
  2517. }
  2518. /**
  2519. * Returns an object that contains a new `CancelToken` and a function that, when called,
  2520. * cancels the `CancelToken`.
  2521. */
  2522. static source() {
  2523. let cancel;
  2524. const token = new CancelToken(function executor(c) {
  2525. cancel = c;
  2526. });
  2527. return {
  2528. token,
  2529. cancel
  2530. };
  2531. }
  2532. }
  2533. var CancelToken$1 = CancelToken;
  2534. /**
  2535. * Syntactic sugar for invoking a function and expanding an array for arguments.
  2536. *
  2537. * Common use case would be to use `Function.prototype.apply`.
  2538. *
  2539. * ```js
  2540. * function f(x, y, z) {}
  2541. * var args = [1, 2, 3];
  2542. * f.apply(null, args);
  2543. * ```
  2544. *
  2545. * With `spread` this example can be re-written.
  2546. *
  2547. * ```js
  2548. * spread(function(x, y, z) {})([1, 2, 3]);
  2549. * ```
  2550. *
  2551. * @param {Function} callback
  2552. *
  2553. * @returns {Function}
  2554. */
  2555. function spread(callback) {
  2556. return function wrap(arr) {
  2557. return callback.apply(null, arr);
  2558. };
  2559. }
  2560. /**
  2561. * Determines whether the payload is an error thrown by Axios
  2562. *
  2563. * @param {*} payload The value to test
  2564. *
  2565. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  2566. */
  2567. function isAxiosError(payload) {
  2568. return utils.isObject(payload) && (payload.isAxiosError === true);
  2569. }
  2570. const HttpStatusCode = {
  2571. Continue: 100,
  2572. SwitchingProtocols: 101,
  2573. Processing: 102,
  2574. EarlyHints: 103,
  2575. Ok: 200,
  2576. Created: 201,
  2577. Accepted: 202,
  2578. NonAuthoritativeInformation: 203,
  2579. NoContent: 204,
  2580. ResetContent: 205,
  2581. PartialContent: 206,
  2582. MultiStatus: 207,
  2583. AlreadyReported: 208,
  2584. ImUsed: 226,
  2585. MultipleChoices: 300,
  2586. MovedPermanently: 301,
  2587. Found: 302,
  2588. SeeOther: 303,
  2589. NotModified: 304,
  2590. UseProxy: 305,
  2591. Unused: 306,
  2592. TemporaryRedirect: 307,
  2593. PermanentRedirect: 308,
  2594. BadRequest: 400,
  2595. Unauthorized: 401,
  2596. PaymentRequired: 402,
  2597. Forbidden: 403,
  2598. NotFound: 404,
  2599. MethodNotAllowed: 405,
  2600. NotAcceptable: 406,
  2601. ProxyAuthenticationRequired: 407,
  2602. RequestTimeout: 408,
  2603. Conflict: 409,
  2604. Gone: 410,
  2605. LengthRequired: 411,
  2606. PreconditionFailed: 412,
  2607. PayloadTooLarge: 413,
  2608. UriTooLong: 414,
  2609. UnsupportedMediaType: 415,
  2610. RangeNotSatisfiable: 416,
  2611. ExpectationFailed: 417,
  2612. ImATeapot: 418,
  2613. MisdirectedRequest: 421,
  2614. UnprocessableEntity: 422,
  2615. Locked: 423,
  2616. FailedDependency: 424,
  2617. TooEarly: 425,
  2618. UpgradeRequired: 426,
  2619. PreconditionRequired: 428,
  2620. TooManyRequests: 429,
  2621. RequestHeaderFieldsTooLarge: 431,
  2622. UnavailableForLegalReasons: 451,
  2623. InternalServerError: 500,
  2624. NotImplemented: 501,
  2625. BadGateway: 502,
  2626. ServiceUnavailable: 503,
  2627. GatewayTimeout: 504,
  2628. HttpVersionNotSupported: 505,
  2629. VariantAlsoNegotiates: 506,
  2630. InsufficientStorage: 507,
  2631. LoopDetected: 508,
  2632. NotExtended: 510,
  2633. NetworkAuthenticationRequired: 511,
  2634. };
  2635. Object.entries(HttpStatusCode).forEach(([key, value]) => {
  2636. HttpStatusCode[value] = key;
  2637. });
  2638. var HttpStatusCode$1 = HttpStatusCode;
  2639. /**
  2640. * Create an instance of Axios
  2641. *
  2642. * @param {Object} defaultConfig The default config for the instance
  2643. *
  2644. * @returns {Axios} A new instance of Axios
  2645. */
  2646. function createInstance(defaultConfig) {
  2647. const context = new Axios$1(defaultConfig);
  2648. const instance = bind(Axios$1.prototype.request, context);
  2649. // Copy axios.prototype to instance
  2650. utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
  2651. // Copy context to instance
  2652. utils.extend(instance, context, null, {allOwnKeys: true});
  2653. // Factory for creating new instances
  2654. instance.create = function create(instanceConfig) {
  2655. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  2656. };
  2657. return instance;
  2658. }
  2659. // Create the default instance to be exported
  2660. const axios = createInstance(defaults$1);
  2661. // Expose Axios class to allow class inheritance
  2662. axios.Axios = Axios$1;
  2663. // Expose Cancel & CancelToken
  2664. axios.CanceledError = CanceledError;
  2665. axios.CancelToken = CancelToken$1;
  2666. axios.isCancel = isCancel;
  2667. axios.VERSION = VERSION;
  2668. axios.toFormData = toFormData;
  2669. // Expose AxiosError class
  2670. axios.AxiosError = AxiosError;
  2671. // alias for CanceledError for backward compatibility
  2672. axios.Cancel = axios.CanceledError;
  2673. // Expose all/spread
  2674. axios.all = function all(promises) {
  2675. return Promise.all(promises);
  2676. };
  2677. axios.spread = spread;
  2678. // Expose isAxiosError
  2679. axios.isAxiosError = isAxiosError;
  2680. // Expose mergeConfig
  2681. axios.mergeConfig = mergeConfig;
  2682. axios.AxiosHeaders = AxiosHeaders$1;
  2683. axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
  2684. axios.HttpStatusCode = HttpStatusCode$1;
  2685. axios.default = axios;
  2686. module.exports = axios;
  2687. //# sourceMappingURL=axios.cjs.map