axios.cjs 126 KB

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