axios.cjs 132 KB

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