axios.cjs 98 KB

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