axios.cjs 127 KB

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