axios.js 82 KB

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