axios.js 96 KB

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