axios.cjs 255 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506
  1. /*! Axios v1.21.1 Copyright (c) 2026 Matt Zabriskie and contributors */
  2. 'use strict';
  3. var FormData$1 = require('form-data');
  4. var crypto = require('crypto');
  5. var url = require('url');
  6. var HttpsProxyAgent = require('https-proxy-agent');
  7. var http = require('http');
  8. var https = require('https');
  9. var http2 = require('http2');
  10. var util = require('util');
  11. var path = require('path');
  12. var followRedirects = require('follow-redirects');
  13. var zlib = require('zlib');
  14. var stream = require('stream');
  15. var events = require('events');
  16. /**
  17. * Create a bound version of a function with a specified `this` context
  18. *
  19. * @param {Function} fn - The function to bind
  20. * @param {*} thisArg - The value to be passed as the `this` parameter
  21. * @returns {Function} A new function that will call the original function with the specified `this` context
  22. */
  23. function bind(fn, thisArg) {
  24. return function wrap() {
  25. return fn.apply(thisArg, arguments);
  26. };
  27. }
  28. // utils is a library of generic helper functions non-specific to axios
  29. const {
  30. toString
  31. } = Object.prototype;
  32. const {
  33. getPrototypeOf
  34. } = Object;
  35. const {
  36. iterator,
  37. toStringTag
  38. } = Symbol;
  39. /* Creating a function that will check if an object has a property. */
  40. const hasOwnProperty = (({
  41. hasOwnProperty
  42. }) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
  43. const isUnsafeObjectKey = prop => typeof prop === 'string' && (prop === '__proto__' || prop === 'constructor' || prop === 'prototype');
  44. /**
  45. * Determine whether an inherited object must be treated as a shared-prototype
  46. * boundary. Cross-realm Object.prototype objects cannot be distinguished
  47. * reliably from application-created null-prototype objects because their
  48. * properties are mutable, so all inherited terminal prototypes are excluded
  49. * as a fail-closed boundary. A null-prototype source still keeps its own
  50. * properties, as produced by mergeConfig and other safe materialization paths.
  51. *
  52. * @param {*} obj The object to inspect
  53. * @param {*} prototype The object's prototype
  54. * @param {boolean} source Whether obj is the original traversal source
  55. *
  56. * @returns {boolean} True when obj is a safe prototype traversal boundary
  57. */
  58. const isPrototypeBoundary = (obj, prototype, source) => obj === Object.prototype || !source && prototype === null;
  59. /**
  60. * Determine whether an object can retain its identity through code paths that
  61. * add, replace, and remove config properties without bypassing unsafe-key
  62. * filtering. Immutable objects, unsafe-key-bearing objects, and objects with
  63. * accessor or restricted data properties must be materialized instead.
  64. *
  65. * @param {*} obj The object to inspect
  66. *
  67. * @returns {boolean} True when every own property is safe and fully mutable
  68. */
  69. const isSafeAndFullyMutable = obj => {
  70. if (!Object.isExtensible(obj)) {
  71. return false;
  72. }
  73. const props = Object.getOwnPropertyNames(obj);
  74. if (Object.getOwnPropertySymbols) {
  75. props.push(...Object.getOwnPropertySymbols(obj));
  76. }
  77. return props.every(prop => {
  78. if (isUnsafeObjectKey(prop)) {
  79. return false;
  80. }
  81. const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  82. return !!descriptor && descriptor.configurable && descriptor.writable === true;
  83. });
  84. };
  85. /**
  86. * Walk the prototype chain (excluding the source realm's Object.prototype)
  87. * looking for an own `prop`. This distinguishes genuine own/inherited members
  88. * — including class accessors and template prototypes — from members injected
  89. * via Object.prototype pollution (e.g. `Object.prototype.username = '...'`),
  90. * which live on Object.prototype itself and are therefore never matched.
  91. *
  92. * @param {*} thing The value whose chain to inspect
  93. * @param {string|symbol} prop The property key to look for
  94. *
  95. * @returns {boolean} True when `prop` is owned below Object.prototype
  96. */
  97. const hasOwnInPrototypeChain = (thing, prop) => {
  98. let obj = thing;
  99. const seen = [];
  100. while (obj != null) {
  101. if (seen.indexOf(obj) !== -1) {
  102. return false;
  103. }
  104. seen.push(obj);
  105. const prototype = getPrototypeOf(obj);
  106. if (isPrototypeBoundary(obj, prototype, obj === thing)) {
  107. return false;
  108. }
  109. if (hasOwnProperty(obj, prop)) {
  110. return true;
  111. }
  112. obj = prototype;
  113. }
  114. return false;
  115. };
  116. /**
  117. * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
  118. * properties and members inherited from a non-Object.prototype source (a class
  119. * instance or template object) are honored; a value reachable only through a
  120. * polluted Object.prototype is ignored and `undefined` is returned.
  121. *
  122. * @param {*} obj The source object
  123. * @param {string|symbol} prop The property key to read
  124. *
  125. * @returns {*} The resolved value, or undefined when unsafe/absent
  126. */
  127. const getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
  128. /**
  129. * Flatten an object and its application-defined prototype chain into a
  130. * null-prototype object. Members inherited only from the source realm's
  131. * Object.prototype are deliberately excluded, while class/template members
  132. * below that boundary are preserved.
  133. *
  134. * @param {*} thing The value to flatten
  135. *
  136. * @returns {*} A null-prototype copy, or the original value when it is already
  137. * structurally safe or is not an object
  138. */
  139. const toSafeFlatObject = thing => {
  140. if (thing == null || typeof thing !== 'object' && typeof thing !== 'function') {
  141. return thing;
  142. }
  143. const sourcePrototype = getPrototypeOf(thing);
  144. if (sourcePrototype === null && isSafeAndFullyMutable(thing)) {
  145. return thing;
  146. }
  147. const result = Object.create(null);
  148. const merged = Object.create(null);
  149. const seen = [];
  150. let current = thing;
  151. while (current != null) {
  152. if (seen.indexOf(current) !== -1) {
  153. break;
  154. }
  155. seen.push(current);
  156. const prototype = current === thing ? sourcePrototype : getPrototypeOf(current);
  157. if (isPrototypeBoundary(current, prototype, current === thing)) {
  158. break;
  159. }
  160. const props = Object.getOwnPropertyNames(current);
  161. if (Object.getOwnPropertySymbols) {
  162. props.push(...Object.getOwnPropertySymbols(current));
  163. }
  164. for (const prop of props) {
  165. if (isUnsafeObjectKey(prop)) {
  166. continue;
  167. }
  168. if (!hasOwnProperty(merged, prop)) {
  169. result[prop] = thing[prop];
  170. merged[prop] = true;
  171. }
  172. }
  173. current = prototype;
  174. }
  175. return result;
  176. };
  177. const kindOf = (cache => thing => {
  178. const str = toString.call(thing);
  179. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  180. })(Object.create(null));
  181. const kindOfTest = type => {
  182. type = type.toLowerCase();
  183. return thing => kindOf(thing) === type;
  184. };
  185. const typeOfTest = type => thing => typeof thing === type;
  186. /**
  187. * Determine if a value is a non-null object
  188. *
  189. * @param {Object} val The value to test
  190. *
  191. * @returns {boolean} True if value is an Array, otherwise false
  192. */
  193. const {
  194. isArray
  195. } = Array;
  196. /**
  197. * Determine if a value is undefined
  198. *
  199. * @param {*} val The value to test
  200. *
  201. * @returns {boolean} True if the value is undefined, otherwise false
  202. */
  203. const isUndefined = typeOfTest('undefined');
  204. /**
  205. * Determine if a value is a Buffer
  206. *
  207. * @param {*} val The value to test
  208. *
  209. * @returns {boolean} True if value is a Buffer, otherwise false
  210. */
  211. function isBuffer(val) {
  212. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
  213. }
  214. /**
  215. * Determine if a value is an ArrayBuffer
  216. *
  217. * @param {*} val The value to test
  218. *
  219. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  220. */
  221. const isArrayBuffer = kindOfTest('ArrayBuffer');
  222. /**
  223. * Determine if a value is a view on an ArrayBuffer
  224. *
  225. * @param {*} val The value to test
  226. *
  227. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  228. */
  229. function isArrayBufferView(val) {
  230. let result;
  231. if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
  232. result = ArrayBuffer.isView(val);
  233. } else {
  234. result = val && val.buffer && isArrayBuffer(val.buffer);
  235. }
  236. return result;
  237. }
  238. /**
  239. * Determine if a value is a String
  240. *
  241. * @param {*} val The value to test
  242. *
  243. * @returns {boolean} True if value is a String, otherwise false
  244. */
  245. const isString = typeOfTest('string');
  246. /**
  247. * Determine if a value is a Function
  248. *
  249. * @param {*} val The value to test
  250. * @returns {boolean} True if value is a Function, otherwise false
  251. */
  252. const isFunction$1 = typeOfTest('function');
  253. /**
  254. * Determine if a value is a Number
  255. *
  256. * @param {*} val The value to test
  257. *
  258. * @returns {boolean} True if value is a Number, otherwise false
  259. */
  260. const isNumber = typeOfTest('number');
  261. /**
  262. * Determine if a value is an Object
  263. *
  264. * @param {*} thing The value to test
  265. *
  266. * @returns {boolean} True if value is an Object, otherwise false
  267. */
  268. const isObject = thing => thing !== null && typeof thing === 'object';
  269. /**
  270. * Determine if a value is a Boolean
  271. *
  272. * @param {*} thing The value to test
  273. * @returns {boolean} True if value is a Boolean, otherwise false
  274. */
  275. const isBoolean = thing => thing === true || thing === false;
  276. /**
  277. * Determine if a value is a plain Object
  278. *
  279. * @param {*} val The value to test
  280. *
  281. * @returns {boolean} True if value is a plain Object, otherwise false
  282. */
  283. const isPlainObject = val => {
  284. if (!isObject(val)) {
  285. return false;
  286. }
  287. const prototype = getPrototypeOf(val);
  288. return (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) && (
  289. // Treat own Symbol.toStringTag or Symbol.iterator members as evidence the
  290. // value is tagged/iterable, ignoring members reachable only through shared
  291. // or terminal prototype boundaries. This is exactly what
  292. // hasOwnInPrototypeChain(val, prop) computes here: every prototype admitted
  293. // above (null, Object.prototype, or a terminal null-prototype template) is
  294. // a boundary, so the walk never inspects anything but `val`'s own members,
  295. // and stops before even those when `val` is itself the boundary
  296. // Object.prototype. Checking that inline avoids allocating the walker's
  297. // `seen` list twice per call on the mergeConfig / merge hot path.
  298. isPrototypeBoundary(val, prototype, true) || !hasOwnProperty(val, toStringTag) && !hasOwnProperty(val, iterator));
  299. };
  300. /**
  301. * Determine if a value is an empty object (safely handles Buffers)
  302. *
  303. * @param {*} val The value to test
  304. *
  305. * @returns {boolean} True if value is an empty object, otherwise false
  306. */
  307. const isEmptyObject = val => {
  308. // Early return for non-objects or Buffers to prevent RangeError
  309. if (!isObject(val) || isBuffer(val)) {
  310. return false;
  311. }
  312. try {
  313. return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  314. } catch (e) {
  315. // Fallback for any other objects that might cause RangeError with Object.keys()
  316. return false;
  317. }
  318. };
  319. /**
  320. * Determine if a value is a Date
  321. *
  322. * @param {*} val The value to test
  323. *
  324. * @returns {boolean} True if value is a Date, otherwise false
  325. */
  326. const isDate = kindOfTest('Date');
  327. /**
  328. * Determine if a value is a File
  329. *
  330. * @param {*} val The value to test
  331. *
  332. * @returns {boolean} True if value is a File, otherwise false
  333. */
  334. const isFile = kindOfTest('File');
  335. /**
  336. * Determine if a value is a React Native Blob
  337. * React Native "blob": an object with a `uri` attribute. Optionally, it can
  338. * also have a `name` and `type` attribute to specify filename and content type
  339. *
  340. * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
  341. *
  342. * @param {*} value The value to test
  343. *
  344. * @returns {boolean} True if value is a React Native Blob, otherwise false
  345. */
  346. const isReactNativeBlob = value => {
  347. return !!(value && typeof value.uri !== 'undefined');
  348. };
  349. /**
  350. * Determine if environment is React Native
  351. * ReactNative `FormData` has a non-standard `getParts()` method
  352. *
  353. * @param {*} formData The formData to test
  354. *
  355. * @returns {boolean} True if environment is React Native, otherwise false
  356. */
  357. const isReactNative = formData => formData && typeof formData.getParts !== 'undefined';
  358. /**
  359. * Determine if a value is a Blob
  360. *
  361. * @param {*} val The value to test
  362. *
  363. * @returns {boolean} True if value is a Blob, otherwise false
  364. */
  365. const isBlob = kindOfTest('Blob');
  366. /**
  367. * Determine if a value is a FileList
  368. *
  369. * @param {*} val The value to test
  370. *
  371. * @returns {boolean} True if value is a FileList, otherwise false
  372. */
  373. const isFileList = kindOfTest('FileList');
  374. const isSet = kindOfTest('Set');
  375. /**
  376. * Determine if a value is a Stream
  377. *
  378. * @param {*} val The value to test
  379. *
  380. * @returns {boolean} True if value is a Stream, otherwise false
  381. */
  382. const isStream = val => isObject(val) && isFunction$1(val.pipe);
  383. /**
  384. * Determine if a value is a FormData
  385. *
  386. * @param {*} thing The value to test
  387. *
  388. * @returns {boolean} True if value is an FormData, otherwise false
  389. */
  390. function getGlobal() {
  391. if (typeof globalThis !== 'undefined') return globalThis;
  392. if (typeof self !== 'undefined') return self;
  393. if (typeof window !== 'undefined') return window;
  394. if (typeof global !== 'undefined') return global;
  395. return {};
  396. }
  397. const G = getGlobal();
  398. const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
  399. const isFormData = thing => {
  400. if (!thing) return false;
  401. if (FormDataCtor && thing instanceof FormDataCtor) return true;
  402. // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
  403. const proto = getPrototypeOf(thing);
  404. if (!proto || proto === Object.prototype) return false;
  405. if (!isFunction$1(thing.append)) return false;
  406. const kind = kindOf(thing);
  407. return kind === 'formdata' ||
  408. // detect form-data instance
  409. kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]';
  410. };
  411. /**
  412. * Determine if a value is a URLSearchParams object
  413. *
  414. * @param {*} val The value to test
  415. *
  416. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  417. */
  418. const isURLSearchParams = kindOfTest('URLSearchParams');
  419. const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
  420. /**
  421. * Trim excess whitespace off the beginning and end of a string
  422. *
  423. * @param {String} str The String to trim
  424. *
  425. * @returns {String} The String freed of excess whitespace
  426. */
  427. const trim = str => {
  428. return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  429. };
  430. /**
  431. * Iterate over an Array or an Object invoking a function for each item.
  432. *
  433. * If `obj` is an Array callback will be called passing
  434. * the value, index, and complete array for each item.
  435. *
  436. * If 'obj' is an Object callback will be called passing
  437. * the value, key, and complete object for each property.
  438. *
  439. * @param {Object|Array<unknown>} obj The object to iterate
  440. * @param {Function} fn The callback to invoke for each item
  441. *
  442. * @param {Object} [options]
  443. * @param {Boolean} [options.allOwnKeys = false]
  444. * @returns {any}
  445. */
  446. function forEach(obj, fn, {
  447. allOwnKeys = false
  448. } = {}) {
  449. // Don't bother if no value provided
  450. if (obj === null || typeof obj === 'undefined') {
  451. return;
  452. }
  453. let i;
  454. let l;
  455. // Force an array if not already something iterable
  456. if (typeof obj !== 'object') {
  457. /*eslint no-param-reassign:0*/
  458. obj = [obj];
  459. }
  460. if (isArray(obj)) {
  461. // Iterate over array values
  462. for (i = 0, l = obj.length; i < l; i++) {
  463. fn.call(null, obj[i], i, obj);
  464. }
  465. } else {
  466. // Buffer check
  467. if (isBuffer(obj)) {
  468. return;
  469. }
  470. // Iterate over object keys
  471. const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  472. const len = keys.length;
  473. let key;
  474. for (i = 0; i < len; i++) {
  475. key = keys[i];
  476. fn.call(null, obj[key], key, obj);
  477. }
  478. }
  479. }
  480. /**
  481. * Finds a key in an object, case-insensitive, returning the actual key name.
  482. * Returns null if the object is a Buffer or if no match is found.
  483. *
  484. * @param {Object} obj - The object to search.
  485. * @param {string} key - The key to find (case-insensitive).
  486. * @returns {?string} The actual key name if found, otherwise null.
  487. */
  488. function findKey(obj, key) {
  489. if (isBuffer(obj)) {
  490. return null;
  491. }
  492. key = key.toLowerCase();
  493. const keys = Object.keys(obj);
  494. let i = keys.length;
  495. let _key;
  496. while (i-- > 0) {
  497. _key = keys[i];
  498. if (key === _key.toLowerCase()) {
  499. return _key;
  500. }
  501. }
  502. return null;
  503. }
  504. const _global = (() => {
  505. /*eslint no-undef:0*/
  506. if (typeof globalThis !== 'undefined') return globalThis;
  507. return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
  508. })();
  509. const isContextDefined = context => !isUndefined(context) && context !== _global;
  510. /**
  511. * Accepts varargs expecting each argument to be an object, then
  512. * immutably merges the properties of each object and returns result.
  513. *
  514. * When multiple objects contain the same key the later object in
  515. * the arguments list will take precedence.
  516. *
  517. * Example:
  518. *
  519. * ```js
  520. * const result = merge({foo: 123}, {foo: 456});
  521. * console.log(result.foo); // outputs 456
  522. * ```
  523. *
  524. * @param {Object} obj1 Object to merge
  525. *
  526. * @returns {Object} Result of all merge properties
  527. */
  528. function merge(...objs) {
  529. const {
  530. caseless,
  531. skipUndefined
  532. } = isContextDefined(this) && this || {};
  533. const result = {};
  534. // Caseless lookup only applies to string keys — symbol keys are
  535. // identity-matched. Every string key that reaches `result` passes through
  536. // this index first, so it can never hold two case variants of one key and a
  537. // lowercase -> key map is exactly what findKey(result, key) would rescan
  538. // Object.keys(result) for on each assignment.
  539. const lowerCaseKeys = caseless ? Object.create(null) : null;
  540. const assignValue = (val, key) => {
  541. // Skip dangerous property names to prevent prototype pollution
  542. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  543. return;
  544. }
  545. let targetKey = key;
  546. if (lowerCaseKeys && typeof key === 'string') {
  547. const lowerKey = key.toLowerCase();
  548. const knownKey = lowerCaseKeys[lowerKey];
  549. // A key recorded but absent from `result` was skipped by skipUndefined;
  550. // the later spelling wins then, as it does for findKey.
  551. if (knownKey !== undefined && hasOwnProperty(result, knownKey)) {
  552. targetKey = knownKey;
  553. } else {
  554. lowerCaseKeys[lowerKey] = key;
  555. }
  556. }
  557. // Read via own-prop only — a bare `result[targetKey]` walks the prototype
  558. // chain, so a polluted Object.prototype value could surface here and get
  559. // copied into the merged result.
  560. const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
  561. if (isPlainObject(existing) && isPlainObject(val)) {
  562. result[targetKey] = merge(existing, val);
  563. } else if (isPlainObject(val)) {
  564. result[targetKey] = merge({}, val);
  565. } else if (isArray(val)) {
  566. result[targetKey] = val.slice();
  567. } else if (!skipUndefined || !isUndefined(val)) {
  568. result[targetKey] = val;
  569. }
  570. };
  571. for (let i = 0, l = objs.length; i < l; i++) {
  572. const source = objs[i];
  573. if (!source || isBuffer(source)) {
  574. continue;
  575. }
  576. forEach(source, assignValue);
  577. if (typeof source !== 'object' || isArray(source) || !Object.getOwnPropertySymbols) {
  578. continue;
  579. }
  580. const symbols = Object.getOwnPropertySymbols(source);
  581. for (let j = 0; j < symbols.length; j++) {
  582. const symbol = symbols[j];
  583. if (propertyIsEnumerable.call(source, symbol)) {
  584. assignValue(source[symbol], symbol);
  585. }
  586. }
  587. }
  588. return result;
  589. }
  590. /**
  591. * Extends object a by mutably adding to it the properties of object b.
  592. *
  593. * @param {Object} a The object to be extended
  594. * @param {Object} b The object to copy properties from
  595. * @param {Object} thisArg The object to bind function to
  596. *
  597. * @param {Object} [options]
  598. * @param {Boolean} [options.allOwnKeys]
  599. * @returns {Object} The resulting value of object a
  600. */
  601. const extend = (a, b, thisArg, {
  602. allOwnKeys
  603. } = {}) => {
  604. forEach(b, (val, key) => {
  605. if (thisArg && isFunction$1(val)) {
  606. Object.defineProperty(a, key, {
  607. // Null-proto descriptor so a polluted Object.prototype.get cannot
  608. // hijack defineProperty's accessor-vs-data resolution.
  609. __proto__: null,
  610. value: bind(val, thisArg),
  611. writable: true,
  612. enumerable: true,
  613. configurable: true
  614. });
  615. } else {
  616. Object.defineProperty(a, key, {
  617. __proto__: null,
  618. value: val,
  619. writable: true,
  620. enumerable: true,
  621. configurable: true
  622. });
  623. }
  624. }, {
  625. allOwnKeys
  626. });
  627. return a;
  628. };
  629. /**
  630. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  631. *
  632. * @param {string} content with BOM
  633. *
  634. * @returns {string} content value without BOM
  635. */
  636. const stripBOM = content => {
  637. if (content.charCodeAt(0) === 0xfeff) {
  638. content = content.slice(1);
  639. }
  640. return content;
  641. };
  642. /**
  643. * Inherit the prototype methods from one constructor into another
  644. * @param {function} constructor
  645. * @param {function} superConstructor
  646. * @param {object} [props]
  647. * @param {object} [descriptors]
  648. *
  649. * @returns {void}
  650. */
  651. const inherits = (constructor, superConstructor, props, descriptors) => {
  652. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  653. Object.defineProperty(constructor.prototype, 'constructor', {
  654. __proto__: null,
  655. value: constructor,
  656. writable: true,
  657. enumerable: false,
  658. configurable: true
  659. });
  660. Object.defineProperty(constructor, 'super', {
  661. __proto__: null,
  662. value: superConstructor.prototype
  663. });
  664. props && Object.assign(constructor.prototype, props);
  665. };
  666. /**
  667. * Resolve object with deep prototype chain to a flat object
  668. * @param {Object} sourceObj source object
  669. * @param {Object} [destObj]
  670. * @param {Function|Boolean} [filter]
  671. * @param {Function} [propFilter]
  672. *
  673. * @returns {Object}
  674. */
  675. const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  676. let props;
  677. let i;
  678. let prop;
  679. const merged = {};
  680. destObj = destObj || {};
  681. // eslint-disable-next-line no-eq-null,eqeqeq
  682. if (sourceObj == null) return destObj;
  683. do {
  684. props = Object.getOwnPropertyNames(sourceObj);
  685. i = props.length;
  686. while (i-- > 0) {
  687. prop = props[i];
  688. if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
  689. destObj[prop] = sourceObj[prop];
  690. merged[prop] = true;
  691. }
  692. }
  693. sourceObj = filter !== false && getPrototypeOf(sourceObj);
  694. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  695. return destObj;
  696. };
  697. /**
  698. * Determines whether a string ends with the characters of a specified string
  699. *
  700. * @param {String} str
  701. * @param {String} searchString
  702. * @param {Number} [position= 0]
  703. *
  704. * @returns {boolean}
  705. */
  706. const endsWith = (str, searchString, position) => {
  707. str = String(str);
  708. if (position === undefined || position > str.length) {
  709. position = str.length;
  710. }
  711. position -= searchString.length;
  712. const lastIndex = str.indexOf(searchString, position);
  713. return lastIndex !== -1 && lastIndex === position;
  714. };
  715. /**
  716. * Returns new array from array like object or null if failed
  717. *
  718. * @param {*} [thing]
  719. *
  720. * @returns {?Array}
  721. */
  722. const toArray = thing => {
  723. if (!thing) return null;
  724. if (isArray(thing)) return thing;
  725. let i = thing.length;
  726. if (!Number.isSafeInteger(i) || i < 0 || i > 0xffffffff) return null;
  727. // Bound the copy by actual indexed properties, including hidden and inherited
  728. // members of array-like collections, rather than by the declared length alone.
  729. const indexes = new Set();
  730. const seen = new Set();
  731. let source = thing;
  732. while (source != null && indexes.size < i) {
  733. if (seen.has(source)) return null;
  734. seen.add(source);
  735. const prototype = getPrototypeOf(source);
  736. if (isPrototypeBoundary(source, prototype, source === thing)) break;
  737. Object.getOwnPropertyNames(source).forEach(key => {
  738. const index = +key;
  739. if (Number.isInteger(index) && index >= 0 && index < i && String(index) === key && hasOwnProperty(source, key)) {
  740. indexes.add(index);
  741. }
  742. });
  743. source = prototype;
  744. }
  745. if (indexes.size !== i) return null;
  746. const arr = new Array(i);
  747. while (i-- > 0) {
  748. arr[i] = thing[i];
  749. }
  750. return arr;
  751. };
  752. /**
  753. * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
  754. * thing passed in is an instance of Uint8Array
  755. *
  756. * @param {TypedArray}
  757. *
  758. * @returns {Array}
  759. */
  760. // eslint-disable-next-line func-names
  761. const isTypedArray = (TypedArray => {
  762. // eslint-disable-next-line func-names
  763. return thing => {
  764. return TypedArray && thing instanceof TypedArray;
  765. };
  766. })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
  767. /**
  768. * For each entry in the object, call the function with the key and value.
  769. *
  770. * @param {Object<any, any>} obj - The object to iterate over.
  771. * @param {Function} fn - The function to call for each entry.
  772. *
  773. * @returns {void}
  774. */
  775. const forEachEntry = (obj, fn) => {
  776. const generator = obj && obj[iterator];
  777. const _iterator = generator.call(obj);
  778. let result;
  779. while ((result = _iterator.next()) && !result.done) {
  780. const pair = result.value;
  781. fn.call(obj, pair[0], pair[1]);
  782. }
  783. };
  784. /**
  785. * It takes a regular expression and a string, and returns an array of all the matches
  786. *
  787. * @param {string} regExp - The regular expression to match against.
  788. * @param {string} str - The string to search.
  789. *
  790. * @returns {Array<boolean>}
  791. */
  792. const matchAll = (regExp, str) => {
  793. let matches;
  794. const arr = [];
  795. while ((matches = regExp.exec(str)) !== null) {
  796. arr.push(matches);
  797. }
  798. return arr;
  799. };
  800. /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
  801. const isHTMLForm = kindOfTest('HTMLFormElement');
  802. const toCamelCase = str => {
  803. return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
  804. return p1.toUpperCase() + p2;
  805. });
  806. };
  807. const {
  808. propertyIsEnumerable
  809. } = Object.prototype;
  810. /**
  811. * Determine if a value is a RegExp object
  812. *
  813. * @param {*} val The value to test
  814. *
  815. * @returns {boolean} True if value is a RegExp object, otherwise false
  816. */
  817. const isRegExp = kindOfTest('RegExp');
  818. const reduceDescriptors = (obj, reducer) => {
  819. const descriptors = Object.getOwnPropertyDescriptors(obj);
  820. const reducedDescriptors = {};
  821. forEach(descriptors, (descriptor, name) => {
  822. let ret;
  823. if ((ret = reducer(descriptor, name, obj)) !== false) {
  824. reducedDescriptors[name] = ret || descriptor;
  825. }
  826. });
  827. Object.defineProperties(obj, reducedDescriptors);
  828. };
  829. /**
  830. * Makes all methods read-only
  831. * @param {Object} obj
  832. */
  833. const freezeMethods = obj => {
  834. reduceDescriptors(obj, (descriptor, name) => {
  835. // skip restricted props in strict mode
  836. if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
  837. return false;
  838. }
  839. const value = obj[name];
  840. if (!isFunction$1(value)) return;
  841. descriptor.enumerable = false;
  842. if ('writable' in descriptor) {
  843. descriptor.writable = false;
  844. return;
  845. }
  846. if (!descriptor.set) {
  847. descriptor.set = () => {
  848. throw Error("Can not rewrite read-only method '" + name + "'");
  849. };
  850. }
  851. });
  852. };
  853. /**
  854. * Converts an array or a delimited string into an object set with values as keys and true as values.
  855. * Useful for fast membership checks.
  856. *
  857. * @param {Array|string} arrayOrString - The array or string to convert.
  858. * @param {string} delimiter - The delimiter to use if input is a string.
  859. * @returns {Object} An object with keys from the array or string, values set to true.
  860. */
  861. const toObjectSet = (arrayOrString, delimiter) => {
  862. const obj = {};
  863. const define = arr => {
  864. arr.forEach(value => {
  865. obj[value] = true;
  866. });
  867. };
  868. isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  869. return obj;
  870. };
  871. const noop = () => {};
  872. const toFiniteNumber = (value, defaultValue) => {
  873. return value != null && Number.isFinite(value = +value) ? value : defaultValue;
  874. };
  875. /**
  876. * If the thing is a FormData object, return true, otherwise return false.
  877. *
  878. * @param {unknown} thing - The thing to check.
  879. *
  880. * @returns {boolean}
  881. */
  882. function isSpecCompliantForm(thing) {
  883. return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
  884. }
  885. /**
  886. * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
  887. *
  888. * @param {Object} obj - The object to convert.
  889. * @returns {Object} The JSON-compatible object.
  890. */
  891. const toJSONObject = obj => {
  892. const visited = new WeakSet();
  893. const visit = source => {
  894. if (isObject(source)) {
  895. if (visited.has(source)) {
  896. return;
  897. }
  898. //Buffer check
  899. if (isBuffer(source)) {
  900. return source;
  901. }
  902. if (!('toJSON' in source)) {
  903. // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
  904. visited.add(source);
  905. let target;
  906. if (isSet(source)) {
  907. target = [];
  908. for (const value of source) {
  909. const reducedValue = visit(value);
  910. !isUndefined(reducedValue) && target.push(reducedValue);
  911. }
  912. } else {
  913. target = isArray(source) ? [] : {};
  914. forEach(source, (value, key) => {
  915. const reducedValue = visit(value);
  916. !isUndefined(reducedValue) && (target[key] = reducedValue);
  917. });
  918. }
  919. visited.delete(source);
  920. return target;
  921. }
  922. }
  923. return source;
  924. };
  925. return visit(obj);
  926. };
  927. /**
  928. * Determines if a value is an async function.
  929. *
  930. * @param {*} thing - The value to test.
  931. * @returns {boolean} True if value is an async function, otherwise false.
  932. */
  933. const isAsyncFn = kindOfTest('AsyncFunction');
  934. /**
  935. * Determines if a value is thenable (has then and catch methods).
  936. *
  937. * @param {*} thing - The value to test.
  938. * @returns {boolean} True if value is thenable, otherwise false.
  939. */
  940. const isThenable = thing => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
  941. // original code
  942. // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
  943. /**
  944. * Provides a cross-platform setImmediate implementation.
  945. * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
  946. *
  947. * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
  948. * @param {boolean} postMessageSupported - Whether postMessage is supported.
  949. * @returns {Function} A function to schedule a callback asynchronously.
  950. */
  951. const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  952. if (setImmediateSupported) {
  953. return setImmediate;
  954. }
  955. return postMessageSupported ? ((token, callbacks) => {
  956. _global.addEventListener('message', ({
  957. source,
  958. data
  959. }) => {
  960. if (source === _global && data === token) {
  961. callbacks.length && callbacks.shift()();
  962. }
  963. }, false);
  964. return cb => {
  965. callbacks.push(cb);
  966. _global.postMessage(token, '*');
  967. };
  968. })(`axios@${Math.random()}`, []) : cb => setTimeout(cb);
  969. })(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
  970. /**
  971. * Schedules a microtask or asynchronous callback as soon as possible.
  972. * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
  973. *
  974. * @type {Function}
  975. */
  976. const asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : typeof process !== 'undefined' && process.nextTick || _setImmediate;
  977. // *********************
  978. const isIterable = thing => thing != null && isFunction$1(thing[iterator]);
  979. /**
  980. * Determine if a value is iterable via an iterator that is NOT sourced solely
  981. * from a polluted Object.prototype. Use this instead of `isIterable` whenever
  982. * the iterable comes from untrusted input (e.g. user-supplied header sources),
  983. * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
  984. * into an attacker-controlled entries iterator.
  985. *
  986. * @param {*} thing The value to test
  987. *
  988. * @returns {boolean} True if value has a non-polluted iterator
  989. */
  990. const isSafeIterable = thing => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
  991. var utils$1 = {
  992. isArray,
  993. isArrayBuffer,
  994. isBuffer,
  995. isFormData,
  996. isArrayBufferView,
  997. isString,
  998. isNumber,
  999. isBoolean,
  1000. isObject,
  1001. isPlainObject,
  1002. isEmptyObject,
  1003. isReadableStream,
  1004. isRequest,
  1005. isResponse,
  1006. isHeaders,
  1007. isUndefined,
  1008. isDate,
  1009. isFile,
  1010. isReactNativeBlob,
  1011. isReactNative,
  1012. isBlob,
  1013. isRegExp,
  1014. isFunction: isFunction$1,
  1015. isStream,
  1016. isURLSearchParams,
  1017. isTypedArray,
  1018. isFileList,
  1019. forEach,
  1020. merge,
  1021. extend,
  1022. trim,
  1023. stripBOM,
  1024. inherits,
  1025. toFlatObject,
  1026. kindOf,
  1027. kindOfTest,
  1028. endsWith,
  1029. toArray,
  1030. forEachEntry,
  1031. matchAll,
  1032. isHTMLForm,
  1033. hasOwnProperty,
  1034. hasOwnProp: hasOwnProperty,
  1035. // an alias to avoid ESLint no-prototype-builtins detection
  1036. hasOwnInPrototypeChain,
  1037. getSafeProp,
  1038. toSafeFlatObject,
  1039. reduceDescriptors,
  1040. freezeMethods,
  1041. toObjectSet,
  1042. toCamelCase,
  1043. noop,
  1044. toFiniteNumber,
  1045. findKey,
  1046. global: _global,
  1047. isContextDefined,
  1048. isSpecCompliantForm,
  1049. toJSONObject,
  1050. isAsyncFn,
  1051. isThenable,
  1052. setImmediate: _setImmediate,
  1053. asap,
  1054. isIterable,
  1055. isSafeIterable
  1056. };
  1057. // RawAxiosHeaders whose duplicates are ignored by node
  1058. // c.f. https://nodejs.org/api/http.html#http_message_headers
  1059. const ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']);
  1060. /**
  1061. * Parse headers into an object
  1062. *
  1063. * ```
  1064. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  1065. * Content-Type: application/json
  1066. * Connection: keep-alive
  1067. * Transfer-Encoding: chunked
  1068. * ```
  1069. *
  1070. * @param {String} rawHeaders Headers needing to be parsed
  1071. *
  1072. * @returns {Object} Headers parsed into an object
  1073. */
  1074. var parseHeaders = rawHeaders => {
  1075. // Header names are data, including __proto__; avoid inherited setters.
  1076. const parsed = Object.create(null);
  1077. let key;
  1078. let val;
  1079. let i;
  1080. rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
  1081. i = line.indexOf(':');
  1082. key = line.substring(0, i).trim().toLowerCase();
  1083. val = line.substring(i + 1).trim();
  1084. const hasKey = utils$1.hasOwnProp(parsed, key);
  1085. if (!key || hasKey && utils$1.hasOwnProp(ignoreDuplicateOf, key)) {
  1086. return;
  1087. }
  1088. if (key === 'set-cookie') {
  1089. if (hasKey) {
  1090. parsed[key].push(val);
  1091. } else {
  1092. parsed[key] = [val];
  1093. }
  1094. } else {
  1095. parsed[key] = hasKey ? parsed[key] + ', ' + val : val;
  1096. }
  1097. });
  1098. return parsed;
  1099. };
  1100. function trimSPorHTAB(str) {
  1101. let start = 0;
  1102. let end = str.length;
  1103. while (start < end) {
  1104. const code = str.charCodeAt(start);
  1105. if (code !== 0x09 && code !== 0x20) {
  1106. break;
  1107. }
  1108. start += 1;
  1109. }
  1110. while (end > start) {
  1111. const code = str.charCodeAt(end - 1);
  1112. if (code !== 0x09 && code !== 0x20) {
  1113. break;
  1114. }
  1115. end -= 1;
  1116. }
  1117. return start === 0 && end === str.length ? str : str.slice(start, end);
  1118. }
  1119. // The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
  1120. // eslint-disable-next-line no-control-regex
  1121. const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
  1122. // eslint-disable-next-line no-control-regex
  1123. const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
  1124. function sanitizeValue(value, invalidChars) {
  1125. if (utils$1.isArray(value)) {
  1126. return value.map(item => sanitizeValue(item, invalidChars));
  1127. }
  1128. return trimSPorHTAB(String(value).replace(invalidChars, ''));
  1129. }
  1130. const sanitizeHeaderValue = value => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
  1131. const sanitizeByteStringHeaderValue = value => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
  1132. function toByteStringHeaderObject(headers) {
  1133. const byteStringHeaders = Object.create(null);
  1134. utils$1.forEach(headers.toJSON(), (value, header) => {
  1135. byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
  1136. });
  1137. return byteStringHeaders;
  1138. }
  1139. const $internals$1 = Symbol('internals');
  1140. function normalizeHeader(header) {
  1141. return header && String(header).trim().toLowerCase();
  1142. }
  1143. function normalizeValue(value) {
  1144. if (value === false || value == null) {
  1145. return value;
  1146. }
  1147. return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
  1148. }
  1149. function parseTokens(str) {
  1150. const tokens = Object.create(null);
  1151. const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  1152. let match;
  1153. while (match = tokensRE.exec(str)) {
  1154. tokens[match[1]] = match[2];
  1155. }
  1156. return tokens;
  1157. }
  1158. const parameterNameRE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  1159. function trimOWS(value) {
  1160. let start = 0;
  1161. let end = value.length;
  1162. while (start < end) {
  1163. const code = value.charCodeAt(start);
  1164. if (code !== 0x09 && code !== 0x20) {
  1165. break;
  1166. }
  1167. start += 1;
  1168. }
  1169. while (end > start) {
  1170. const code = value.charCodeAt(end - 1);
  1171. if (code !== 0x09 && code !== 0x20) {
  1172. break;
  1173. }
  1174. end -= 1;
  1175. }
  1176. return start === 0 && end === value.length ? value : value.slice(start, end);
  1177. }
  1178. function decodeQuotedString(value) {
  1179. const last = value.length - 1;
  1180. if (last < 1 || value.charCodeAt(0) !== 0x22 || value.charCodeAt(last) !== 0x22) {
  1181. return value;
  1182. }
  1183. let decoded = '';
  1184. for (let i = 1; i < last; i++) {
  1185. const code = value.charCodeAt(i);
  1186. if (code === 0x22) {
  1187. return value;
  1188. }
  1189. if (code === 0x5c) {
  1190. i += 1;
  1191. if (i >= last) {
  1192. return value;
  1193. }
  1194. }
  1195. decoded += value[i];
  1196. }
  1197. return decoded;
  1198. }
  1199. function parseParameters(value) {
  1200. const parameters = Object.create(null);
  1201. const str = String(value);
  1202. let start = 0;
  1203. let quoted = false;
  1204. let escaped = false;
  1205. function parseParameter(end) {
  1206. const part = trimOWS(str.slice(start, end));
  1207. const equals = part.indexOf('=');
  1208. if (equals < 1) {
  1209. return;
  1210. }
  1211. const name = trimOWS(part.slice(0, equals));
  1212. if (!parameterNameRE.test(name)) {
  1213. return;
  1214. }
  1215. const normalizedName = name.toLowerCase();
  1216. if (normalizedName === '__proto__' || normalizedName === 'constructor' || normalizedName === 'prototype') {
  1217. return;
  1218. }
  1219. const parameterValue = trimOWS(part.slice(equals + 1));
  1220. parameters[normalizedName] = decodeQuotedString(parameterValue);
  1221. }
  1222. for (let i = 0; i < str.length; i++) {
  1223. const code = str.charCodeAt(i);
  1224. if (quoted) {
  1225. if (escaped) {
  1226. escaped = false;
  1227. } else if (code === 0x5c) {
  1228. escaped = true;
  1229. } else if (code === 0x22) {
  1230. quoted = false;
  1231. }
  1232. } else if (code === 0x22) {
  1233. quoted = true;
  1234. } else if (code === 0x2c || code === 0x3b) {
  1235. parseParameter(i);
  1236. start = i + 1;
  1237. }
  1238. }
  1239. parseParameter(str.length);
  1240. return parameters;
  1241. }
  1242. const isValidHeaderName = str => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
  1243. // `__proto__` is a valid field name, and the one name the uppercase mapping at
  1244. // the bottom of this file cannot reach: it is inherited from Object.prototype
  1245. // instead of being declared on AxiosHeaders.prototype, so `self.__proto__ = v`
  1246. // runs the inherited setter. That silently discards the header, and an array
  1247. // value replaces the instance prototype, taking every method with it.
  1248. // Store it under the same kind of case variant that mapping uses for `set` and
  1249. // `constructor`. Header lookup is caseless, so it reads back under either
  1250. // spelling, and no own `__proto__` slot is ever created for a later
  1251. // `Object.assign` to copy onto a plain object through the same setter.
  1252. const PROTO_HEADER_SLOT = '__Proto__';
  1253. const headerSlot = name => name === '__proto__' ? PROTO_HEADER_SLOT : name;
  1254. function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  1255. if (utils$1.isFunction(filter)) {
  1256. return filter.call(context, value, header);
  1257. }
  1258. if (isHeaderNameFilter) {
  1259. value = header;
  1260. }
  1261. if (!utils$1.isString(value)) return;
  1262. if (utils$1.isString(filter)) {
  1263. return value.indexOf(filter) !== -1;
  1264. }
  1265. if (utils$1.isRegExp(filter)) {
  1266. return filter.test(value);
  1267. }
  1268. }
  1269. function formatHeader(header) {
  1270. return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
  1271. return char.toUpperCase() + str;
  1272. });
  1273. }
  1274. function buildAccessors(obj, header) {
  1275. const accessorName = utils$1.toCamelCase(' ' + header);
  1276. ['get', 'set', 'has'].forEach(methodName => {
  1277. Object.defineProperty(obj, methodName + accessorName, {
  1278. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  1279. // this data descriptor into an accessor descriptor on the way in.
  1280. __proto__: null,
  1281. value: function (arg1, arg2, arg3) {
  1282. return this[methodName].call(this, header, arg1, arg2, arg3);
  1283. },
  1284. configurable: true
  1285. });
  1286. });
  1287. }
  1288. class AxiosHeaders {
  1289. constructor(headers) {
  1290. headers && this.set(headers);
  1291. }
  1292. set(header, valueOrRewrite, rewrite) {
  1293. const self = this;
  1294. function setHeader(_value, _header, _rewrite) {
  1295. const lHeader = normalizeHeader(_header);
  1296. if (!lHeader) {
  1297. return;
  1298. }
  1299. const key = utils$1.findKey(self, lHeader);
  1300. if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
  1301. self[headerSlot(key || _header)] = normalizeValue(_value);
  1302. }
  1303. }
  1304. const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
  1305. if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
  1306. setHeaders(header, valueOrRewrite);
  1307. } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
  1308. setHeaders(parseHeaders(header), valueOrRewrite);
  1309. } else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
  1310. let obj = Object.create(null),
  1311. dest,
  1312. key;
  1313. for (const entry of header) {
  1314. if (!utils$1.isArray(entry)) {
  1315. throw new TypeError('Object iterator must return a key-value pair');
  1316. }
  1317. key = entry[0];
  1318. if (utils$1.hasOwnProp(obj, key)) {
  1319. dest = obj[key];
  1320. obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
  1321. } else {
  1322. obj[key] = entry[1];
  1323. }
  1324. }
  1325. setHeaders(obj, valueOrRewrite);
  1326. } else {
  1327. header != null && setHeader(valueOrRewrite, header, rewrite);
  1328. }
  1329. return this;
  1330. }
  1331. get(header, parser) {
  1332. header = normalizeHeader(header);
  1333. if (header) {
  1334. const key = utils$1.findKey(this, header);
  1335. if (key) {
  1336. const value = this[key];
  1337. if (!parser) {
  1338. return value;
  1339. }
  1340. if (parser === true) {
  1341. return parseTokens(value);
  1342. }
  1343. if (utils$1.isFunction(parser)) {
  1344. return parser.call(this, value, key);
  1345. }
  1346. if (utils$1.isRegExp(parser)) {
  1347. return parser.exec(value);
  1348. }
  1349. throw new TypeError('parser must be boolean|regexp|function');
  1350. }
  1351. }
  1352. }
  1353. has(header, matcher) {
  1354. header = normalizeHeader(header);
  1355. if (header) {
  1356. const key = utils$1.findKey(this, header);
  1357. return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
  1358. }
  1359. return false;
  1360. }
  1361. delete(header, matcher) {
  1362. const self = this;
  1363. let deleted = false;
  1364. function deleteHeader(_header) {
  1365. _header = normalizeHeader(_header);
  1366. if (_header) {
  1367. const key = utils$1.findKey(self, _header);
  1368. if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
  1369. delete self[key];
  1370. deleted = true;
  1371. }
  1372. }
  1373. }
  1374. if (utils$1.isArray(header)) {
  1375. header.forEach(deleteHeader);
  1376. } else {
  1377. deleteHeader(header);
  1378. }
  1379. return deleted;
  1380. }
  1381. clear(matcher) {
  1382. const keys = Object.keys(this);
  1383. let i = keys.length;
  1384. let deleted = false;
  1385. while (i--) {
  1386. const key = keys[i];
  1387. if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
  1388. delete this[key];
  1389. deleted = true;
  1390. }
  1391. }
  1392. return deleted;
  1393. }
  1394. normalize(format) {
  1395. const self = this;
  1396. const headers = Object.create(null);
  1397. utils$1.forEach(this, (value, header) => {
  1398. const key = utils$1.findKey(headers, header);
  1399. if (key) {
  1400. self[key] = normalizeValue(value);
  1401. delete self[header];
  1402. return;
  1403. }
  1404. const normalized = headerSlot(format ? formatHeader(header) : String(header).trim());
  1405. if (normalized !== header) {
  1406. delete self[header];
  1407. }
  1408. self[normalized] = normalizeValue(value);
  1409. headers[normalized] = true;
  1410. });
  1411. return this;
  1412. }
  1413. concat(...targets) {
  1414. return this.constructor.concat(this, ...targets);
  1415. }
  1416. toJSON(asStrings) {
  1417. const obj = Object.create(null);
  1418. utils$1.forEach(this, (value, header) => {
  1419. value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
  1420. });
  1421. return obj;
  1422. }
  1423. [Symbol.iterator]() {
  1424. return Object.entries(this.toJSON())[Symbol.iterator]();
  1425. }
  1426. toString() {
  1427. return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  1428. }
  1429. getSetCookie() {
  1430. const value = this.get('set-cookie');
  1431. return utils$1.isArray(value) ? value : value == null || value === false ? [] : [value];
  1432. }
  1433. get [Symbol.toStringTag]() {
  1434. return 'AxiosHeaders';
  1435. }
  1436. static from(thing) {
  1437. return thing instanceof this ? thing : new this(thing);
  1438. }
  1439. static parseParameters(value) {
  1440. return parseParameters(value);
  1441. }
  1442. static concat(first, ...targets) {
  1443. const computed = new this(first);
  1444. targets.forEach(target => computed.set(target));
  1445. return computed;
  1446. }
  1447. static accessor(header) {
  1448. const internals = this[$internals$1] = this[$internals$1] = {
  1449. accessors: {}
  1450. };
  1451. const accessors = internals.accessors;
  1452. const prototype = this.prototype;
  1453. function defineAccessor(_header) {
  1454. const lHeader = normalizeHeader(_header);
  1455. if (!accessors[lHeader]) {
  1456. buildAccessors(prototype, _header);
  1457. accessors[lHeader] = true;
  1458. }
  1459. }
  1460. utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
  1461. return this;
  1462. }
  1463. }
  1464. AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
  1465. // reserved names hotfix
  1466. utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
  1467. value
  1468. }, key) => {
  1469. let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  1470. return {
  1471. get: () => value,
  1472. set(headerValue) {
  1473. this[mapped] = headerValue;
  1474. }
  1475. };
  1476. });
  1477. utils$1.freezeMethods(AxiosHeaders);
  1478. const REDACTED = '[REDACTED ****]';
  1479. function hasOwnOrPrototypeToJSON(source) {
  1480. if (utils$1.hasOwnProp(source, 'toJSON')) {
  1481. return true;
  1482. }
  1483. let prototype = Object.getPrototypeOf(source);
  1484. while (prototype && prototype !== Object.prototype) {
  1485. if (utils$1.hasOwnProp(prototype, 'toJSON')) {
  1486. return true;
  1487. }
  1488. prototype = Object.getPrototypeOf(prototype);
  1489. }
  1490. return false;
  1491. }
  1492. // Build a plain-object snapshot of `config` and replace the value of any key
  1493. // (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
  1494. // and AxiosHeaders, and short-circuits on circular references.
  1495. function redactConfig(config, redactKeys) {
  1496. const lowerKeys = new Set(redactKeys.map(k => String(k).toLowerCase()));
  1497. const seen = [];
  1498. const visit = source => {
  1499. if (source === null || typeof source !== 'object') return source;
  1500. if (utils$1.isBuffer(source)) return source;
  1501. if (seen.indexOf(source) !== -1) return undefined;
  1502. if (source instanceof AxiosHeaders) {
  1503. source = source.toJSON();
  1504. }
  1505. seen.push(source);
  1506. let result;
  1507. if (utils$1.isArray(source)) {
  1508. result = [];
  1509. source.forEach((v, i) => {
  1510. const reducedValue = visit(v);
  1511. if (!utils$1.isUndefined(reducedValue)) {
  1512. result[i] = reducedValue;
  1513. }
  1514. });
  1515. } else {
  1516. if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
  1517. seen.pop();
  1518. return source;
  1519. }
  1520. result = Object.create(null);
  1521. for (const [key, value] of Object.entries(source)) {
  1522. const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
  1523. if (!utils$1.isUndefined(reducedValue)) {
  1524. result[key] = reducedValue;
  1525. }
  1526. }
  1527. }
  1528. seen.pop();
  1529. return result;
  1530. };
  1531. return visit(config);
  1532. }
  1533. function stringifySafely$1(value) {
  1534. try {
  1535. return String(value);
  1536. } catch (err) {
  1537. return '';
  1538. }
  1539. }
  1540. function aggregateErrorMessage(error) {
  1541. const message = error.errors.map(entry => {
  1542. try {
  1543. return entry && entry.message ? stringifySafely$1(entry.message) : stringifySafely$1(entry);
  1544. } catch (err) {
  1545. return '';
  1546. }
  1547. }).filter(Boolean).join('; ');
  1548. return message || error.name || 'AggregateError';
  1549. }
  1550. // Shared with `Axios.prototype.request`, which splices the reconstructed
  1551. // caller frames in ahead of this marker.
  1552. const CAUSED_BY_SEPARATOR = '\nCaused by: ';
  1553. const $causeStack = Symbol('causeStack');
  1554. // Match the section we appended, not marker-like text in an error message or
  1555. // a replacement stack supplied by the caller. Do not re-read the cause's stack.
  1556. function getCauseStackIndex(error, stack) {
  1557. const causeStack = utils$1.hasOwnProp(error, $causeStack) && error[$causeStack];
  1558. return causeStack && stack.endsWith(causeStack) ? stack.length - causeStack.length : -1;
  1559. }
  1560. /**
  1561. * Append the stack of a wrapped error to `target.stack`.
  1562. *
  1563. * `cause` already exposes the original error for tooling that walks the standard
  1564. * cause chain, but many error reporters read `stack` and nothing else. Inlining
  1565. * the wrapped stack there means those reporters surface the underlying failure
  1566. * instead of the axios frames that normalized it (see #6670).
  1567. *
  1568. * Every read is defensive: a custom `Error.prepareStackTrace` hook, a runtime
  1569. * without stack support, or a replaced `stack` property can leave the value
  1570. * missing, non-string, or read-only, and normalizing an error must not throw
  1571. * because of that.
  1572. *
  1573. * @param {Error} target The AxiosError being built.
  1574. * @param {Error} source The error being wrapped.
  1575. *
  1576. * @returns {void}
  1577. */
  1578. function appendCauseStack(target, source) {
  1579. try {
  1580. const sourceStack = source && source.stack;
  1581. if (typeof sourceStack !== 'string' || !sourceStack) {
  1582. return;
  1583. }
  1584. const targetStack = target.stack;
  1585. if (typeof targetStack !== 'string' || !targetStack) {
  1586. return;
  1587. }
  1588. // Each call to `from()` creates a fresh target. Re-wrapping includes the
  1589. // previous stack verbatim, adding one cause section per wrap.
  1590. const causeStack = CAUSED_BY_SEPARATOR + sourceStack;
  1591. target.stack = targetStack + causeStack;
  1592. Object.defineProperty(target, $causeStack, {
  1593. __proto__: null,
  1594. value: causeStack
  1595. });
  1596. } catch (e) {
  1597. // Ignore failures from custom stack hooks or un-writable stack properties.
  1598. }
  1599. }
  1600. class AxiosError extends Error {
  1601. static from(error, code, config, request, response, customProps) {
  1602. // `AggregateError` (thrown by Node on dual-stack/Happy-Eyeballs connection
  1603. // failures) has an empty `message`; its detail lives in `errors[]`. Without
  1604. // this, the wrapped error surfaces with a blank message (see #6721).
  1605. let message = error.message;
  1606. if (!message && utils$1.isArray(error.errors) && error.errors.length) {
  1607. message = aggregateErrorMessage(error);
  1608. }
  1609. const axiosError = new AxiosError(message, code || error.code, config, request, response);
  1610. // Match native `Error` `cause` semantics: non-enumerable. The wrapped
  1611. // error often carries circular internals (sockets, requests, agents), so
  1612. // an enumerable `cause` makes structured loggers (pino/winston) and any
  1613. // own-property walk throw "Converting circular structure to JSON".
  1614. // Regression from #6982; see #7205. `__proto__: null` mirrors the
  1615. // `message` descriptor below (prototype-pollution-safe descriptor).
  1616. Object.defineProperty(axiosError, 'cause', {
  1617. __proto__: null,
  1618. value: error,
  1619. writable: true,
  1620. enumerable: false,
  1621. configurable: true
  1622. });
  1623. axiosError.name = error.name;
  1624. // Inline the wrapped stack for reporters that read only `stack`; the `cause`
  1625. // property above already covers cause-aware tooling.
  1626. appendCauseStack(axiosError, error);
  1627. // Preserve status from the original error if not already set from response
  1628. if (error.status != null && axiosError.status == null) {
  1629. axiosError.status = error.status;
  1630. }
  1631. customProps && Object.assign(axiosError, customProps);
  1632. return axiosError;
  1633. }
  1634. /**
  1635. * Create an Error with the specified message, config, error code, request and response.
  1636. *
  1637. * @param {string} message The error message.
  1638. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1639. * @param {Object} [config] The config.
  1640. * @param {Object} [request] The request.
  1641. * @param {Object} [response] The response.
  1642. *
  1643. * @returns {Error} The created error.
  1644. */
  1645. constructor(message, code, config, request, response) {
  1646. super(message);
  1647. // Make message enumerable to maintain backward compatibility
  1648. // The native Error constructor sets message as non-enumerable,
  1649. // but axios < v1.13.3 had it as enumerable
  1650. Object.defineProperty(this, 'message', {
  1651. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  1652. // this data descriptor into an accessor descriptor on the way in.
  1653. __proto__: null,
  1654. value: message,
  1655. enumerable: true,
  1656. writable: true,
  1657. configurable: true
  1658. });
  1659. this.name = 'AxiosError';
  1660. this.isAxiosError = true;
  1661. code && (this.code = code);
  1662. config && (this.config = config);
  1663. request && (this.request = request);
  1664. if (response) {
  1665. this.response = response;
  1666. this.status = response.status;
  1667. }
  1668. }
  1669. toJSON() {
  1670. // Opt-in redaction: when the request config carries a `redact` array, the
  1671. // value of any matching key (case-insensitive, at any depth) is replaced
  1672. // with REDACTED in the serialized snapshot. Undefined or empty leaves the
  1673. // existing serialization behavior unchanged.
  1674. const config = this.config;
  1675. const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
  1676. const serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils$1.toJSONObject(config);
  1677. return {
  1678. // Standard
  1679. message: this.message,
  1680. name: this.name,
  1681. // Microsoft
  1682. description: this.description,
  1683. number: this.number,
  1684. // Mozilla
  1685. fileName: this.fileName,
  1686. lineNumber: this.lineNumber,
  1687. columnNumber: this.columnNumber,
  1688. stack: this.stack,
  1689. // Axios
  1690. config: serializedConfig,
  1691. code: this.code,
  1692. status: this.status
  1693. };
  1694. }
  1695. }
  1696. // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
  1697. AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
  1698. AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
  1699. AxiosError.ECONNABORTED = 'ECONNABORTED';
  1700. AxiosError.ETIMEDOUT = 'ETIMEDOUT';
  1701. AxiosError.ECONNREFUSED = 'ECONNREFUSED';
  1702. AxiosError.ERR_NETWORK = 'ERR_NETWORK';
  1703. AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
  1704. AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
  1705. AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
  1706. AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
  1707. AxiosError.ERR_CANCELED = 'ERR_CANCELED';
  1708. AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
  1709. AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
  1710. AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
  1711. var PlatformBuffer = {
  1712. isBufferAvailable() {
  1713. return typeof Buffer !== 'undefined';
  1714. },
  1715. from(value) {
  1716. return Buffer.from(value);
  1717. }
  1718. };
  1719. // Default nesting limit shared with the inverse transform (formDataToJSON) so
  1720. // the FormData <-> JSON round-trip stays symmetric.
  1721. const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
  1722. /**
  1723. * Determines if the given thing is a array or js object.
  1724. *
  1725. * @param {string} thing - The object or array to be visited.
  1726. *
  1727. * @returns {boolean}
  1728. */
  1729. function isVisitable(thing) {
  1730. return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
  1731. }
  1732. /**
  1733. * It removes the brackets from the end of a string
  1734. *
  1735. * @param {string} key - The key of the parameter.
  1736. *
  1737. * @returns {string} the key without the brackets.
  1738. */
  1739. function removeBrackets(key) {
  1740. return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
  1741. }
  1742. /**
  1743. * It takes a path, a key, and a boolean, and returns a string
  1744. *
  1745. * @param {string} path - The path to the current key.
  1746. * @param {string} key - The key of the current object being iterated over.
  1747. * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
  1748. *
  1749. * @returns {string} The path to the current key.
  1750. */
  1751. function renderKey(path, key, dots) {
  1752. if (!path) return key;
  1753. return path.concat(key).map(function each(token, i) {
  1754. // eslint-disable-next-line no-param-reassign
  1755. token = removeBrackets(token);
  1756. return !dots && i ? '[' + token + ']' : token;
  1757. }).join(dots ? '.' : '');
  1758. }
  1759. /**
  1760. * If the array is an array and none of its elements are visitable, then it's a flat array.
  1761. *
  1762. * @param {Array<any>} arr - The array to check
  1763. *
  1764. * @returns {boolean}
  1765. */
  1766. function isFlatArray(arr) {
  1767. return utils$1.isArray(arr) && !arr.some(isVisitable);
  1768. }
  1769. const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
  1770. return /^is[A-Z]/.test(prop);
  1771. });
  1772. /**
  1773. * Convert a data object to FormData
  1774. *
  1775. * @param {Object} obj
  1776. * @param {?Object} [formData]
  1777. * @param {?Object} [options]
  1778. * @param {Function} [options.visitor]
  1779. * @param {Boolean} [options.metaTokens = true]
  1780. * @param {Boolean} [options.dots = false]
  1781. * @param {?Boolean} [options.indexes = false]
  1782. *
  1783. * @returns {Object}
  1784. **/
  1785. /**
  1786. * It converts an object into a FormData object
  1787. *
  1788. * @param {Object<any, any>} obj - The object to convert to form data.
  1789. * @param {string} formData - The FormData object to append to.
  1790. * @param {Object<string, any>} options
  1791. *
  1792. * @returns
  1793. */
  1794. function toFormData(obj, formData, options) {
  1795. if (!utils$1.isObject(obj)) {
  1796. throw new TypeError('target must be an object');
  1797. }
  1798. // eslint-disable-next-line no-param-reassign
  1799. formData = formData || new (FormData$1 || FormData)();
  1800. const option = (name, fallback) => {
  1801. const value = utils$1.getSafeProp(options, name);
  1802. return utils$1.isUndefined(value) ? fallback : value;
  1803. };
  1804. const metaTokens = option('metaTokens', true);
  1805. // eslint-disable-next-line no-use-before-define
  1806. const visitor = option('visitor') || defaultVisitor;
  1807. const dots = option('dots', false);
  1808. const indexes = option('indexes', false);
  1809. const _Blob = option('Blob') || typeof Blob !== 'undefined' && Blob;
  1810. const maxDepth = option('maxDepth', DEFAULT_FORM_DATA_MAX_DEPTH);
  1811. const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
  1812. const stack = [];
  1813. if (!utils$1.isFunction(visitor)) {
  1814. throw new TypeError('visitor must be a function');
  1815. }
  1816. function convertValue(value) {
  1817. if (value === null) return '';
  1818. if (utils$1.isDate(value)) {
  1819. return value.toISOString();
  1820. }
  1821. if (utils$1.isBoolean(value)) {
  1822. return value.toString();
  1823. }
  1824. if (!useBlob && utils$1.isBlob(value)) {
  1825. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  1826. }
  1827. if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
  1828. if (useBlob && typeof _Blob === 'function') {
  1829. return new _Blob([value]);
  1830. }
  1831. if (PlatformBuffer && PlatformBuffer.isBufferAvailable()) {
  1832. return PlatformBuffer.from(value);
  1833. }
  1834. throw new AxiosError('Blob is not supported. Use a Buffer instead.', AxiosError.ERR_NOT_SUPPORT);
  1835. }
  1836. return value;
  1837. }
  1838. function throwIfMaxDepthExceeded(depth) {
  1839. if (depth > maxDepth) {
  1840. throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
  1841. }
  1842. }
  1843. function stringifyWithDepthLimit(value, depth) {
  1844. if (maxDepth === Infinity) {
  1845. return JSON.stringify(value);
  1846. }
  1847. const ancestors = [];
  1848. return JSON.stringify(value, function limitDepth(_key, currentValue) {
  1849. if (!utils$1.isObject(currentValue)) {
  1850. return currentValue;
  1851. }
  1852. while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
  1853. ancestors.pop();
  1854. }
  1855. ancestors.push(currentValue);
  1856. throwIfMaxDepthExceeded(depth + ancestors.length - 1);
  1857. return currentValue;
  1858. });
  1859. }
  1860. /**
  1861. * Default visitor.
  1862. *
  1863. * @param {*} value
  1864. * @param {String|Number} key
  1865. * @param {Array<String|Number>} path
  1866. * @this {FormData}
  1867. *
  1868. * @returns {boolean} return true to visit the each prop of the value recursively
  1869. */
  1870. function defaultVisitor(value, key, path) {
  1871. let arr = value;
  1872. if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
  1873. formData.append(renderKey(path, key, dots), convertValue(value));
  1874. return false;
  1875. }
  1876. if (value && !path && typeof value === 'object') {
  1877. if (utils$1.endsWith(key, '{}')) {
  1878. // eslint-disable-next-line no-param-reassign
  1879. key = metaTokens ? key : key.slice(0, -2);
  1880. // eslint-disable-next-line no-param-reassign
  1881. value = stringifyWithDepthLimit(value, 1);
  1882. } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
  1883. // eslint-disable-next-line no-param-reassign
  1884. key = removeBrackets(key);
  1885. arr.forEach(function each(el, index) {
  1886. !(utils$1.isUndefined(el) || el === null) && formData.append(
  1887. // eslint-disable-next-line no-nested-ternary
  1888. indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
  1889. });
  1890. return false;
  1891. }
  1892. }
  1893. if (isVisitable(value)) {
  1894. return true;
  1895. }
  1896. formData.append(renderKey(path, key, dots), convertValue(value));
  1897. return false;
  1898. }
  1899. const exposedHelpers = Object.assign(predicates, {
  1900. defaultVisitor,
  1901. convertValue,
  1902. isVisitable
  1903. });
  1904. function build(value, path, depth = 0) {
  1905. if (utils$1.isUndefined(value)) return;
  1906. throwIfMaxDepthExceeded(depth);
  1907. if (stack.indexOf(value) !== -1) {
  1908. throw new Error('Circular reference detected in ' + path.join('.'));
  1909. }
  1910. stack.push(value);
  1911. utils$1.forEach(value, function each(el, key) {
  1912. const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
  1913. if (result === true) {
  1914. build(el, path ? path.concat(key) : [key], depth + 1);
  1915. }
  1916. });
  1917. stack.pop();
  1918. }
  1919. if (!utils$1.isObject(obj)) {
  1920. throw new TypeError('data must be an object');
  1921. }
  1922. build(obj);
  1923. return formData;
  1924. }
  1925. /**
  1926. * It encodes a string by replacing all characters that are not in the unreserved set with
  1927. * their percent-encoded equivalents
  1928. *
  1929. * @param {string} str - The string to encode.
  1930. *
  1931. * @returns {string} The encoded string.
  1932. */
  1933. function encode$1(str) {
  1934. const charMap = {
  1935. '!': '%21',
  1936. "'": '%27',
  1937. '(': '%28',
  1938. ')': '%29',
  1939. '~': '%7E',
  1940. '%20': '+'
  1941. };
  1942. return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
  1943. return charMap[match];
  1944. });
  1945. }
  1946. /**
  1947. * It takes a params object and converts it to a FormData object
  1948. *
  1949. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  1950. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  1951. *
  1952. * @returns {void}
  1953. */
  1954. function AxiosURLSearchParams(params, options) {
  1955. this._pairs = [];
  1956. params && toFormData(params, this, options);
  1957. }
  1958. const prototype = AxiosURLSearchParams.prototype;
  1959. prototype.append = function append(name, value) {
  1960. this._pairs.push([name, value]);
  1961. };
  1962. prototype.toString = function toString(encoder) {
  1963. const _encode = encoder ? value => encoder.call(this, value, encode$1) : encode$1;
  1964. return this._pairs.map(function each(pair) {
  1965. return _encode(pair[0]) + '=' + _encode(pair[1]);
  1966. }, '').join('&');
  1967. };
  1968. /**
  1969. * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
  1970. * their plain counterparts (`:`, `$`, `,`, `+`).
  1971. *
  1972. * @param {string} val The value to be encoded.
  1973. *
  1974. * @returns {string} The encoded value.
  1975. */
  1976. function encode(val) {
  1977. return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
  1978. }
  1979. /**
  1980. * Build a URL by appending params to the end
  1981. *
  1982. * @param {string} url The base of the url (e.g., http://www.google.com)
  1983. * @param {object} [params] The params to be appended
  1984. * @param {?(object|Function)} options
  1985. *
  1986. * @returns {string} The formatted url
  1987. */
  1988. function buildURL(url, params, options) {
  1989. if (!params) {
  1990. return url;
  1991. }
  1992. url = url || '';
  1993. const _options = utils$1.isFunction(options) ? {
  1994. serialize: options
  1995. } : options;
  1996. // Read serializer options pollution-safely: own properties and methods on a
  1997. // class/template prototype are honored, but values injected onto a polluted
  1998. // Object.prototype are ignored.
  1999. const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
  2000. const serializeFn = utils$1.getSafeProp(_options, 'serialize');
  2001. let serializedParams;
  2002. if (serializeFn) {
  2003. serializedParams = serializeFn(params, _options);
  2004. } else {
  2005. serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
  2006. }
  2007. if (serializedParams) {
  2008. const hashmarkIndex = url.indexOf('#');
  2009. if (hashmarkIndex !== -1) {
  2010. url = url.slice(0, hashmarkIndex);
  2011. }
  2012. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  2013. }
  2014. return url;
  2015. }
  2016. const $internals = Symbol('internals');
  2017. // `handlers` is public and may be replaced with a nullish value by user code;
  2018. // `clear()` has always tolerated that. Treat it as an empty stack rather than
  2019. // dereferencing it.
  2020. function countHandlers(handlers) {
  2021. return handlers ? handlers.length : 0;
  2022. }
  2023. function trimHandlers(handlers) {
  2024. if (!handlers) {
  2025. return;
  2026. }
  2027. while (handlers.length && handlers[handlers.length - 1] === null) {
  2028. handlers.pop();
  2029. }
  2030. }
  2031. // Preserve the array-key coercion used before IDs were stored in a Map, without
  2032. // treating null, empty strings, or noncanonical numeric strings as ID zero.
  2033. function normalizeHandlerId(id) {
  2034. if (typeof id === 'string' && id !== '' && String(Number(id)) === id) {
  2035. return Number(id);
  2036. }
  2037. return id;
  2038. }
  2039. function syncHandlerEntries(manager, internals) {
  2040. const handlers = manager.handlers;
  2041. const length = countHandlers(handlers);
  2042. if (handlers !== internals.handlersRef) {
  2043. internals.handlersRef = handlers;
  2044. internals.handlerEntries.clear();
  2045. } else if (length !== internals.handlersLength) {
  2046. if (!length) {
  2047. internals.handlerEntries.clear();
  2048. } else {
  2049. internals.handlerEntries.forEach(function removeStaleEntry(entry, id) {
  2050. if (handlers[entry.index] !== entry.handler) {
  2051. internals.handlerEntries.delete(id);
  2052. }
  2053. });
  2054. }
  2055. }
  2056. internals.handlersLength = length;
  2057. }
  2058. class InterceptorManager {
  2059. constructor() {
  2060. this.handlers = [];
  2061. this[$internals] = {
  2062. handlersRef: this.handlers,
  2063. handlersLength: this.handlers.length,
  2064. handlerEntries: new Map(),
  2065. iterationDepth: 0,
  2066. nextId: 0
  2067. };
  2068. }
  2069. /**
  2070. * Add a new interceptor to the stack
  2071. *
  2072. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  2073. * @param {Function} rejected The function to handle `reject` for a `Promise`
  2074. * @param {Object} options The options for the interceptor, synchronous and runWhen
  2075. *
  2076. * @return {Number} An ID used to remove interceptor later
  2077. */
  2078. use(fulfilled, rejected, options) {
  2079. const handler = {
  2080. fulfilled,
  2081. rejected,
  2082. synchronous: options ? options.synchronous : false,
  2083. runWhen: options ? options.runWhen : null
  2084. };
  2085. const internals = this[$internals];
  2086. if (this.handlers == null) {
  2087. this.handlers = [];
  2088. }
  2089. syncHandlerEntries(this, internals);
  2090. const id = internals.nextId++;
  2091. this.handlers.push(handler);
  2092. internals.handlerEntries.set(id, {
  2093. handler,
  2094. index: this.handlers.length - 1
  2095. });
  2096. internals.handlersLength = this.handlers.length;
  2097. return id;
  2098. }
  2099. /**
  2100. * Remove an interceptor from the stack
  2101. *
  2102. * @param {Number} id The ID that was returned by `use`
  2103. *
  2104. * @returns {void}
  2105. */
  2106. eject(id) {
  2107. const internals = this[$internals];
  2108. syncHandlerEntries(this, internals);
  2109. const handlerId = normalizeHandlerId(id);
  2110. const entry = internals.handlerEntries.get(handlerId);
  2111. if (entry) {
  2112. internals.handlerEntries.delete(handlerId);
  2113. // Ignore IDs invalidated by clear or direct replacement of handlers.
  2114. if (this.handlers[entry.index] !== entry.handler) {
  2115. return;
  2116. }
  2117. this.handlers[entry.index] = null;
  2118. // Do not reuse an index while forEach is walking its length snapshot.
  2119. if (!internals.iterationDepth) {
  2120. trimHandlers(this.handlers);
  2121. internals.handlersLength = this.handlers.length;
  2122. }
  2123. }
  2124. }
  2125. /**
  2126. * Clear all interceptors from the stack
  2127. *
  2128. * @returns {void}
  2129. */
  2130. clear() {
  2131. if (this.handlers) {
  2132. this.handlers = [];
  2133. syncHandlerEntries(this, this[$internals]);
  2134. }
  2135. }
  2136. /**
  2137. * Iterate over all the registered interceptors
  2138. *
  2139. * This method is particularly useful for skipping over any
  2140. * interceptors that may have become `null` calling `eject`.
  2141. *
  2142. * @param {Function} fn The function to call for each interceptor
  2143. *
  2144. * @returns {void}
  2145. */
  2146. forEach(fn) {
  2147. const internals = this[$internals];
  2148. syncHandlerEntries(this, internals);
  2149. internals.iterationDepth++;
  2150. try {
  2151. utils$1.forEach(this.handlers, function forEachHandler(h) {
  2152. if (h !== null) {
  2153. fn(h);
  2154. }
  2155. });
  2156. } finally {
  2157. if (! --internals.iterationDepth) {
  2158. syncHandlerEntries(this, internals);
  2159. trimHandlers(this.handlers);
  2160. internals.handlersLength = countHandlers(this.handlers);
  2161. }
  2162. }
  2163. }
  2164. }
  2165. var transitionalDefaults = {
  2166. silentJSONParsing: true,
  2167. forcedJSONParsing: true,
  2168. clarifyTimeoutError: false,
  2169. legacyInterceptorReqResOrdering: true,
  2170. advertiseZstdAcceptEncoding: false,
  2171. validateStatusUndefinedResolves: true,
  2172. encodeBasicAuthUsername: false
  2173. };
  2174. var URLSearchParams = url.URLSearchParams;
  2175. const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
  2176. const DIGIT = '0123456789';
  2177. const ALPHABET = {
  2178. DIGIT,
  2179. ALPHA,
  2180. ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
  2181. };
  2182. const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
  2183. let str = '';
  2184. const {
  2185. length
  2186. } = alphabet;
  2187. const randomValues = new Uint32Array(size);
  2188. crypto.randomFillSync(randomValues);
  2189. for (let i = 0; i < size; i++) {
  2190. str += alphabet[randomValues[i] % length];
  2191. }
  2192. return str;
  2193. };
  2194. var platform$1 = {
  2195. isNode: true,
  2196. classes: {
  2197. URLSearchParams,
  2198. FormData: FormData$1,
  2199. Blob: typeof Blob !== 'undefined' && Blob || null
  2200. },
  2201. ALPHABET,
  2202. generateString,
  2203. protocols: ['http', 'https', 'file', 'data']
  2204. };
  2205. const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
  2206. const _navigator = typeof navigator === 'object' && navigator || undefined;
  2207. /**
  2208. * Determine if we're running in a standard browser environment
  2209. *
  2210. * This allows axios to run in a web worker, and react-native.
  2211. * Both environments support XMLHttpRequest, but not fully standard globals.
  2212. *
  2213. * web workers:
  2214. * typeof window -> undefined
  2215. * typeof document -> undefined
  2216. *
  2217. * react-native:
  2218. * navigator.product -> 'ReactNative'
  2219. * nativescript
  2220. * navigator.product -> 'NativeScript' or 'NS'
  2221. *
  2222. * @returns {boolean}
  2223. */
  2224. const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
  2225. /**
  2226. * Determine if we're running in a standard browser webWorker environment
  2227. *
  2228. * Although the `isStandardBrowserEnv` method indicates that
  2229. * `allows axios to run in a web worker`, the WebWorker will still be
  2230. * filtered out due to its judgment standard
  2231. * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
  2232. * This leads to a problem when axios post `FormData` in webWorker
  2233. */
  2234. const hasStandardBrowserWebWorkerEnv = (() => {
  2235. return typeof WorkerGlobalScope !== 'undefined' &&
  2236. // eslint-disable-next-line no-undef
  2237. self instanceof WorkerGlobalScope && typeof self.importScripts === 'function';
  2238. })();
  2239. const origin = hasBrowserEnv && window.location.href || 'http://localhost';
  2240. var utils = /*#__PURE__*/Object.freeze({
  2241. __proto__: null,
  2242. hasBrowserEnv: hasBrowserEnv,
  2243. hasStandardBrowserEnv: hasStandardBrowserEnv,
  2244. hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
  2245. navigator: _navigator,
  2246. origin: origin
  2247. });
  2248. var platform = {
  2249. ...utils,
  2250. ...platform$1
  2251. };
  2252. function toURLEncodedForm(data, options) {
  2253. return toFormData(data, new platform.classes.URLSearchParams(), {
  2254. visitor: function (value, key, path, helpers) {
  2255. if (platform.isNode && utils$1.isBuffer(value)) {
  2256. this.append(key, value.toString('base64'));
  2257. return false;
  2258. }
  2259. return helpers.defaultVisitor.apply(this, arguments);
  2260. },
  2261. ...options
  2262. });
  2263. }
  2264. const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
  2265. function throwIfDepthExceeded(index) {
  2266. if (index > MAX_DEPTH) {
  2267. throw new AxiosError('FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
  2268. }
  2269. }
  2270. /**
  2271. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  2272. *
  2273. * @param {string} name - The name of the property to get.
  2274. *
  2275. * @returns An array of strings.
  2276. */
  2277. function parsePropPath(name) {
  2278. // foo[x][y][z] -> ['foo', 'x', 'y', 'z']
  2279. // foo.x.y.z -> ['foo', 'x', 'y', 'z']
  2280. // A path is split on `.` and on `[...]` groups. A segment — whether written
  2281. // in dot notation or captured inside brackets — may contain any character
  2282. // except `.`, `[` and `]`, so a key like `user-name` or `user name` is kept
  2283. // literal instead of being split (#5402). `.`, `[` and `]` keep their existing
  2284. // meaning, e.g. `foo[bar.baz]` -> ['foo', 'bar', 'baz'] and `[]` is an array push.
  2285. // Excluding `[` from the bracket group also makes the match fail fast at the
  2286. // next `[`, so a malformed name cannot rescan to the end of the string from
  2287. // every unmatched `[` — parsing stays linear in the length of the name.
  2288. const path = [];
  2289. const pattern = /[^.[\]]+|\[([^.[\]]*)]/g;
  2290. let match;
  2291. while ((match = pattern.exec(name)) !== null) {
  2292. throwIfDepthExceeded(path.length);
  2293. path.push(match[0] === '[]' ? '' : match[1] || match[0]);
  2294. }
  2295. return path;
  2296. }
  2297. /**
  2298. * Convert an array to an object.
  2299. *
  2300. * @param {Array<any>} arr - The array to convert to an object.
  2301. *
  2302. * @returns An object with the same keys and values as the array.
  2303. */
  2304. function arrayToObject(arr) {
  2305. const obj = {};
  2306. const keys = Object.keys(arr);
  2307. let i;
  2308. const len = keys.length;
  2309. let key;
  2310. for (i = 0; i < len; i++) {
  2311. key = keys[i];
  2312. obj[key] = arr[key];
  2313. }
  2314. return obj;
  2315. }
  2316. function normalizeArray(value) {
  2317. if (!utils$1.isArray(value)) return value;
  2318. const keys = Object.keys(value);
  2319. return keys.length !== value.length || keys.some((key, index) => key !== String(index)) ? arrayToObject(value) : value;
  2320. }
  2321. function normalizeArrays(obj) {
  2322. const pending = [obj];
  2323. while (pending.length) {
  2324. const target = pending.pop();
  2325. Object.keys(target).forEach(key => {
  2326. const value = target[key] = normalizeArray(target[key]);
  2327. if (utils$1.isArray(value) || utils$1.isPlainObject(value)) {
  2328. pending.push(value);
  2329. }
  2330. });
  2331. }
  2332. return obj;
  2333. }
  2334. /**
  2335. * It takes a FormData object and returns a JavaScript object
  2336. *
  2337. * @param {string} formData The FormData object to convert to JSON.
  2338. *
  2339. * @returns {Object<string, any> | null} The converted object.
  2340. */
  2341. function formDataToJSON(formData) {
  2342. function buildPath(path, value, target, index) {
  2343. throwIfDepthExceeded(index);
  2344. let name = path[index++];
  2345. if (name === '__proto__') return true;
  2346. const isNumericKey = Number.isFinite(+name);
  2347. const isLast = index >= path.length;
  2348. name = !name && utils$1.isArray(target) ? target.length : name;
  2349. if (isLast) {
  2350. if (utils$1.hasOwnProp(target, name)) {
  2351. target[name] = normalizeArray(target[name]);
  2352. target[name] = utils$1.isArray(target[name]) ? target[name].concat(value) : [target[name], value];
  2353. } else {
  2354. target[name] = value;
  2355. }
  2356. return !isNumericKey;
  2357. }
  2358. if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
  2359. target[name] = [];
  2360. }
  2361. const result = buildPath(path, value, target[name], index);
  2362. if (result && utils$1.isArray(target[name])) {
  2363. target[name] = arrayToObject(target[name]);
  2364. }
  2365. return !isNumericKey;
  2366. }
  2367. if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
  2368. const obj = {};
  2369. utils$1.forEachEntry(formData, (name, value) => {
  2370. buildPath(parsePropPath(name), value, obj, 0);
  2371. });
  2372. return normalizeArrays(obj);
  2373. }
  2374. return null;
  2375. }
  2376. const methodList = Object.freeze(['get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'purge', 'link', 'unlink', 'query']);
  2377. const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
  2378. /**
  2379. * It takes a string, tries to parse it, and if it fails, it returns the stringified version
  2380. * of the input
  2381. *
  2382. * @param {any} rawValue - The value to be stringified.
  2383. * @param {Function} parser - A function that parses a string into a JavaScript object.
  2384. * @param {Function} encoder - A function that takes a value and returns a string.
  2385. *
  2386. * @returns {string} A stringified version of the rawValue.
  2387. */
  2388. function stringifySafely(rawValue, parser, encoder) {
  2389. if (utils$1.isString(rawValue)) {
  2390. try {
  2391. (parser || JSON.parse)(rawValue);
  2392. return utils$1.trim(rawValue);
  2393. } catch (e) {
  2394. if (e.name !== 'SyntaxError') {
  2395. throw e;
  2396. }
  2397. }
  2398. }
  2399. return (encoder || JSON.stringify)(rawValue);
  2400. }
  2401. const defaults = {
  2402. transitional: transitionalDefaults,
  2403. adapter: ['xhr', 'http', 'fetch'],
  2404. transformRequest: [function transformRequest(data, headers) {
  2405. const contentType = headers.getContentType() || '';
  2406. const hasJSONContentType = contentType.indexOf('application/json') > -1;
  2407. const isObjectPayload = utils$1.isObject(data);
  2408. if (isObjectPayload && utils$1.isHTMLForm(data)) {
  2409. data = new FormData(data);
  2410. }
  2411. const isFormData = utils$1.isFormData(data);
  2412. if (isFormData) {
  2413. return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
  2414. }
  2415. if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
  2416. return data;
  2417. }
  2418. if (utils$1.isArrayBufferView(data)) {
  2419. return data.buffer;
  2420. }
  2421. if (utils$1.isURLSearchParams(data)) {
  2422. headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
  2423. return data.toString();
  2424. }
  2425. let isFileList;
  2426. if (isObjectPayload) {
  2427. const formSerializer = own(this, 'formSerializer');
  2428. if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
  2429. return toURLEncodedForm(data, formSerializer).toString();
  2430. }
  2431. if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
  2432. const env = own(this, 'env');
  2433. const _FormData = env && env.FormData;
  2434. return toFormData(isFileList ? {
  2435. 'files[]': data
  2436. } : data, _FormData && new _FormData(), formSerializer);
  2437. }
  2438. }
  2439. if (isObjectPayload || hasJSONContentType) {
  2440. headers.setContentType('application/json', false);
  2441. return stringifySafely(data);
  2442. }
  2443. return data;
  2444. }],
  2445. transformResponse: [function transformResponse(data) {
  2446. const transitional = own(this, 'transitional') || defaults.transitional;
  2447. const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  2448. const responseType = own(this, 'responseType');
  2449. const JSONRequested = responseType === 'json';
  2450. if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
  2451. return data;
  2452. }
  2453. if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
  2454. const silentJSONParsing = transitional && transitional.silentJSONParsing;
  2455. const strictJSONParsing = !silentJSONParsing && JSONRequested;
  2456. try {
  2457. return JSON.parse(data, own(this, 'parseReviver'));
  2458. } catch (e) {
  2459. if (strictJSONParsing) {
  2460. if (e.name === 'SyntaxError') {
  2461. throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
  2462. }
  2463. throw e;
  2464. }
  2465. }
  2466. }
  2467. return data;
  2468. }],
  2469. /**
  2470. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  2471. * timeout is not created.
  2472. */
  2473. timeout: 0,
  2474. xsrfCookieName: 'XSRF-TOKEN',
  2475. xsrfHeaderName: 'X-XSRF-TOKEN',
  2476. maxContentLength: -1,
  2477. maxBodyLength: -1,
  2478. env: {
  2479. FormData: platform.classes.FormData,
  2480. Blob: platform.classes.Blob
  2481. },
  2482. validateStatus: function validateStatus(status) {
  2483. return status >= 200 && status < 300;
  2484. },
  2485. headers: {
  2486. common: {
  2487. Accept: 'application/json, text/plain, */*',
  2488. 'Content-Type': undefined
  2489. }
  2490. }
  2491. };
  2492. utils$1.forEach(methodList, method => {
  2493. defaults.headers[method] = {};
  2494. });
  2495. /**
  2496. * Transform the data for a request or a response
  2497. *
  2498. * @param {Array|Function} fns A single function or Array of functions
  2499. * @param {?Object} response The response object
  2500. *
  2501. * @returns {*} The resulting transformed data
  2502. */
  2503. function transformData(fns, response) {
  2504. const config = this || defaults;
  2505. const context = response || config;
  2506. const headers = AxiosHeaders.from(context.headers);
  2507. let data = context.data;
  2508. utils$1.forEach(fns, function transform(fn) {
  2509. data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  2510. });
  2511. headers.normalize();
  2512. return data;
  2513. }
  2514. function isCancel(value) {
  2515. return !!(value && value.__CANCEL__);
  2516. }
  2517. class CanceledError extends AxiosError {
  2518. /**
  2519. * A `CanceledError` is an object that is thrown when an operation is canceled.
  2520. *
  2521. * @param {string=} message The message.
  2522. * @param {Object=} config The config.
  2523. * @param {Object=} request The request.
  2524. *
  2525. * @returns {CanceledError} The created error.
  2526. */
  2527. constructor(message, config, request) {
  2528. super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
  2529. this.name = 'CanceledError';
  2530. this.__CANCEL__ = true;
  2531. }
  2532. }
  2533. /**
  2534. * Resolve or reject a Promise based on response status.
  2535. *
  2536. * @param {Function} resolve A function that resolves the promise.
  2537. * @param {Function} reject A function that rejects the promise.
  2538. * @param {object} response The response.
  2539. *
  2540. * @returns {object} The response.
  2541. */
  2542. function settle(resolve, reject, response) {
  2543. const validateStatus = response.config.validateStatus;
  2544. if (!response.status || !validateStatus || validateStatus(response.status)) {
  2545. resolve(response);
  2546. } else {
  2547. reject(new AxiosError('Request failed with status code ' + response.status, response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, response.config, response.request, response));
  2548. }
  2549. }
  2550. /**
  2551. * Determines whether the specified URL is absolute
  2552. *
  2553. * @param {string} url The URL to test
  2554. *
  2555. * @returns {boolean} True if the specified URL is absolute, otherwise false
  2556. */
  2557. function isAbsoluteURL(url) {
  2558. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  2559. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  2560. // by any combination of letters, digits, plus, period, or hyphen.
  2561. if (typeof url !== 'string') {
  2562. return false;
  2563. }
  2564. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  2565. }
  2566. /**
  2567. * Creates a new URL by combining the specified URLs
  2568. *
  2569. * @param {string} baseURL The base URL
  2570. * @param {string} relativeURL The relative URL
  2571. *
  2572. * @returns {string} The combined URL
  2573. */
  2574. function combineURLs(baseURL, relativeURL) {
  2575. if (!relativeURL) {
  2576. return baseURL;
  2577. }
  2578. let end = baseURL.length;
  2579. while (end > 0 && baseURL.charCodeAt(end - 1) === 47) {
  2580. end--;
  2581. }
  2582. return baseURL.slice(0, end) + '/' + relativeURL.replace(/^\/+/, '');
  2583. }
  2584. const urlParserControlCharacters = /[\t\n\r]/g;
  2585. /**
  2586. * Match WHATWG URL preprocessing before checking a URL's protocol.
  2587. *
  2588. * @param {string} url
  2589. *
  2590. * @returns {string}
  2591. */
  2592. function normalizeURLForProtocolCheck(url) {
  2593. if (typeof url !== 'string') {
  2594. return url;
  2595. }
  2596. let start = 0;
  2597. while (start < url.length && url.charCodeAt(start) <= 0x20) {
  2598. start++;
  2599. }
  2600. return url.slice(start).replace(urlParserControlCharacters, '');
  2601. }
  2602. const malformedHttpProtocol = /^https?:(?!\/\/)/i;
  2603. // Redact the parts of a URL that can carry secrets before it is embedded in an
  2604. // error message. AxiosError.toJSON() serializes `message` verbatim and errors
  2605. // are commonly logged, while the opt-in `config.redact` model only cleans
  2606. // config keys — it cannot reach the message. Redact only the genuinely
  2607. // sensitive substrings — userinfo (credentials), query parameter values and
  2608. // fragment contents — with the same REDACTED marker the config redaction uses,
  2609. // while keeping the scheme, host, path and parameter names so the offending
  2610. // request stays accurately identifiable.
  2611. function redactFragment(fragment) {
  2612. if (!fragment) {
  2613. return fragment;
  2614. }
  2615. return fragment.replace(/(^|&)([^=&]*=)?[^&]+/g, (match, separator, parameterName = '') => {
  2616. return `${separator}${parameterName}${REDACTED}`;
  2617. });
  2618. }
  2619. function redactSensitiveURLParts(url) {
  2620. const redactedURL = url.replace(/^(https?:\/{0,2})[^/?#]*@/i, `$1${REDACTED}@`);
  2621. const fragmentIndex = redactedURL.indexOf('#');
  2622. const urlWithoutFragment = fragmentIndex === -1 ? redactedURL : redactedURL.slice(0, fragmentIndex);
  2623. const redactedURLWithoutFragment = urlWithoutFragment.replace(/([?&][^=&#]*=)[^&#]*/g, `$1${REDACTED}`);
  2624. if (fragmentIndex === -1) {
  2625. return redactedURLWithoutFragment;
  2626. }
  2627. return `${redactedURLWithoutFragment}#${redactFragment(redactedURL.slice(fragmentIndex + 1))}`;
  2628. }
  2629. function assertValidHttpProtocolURL(url, config) {
  2630. if (typeof url === 'string') {
  2631. const normalizedURL = normalizeURLForProtocolCheck(url);
  2632. if (malformedHttpProtocol.test(normalizedURL)) {
  2633. throw new AxiosError(`Invalid URL ${JSON.stringify(redactSensitiveURLParts(normalizedURL))}: missing "//" after protocol`, AxiosError.ERR_INVALID_URL, config);
  2634. }
  2635. }
  2636. }
  2637. /**
  2638. * Creates a new URL by combining the baseURL with the requestedURL,
  2639. * only when the requestedURL is not already an absolute URL.
  2640. * If the requestURL is absolute, this function returns the requestedURL untouched.
  2641. *
  2642. * @param {string} baseURL The base URL
  2643. * @param {string} requestedURL Absolute or relative URL to combine
  2644. *
  2645. * @returns {string} The combined full path
  2646. */
  2647. function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
  2648. assertValidHttpProtocolURL(requestedURL, config);
  2649. let isRelativeUrl = !isAbsoluteURL(requestedURL);
  2650. if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
  2651. assertValidHttpProtocolURL(baseURL, config);
  2652. return combineURLs(baseURL, requestedURL);
  2653. }
  2654. return requestedURL;
  2655. }
  2656. var DEFAULT_PORTS$1 = {
  2657. ftp: 21,
  2658. gopher: 70,
  2659. http: 80,
  2660. https: 443,
  2661. ws: 80,
  2662. wss: 443
  2663. };
  2664. function parseUrl(urlString) {
  2665. try {
  2666. return new URL(urlString);
  2667. } catch {
  2668. return null;
  2669. }
  2670. }
  2671. /**
  2672. * @param {string|object|URL} url - The URL as a string or URL instance, or a
  2673. * compatible object (such as the result from legacy url.parse).
  2674. * @return {string} The URL of the proxy that should handle the request to the
  2675. * given URL. If no proxy is set, this will be an empty string.
  2676. */
  2677. function getProxyForUrl(url) {
  2678. var parsedUrl = (typeof url === 'string' ? parseUrl(url) : url) || {};
  2679. var proto = parsedUrl.protocol;
  2680. var hostname = parsedUrl.host;
  2681. var port = parsedUrl.port;
  2682. if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
  2683. return ''; // Don't proxy URLs without a valid scheme or host.
  2684. }
  2685. proto = proto.split(':', 1)[0];
  2686. // Stripping ports in this way instead of using parsedUrl.hostname to make
  2687. // sure that the brackets around IPv6 addresses are kept.
  2688. hostname = hostname.replace(/:\d*$/, '');
  2689. port = parseInt(port) || DEFAULT_PORTS$1[proto] || 0;
  2690. if (!shouldProxy(hostname, port)) {
  2691. return ''; // Don't proxy URLs that match NO_PROXY.
  2692. }
  2693. var proxy = getEnv(proto + '_proxy') || getEnv('all_proxy');
  2694. if (proxy && proxy.indexOf('://') === -1) {
  2695. // Missing scheme in proxy, default to the requested URL's scheme.
  2696. proxy = proto + '://' + proxy;
  2697. }
  2698. return proxy;
  2699. }
  2700. /**
  2701. * Determines whether a given URL should be proxied.
  2702. *
  2703. * @param {string} hostname - The host name of the URL.
  2704. * @param {number} port - The effective port of the URL.
  2705. * @returns {boolean} Whether the given URL should be proxied.
  2706. * @private
  2707. */
  2708. function shouldProxy(hostname, port) {
  2709. var NO_PROXY = getEnv('no_proxy').toLowerCase();
  2710. if (!NO_PROXY) {
  2711. return true; // Always proxy if NO_PROXY is not set.
  2712. }
  2713. if (NO_PROXY === '*') {
  2714. return false; // Never proxy if wildcard is set.
  2715. }
  2716. return NO_PROXY.split(/[,\s]/).every(function (proxy) {
  2717. if (!proxy) {
  2718. return true; // Skip zero-length hosts.
  2719. }
  2720. var parsedProxy = proxy.match(/^(.+):(\d+)$/);
  2721. var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
  2722. var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
  2723. if (parsedProxyPort && parsedProxyPort !== port) {
  2724. return true; // Skip if ports don't match.
  2725. }
  2726. if (!/^[.*]/.test(parsedProxyHostname)) {
  2727. // No wildcards, so stop proxying if there is an exact match.
  2728. return hostname !== parsedProxyHostname;
  2729. }
  2730. if (parsedProxyHostname.charAt(0) === '*') {
  2731. // Remove leading wildcard.
  2732. parsedProxyHostname = parsedProxyHostname.slice(1);
  2733. }
  2734. // Stop proxying if the hostname ends with the no_proxy host.
  2735. return !hostname.endsWith(parsedProxyHostname);
  2736. });
  2737. }
  2738. /**
  2739. * Get the value for an environment variable.
  2740. *
  2741. * @param {string} key - The name of the environment variable.
  2742. * @return {string} The value of the environment variable.
  2743. * @private
  2744. */
  2745. function getEnv(key) {
  2746. return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
  2747. }
  2748. const VERSION = "1.21.1";
  2749. function parseProtocol(url) {
  2750. const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
  2751. return match && match[1].toLowerCase() || '';
  2752. }
  2753. // RFC 2397: data:[<mediatype>][;base64],<data>
  2754. // mediatype = type/subtype followed by optional ;name=value parameters
  2755. // The `i` flag makes the `;base64` token case-insensitive, matching the WHATWG
  2756. // URL/Fetch data URL processor (and therefore the fetch adapter and browsers).
  2757. // The remaining character classes do not depend on letter case.
  2758. const DATA_URL_PATTERN = /^([^,;/]+\/[^,;/]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/i;
  2759. /**
  2760. * Parse data uri to a Buffer or Blob
  2761. *
  2762. * @param {String} uri
  2763. * @param {?Boolean} asBlob
  2764. * @param {?Object} options
  2765. * @param {?Function} options.Blob
  2766. *
  2767. * @returns {Buffer|Blob}
  2768. */
  2769. function fromDataURI(uri, asBlob, options) {
  2770. const _Blob = options && options.Blob || platform.classes.Blob;
  2771. const protocol = parseProtocol(uri);
  2772. if (asBlob === undefined && _Blob) {
  2773. asBlob = true;
  2774. }
  2775. if (protocol === 'data') {
  2776. uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
  2777. const match = DATA_URL_PATTERN.exec(uri);
  2778. if (!match) {
  2779. throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
  2780. }
  2781. const type = match[1];
  2782. const params = match[2];
  2783. const encoding = match[3] ? 'base64' : 'utf8';
  2784. const body = match[4];
  2785. // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
  2786. // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
  2787. let mime = '';
  2788. if (type) {
  2789. mime = params ? type + params : type;
  2790. } else if (params) {
  2791. mime = 'text/plain' + params;
  2792. }
  2793. const buffer = encoding === 'base64' ? Buffer.from(body.replace(/%([\da-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))), 'base64') : Buffer.from(decodeURIComponent(body), encoding);
  2794. if (asBlob) {
  2795. if (!_Blob) {
  2796. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  2797. }
  2798. return new _Blob([buffer], {
  2799. type: mime
  2800. });
  2801. }
  2802. return buffer;
  2803. }
  2804. throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
  2805. }
  2806. const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
  2807. /**
  2808. * Apply the headers generated by a FormData implementation to the request headers,
  2809. * honoring the `formDataHeaderPolicy` option: with 'content-only', copy only the
  2810. * content-* headers; otherwise merge all of them.
  2811. *
  2812. * @param {AxiosHeaders} headers - the request headers to mutate
  2813. * @param {Object | null | undefined} formHeaders - headers produced by the FormData implementation
  2814. * @param {String} [policy] - the resolved `formDataHeaderPolicy` config value
  2815. *
  2816. * @returns {void}
  2817. */
  2818. function setFormDataHeaders(headers, formHeaders, policy) {
  2819. if (policy !== 'content-only') {
  2820. headers.set(formHeaders);
  2821. return;
  2822. }
  2823. Object.entries(formHeaders || {}).forEach(([key, val]) => {
  2824. if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
  2825. headers.set(key, val);
  2826. }
  2827. });
  2828. }
  2829. const kInternals = Symbol('internals');
  2830. class AxiosTransformStream extends stream.Transform {
  2831. constructor(options) {
  2832. options = utils$1.toFlatObject(options, {
  2833. maxRate: 0,
  2834. chunkSize: 64 * 1024,
  2835. minChunkSize: 100,
  2836. timeWindow: 500,
  2837. ticksRate: 2,
  2838. samplesCount: 15
  2839. }, null, (prop, source) => {
  2840. return !utils$1.isUndefined(source[prop]);
  2841. });
  2842. super({
  2843. readableHighWaterMark: options.chunkSize
  2844. });
  2845. const internals = this[kInternals] = {
  2846. timeWindow: options.timeWindow,
  2847. chunkSize: options.chunkSize,
  2848. maxRate: options.maxRate,
  2849. minChunkSize: options.minChunkSize,
  2850. bytesSeen: 0,
  2851. isCaptured: false,
  2852. notifiedBytesLoaded: 0,
  2853. ts: Date.now(),
  2854. bytes: 0,
  2855. onReadCallback: null
  2856. };
  2857. this.on('newListener', event => {
  2858. if (event === 'progress') {
  2859. if (!internals.isCaptured) {
  2860. internals.isCaptured = true;
  2861. }
  2862. }
  2863. });
  2864. }
  2865. _read(size) {
  2866. const internals = this[kInternals];
  2867. if (internals.onReadCallback) {
  2868. internals.onReadCallback();
  2869. }
  2870. return super._read(size);
  2871. }
  2872. _transform(chunk, encoding, callback) {
  2873. const internals = this[kInternals];
  2874. const maxRate = internals.maxRate;
  2875. const readableHighWaterMark = this.readableHighWaterMark;
  2876. const timeWindow = internals.timeWindow;
  2877. const divider = 1000 / timeWindow;
  2878. const bytesThreshold = maxRate / divider;
  2879. let minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
  2880. if (maxRate) {
  2881. minChunkSize = Math.min(bytesThreshold, minChunkSize);
  2882. }
  2883. const pushChunk = (_chunk, _callback) => {
  2884. const bytes = Buffer.byteLength(_chunk);
  2885. internals.bytesSeen += bytes;
  2886. internals.bytes += bytes;
  2887. internals.isCaptured && this.emit('progress', internals.bytesSeen);
  2888. if (this.push(_chunk)) {
  2889. process.nextTick(_callback);
  2890. } else {
  2891. internals.onReadCallback = () => {
  2892. internals.onReadCallback = null;
  2893. process.nextTick(_callback);
  2894. };
  2895. }
  2896. };
  2897. const transformChunk = (_chunk, _callback) => {
  2898. if (this.destroyed) {
  2899. return _callback();
  2900. }
  2901. const chunkSize = Buffer.byteLength(_chunk);
  2902. let chunkRemainder = null;
  2903. let maxChunkSize = readableHighWaterMark;
  2904. let bytesLeft;
  2905. let passed = 0;
  2906. if (maxRate) {
  2907. const now = Date.now();
  2908. if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
  2909. internals.ts = now;
  2910. bytesLeft = bytesThreshold - internals.bytes;
  2911. internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
  2912. passed = 0;
  2913. }
  2914. bytesLeft = bytesThreshold - internals.bytes;
  2915. }
  2916. if (maxRate) {
  2917. if (bytesLeft <= 0) {
  2918. // next time window
  2919. return setTimeout(() => {
  2920. _callback(null, _chunk);
  2921. }, timeWindow - passed);
  2922. }
  2923. if (bytesLeft < maxChunkSize) {
  2924. // A buffer boundary must consume at least one byte. Carry any
  2925. // fractional allowance forward in the next accounting window.
  2926. maxChunkSize = Math.max(1, Math.floor(bytesLeft));
  2927. }
  2928. }
  2929. if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
  2930. chunkRemainder = _chunk.subarray(maxChunkSize);
  2931. _chunk = _chunk.subarray(0, maxChunkSize);
  2932. }
  2933. pushChunk(_chunk, chunkRemainder ? () => {
  2934. process.nextTick(_callback, null, chunkRemainder);
  2935. } : _callback);
  2936. };
  2937. transformChunk(chunk, function transformNextChunk(err, _chunk) {
  2938. if (err) {
  2939. return callback(err);
  2940. }
  2941. if (_chunk) {
  2942. transformChunk(_chunk, transformNextChunk);
  2943. } else {
  2944. callback(null);
  2945. }
  2946. });
  2947. }
  2948. }
  2949. const {
  2950. asyncIterator
  2951. } = Symbol;
  2952. const readBlob = async function* (blob) {
  2953. if (blob.stream) {
  2954. yield* blob.stream();
  2955. } else if (blob.arrayBuffer) {
  2956. yield await blob.arrayBuffer();
  2957. } else if (blob[asyncIterator]) {
  2958. yield* blob[asyncIterator]();
  2959. } else {
  2960. yield blob;
  2961. }
  2962. };
  2963. const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_';
  2964. const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder();
  2965. const CRLF$1 = '\r\n';
  2966. const CRLF_BYTES = textEncoder.encode(CRLF$1);
  2967. const CRLF_BYTES_COUNT = 2;
  2968. class FormDataPart {
  2969. constructor(name, value) {
  2970. const {
  2971. escapeName
  2972. } = this.constructor;
  2973. const isStringValue = utils$1.isString(value);
  2974. let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''}${CRLF$1}`;
  2975. if (isStringValue) {
  2976. value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF$1));
  2977. } else {
  2978. const safeType = String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
  2979. headers += `Content-Type: ${safeType}${CRLF$1}`;
  2980. }
  2981. this.headers = textEncoder.encode(headers + CRLF$1);
  2982. this.contentLength = isStringValue ? value.byteLength : value.size;
  2983. this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
  2984. this.name = name;
  2985. this.value = value;
  2986. }
  2987. async *encode() {
  2988. yield this.headers;
  2989. const {
  2990. value
  2991. } = this;
  2992. if (utils$1.isTypedArray(value)) {
  2993. yield value;
  2994. } else {
  2995. yield* readBlob(value);
  2996. }
  2997. yield CRLF_BYTES;
  2998. }
  2999. static escapeName(name) {
  3000. return String(name).replace(/[\r\n"]/g, match => ({
  3001. '\r': '%0D',
  3002. '\n': '%0A',
  3003. '"': '%22'
  3004. })[match]);
  3005. }
  3006. }
  3007. const formDataToStream = (form, headersHandler, options) => {
  3008. const {
  3009. tag = 'form-data-boundary',
  3010. size = 25,
  3011. boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET)
  3012. } = options || {};
  3013. if (!utils$1.isFormData(form)) {
  3014. throw new TypeError('FormData instance required');
  3015. }
  3016. if (boundary.length < 1 || boundary.length > 70) {
  3017. throw new Error('boundary must be 1-70 characters long');
  3018. }
  3019. const boundaryBytes = textEncoder.encode('--' + boundary + CRLF$1);
  3020. const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF$1);
  3021. let contentLength = footerBytes.byteLength;
  3022. const parts = Array.from(form.entries()).map(([name, value]) => {
  3023. const part = new FormDataPart(name, value);
  3024. contentLength += part.size;
  3025. return part;
  3026. });
  3027. contentLength += boundaryBytes.byteLength * parts.length;
  3028. contentLength = utils$1.toFiniteNumber(contentLength);
  3029. const computedHeaders = {
  3030. 'Content-Type': `multipart/form-data; boundary=${boundary}`
  3031. };
  3032. if (Number.isFinite(contentLength)) {
  3033. computedHeaders['Content-Length'] = contentLength;
  3034. }
  3035. headersHandler && headersHandler(computedHeaders);
  3036. return stream.Readable.from(async function* () {
  3037. for (const part of parts) {
  3038. yield boundaryBytes;
  3039. yield* part.encode();
  3040. }
  3041. yield footerBytes;
  3042. }());
  3043. };
  3044. class ZlibHeaderTransformStream extends stream.Transform {
  3045. __transform(chunk, encoding, callback) {
  3046. this.push(chunk);
  3047. callback();
  3048. }
  3049. _transform(chunk, encoding, callback) {
  3050. if (chunk.length !== 0) {
  3051. this._transform = this.__transform;
  3052. // Add Default Compression headers if no zlib headers are present
  3053. if (chunk[0] !== 120) {
  3054. // Hex: 78
  3055. const header = Buffer.alloc(2);
  3056. header[0] = 120; // Hex: 78
  3057. header[1] = 156; // Hex: 9C
  3058. this.push(header, encoding);
  3059. }
  3060. }
  3061. this.__transform(chunk, encoding, callback);
  3062. }
  3063. }
  3064. class Http2Sessions {
  3065. constructor() {
  3066. this.sessions = Object.create(null);
  3067. }
  3068. getSession(authority, options) {
  3069. options = Object.assign(Object.create(null), {
  3070. sessionTimeout: 1000
  3071. }, options);
  3072. let authoritySessions = this.sessions[authority];
  3073. if (authoritySessions) {
  3074. let len = authoritySessions.length;
  3075. for (let i = 0; i < len; i++) {
  3076. const [sessionHandle, sessionOptions] = authoritySessions[i];
  3077. if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) {
  3078. return sessionHandle;
  3079. }
  3080. }
  3081. }
  3082. const session = http2.connect(authority, options);
  3083. let removed;
  3084. let timer;
  3085. const removeSession = () => {
  3086. if (removed) {
  3087. return;
  3088. }
  3089. removed = true;
  3090. if (timer) {
  3091. clearTimeout(timer);
  3092. timer = null;
  3093. }
  3094. let entries = authoritySessions,
  3095. len = entries.length,
  3096. i = len;
  3097. while (i--) {
  3098. if (entries[i][0] === session) {
  3099. if (len === 1) {
  3100. delete this.sessions[authority];
  3101. } else {
  3102. entries.splice(i, 1);
  3103. }
  3104. if (!session.closed) {
  3105. session.close();
  3106. }
  3107. return;
  3108. }
  3109. }
  3110. };
  3111. const originalRequestFn = session.request;
  3112. const {
  3113. sessionTimeout
  3114. } = options;
  3115. if (sessionTimeout != null) {
  3116. let streamsCount = 0;
  3117. session.request = function () {
  3118. const stream = originalRequestFn.apply(this, arguments);
  3119. streamsCount++;
  3120. if (timer) {
  3121. clearTimeout(timer);
  3122. timer = null;
  3123. }
  3124. stream.once('close', () => {
  3125. if (! --streamsCount && !removed) {
  3126. timer = setTimeout(() => {
  3127. timer = null;
  3128. removeSession();
  3129. }, sessionTimeout);
  3130. }
  3131. });
  3132. return stream;
  3133. };
  3134. }
  3135. session.once('close', removeSession);
  3136. session.once('error', removeSession);
  3137. session.once('goaway', removeSession);
  3138. let entry = [session, options];
  3139. authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
  3140. return session;
  3141. }
  3142. }
  3143. const callbackify = (fn, reducer) => {
  3144. return utils$1.isAsyncFn(fn) ? function (...args) {
  3145. const cb = args.pop();
  3146. fn.apply(this, args).then(value => {
  3147. try {
  3148. reducer ? cb(null, ...reducer(value)) : cb(null, value);
  3149. } catch (err) {
  3150. cb(err);
  3151. }
  3152. }, cb);
  3153. } : fn;
  3154. };
  3155. const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']);
  3156. const trimTrailingDots = value => {
  3157. let end = value.length;
  3158. while (end && value.charCodeAt(end - 1) === 46) {
  3159. end--;
  3160. }
  3161. return end === value.length ? value : value.slice(0, end);
  3162. };
  3163. const isIPv4Loopback = host => {
  3164. const parts = host.split('.');
  3165. if (parts.length !== 4) return false;
  3166. if (parts[0] !== '127') return false;
  3167. return parts.every(p => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
  3168. };
  3169. /**
  3170. * Canonicalize an IPv4 address written in shorthand, octal, or hex form into
  3171. * dotted-decimal. IPv6 addresses and non-IP strings are returned unchanged so
  3172. * the existing IPv4-mapped IPv6 unmap path and the isLoopback path can still
  3173. * see them.
  3174. *
  3175. * Shorthand expansion mirrors Node's URL parser: literal parts fill from the
  3176. * left, the final part fills the remaining octets from the right with
  3177. * zero-padding on the left.
  3178. * 127.1 -> 127.0.0.1
  3179. * 127.0.1 -> 127.0.0.1
  3180. * 1.2.3 -> 1.2.0.3
  3181. *
  3182. * Each octet is parsed with an explicit base: 16 for `0x`/`0X` prefix, 8 for
  3183. * zero-prefixed multi-digit all-`0-7` parts, 10 otherwise. Zero-prefixed
  3184. * decimal-looking parts that contain `8` or `9` are rejected to match Node's
  3185. * URL parser, and the comparison layer falls through to non-bypass if either
  3186. * side rejects the form (fail-safe).
  3187. *
  3188. * Returns the input unchanged on any parse failure, out-of-range octet, or
  3189. * unusual shape (1-part, 5+ parts) so the comparison layer fails closed.
  3190. */
  3191. const parseIPv4Octet = text => {
  3192. if (/^0[xX][0-9a-fA-F]+$/.test(text)) {
  3193. const n = parseInt(text.slice(2), 16);
  3194. return Number.isFinite(n) ? n : null;
  3195. }
  3196. if (text.length > 1 && /^0[0-7]+$/.test(text)) {
  3197. const n = parseInt(text, 8);
  3198. return Number.isFinite(n) ? n : null;
  3199. }
  3200. if (text.length > 1 && /^0[0-9]+$/.test(text)) {
  3201. return null;
  3202. }
  3203. if (/^[0-9]+$/.test(text)) {
  3204. const n = parseInt(text, 10);
  3205. return Number.isFinite(n) ? n : null;
  3206. }
  3207. return null;
  3208. };
  3209. const normalizeIPAddress = host => {
  3210. if (typeof host !== 'string' || !host || host.indexOf(':') !== -1) {
  3211. return host;
  3212. }
  3213. let h = host;
  3214. if (h.charAt(0) === '[' && h.charAt(h.length - 1) === ']') {
  3215. h = h.slice(1, -1);
  3216. }
  3217. h = trimTrailingDots(h);
  3218. // Allowed characters for any IPv4 shape: digits, dot, 'x', 'X', hex digits.
  3219. if (!/^[0-9.xXa-fA-F]+$/.test(h)) return host;
  3220. const parts = h.split('.');
  3221. // No part may be empty (e.g. "127..0.1" or "127.0.0."). Trailing dots are
  3222. // already stripped above; this guards against the empty-middle case.
  3223. if (parts.some(p => p === '')) return host;
  3224. if (parts.length === 4) {
  3225. // Full IPv4 form: each part is an octet.
  3226. const octets = parts.map(parseIPv4Octet);
  3227. if (octets.some(n => n === null || n < 0 || n > 255)) return host;
  3228. return octets.join('.');
  3229. }
  3230. if (parts.length > 4) {
  3231. return host;
  3232. }
  3233. // Shorthand: 1..3 parts. Node's URL parser treats a 1-part input as a 32-bit
  3234. // integer split into octets, which has surprising semantics (e.g. "127" ->
  3235. // "0.0.0.127"). Reject 1-part inputs to keep the helper predictable: the
  3236. // fail-safe returns the input unchanged and the comparison layer falls
  3237. // through to non-bypass.
  3238. if (parts.length === 1) return host;
  3239. // 2..3 parts: literal parts fill from the left, tail fills remaining octets
  3240. // from the right with zero-padding.
  3241. const literalOctets = parts.slice(0, -1);
  3242. const tail = parts[parts.length - 1];
  3243. const tailSlots = 4 - literalOctets.length;
  3244. // Tail is parsed as a full IPv4 number (hex/octal/decimal) and packed
  3245. // low-byte-right into the remaining octets, matching Node's URL parser.
  3246. // e.g. 127.65535 (tail 0xFFFF into 3 slots) -> 127.0.255.255;
  3247. // 127.0x00ff (tail 0xFF into 3 slots) -> 127.0.0.255;
  3248. // 127.0.65535 (tail 0xFFFF into 2 slots) -> 127.0.255.255.
  3249. const tailValue = parseIPv4Octet(tail);
  3250. if (tailValue === null) return host;
  3251. const maxTail = (1 << 8 * tailSlots) - 1;
  3252. if (tailValue < 0 || tailValue > maxTail) return host;
  3253. const tailOctets = new Array(tailSlots).fill(0);
  3254. for (let i = tailSlots - 1, v = tailValue; i >= 0; i--, v >>= 8) {
  3255. tailOctets[i] = v & 0xff;
  3256. }
  3257. const literal = literalOctets.map(parseIPv4Octet);
  3258. if (literal.some(n => n === null || n < 0 || n > 255)) return host;
  3259. return [...literal, ...tailOctets].join('.');
  3260. };
  3261. const isIPv6ZeroGroup = group => /^0{1,4}$/.test(group);
  3262. // The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host
  3263. // for outbound connections, so treat it as loopback-equivalent for NO_PROXY
  3264. // matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed
  3265. // and full IPv6 all-zero forms so both families bypass symmetrically.
  3266. const isIPv6Unspecified = host => {
  3267. if (host === '::') return true;
  3268. const compressionIndex = host.indexOf('::');
  3269. if (compressionIndex !== -1) {
  3270. if (compressionIndex !== host.lastIndexOf('::')) return false;
  3271. const left = host.slice(0, compressionIndex);
  3272. const right = host.slice(compressionIndex + 2);
  3273. const leftGroups = left ? left.split(':') : [];
  3274. const rightGroups = right ? right.split(':') : [];
  3275. const explicitGroups = leftGroups.length + rightGroups.length;
  3276. return explicitGroups < 8 && leftGroups.every(isIPv6ZeroGroup) && rightGroups.every(isIPv6ZeroGroup);
  3277. }
  3278. const groups = host.split(':');
  3279. return groups.length === 8 && groups.every(isIPv6ZeroGroup);
  3280. };
  3281. const isIPv6Loopback = host => {
  3282. // Collapse all-zero groups: any form of ::1 / 0:0:...:0:1
  3283. // First, strip any leading "::" by normalising with Set lookup of common forms,
  3284. // then fall back to structural check.
  3285. if (host === '::1') return true;
  3286. // Check IPv4-mapped IPv6 loopback: ::ffff:<v4-loopback> or ::ffff:<hex-v4-loopback>
  3287. // Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1
  3288. const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
  3289. if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]);
  3290. const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
  3291. if (v4MappedHex) {
  3292. const high = parseInt(v4MappedHex[1], 16);
  3293. // High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff
  3294. return high >= 0x7f00 && high <= 0x7fff;
  3295. }
  3296. // Full-form ::1 variants: any number of zero groups followed by trailing 1
  3297. // e.g. 0:0:0:0:0:0:0:1, 0000:...:0001
  3298. const groups = host.split(':');
  3299. if (groups.length === 8) {
  3300. for (let i = 0; i < 7; i++) {
  3301. if (!/^0+$/.test(groups[i])) return false;
  3302. }
  3303. return /^0*1$/.test(groups[7]);
  3304. }
  3305. return false;
  3306. };
  3307. const isLoopback = host => {
  3308. if (!host) return false;
  3309. if (LOOPBACK_HOSTNAMES.has(host)) return true;
  3310. if (isIPv4Loopback(host)) return true;
  3311. if (isIPv6Unspecified(host)) return true;
  3312. return isIPv6Loopback(host);
  3313. };
  3314. const DEFAULT_PORTS = {
  3315. http: 80,
  3316. https: 443,
  3317. ws: 80,
  3318. wss: 443,
  3319. ftp: 21
  3320. };
  3321. const parseNoProxyEntry = entry => {
  3322. let entryHost = entry;
  3323. let entryPort = 0;
  3324. if (entryHost.charAt(0) === '[') {
  3325. const bracketIndex = entryHost.indexOf(']');
  3326. if (bracketIndex !== -1) {
  3327. const host = entryHost.slice(1, bracketIndex);
  3328. const rest = entryHost.slice(bracketIndex + 1);
  3329. if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
  3330. entryPort = Number.parseInt(rest.slice(1), 10);
  3331. }
  3332. return [host, entryPort];
  3333. }
  3334. }
  3335. const firstColon = entryHost.indexOf(':');
  3336. const lastColon = entryHost.lastIndexOf(':');
  3337. if (firstColon !== -1 && firstColon === lastColon && /^\d+$/.test(entryHost.slice(lastColon + 1))) {
  3338. entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
  3339. entryHost = entryHost.slice(0, lastColon);
  3340. }
  3341. return [entryHost, entryPort];
  3342. };
  3343. // Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
  3344. // sides of a NO_PROXY comparison see the same canonical address. Without this,
  3345. // `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
  3346. // (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
  3347. // allowing the proxy-bypass policy to be circumvented by using the alternate
  3348. // representation. Returns the input unchanged when not IPv4-mapped.
  3349. const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
  3350. const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
  3351. const unmapIPv4MappedIPv6 = host => {
  3352. if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
  3353. const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
  3354. if (dotted) return dotted[1];
  3355. const hex = host.match(IPV4_MAPPED_HEX_RE);
  3356. if (hex) {
  3357. const high = parseInt(hex[1], 16);
  3358. const low = parseInt(hex[2], 16);
  3359. return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
  3360. }
  3361. return host;
  3362. };
  3363. const IPV4_OCTET_RE = /^(?:0|[1-9]\d{0,2})$/;
  3364. const ipv4ToBytes = host => {
  3365. const parts = host.split('.');
  3366. return parts.length === 4 && parts.every(part => IPV4_OCTET_RE.test(part) && Number(part) <= 255) ? parts.map(Number) : null;
  3367. };
  3368. const IPV6_GROUP_RE = /^[0-9a-f]{1,4}$/i;
  3369. const ipv6ToBytes = host => {
  3370. const halves = host.split('::');
  3371. if (halves.length > 2) {
  3372. return null;
  3373. }
  3374. const groups = halves[0] ? halves[0].split(':') : [];
  3375. if (halves.length === 2) {
  3376. const rear = halves[1] ? halves[1].split(':') : [];
  3377. const missing = 8 - groups.length - rear.length;
  3378. if (missing < 1) {
  3379. return null;
  3380. }
  3381. groups.push(...new Array(missing).fill('0'), ...rear);
  3382. }
  3383. if (groups.length !== 8 || groups.some(group => !IPV6_GROUP_RE.test(group))) {
  3384. return null;
  3385. }
  3386. return groups.flatMap(group => {
  3387. const value = Number.parseInt(group, 16);
  3388. return [value >> 8 & 0xff, value & 0xff];
  3389. });
  3390. };
  3391. const ipToBytes = host => {
  3392. if (typeof host !== 'string' || !host) {
  3393. return null;
  3394. }
  3395. return host.indexOf(':') !== -1 ? ipv6ToBytes(host) : ipv4ToBytes(host);
  3396. };
  3397. const normalizeNoProxyHost = hostname => {
  3398. if (!hostname) {
  3399. return hostname;
  3400. }
  3401. if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
  3402. hostname = hostname.slice(1, -1);
  3403. }
  3404. let trimmed = trimTrailingDots(hostname);
  3405. if (trimmed.indexOf(':') !== -1) {
  3406. try {
  3407. trimmed = new URL('http://[' + trimmed + ']/').hostname.slice(1, -1);
  3408. } catch (_err) {
  3409. return trimmed;
  3410. }
  3411. } else if (/[\u0080-\uffff]/.test(trimmed)) {
  3412. const prefix = /^[*.]+/.exec(trimmed);
  3413. const start = prefix ? prefix[0] : '';
  3414. const ascii = url.domainToASCII(trimmed.slice(start.length));
  3415. if (!ascii) return '';
  3416. trimmed = start + trimTrailingDots(ascii);
  3417. }
  3418. // IPv4 shorthand/octal/hex → dotted-decimal; helper is a no-op for inputs
  3419. // containing ':' (IPv6 and IPv4-mapped IPv6) so we fall through to unmap.
  3420. const ipv4 = normalizeIPAddress(trimmed);
  3421. if (ipv4 !== trimmed) {
  3422. return ipv4;
  3423. }
  3424. return unmapIPv4MappedIPv6(trimmed);
  3425. };
  3426. const normalizeCidrBase = input => {
  3427. let base = input;
  3428. const startsBracket = base.charAt(0) === '[';
  3429. const endsBracket = base.charAt(base.length - 1) === ']';
  3430. const hasBracket = base.includes('[') || base.includes(']');
  3431. if (startsBracket || endsBracket) {
  3432. if (!startsBracket || !endsBracket) {
  3433. return null;
  3434. }
  3435. base = base.slice(1, -1);
  3436. if (base.indexOf(':') === -1 || base.includes('[') || base.includes(']')) {
  3437. return null;
  3438. }
  3439. } else if (hasBracket) {
  3440. return null;
  3441. }
  3442. if (!base || base.charAt(base.length - 1) === '.') {
  3443. return null;
  3444. }
  3445. const wasIPv6 = base.indexOf(':') !== -1;
  3446. if (wasIPv6) {
  3447. try {
  3448. base = new URL(`http://[${base}]/`).hostname.slice(1, -1);
  3449. } catch (_err) {
  3450. return null;
  3451. }
  3452. } else {
  3453. base = normalizeIPAddress(base);
  3454. if (!ipv4ToBytes(base)) {
  3455. return null;
  3456. }
  3457. }
  3458. return {
  3459. normalized: unmapIPv4MappedIPv6(base),
  3460. wasIPv6
  3461. };
  3462. };
  3463. const CIDR_ENTRY_RE = /^(.+)\/(0|[1-9]\d{0,2})$/;
  3464. const parseCidrEntry = entry => {
  3465. if (entry.indexOf('/') === -1) {
  3466. return undefined;
  3467. }
  3468. const match = CIDR_ENTRY_RE.exec(entry);
  3469. if (!match) {
  3470. return null;
  3471. }
  3472. let prefix = Number(match[2]);
  3473. const parsedBase = normalizeCidrBase(match[1]);
  3474. if (!parsedBase) {
  3475. return null;
  3476. }
  3477. const {
  3478. normalized,
  3479. wasIPv6
  3480. } = parsedBase;
  3481. if (wasIPv6 && normalized.indexOf(':') === -1) {
  3482. if (prefix < 96) {
  3483. return null;
  3484. }
  3485. prefix -= 96;
  3486. }
  3487. const bytes = ipToBytes(normalized);
  3488. if (!bytes || prefix > bytes.length * 8) {
  3489. return null;
  3490. }
  3491. return {
  3492. bytes,
  3493. prefix
  3494. };
  3495. };
  3496. const isInSubnet = (addressBytes, networkBytes, prefix) => {
  3497. const fullBytes = prefix >> 3;
  3498. for (let i = 0; i < fullBytes; i++) {
  3499. if (addressBytes[i] !== networkBytes[i]) {
  3500. return false;
  3501. }
  3502. }
  3503. const remainingBits = prefix & 7;
  3504. if (remainingBits) {
  3505. const mask = 0xff << 8 - remainingBits & 0xff;
  3506. if ((addressBytes[fullBytes] & mask) !== (networkBytes[fullBytes] & mask)) {
  3507. return false;
  3508. }
  3509. }
  3510. return true;
  3511. };
  3512. function shouldBypassProxy(location) {
  3513. let parsed;
  3514. try {
  3515. parsed = new URL(location);
  3516. } catch (_err) {
  3517. return false;
  3518. }
  3519. const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
  3520. if (!noProxy) {
  3521. return false;
  3522. }
  3523. if (noProxy === '*') {
  3524. return true;
  3525. }
  3526. const port = Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
  3527. const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
  3528. const hostnameBytes = ipToBytes(hostname);
  3529. return noProxy.split(/[\s,]+/).some(entry => {
  3530. if (!entry) {
  3531. return false;
  3532. }
  3533. if (entry === '*') {
  3534. return true;
  3535. }
  3536. const cidr = parseCidrEntry(entry);
  3537. if (cidr !== undefined) {
  3538. return cidr !== null && !!hostnameBytes && hostnameBytes.length === cidr.bytes.length && isInSubnet(hostnameBytes, cidr.bytes, cidr.prefix);
  3539. }
  3540. let [entryHost, entryPort] = parseNoProxyEntry(entry);
  3541. entryHost = normalizeNoProxyHost(entryHost);
  3542. if (!entryHost) {
  3543. return false;
  3544. }
  3545. if (entryPort && entryPort !== port) {
  3546. return false;
  3547. }
  3548. if (entryHost.charAt(0) === '*') {
  3549. entryHost = entryHost.slice(1);
  3550. }
  3551. if (entryHost.charAt(0) === '.') {
  3552. return hostname.endsWith(entryHost);
  3553. }
  3554. return hostname === entryHost || isLoopback(hostname) && isLoopback(entryHost);
  3555. });
  3556. }
  3557. /**
  3558. * Calculate data maxRate
  3559. * @param {Number} [samplesCount= 10]
  3560. * @param {Number} [min= 1000]
  3561. * @returns {Function}
  3562. */
  3563. function speedometer(samplesCount, min) {
  3564. samplesCount = samplesCount || 10;
  3565. const bytes = new Array(samplesCount);
  3566. const timestamps = new Array(samplesCount);
  3567. let head = 0;
  3568. let tail = 0;
  3569. let firstSampleTS;
  3570. min = min !== undefined ? min : 1000;
  3571. return function push(chunkLength) {
  3572. const now = Date.now();
  3573. const startedAt = timestamps[tail];
  3574. if (!firstSampleTS) {
  3575. firstSampleTS = now;
  3576. }
  3577. bytes[head] = chunkLength;
  3578. timestamps[head] = now;
  3579. let i = tail;
  3580. let bytesCount = 0;
  3581. while (i !== head) {
  3582. bytesCount += bytes[i++];
  3583. i = i % samplesCount;
  3584. }
  3585. head = (head + 1) % samplesCount;
  3586. if (head === tail) {
  3587. tail = (tail + 1) % samplesCount;
  3588. }
  3589. if (now - firstSampleTS < min) {
  3590. return;
  3591. }
  3592. const passed = startedAt && now - startedAt;
  3593. return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  3594. };
  3595. }
  3596. /**
  3597. * Throttle decorator
  3598. * @param {Function} fn
  3599. * @param {Number} freq
  3600. * @return {Array<Function>}
  3601. */
  3602. function throttle(fn, freq) {
  3603. let timestamp = 0;
  3604. let threshold = 1000 / freq;
  3605. let lastArgs;
  3606. let timer;
  3607. const invoke = (args, now = Date.now()) => {
  3608. timestamp = now;
  3609. lastArgs = null;
  3610. if (timer) {
  3611. clearTimeout(timer);
  3612. timer = null;
  3613. }
  3614. fn(...args);
  3615. };
  3616. const throttled = (...args) => {
  3617. const now = Date.now();
  3618. const passed = now - timestamp;
  3619. if (passed >= threshold) {
  3620. invoke(args, now);
  3621. } else {
  3622. lastArgs = args;
  3623. if (!timer) {
  3624. timer = setTimeout(() => {
  3625. timer = null;
  3626. invoke(lastArgs);
  3627. }, threshold - passed);
  3628. }
  3629. }
  3630. };
  3631. const flush = () => lastArgs && invoke(lastArgs);
  3632. const flushWith = (...args) => invoke(args);
  3633. return [throttled, flush, flushWith];
  3634. }
  3635. const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  3636. let bytesNotified = 0;
  3637. const _speedometer = speedometer(50, 250);
  3638. return throttle(e => {
  3639. if (!e || !utils$1.isNumber(e.loaded)) {
  3640. return;
  3641. }
  3642. const rawLoaded = e.loaded;
  3643. const total = e.lengthComputable ? e.total : undefined;
  3644. const loaded = Math.max(0, total != null ? Math.min(rawLoaded, total) : rawLoaded);
  3645. const progressBytes = Math.max(0, loaded - bytesNotified);
  3646. const rate = _speedometer(progressBytes);
  3647. bytesNotified = Math.max(bytesNotified, loaded);
  3648. const data = {
  3649. loaded,
  3650. total,
  3651. progress: total ? loaded / total : undefined,
  3652. bytes: progressBytes,
  3653. rate: rate ? rate : undefined,
  3654. estimated: rate && total ? (total - loaded) / rate : undefined,
  3655. event: e,
  3656. lengthComputable: total != null,
  3657. [isDownloadStream ? 'download' : 'upload']: true
  3658. };
  3659. listener(data);
  3660. }, freq);
  3661. };
  3662. const progressEventDecorator = (total, throttled) => {
  3663. const lengthComputable = total != null;
  3664. return [loaded => throttled[0]({
  3665. lengthComputable,
  3666. total,
  3667. loaded
  3668. }), throttled[1]];
  3669. };
  3670. const asyncDecorator = (fn, scheduler = utils$1.asap) => (...args) => scheduler(() => fn(...args));
  3671. /**
  3672. * Estimate data: URL byte lengths *without* allocating large buffers.
  3673. * - Fetch percent-decodes a base64 body before decoding it.
  3674. * - Node's Buffer.from(body, 'base64') sizes its backing allocation from the
  3675. * percent-decoded body, including ignored characters and content after padding.
  3676. * - Non-base64 data is percent-decoded and then encoded as UTF-8.
  3677. */
  3678. const isHexDigit = charCode => charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102;
  3679. const isPercentEncodedByte = (str, i, len) => i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
  3680. const hexValue = charCode => charCode <= 57 ? charCode - 48 : (charCode & 0xdf) - 55;
  3681. const isBase64Char = charCode => charCode >= 65 && charCode <= 90 ||
  3682. // A-Z
  3683. charCode >= 97 && charCode <= 122 ||
  3684. // a-z
  3685. charCode >= 48 && charCode <= 57 ||
  3686. // 0-9
  3687. charCode === 43 ||
  3688. // +
  3689. charCode === 47 ||
  3690. // /
  3691. charCode === 45 ||
  3692. // - (base64url)
  3693. charCode === 95; // _ (base64url)
  3694. const isBase64Whitespace = charCode => charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32;
  3695. const base64Bytes = significant => {
  3696. const groups = Math.floor(significant / 4);
  3697. const remainder = significant % 4;
  3698. return groups * 3 + (remainder === 2 ? 1 : remainder === 3 ? 2 : 0);
  3699. };
  3700. // Buffer.byteLength(body, 'base64') uses the raw string length as an allocation
  3701. // upper bound even when Buffer.from later ignores characters or stops at '='.
  3702. const estimateBase64BufferAllocation = body => {
  3703. const len = body.length;
  3704. let padding = 0;
  3705. if (len > 0 && body.charCodeAt(len - 1) === 61 /* '=' */) {
  3706. padding++;
  3707. if (len > 1 && body.charCodeAt(len - 2) === 61 /* '=' */) {
  3708. padding++;
  3709. }
  3710. }
  3711. return Math.floor((len - padding) * 3 / 4);
  3712. };
  3713. const estimatePercentDecodedBase64BufferAllocation = body => {
  3714. // Ordinary Base64 needs only its length and trailing padding.
  3715. if (body.indexOf('%') === -1) {
  3716. return estimateBase64BufferAllocation(body);
  3717. }
  3718. let length = 0;
  3719. let previous = 0;
  3720. let last = 0;
  3721. for (let i = 0, len = body.length; i < len; i++) {
  3722. let code = body.charCodeAt(i);
  3723. if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  3724. code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));
  3725. i += 2;
  3726. }
  3727. length++;
  3728. previous = last;
  3729. last = code;
  3730. }
  3731. const padding = last === 61 ? previous === 61 ? 2 : 1 : 0;
  3732. return Math.floor((length - padding) * 3 / 4);
  3733. };
  3734. const estimatePercentDecodedBase64Bytes = body => {
  3735. const len = body.length;
  3736. let significant = 0;
  3737. let padding = 0;
  3738. let invalid = false;
  3739. for (let i = 0; i < len; i++) {
  3740. let code = body.charCodeAt(i);
  3741. if (code === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  3742. code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2));
  3743. i += 2;
  3744. }
  3745. if (isBase64Whitespace(code)) {
  3746. continue;
  3747. }
  3748. if (code === 61 /* '=' */) {
  3749. padding++;
  3750. continue;
  3751. }
  3752. if (!isBase64Char(code) || padding > 0) {
  3753. invalid = true;
  3754. continue;
  3755. }
  3756. significant++;
  3757. }
  3758. // Fetch rejects malformed forgiving-base64 input. Returning the raw-size
  3759. // allocation bound keeps that invalid input from becoming a pre-check bypass.
  3760. if (invalid || padding > 2 || padding > 0 && (significant + padding) % 4 !== 0 || significant % 4 === 1) {
  3761. return estimateBase64BufferAllocation(body);
  3762. }
  3763. return base64Bytes(significant);
  3764. };
  3765. const estimateDataURLBytes = (url, estimateBase64, base64Pattern) => {
  3766. if (!url || typeof url !== 'string') return 0;
  3767. if (!/^data:/i.test(url)) return 0;
  3768. const comma = url.indexOf(',');
  3769. if (comma < 0) return 0;
  3770. const meta = url.slice(5, comma);
  3771. const body = url.slice(comma + 1);
  3772. const isBase64 = base64Pattern.test(meta);
  3773. if (isBase64) {
  3774. return estimateBase64(body);
  3775. }
  3776. // Compute UTF-8 byte length directly from UTF-16 code units without allocating
  3777. // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
  3778. // Valid %XX triplets count as one decoded byte; this matches the bytes that
  3779. // decodeURIComponent(body) would produce before Buffer re-encodes the string.
  3780. let bytes = 0;
  3781. for (let i = 0, len = body.length; i < len; i++) {
  3782. const c = body.charCodeAt(i);
  3783. if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  3784. bytes += 1;
  3785. i += 2;
  3786. } else if (c < 0x80) {
  3787. bytes += 1;
  3788. } else if (c < 0x800) {
  3789. bytes += 2;
  3790. } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
  3791. const next = body.charCodeAt(i + 1);
  3792. if (next >= 0xdc00 && next <= 0xdfff) {
  3793. bytes += 4;
  3794. i++;
  3795. } else {
  3796. bytes += 3;
  3797. }
  3798. } else {
  3799. bytes += 3;
  3800. }
  3801. }
  3802. return bytes;
  3803. };
  3804. /**
  3805. * Estimate the percent-decoded payload size used by Fetch data: URLs.
  3806. *
  3807. * @param {string} url
  3808. * @returns {number}
  3809. */
  3810. function estimateDataURLDecodedBytes(url) {
  3811. // Fetch removes URL fragments before processing a data: URL.
  3812. const fragmentIndex = typeof url === 'string' ? url.indexOf('#') : -1;
  3813. return estimateDataURLBytes(fragmentIndex === -1 ? url : url.slice(0, fragmentIndex), estimatePercentDecodedBase64Bytes, /; *base64[\t\n\f\r ]*$/i);
  3814. }
  3815. /**
  3816. * Estimate the Buffer backing allocation used after Node's percent-decoding step.
  3817. *
  3818. * @param {string} url
  3819. * @returns {number}
  3820. */
  3821. function estimateDataURLBufferAllocation(url) {
  3822. // Match fromDataURI's case-insensitive protocol and encoding suffix.
  3823. return estimateDataURLBytes(url, estimatePercentDecodedBase64BufferAllocation, /;base64$/i);
  3824. }
  3825. const zlibOptions = {
  3826. flush: zlib.constants.Z_SYNC_FLUSH,
  3827. finishFlush: zlib.constants.Z_SYNC_FLUSH
  3828. };
  3829. const brotliOptions = {
  3830. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  3831. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  3832. };
  3833. const zstdOptions = {
  3834. flush: zlib.constants.ZSTD_e_flush,
  3835. finishFlush: zlib.constants.ZSTD_e_flush
  3836. };
  3837. const isBrotliSupported = utils$1.isFunction(zlib.createBrotliDecompress);
  3838. const isZstdSupported = utils$1.isFunction(zlib.createZstdDecompress);
  3839. const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
  3840. const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
  3841. const scheduleProgress = typeof process !== 'undefined' && process.nextTick ? process.nextTick.bind(process) : utils$1.asap;
  3842. const {
  3843. http: httpFollow,
  3844. https: httpsFollow
  3845. } = followRedirects;
  3846. const isHttps = /https:?/;
  3847. // Symbols used to bind a single 'error' listener to a pooled socket and track
  3848. // the request currently owning that socket across keep-alive reuse (issue #10780).
  3849. const kAxiosSocketListener = Symbol('axios.http.socketListener');
  3850. const kAxiosCurrentReq = Symbol('axios.http.currentReq');
  3851. // A shared listener avoids retaining an adapter context for the lifetime of a
  3852. // pooled socket. EventEmitter invokes listeners with `this` set to the emitter.
  3853. function handleSocketError(err) {
  3854. const current = this[kAxiosCurrentReq];
  3855. if (current && !current.destroyed) {
  3856. current.destroy(err);
  3857. }
  3858. }
  3859. // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
  3860. // can strip them without clobbering a user-supplied agent that happens to be
  3861. // an HttpsProxyAgent.
  3862. const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
  3863. // Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
  3864. // through the same proxy reuse a single agent (and its socket pool). The
  3865. // keyspace is bounded by the set of distinct proxy configs the process uses,
  3866. // so unbounded growth is not a concern in practice.
  3867. const tunnelingAgentCache = new Map();
  3868. const tunnelingAgentCacheUser = new WeakMap();
  3869. const directAgents = new WeakMap();
  3870. const directAgentHooks = ['createConnection', 'getName'];
  3871. const nativeAgentPoolHooks = ['addRequest', 'createSocket', 'removeSocket', 'keepSocketAlive', 'reuseSocket', '_getSession', '_cacheSession', '_evictSession'];
  3872. // Minimum minor versions where Node's HTTP Agent supports native proxyEnv
  3873. // handling. Checking the selected agent below also covers startup modes such
  3874. // as NODE_OPTIONS=--use-env-proxy and --no-use-env-proxy precedence.
  3875. const NODE_NATIVE_ENV_PROXY_SUPPORT = {
  3876. 22: 21,
  3877. 24: 5
  3878. };
  3879. function isNodeNativeEnvProxySupported(nodeVersion = process.versions && process.versions.node) {
  3880. if (!nodeVersion) {
  3881. return false;
  3882. }
  3883. const [major, minor] = nodeVersion.split('.').map(part => Number(part));
  3884. if (!Number.isInteger(major) || !Number.isInteger(minor)) {
  3885. return false;
  3886. }
  3887. if (major > 24) {
  3888. return true;
  3889. }
  3890. return NODE_NATIVE_ENV_PROXY_SUPPORT[major] != null && minor >= NODE_NATIVE_ENV_PROXY_SUPPORT[major];
  3891. }
  3892. function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process.versions.node) {
  3893. if (!isNodeNativeEnvProxySupported(nodeVersion)) {
  3894. return false;
  3895. }
  3896. const agentOptions = agent && agent.options;
  3897. return Boolean(agentOptions && utils$1.hasOwnProp(agentOptions, 'proxyEnv') && agentOptions.proxyEnv != null);
  3898. }
  3899. function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) {
  3900. return isHttps.test(options.protocol) ? configHttpsAgent || https.globalAgent : configHttpAgent || http.globalAgent;
  3901. }
  3902. function getDirectAgent(configuredAgent, transport) {
  3903. if (!process.allowedNodeEnvironmentFlags || !process.allowedNodeEnvironmentFlags.has('--use-env-proxy')) {
  3904. return configuredAgent;
  3905. }
  3906. const agent = configuredAgent || transport.globalAgent;
  3907. const options = agent && agent.options;
  3908. if (!(agent instanceof transport.Agent) || agent.protocol !== transport.globalAgent.protocol || !options || !utils$1.hasOwnProp(options, 'proxyEnv') || typeof options.proxyEnv !== 'object' || options.proxyEnv === null) {
  3909. return configuredAgent;
  3910. }
  3911. // These hooks own pool queues or TLS session state. Neither binding them to
  3912. // the source agent nor copying them without subclass state preserves their
  3913. // behavior on a separate direct pool.
  3914. for (const hook of nativeAgentPoolHooks) {
  3915. if (utils$1.isFunction(transport.Agent.prototype[hook]) && agent[hook] !== transport.Agent.prototype[hook]) {
  3916. throw new AxiosError('proxy: false cannot adapt an agent overriding ' + hook + '; use an agent constructed without proxyEnv', AxiosError.ERR_BAD_OPTION_VALUE);
  3917. }
  3918. }
  3919. // Node snapshots proxyEnv when constructing the agent. Keep this check
  3920. // conservative even when the caller later removes protocol-specific entries.
  3921. let direct = directAgents.get(agent);
  3922. if (!direct) {
  3923. direct = new transport.Agent({
  3924. ...options,
  3925. proxyEnv: undefined
  3926. });
  3927. // Agent.destroy() does not emit an event. Keep the associated pool under
  3928. // the configured agent's lifetime, including agents reused after destroy().
  3929. const destroy = agent.destroy;
  3930. agent.destroy = function destroyWithDirectAgent() {
  3931. try {
  3932. return destroy.apply(this, arguments);
  3933. } finally {
  3934. direct.destroy();
  3935. }
  3936. };
  3937. directAgents.set(agent, direct);
  3938. }
  3939. // Connections and pool keys do not own the direct pool's queues. Preserve
  3940. // their configured receiver and refresh hooks that change between requests.
  3941. for (const hook of directAgentHooks) {
  3942. direct[hook] = agent[hook] === transport.Agent.prototype[hook] ? transport.Agent.prototype[hook] : bind(agent[hook], agent);
  3943. }
  3944. return direct;
  3945. }
  3946. function setDirectAgent(options, configHttpAgent, configHttpsAgent) {
  3947. const secure = isHttps.test(options.protocol);
  3948. const agent = getDirectAgent(secure ? configHttpsAgent : configHttpAgent, secure ? https : http);
  3949. options.agent = agent;
  3950. if (options.agents) {
  3951. options.agents[secure ? 'https' : 'http'] = agent;
  3952. }
  3953. }
  3954. function getTunnelingAgent(agentOptions, userHttpsAgent) {
  3955. const key = agentOptions.protocol + '//' + agentOptions.hostname + ':' + (agentOptions.port || '') + '#' + (agentOptions.auth || '');
  3956. const cache = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent) : tunnelingAgentCache;
  3957. let agent = cache.get(key);
  3958. if (agent) return agent;
  3959. // Preserve per-request TLS options for the proxy connection, with our proxy
  3960. // fields taking precedence. Global-agent options belong only to the origin
  3961. // TLS upgrade in the callback below.
  3962. const merged = userHttpsAgent && userHttpsAgent.options ? {
  3963. ...userHttpsAgent.options,
  3964. ...agentOptions
  3965. } : agentOptions;
  3966. agent = new HttpsProxyAgent(merged);
  3967. const callback = agent.callback;
  3968. agent.callback = function axiosTunnelingAgentCallback(req, opts) {
  3969. // Without a proxy the origin TLS connection would be made by https.globalAgent,
  3970. // so its options have to reach the tunneled origin too. Resolved per request
  3971. // because the tunneling agent outlives any one of them.
  3972. const originTLSAgent = userHttpsAgent || https.globalAgent;
  3973. const originTLSOptions = originTLSAgent && originTLSAgent.options;
  3974. // HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
  3975. return callback.call(this, req, {
  3976. ...originTLSOptions,
  3977. ...opts
  3978. });
  3979. };
  3980. agent[kAxiosInstalledTunnel] = true;
  3981. cache.set(key, agent);
  3982. return agent;
  3983. }
  3984. const supportedProtocols = platform.protocols.map(protocol => {
  3985. return protocol + ':';
  3986. });
  3987. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  3988. // Decode before composing the `auth` option so credentials such as
  3989. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  3990. // original value for malformed input so a bad encoding never throws.
  3991. const decodeURIComponentSafe$1 = value => {
  3992. if (!utils$1.isString(value)) {
  3993. return value;
  3994. }
  3995. try {
  3996. return decodeURIComponent(value);
  3997. } catch (error) {
  3998. return value;
  3999. }
  4000. };
  4001. const flushOnFinish = (stream, [throttled, flush]) => {
  4002. stream.on('end', flush).on('error', flush);
  4003. return throttled;
  4004. };
  4005. const http2Sessions = new Http2Sessions();
  4006. /**
  4007. * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
  4008. * call them with the options object.
  4009. *
  4010. * @param {Object<string, any>} options - The options object that was passed to the request.
  4011. *
  4012. * @returns {Object<string, any>}
  4013. */
  4014. function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
  4015. if (!isSameOriginRedirect(options, requestDetails)) {
  4016. stripMatchingHeaders(options.headers, new Set(['authorization', 'cookie']));
  4017. delete options.auth;
  4018. }
  4019. if (options.beforeRedirects.proxy) {
  4020. options.beforeRedirects.proxy(options);
  4021. }
  4022. if (options.beforeRedirects.auth) {
  4023. options.beforeRedirects.auth(options);
  4024. }
  4025. if (options.beforeRedirects.sensitiveHeaders) {
  4026. options.beforeRedirects.sensitiveHeaders(options, requestDetails);
  4027. }
  4028. if (options.beforeRedirects.direct) {
  4029. options.beforeRedirects.direct(options);
  4030. }
  4031. if (options.beforeRedirects.config) {
  4032. options.beforeRedirects.config(options, responseDetails, requestDetails);
  4033. }
  4034. }
  4035. function stripMatchingHeaders(headers, sensitiveSet) {
  4036. if (!headers) {
  4037. return;
  4038. }
  4039. Object.keys(headers).forEach(header => {
  4040. if (sensitiveSet.has(header.toLowerCase())) {
  4041. delete headers[header];
  4042. }
  4043. });
  4044. }
  4045. function isSameOriginRedirect(redirectOptions, requestDetails) {
  4046. if (!requestDetails) {
  4047. return false;
  4048. }
  4049. try {
  4050. return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
  4051. } catch (e) {
  4052. // If origin comparison fails, treat the redirect as unsafe.
  4053. return false;
  4054. }
  4055. }
  4056. /**
  4057. * If the proxy or config afterRedirects functions are defined, call them with the options
  4058. *
  4059. * @param {http.ClientRequestArgs} options
  4060. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  4061. * @param {string} location
  4062. * @param {boolean} [allowEnvProxy=true] whether environment proxy configuration can be used
  4063. *
  4064. * @returns {boolean} whether a proxy applies to the selected transport
  4065. */
  4066. function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent, allowEnvProxy = true) {
  4067. let proxy = configProxy;
  4068. const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
  4069. if (!proxy && proxy !== false && allowEnvProxy && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
  4070. const proxyUrl = getProxyForUrl(location);
  4071. if (proxyUrl) {
  4072. if (!shouldBypassProxy(location)) {
  4073. proxy = new URL(proxyUrl);
  4074. }
  4075. }
  4076. }
  4077. // On redirect re-invocation, strip any stale Proxy-Authorization header carried
  4078. // over from the prior request (e.g. new target no longer uses a proxy, or uses
  4079. // a different proxy). Skip on the initial request so user-supplied headers are
  4080. // preserved. Header names are case-insensitive, so remove every case variant.
  4081. if (isRedirect && options.headers) {
  4082. for (const name of Object.keys(options.headers)) {
  4083. if (name.toLowerCase() === 'proxy-authorization') {
  4084. delete options.headers[name];
  4085. }
  4086. }
  4087. }
  4088. // Strip any tunneling agent we installed for the previous hop so a redirect
  4089. // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
  4090. // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
  4091. // (which won't carry the marker) is left alone.
  4092. if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
  4093. options.agent = undefined;
  4094. }
  4095. if (isRedirect && options.agents && options.agents.https && options.agents.https[kAxiosInstalledTunnel]) {
  4096. options.agents.https = configHttpsAgent;
  4097. }
  4098. if (proxy) {
  4099. // Read proxy fields without traversing the prototype chain. URL instances expose
  4100. // username/password/hostname/host/port/protocol via getters on URL.prototype (so
  4101. // direct reads are shielded), but plain object proxies — and the `auth` field
  4102. // (which URL does not expose) — must be guarded so a polluted Object.prototype
  4103. // (e.g. Object.prototype.auth = { username, password }) cannot inject
  4104. // attacker-controlled credentials into the Proxy-Authorization header or
  4105. // redirect proxying to an attacker-controlled host.
  4106. const isProxyURL = proxy instanceof URL;
  4107. const readProxyField = key => isProxyURL || utils$1.hasOwnProp(proxy, key) ? proxy[key] : undefined;
  4108. const proxyUsername = readProxyField('username');
  4109. const proxyPassword = readProxyField('password');
  4110. let proxyAuth = utils$1.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
  4111. // Basic proxy authorization
  4112. if (proxyUsername) {
  4113. proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
  4114. }
  4115. if (proxyAuth) {
  4116. // Support proxy auth object form. Read sub-fields via own-prop checks so a
  4117. // plain object inheriting from polluted Object.prototype cannot leak creds.
  4118. const authIsObject = typeof proxyAuth === 'object';
  4119. const authUsername = authIsObject && utils$1.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
  4120. const authPassword = authIsObject && utils$1.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
  4121. const validProxyAuth = Boolean(authUsername || authPassword);
  4122. if (validProxyAuth) {
  4123. proxyAuth = (authUsername || '') + ':' + (authPassword || '');
  4124. } else if (authIsObject) {
  4125. throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, {
  4126. proxy
  4127. });
  4128. }
  4129. }
  4130. const targetIsHttps = isHttps.test(options.protocol);
  4131. if (targetIsHttps) {
  4132. // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
  4133. // the origin so the proxy cannot inspect the URL, headers, or body — the
  4134. // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
  4135. // sends Proxy-Authorization on the CONNECT request only, never on the
  4136. // wrapped TLS request, which is why we don't stamp it onto
  4137. // options.headers here. If the user already supplied an HttpsProxyAgent,
  4138. // they own tunneling end-to-end and we leave them alone; otherwise we
  4139. // install our own tunneling agent and forward their TLS options (if any)
  4140. // so a custom httpsAgent for cert pinning / rejectUnauthorized still
  4141. // applies to the origin TLS upgrade.
  4142. if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
  4143. const proxyHost = readProxyField('hostname') || readProxyField('host');
  4144. const proxyPort = readProxyField('port');
  4145. const rawProxyProtocol = readProxyField('protocol');
  4146. const normalizedProtocol = rawProxyProtocol ? rawProxyProtocol.includes(':') ? rawProxyProtocol : `${rawProxyProtocol}:` : 'http:';
  4147. // Bracket IPv6 literals for URL parsing; URL.hostname strips the
  4148. // brackets again on read so the agent receives the raw form.
  4149. const proxyHostForURL = proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[') ? `[${proxyHost}]` : proxyHost;
  4150. const proxyURL = new URL(`${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`);
  4151. const agentOptions = {
  4152. protocol: proxyURL.protocol,
  4153. hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
  4154. port: proxyURL.port,
  4155. auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined
  4156. };
  4157. if (proxyURL.protocol === 'https:') {
  4158. agentOptions.ALPNProtocols = ['http/1.1'];
  4159. }
  4160. const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
  4161. // Set both: `options.agent` is consumed by the native https.request path
  4162. // (maxRedirects === 0); `options.agents.https` is consumed by
  4163. // follow-redirects, which ignores `options.agent` when `options.agents`
  4164. // is present.
  4165. options.agent = tunnelingAgent;
  4166. if (options.agents) {
  4167. options.agents.https = tunnelingAgent;
  4168. }
  4169. }
  4170. } else {
  4171. // Forward-proxy mode for plaintext HTTP targets. The request line carries
  4172. // the absolute URL and the proxy sees everything — acceptable for plain
  4173. // HTTP since the wire was already plaintext.
  4174. if (proxyAuth) {
  4175. const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
  4176. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  4177. }
  4178. // Preserve a user-supplied Host header (case-insensitive) so callers can override
  4179. // the value forwarded to the proxy; otherwise default to the request URL's host.
  4180. let hasUserHostHeader = false;
  4181. for (const name of Object.keys(options.headers)) {
  4182. if (name.toLowerCase() === 'host') {
  4183. hasUserHostHeader = true;
  4184. break;
  4185. }
  4186. }
  4187. if (!hasUserHostHeader) {
  4188. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  4189. }
  4190. const proxyHost = readProxyField('hostname') || readProxyField('host');
  4191. options.hostname = proxyHost;
  4192. // Replace 'host' since options is not a URL object
  4193. options.host = proxyHost;
  4194. options.port = readProxyField('port');
  4195. options.path = location;
  4196. const proxyProtocol = readProxyField('protocol');
  4197. if (proxyProtocol) {
  4198. options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
  4199. }
  4200. }
  4201. }
  4202. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  4203. // Configure proxy for redirected request, passing the original config proxy to apply
  4204. // the exact same logic as if the redirected request was performed by axios directly.
  4205. setProxy(redirectOptions, configProxy, redirectOptions.href, true, configHttpsAgent, configHttpAgent, allowEnvProxy);
  4206. };
  4207. return Boolean(proxy || configProxy !== false && allowEnvProxy && isNodeEnvProxyEnabled(proxyEnvAgent));
  4208. }
  4209. const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
  4210. // temporary hotfix
  4211. const wrapAsync = asyncExecutor => {
  4212. return new Promise((resolve, reject) => {
  4213. let onDone;
  4214. let isDone;
  4215. const done = (value, isRejected) => {
  4216. if (isDone) return;
  4217. isDone = true;
  4218. onDone && onDone(value, isRejected);
  4219. };
  4220. const _resolve = value => {
  4221. done(value);
  4222. resolve(value);
  4223. };
  4224. const _reject = reason => {
  4225. done(reason, true);
  4226. reject(reason);
  4227. };
  4228. asyncExecutor(_resolve, _reject, onDoneHandler => onDone = onDoneHandler).catch(_reject);
  4229. });
  4230. };
  4231. const resolveFamily = ({
  4232. address,
  4233. family
  4234. }) => {
  4235. if (!utils$1.isString(address)) {
  4236. throw new AxiosError('address must be a string', AxiosError.ERR_BAD_OPTION_VALUE);
  4237. }
  4238. return {
  4239. address,
  4240. family: family || (address.indexOf('.') < 0 ? 6 : 4)
  4241. };
  4242. };
  4243. const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {
  4244. address,
  4245. family
  4246. });
  4247. const normalizedLookupCache = new WeakMap();
  4248. const normalizeLookup = lookup => {
  4249. let normalized = normalizedLookupCache.get(lookup);
  4250. if (normalized) {
  4251. return normalized;
  4252. }
  4253. const callbackLookup = callbackify(lookup, value => utils$1.isArray(value) ? value : [value]);
  4254. // Support opt.all, which is required by current Node.js releases.
  4255. normalized = (hostname, opt, cb) => {
  4256. callbackLookup(hostname, opt, (err, arg0, arg1) => {
  4257. if (err) {
  4258. return cb(err);
  4259. }
  4260. let addresses;
  4261. try {
  4262. addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
  4263. } catch (error) {
  4264. return cb(error);
  4265. }
  4266. opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
  4267. });
  4268. };
  4269. normalizedLookupCache.set(lookup, normalized);
  4270. return normalized;
  4271. };
  4272. const http2Transport = {
  4273. request(options, cb) {
  4274. const authority = options.protocol + '//' + options.hostname + ':' + (options.port || (options.protocol === 'https:' ? 443 : 80));
  4275. const {
  4276. http2Options,
  4277. headers
  4278. } = options;
  4279. const session = http2Sessions.getSession(authority, http2Options);
  4280. const {
  4281. HTTP2_HEADER_SCHEME,
  4282. HTTP2_HEADER_METHOD,
  4283. HTTP2_HEADER_PATH,
  4284. HTTP2_HEADER_STATUS
  4285. } = http2.constants;
  4286. const http2Headers = {
  4287. [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
  4288. [HTTP2_HEADER_METHOD]: options.method,
  4289. [HTTP2_HEADER_PATH]: options.path
  4290. };
  4291. utils$1.forEach(headers, (header, name) => {
  4292. name.charAt(0) !== ':' && (http2Headers[name] = header);
  4293. });
  4294. const req = session.request(http2Headers);
  4295. req.once('response', responseHeaders => {
  4296. const response = req; //duplex
  4297. responseHeaders = Object.assign({}, responseHeaders);
  4298. const status = responseHeaders[HTTP2_HEADER_STATUS];
  4299. delete responseHeaders[HTTP2_HEADER_STATUS];
  4300. response.headers = responseHeaders;
  4301. response.statusCode = +status;
  4302. cb(response);
  4303. });
  4304. return req;
  4305. }
  4306. };
  4307. /*eslint consistent-return:0*/
  4308. var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
  4309. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  4310. // Read config pollution-safely: own properties and members inherited from
  4311. // a non-Object.prototype source (e.g. an Object.create(defaults) template)
  4312. // are honored, but values injected onto a polluted Object.prototype are
  4313. // ignored. All behavior-affecting reads in this adapter go through own()
  4314. // so the protection boundary stays consistent.
  4315. const own = key => utils$1.getSafeProp(config, key);
  4316. const transitional = own('transitional') || transitionalDefaults;
  4317. let data = own('data');
  4318. let lookup = own('lookup');
  4319. let family = own('family');
  4320. let httpVersion = own('httpVersion');
  4321. if (httpVersion === undefined) httpVersion = 1;
  4322. const rawHttpVersion = httpVersion;
  4323. let http2Options = own('http2Options');
  4324. const configProxy = own('proxy');
  4325. const httpAgent = own('httpAgent');
  4326. const httpsAgent = own('httpsAgent');
  4327. const responseType = own('responseType');
  4328. const responseEncoding = own('responseEncoding');
  4329. const socketPath = own('socketPath');
  4330. const method = own('method').toUpperCase();
  4331. const maxRedirects = own('maxRedirects');
  4332. const maxBodyLength = own('maxBodyLength');
  4333. const maxContentLength = own('maxContentLength');
  4334. const decompress = own('decompress');
  4335. let isDone;
  4336. let rejected = false;
  4337. let req;
  4338. let connectPhaseTimer;
  4339. try {
  4340. httpVersion = +httpVersion;
  4341. } catch (err) {
  4342. throw new AxiosError('Invalid protocol version: value is not a number', AxiosError.ERR_BAD_OPTION_VALUE, config);
  4343. }
  4344. if (Number.isNaN(httpVersion)) {
  4345. throw new AxiosError(`Invalid protocol version: '${rawHttpVersion}' is not a number`, AxiosError.ERR_BAD_OPTION_VALUE, config);
  4346. }
  4347. if (httpVersion !== 1 && httpVersion !== 2) {
  4348. throw new AxiosError(`Unsupported protocol version '${httpVersion}'`, AxiosError.ERR_BAD_OPTION_VALUE, config);
  4349. }
  4350. const isHttp2 = httpVersion === 2;
  4351. if (lookup) {
  4352. lookup = normalizeLookup(lookup);
  4353. }
  4354. const abortEmitter = new events.EventEmitter();
  4355. function abort(reason) {
  4356. try {
  4357. abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
  4358. } catch (err) {
  4359. // ignore emit errors
  4360. }
  4361. }
  4362. function clearConnectPhaseTimer() {
  4363. if (connectPhaseTimer) {
  4364. clearTimeout(connectPhaseTimer);
  4365. connectPhaseTimer = null;
  4366. }
  4367. }
  4368. function createTimeoutError() {
  4369. const configTimeout = own('timeout');
  4370. let timeoutErrorMessage = configTimeout ? 'timeout of ' + configTimeout + 'ms exceeded' : 'timeout exceeded';
  4371. const configTimeoutErrorMessage = own('timeoutErrorMessage');
  4372. if (configTimeoutErrorMessage) {
  4373. timeoutErrorMessage = configTimeoutErrorMessage;
  4374. }
  4375. return new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, req);
  4376. }
  4377. abortEmitter.once('abort', reject);
  4378. const onFinished = () => {
  4379. clearConnectPhaseTimer();
  4380. if (config.cancelToken) {
  4381. config.cancelToken.unsubscribe(abort);
  4382. }
  4383. if (config.signal) {
  4384. config.signal.removeEventListener('abort', abort);
  4385. }
  4386. abortEmitter.removeAllListeners();
  4387. };
  4388. if (config.cancelToken || config.signal) {
  4389. config.cancelToken && config.cancelToken.subscribe(abort);
  4390. if (config.signal) {
  4391. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  4392. }
  4393. }
  4394. onDone((response, isRejected) => {
  4395. isDone = true;
  4396. clearConnectPhaseTimer();
  4397. if (isRejected) {
  4398. rejected = true;
  4399. onFinished();
  4400. return;
  4401. }
  4402. const {
  4403. data
  4404. } = response;
  4405. if (data instanceof stream.Readable || data instanceof stream.Duplex) {
  4406. const offListeners = stream.finished(data, () => {
  4407. offListeners();
  4408. onFinished();
  4409. });
  4410. } else {
  4411. onFinished();
  4412. }
  4413. });
  4414. // Parse url
  4415. const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
  4416. // Unix-socket requests (own socketPath) commonly pass a path-only url
  4417. // like '/foo'; supply a synthetic base so new URL() can still parse it.
  4418. // Use the own-property value (not config.socketPath) so a polluted
  4419. // prototype cannot influence URL base selection.
  4420. const urlBase = socketPath ? 'http://localhost' : platform.hasBrowserEnv ? platform.origin : undefined;
  4421. const parsed = new URL(fullPath, urlBase);
  4422. const protocol = parsed.protocol || supportedProtocols[0];
  4423. if (protocol === 'data:') {
  4424. // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
  4425. if (maxContentLength > -1) {
  4426. // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
  4427. const dataUrl = String(own('url') || fullPath || '');
  4428. const estimated = estimateDataURLBufferAllocation(dataUrl);
  4429. if (estimated > maxContentLength) {
  4430. return reject(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config));
  4431. }
  4432. }
  4433. let convertedData;
  4434. if (method !== 'GET') {
  4435. return settle(resolve, reject, {
  4436. status: 405,
  4437. statusText: 'method not allowed',
  4438. headers: {},
  4439. config
  4440. });
  4441. }
  4442. try {
  4443. convertedData = fromDataURI(own('url'), responseType === 'blob', {
  4444. Blob: config.env && config.env.Blob
  4445. });
  4446. } catch (err) {
  4447. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  4448. }
  4449. // Check bytes before converting the result to text or a stream.
  4450. if (maxContentLength > -1 && (responseType === 'blob' ? convertedData.size : convertedData.length) > maxContentLength) {
  4451. return reject(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config));
  4452. }
  4453. if (responseType === 'text') {
  4454. convertedData = convertedData.toString(responseEncoding);
  4455. if (!responseEncoding || responseEncoding === 'utf8') {
  4456. convertedData = utils$1.stripBOM(convertedData);
  4457. }
  4458. } else if (responseType === 'stream') {
  4459. convertedData = stream.Readable.from(convertedData);
  4460. }
  4461. return settle(resolve, reject, {
  4462. data: convertedData,
  4463. status: 200,
  4464. statusText: 'OK',
  4465. headers: new AxiosHeaders(),
  4466. config
  4467. });
  4468. }
  4469. if (supportedProtocols.indexOf(protocol) === -1) {
  4470. return reject(new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config));
  4471. }
  4472. const headers = AxiosHeaders.from(config.headers).normalize();
  4473. // Set User-Agent (required by some servers)
  4474. // See https://github.com/axios/axios/issues/69
  4475. // User-Agent is specified; handle case where no UA header is desired
  4476. // Only set header if it hasn't been set in config
  4477. headers.set('User-Agent', 'axios/' + VERSION, false);
  4478. const {
  4479. onUploadProgress,
  4480. onDownloadProgress
  4481. } = config;
  4482. const maxRate = config.maxRate;
  4483. let maxUploadRate = undefined;
  4484. let maxDownloadRate = undefined;
  4485. // support for spec compliant FormData objects
  4486. if (utils$1.isSpecCompliantForm(data)) {
  4487. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  4488. data = formDataToStream(data, formHeaders => {
  4489. headers.set(formHeaders);
  4490. }, {
  4491. tag: `axios-${VERSION}-boundary`,
  4492. boundary: userBoundary && userBoundary[1] || undefined
  4493. });
  4494. // support for https://www.npmjs.com/package/form-data api
  4495. } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders) && data.getHeaders !== Object.prototype.getHeaders) {
  4496. setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  4497. if (!headers.hasContentLength()) {
  4498. try {
  4499. const knownLength = await util.promisify(data.getLength).call(data);
  4500. Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
  4501. /*eslint no-empty:0*/
  4502. } catch (e) {}
  4503. }
  4504. } else if (utils$1.isBlob(data) || utils$1.isFile(data)) {
  4505. data.size && headers.setContentType(data.type || 'application/octet-stream');
  4506. headers.setContentLength(data.size || 0);
  4507. data = stream.Readable.from(readBlob(data));
  4508. } else if (data && !utils$1.isStream(data)) {
  4509. if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) {
  4510. data = Buffer.from(new Uint8Array(data));
  4511. } else if (utils$1.isString(data)) {
  4512. data = Buffer.from(data, 'utf-8');
  4513. } else {
  4514. return reject(new AxiosError('Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', AxiosError.ERR_BAD_REQUEST, config));
  4515. }
  4516. // Add Content-Length header if data exists
  4517. headers.setContentLength(data.length, false);
  4518. if (maxBodyLength > -1 && data.length > maxBodyLength) {
  4519. return reject(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config));
  4520. }
  4521. }
  4522. const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
  4523. if (utils$1.isArray(maxRate)) {
  4524. maxUploadRate = maxRate[0];
  4525. maxDownloadRate = maxRate[1];
  4526. } else {
  4527. maxUploadRate = maxDownloadRate = maxRate;
  4528. }
  4529. if (data && (onUploadProgress || maxUploadRate)) {
  4530. if (!utils$1.isStream(data)) {
  4531. data = stream.Readable.from(data, {
  4532. objectMode: false
  4533. });
  4534. }
  4535. data = stream.pipeline([data, new AxiosTransformStream({
  4536. maxRate: utils$1.toFiniteNumber(maxUploadRate)
  4537. })], utils$1.noop);
  4538. onUploadProgress && data.on('progress', flushOnFinish(data, progressEventDecorator(contentLength, progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3))));
  4539. }
  4540. // HTTP basic authentication
  4541. let auth = undefined;
  4542. const configAuth = own('auth');
  4543. if (configAuth) {
  4544. const username = utils$1.getSafeProp(configAuth, 'username') || '';
  4545. const password = utils$1.getSafeProp(configAuth, 'password') || '';
  4546. auth = username + ':' + password;
  4547. }
  4548. if (!auth && (parsed.username || parsed.password)) {
  4549. const urlUsername = decodeURIComponentSafe$1(parsed.username);
  4550. const urlPassword = decodeURIComponentSafe$1(parsed.password);
  4551. auth = urlUsername + ':' + urlPassword;
  4552. }
  4553. auth && headers.delete('authorization');
  4554. let path$1;
  4555. try {
  4556. path$1 = buildURL(parsed.pathname + parsed.search, own('params'), own('paramsSerializer')).replace(/^\?/, '');
  4557. } catch (err) {
  4558. return reject(AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config, null, null, {
  4559. url: own('url'),
  4560. exists: true
  4561. }));
  4562. }
  4563. headers.set('Accept-Encoding', utils$1.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') && transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING, false);
  4564. if (isHttp2 && lookup) {
  4565. http2Options = Object.assign(Object.create(null), http2Options, {
  4566. lookup
  4567. });
  4568. }
  4569. // Null-prototype to block prototype pollution gadgets on properties read
  4570. // directly by Node's http.request (e.g. insecureHTTPParser, lookup).
  4571. const options = Object.assign(Object.create(null), {
  4572. path: path$1,
  4573. method: method,
  4574. headers: toByteStringHeaderObject(headers),
  4575. agents: {
  4576. http: httpAgent,
  4577. https: httpsAgent
  4578. },
  4579. auth,
  4580. protocol,
  4581. family,
  4582. beforeRedirect: dispatchBeforeRedirect,
  4583. beforeRedirects: Object.create(null),
  4584. http2Options,
  4585. createConnection: undefined
  4586. });
  4587. // cacheable-lookup integration hotfix
  4588. !utils$1.isUndefined(lookup) && (options.lookup = lookup);
  4589. let proxyApplied = false;
  4590. if (socketPath) {
  4591. if (typeof socketPath !== 'string') {
  4592. return reject(new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config));
  4593. }
  4594. const allowedSocketPaths = own('allowedSocketPaths');
  4595. if (allowedSocketPaths != null) {
  4596. const allowed = Array.isArray(allowedSocketPaths) ? allowedSocketPaths : [allowedSocketPaths];
  4597. const resolvedSocket = path.resolve(socketPath);
  4598. const isAllowed = allowed.some(entry => typeof entry === 'string' && path.resolve(entry) === resolvedSocket);
  4599. if (!isAllowed) {
  4600. return reject(new AxiosError(`socketPath "${socketPath}" is not permitted by allowedSocketPaths`, AxiosError.ERR_BAD_OPTION_VALUE, config));
  4601. }
  4602. }
  4603. options.socketPath = socketPath;
  4604. } else {
  4605. options.hostname = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
  4606. options.port = parsed.port;
  4607. proxyApplied = setProxy(options, configProxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, false, httpsAgent, httpAgent,
  4608. // The HTTP/2 transport connects independently of HTTP/1 agents, so it
  4609. // cannot apply either axios-resolved or agent-local environment proxies.
  4610. // Explicit proxy config is still processed and rejected below.
  4611. !isHttp2);
  4612. }
  4613. let transport;
  4614. let isNativeTransport = false;
  4615. const isHttpsRequest = isHttps.test(options.protocol);
  4616. // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
  4617. // HTTPS target.
  4618. if (!isHttp2 && configProxy === false) {
  4619. setDirectAgent(options, httpAgent, httpsAgent);
  4620. options.beforeRedirects.direct = redirectOptions => {
  4621. setDirectAgent(redirectOptions, httpAgent, httpsAgent);
  4622. };
  4623. } else if (options.agent == null) {
  4624. options.agent = isHttpsRequest ? httpsAgent : httpAgent;
  4625. }
  4626. if (isHttp2) {
  4627. if (proxyApplied) {
  4628. return reject(new AxiosError('HTTP/2 requests with a proxy are not supported', AxiosError.ERR_NOT_SUPPORT, config));
  4629. }
  4630. transport = http2Transport;
  4631. } else {
  4632. const configTransport = own('transport');
  4633. if (configTransport) {
  4634. transport = configTransport;
  4635. } else if (maxRedirects === 0) {
  4636. transport = isHttpsRequest ? https : http;
  4637. isNativeTransport = true;
  4638. } else {
  4639. options.sensitiveHeaders = [];
  4640. if (maxRedirects) {
  4641. options.maxRedirects = maxRedirects;
  4642. }
  4643. const configBeforeRedirect = own('beforeRedirect');
  4644. if (configBeforeRedirect) {
  4645. options.beforeRedirects.config = configBeforeRedirect;
  4646. }
  4647. if (auth) {
  4648. // Restore HTTP Basic credentials on same-origin redirects only.
  4649. // follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
  4650. // cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
  4651. // and is preserved by deliberately not restoring on origin change.
  4652. const requestOrigin = parsed.origin;
  4653. const authToRestore = auth;
  4654. options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
  4655. try {
  4656. if (new URL(redirectOptions.href).origin === requestOrigin) {
  4657. redirectOptions.auth = authToRestore;
  4658. }
  4659. } catch (e) {
  4660. // ignore malformed URL: leaving auth stripped is fail-safe
  4661. }
  4662. };
  4663. }
  4664. const sensitiveHeaders = own('sensitiveHeaders');
  4665. if (sensitiveHeaders != null) {
  4666. if (!utils$1.isArray(sensitiveHeaders)) {
  4667. return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
  4668. }
  4669. const sensitiveSet = new Set();
  4670. for (const header of sensitiveHeaders) {
  4671. if (!utils$1.isString(header)) {
  4672. return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
  4673. }
  4674. sensitiveSet.add(header.toLowerCase());
  4675. }
  4676. if (sensitiveSet.size) {
  4677. options.sensitiveHeaders = Array.from(sensitiveSet);
  4678. options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(redirectOptions, requestDetails) {
  4679. if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
  4680. stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
  4681. }
  4682. };
  4683. }
  4684. }
  4685. transport = isHttpsRequest ? httpsFollow : httpFollow;
  4686. }
  4687. }
  4688. // Set an explicit maxBodyLength option for transports that inspect it.
  4689. // When maxBodyLength is -1 (default/unlimited), use Infinity so
  4690. // follow-redirects does not fall back to its own 10MB default.
  4691. if (maxBodyLength > -1) {
  4692. options.maxBodyLength = maxBodyLength;
  4693. } else {
  4694. options.maxBodyLength = Infinity;
  4695. }
  4696. // Always set an explicit own value so a polluted
  4697. // Object.prototype.insecureHTTPParser cannot enable the lenient parser
  4698. // through Node's internal options copy
  4699. options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
  4700. // Create the request
  4701. req = transport.request(options, function handleResponse(res) {
  4702. clearConnectPhaseTimer();
  4703. if (req.destroyed) return;
  4704. const streams = [res];
  4705. const responseLength = utils$1.toFiniteNumber(res.headers['content-length']);
  4706. if (onDownloadProgress || maxDownloadRate) {
  4707. const transformStream = new AxiosTransformStream({
  4708. maxRate: utils$1.toFiniteNumber(maxDownloadRate)
  4709. });
  4710. onDownloadProgress && transformStream.on('progress', flushOnFinish(transformStream, progressEventDecorator(responseLength, progressEventReducer(asyncDecorator(onDownloadProgress, scheduleProgress), true, 3))));
  4711. streams.push(transformStream);
  4712. }
  4713. // decompress the response body transparently if required
  4714. let responseStream = res;
  4715. // return the last request in case of redirects
  4716. const lastRequest = res.req || req;
  4717. // if decompress disabled we should not decompress
  4718. if (decompress !== false && res.headers['content-encoding']) {
  4719. // if no content, but headers still say that it is encoded,
  4720. // remove the header not confuse downstream operations
  4721. if (method === 'HEAD' || res.statusCode === 204) {
  4722. delete res.headers['content-encoding'];
  4723. }
  4724. switch ((res.headers['content-encoding'] || '').toLowerCase()) {
  4725. /*eslint default-case:0*/
  4726. case 'gzip':
  4727. case 'x-gzip':
  4728. case 'compress':
  4729. case 'x-compress':
  4730. // add the unzipper to the body stream processing pipeline
  4731. streams.push(zlib.createUnzip(zlibOptions));
  4732. // remove the content-encoding in order to not confuse downstream operations
  4733. delete res.headers['content-encoding'];
  4734. break;
  4735. case 'deflate':
  4736. streams.push(new ZlibHeaderTransformStream());
  4737. // add the unzipper to the body stream processing pipeline
  4738. streams.push(zlib.createUnzip(zlibOptions));
  4739. // remove the content-encoding in order to not confuse downstream operations
  4740. delete res.headers['content-encoding'];
  4741. break;
  4742. case 'br':
  4743. if (isBrotliSupported) {
  4744. streams.push(zlib.createBrotliDecompress(brotliOptions));
  4745. delete res.headers['content-encoding'];
  4746. }
  4747. break;
  4748. case 'zstd':
  4749. if (isZstdSupported) {
  4750. streams.push(zlib.createZstdDecompress(zstdOptions));
  4751. delete res.headers['content-encoding'];
  4752. }
  4753. break;
  4754. }
  4755. }
  4756. responseStream = streams.length > 1 ? stream.pipeline(streams, utils$1.noop) : streams[0];
  4757. const response = {
  4758. status: res.statusCode,
  4759. statusText: res.statusMessage,
  4760. headers: new AxiosHeaders(res.headers),
  4761. config,
  4762. request: lastRequest
  4763. };
  4764. if (responseType === 'stream') {
  4765. // Enforce maxContentLength on streamed responses; previously this
  4766. // was applied only to buffered responses.
  4767. if (maxContentLength > -1) {
  4768. const limit = maxContentLength;
  4769. const source = responseStream;
  4770. async function* enforceMaxContentLength() {
  4771. let totalResponseBytes = 0;
  4772. for await (const chunk of source) {
  4773. totalResponseBytes += chunk.length;
  4774. if (totalResponseBytes > limit) {
  4775. throw new AxiosError('maxContentLength size of ' + limit + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest);
  4776. }
  4777. yield chunk;
  4778. }
  4779. }
  4780. responseStream = stream.Readable.from(enforceMaxContentLength(), {
  4781. objectMode: false
  4782. });
  4783. }
  4784. response.data = responseStream;
  4785. settle(resolve, reject, response);
  4786. } else {
  4787. const responseBuffer = [];
  4788. let totalResponseBytes = 0;
  4789. responseStream.on('data', function handleStreamData(chunk) {
  4790. responseBuffer.push(chunk);
  4791. totalResponseBytes += chunk.length;
  4792. // make sure the content length is not over the maxContentLength if specified
  4793. if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
  4794. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  4795. rejected = true;
  4796. responseStream.destroy();
  4797. abort(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
  4798. }
  4799. });
  4800. responseStream.on('aborted', function handlerStreamAborted() {
  4801. if (rejected) {
  4802. return;
  4803. }
  4804. const err = new AxiosError('stream has been aborted', AxiosError.ERR_BAD_RESPONSE, config, lastRequest, response);
  4805. responseStream.destroy(err);
  4806. reject(err);
  4807. });
  4808. responseStream.on('error', function handleStreamError(err) {
  4809. if (rejected) return;
  4810. reject(AxiosError.from(err, null, config, lastRequest, response));
  4811. });
  4812. responseStream.on('end', function handleStreamEnd() {
  4813. try {
  4814. let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  4815. if (responseType !== 'arraybuffer') {
  4816. responseData = responseData.toString(responseEncoding);
  4817. if (!responseEncoding || responseEncoding === 'utf8') {
  4818. responseData = utils$1.stripBOM(responseData);
  4819. }
  4820. }
  4821. response.data = responseData;
  4822. } catch (err) {
  4823. return reject(AxiosError.from(err, null, config, response.request, response));
  4824. }
  4825. settle(resolve, reject, response);
  4826. });
  4827. }
  4828. abortEmitter.once('abort', err => {
  4829. if (!responseStream.destroyed) {
  4830. responseStream.emit('error', err);
  4831. responseStream.destroy();
  4832. }
  4833. });
  4834. });
  4835. abortEmitter.once('abort', err => {
  4836. if (req.close) {
  4837. req.close();
  4838. } else {
  4839. req.destroy(err);
  4840. }
  4841. });
  4842. // Handle errors
  4843. req.on('error', function handleRequestError(err) {
  4844. reject(AxiosError.from(err, null, config, req));
  4845. });
  4846. // set tcp keep alive to prevent drop connection by peer
  4847. // Track every socket bound to this outer RedirectableRequest so a single
  4848. // 'close' listener can release ownership on all of them. follow-redirects
  4849. // re-emits the 'socket' event for each hop's native request onto the same
  4850. // outer request, so attaching per-request listeners inside this handler
  4851. // would accumulate across hops and trigger MaxListenersExceededWarning at
  4852. // >= 11 redirects. Clearing only the last-bound socket would leave stale
  4853. // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
  4854. // pool, causing an idle-pool 'error' to be attributed to a closed req.
  4855. const boundSockets = new Set();
  4856. req.on('socket', function handleRequestSocket(socket) {
  4857. // default interval of sending ack packet is 1 minute
  4858. // proxy agents (e.g. agent-base) may return a generic Duplex stream
  4859. // that doesn't have setKeepAlive, so guard before calling
  4860. if (typeof socket.setKeepAlive === 'function') {
  4861. socket.setKeepAlive(true, 1000 * 60);
  4862. }
  4863. // Install one shared 'error' listener per socket. The symbol follows the
  4864. // currently-active request as pooled sockets are reassigned (issue #10780).
  4865. if (!socket[kAxiosSocketListener]) {
  4866. socket.on('error', handleSocketError);
  4867. socket[kAxiosSocketListener] = true;
  4868. }
  4869. socket[kAxiosCurrentReq] = req;
  4870. boundSockets.add(socket);
  4871. });
  4872. req.once('close', function clearCurrentReq() {
  4873. clearConnectPhaseTimer();
  4874. for (const socket of boundSockets) {
  4875. if (socket[kAxiosCurrentReq] === req) {
  4876. socket[kAxiosCurrentReq] = null;
  4877. }
  4878. }
  4879. boundSockets.clear();
  4880. });
  4881. // Handle request timeout
  4882. if (own('timeout')) {
  4883. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  4884. const timeout = parseInt(own('timeout'), 10);
  4885. if (Number.isNaN(timeout)) {
  4886. abort(new AxiosError('error trying to parse `config.timeout` to int', AxiosError.ERR_BAD_OPTION_VALUE, config, req));
  4887. return;
  4888. }
  4889. const handleTimeout = function handleTimeout() {
  4890. if (isDone) return;
  4891. abort(createTimeoutError());
  4892. };
  4893. if (isNativeTransport && timeout > 0) {
  4894. // Native ClientRequest#setTimeout starts from the socket lifecycle and
  4895. // may not fire while TCP connect is still pending. Mirror the
  4896. // follow-redirects wall-clock timer for the maxRedirects === 0 path.
  4897. connectPhaseTimer = setTimeout(handleTimeout, timeout);
  4898. }
  4899. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  4900. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  4901. // 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.
  4902. // And then these socket which be hang up will devouring CPU little by little.
  4903. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  4904. req.setTimeout(timeout, handleTimeout);
  4905. } else {
  4906. // explicitly reset the socket timeout value for a possible `keep-alive` request
  4907. req.setTimeout(0);
  4908. }
  4909. // Send the request
  4910. if (utils$1.isStream(data)) {
  4911. let ended = false;
  4912. let errored = false;
  4913. data.on('end', () => {
  4914. ended = true;
  4915. });
  4916. data.once('error', err => {
  4917. errored = true;
  4918. req.destroy(err);
  4919. });
  4920. data.on('close', () => {
  4921. if (!ended && !errored) {
  4922. abort(new CanceledError('Request stream has been aborted', config, req));
  4923. }
  4924. });
  4925. // Transform decodes string chunks to Buffers before counting, so every
  4926. // transport receives at most maxBodyLength encoded bytes.
  4927. let uploadStream = data;
  4928. if (maxBodyLength > -1) {
  4929. const limit = maxBodyLength;
  4930. let bytesSent = 0;
  4931. uploadStream = stream.pipeline([data, new stream.Transform({
  4932. transform(chunk, _enc, cb) {
  4933. bytesSent += chunk.length;
  4934. if (bytesSent > limit) {
  4935. return cb(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, req));
  4936. }
  4937. cb(null, chunk);
  4938. }
  4939. })], utils$1.noop);
  4940. uploadStream.on('error', err => {
  4941. if (!req.destroyed) req.destroy(err);
  4942. });
  4943. }
  4944. uploadStream.pipe(req);
  4945. } else {
  4946. data && req.write(data);
  4947. req.end();
  4948. }
  4949. });
  4950. };
  4951. const decodeCookieValue = value => {
  4952. try {
  4953. return decodeURIComponent(value);
  4954. } catch (e) {
  4955. return value;
  4956. }
  4957. };
  4958. var cookies = platform.hasStandardBrowserEnv ?
  4959. // Standard browser envs support document.cookie
  4960. {
  4961. write(name, value, expires, path, domain, secure, sameSite) {
  4962. if (typeof document === 'undefined') return;
  4963. const cookie = [`${name}=${encodeURIComponent(value)}`];
  4964. if (utils$1.isNumber(expires)) {
  4965. cookie.push(`expires=${new Date(expires).toUTCString()}`);
  4966. }
  4967. if (utils$1.isString(path)) {
  4968. cookie.push(`path=${path}`);
  4969. }
  4970. if (utils$1.isString(domain)) {
  4971. cookie.push(`domain=${domain}`);
  4972. }
  4973. if (secure === true) {
  4974. cookie.push('secure');
  4975. }
  4976. if (utils$1.isString(sameSite)) {
  4977. cookie.push(`SameSite=${sameSite}`);
  4978. }
  4979. document.cookie = cookie.join('; ');
  4980. },
  4981. read(name) {
  4982. if (typeof document === 'undefined') return null;
  4983. const cookieString = document.cookie;
  4984. if (!cookieString) return null;
  4985. // Match name=value by splitting on the semicolon separator instead of building a
  4986. // RegExp from `name` — interpolating an unescaped string into a RegExp would let
  4987. // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
  4988. // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
  4989. // "; ", so ignore optional whitespace before each cookie name.
  4990. const cookies = cookieString.split(';');
  4991. for (let i = 0; i < cookies.length; i++) {
  4992. const cookie = cookies[i].replace(/^\s+/, '');
  4993. const eq = cookie.indexOf('=');
  4994. if (eq !== -1 && cookie.slice(0, eq) === name) {
  4995. return decodeCookieValue(cookie.slice(eq + 1));
  4996. }
  4997. }
  4998. return null;
  4999. },
  5000. async readAsync(name) {
  5001. try {
  5002. const store = typeof window !== 'undefined' && window.cookieStore;
  5003. if (store && utils$1.isFunction(store.get)) {
  5004. const cookie = await store.get(name);
  5005. // Both APIs expose stored bytes; preserve Axios's existing URI decoding.
  5006. return cookie ? decodeCookieValue(cookie.value) : null;
  5007. }
  5008. } catch (e) {
  5009. // Restricted or unavailable storage retains the synchronous fallback.
  5010. }
  5011. return this.read(name);
  5012. },
  5013. remove(name) {
  5014. this.write(name, '', Date.now() - 86400000, '/');
  5015. }
  5016. } :
  5017. // Non-standard browser env (web workers, react-native) lack needed support.
  5018. {
  5019. write() {},
  5020. read() {
  5021. return null;
  5022. },
  5023. async readAsync() {
  5024. return null;
  5025. },
  5026. remove() {}
  5027. };
  5028. var isURLSameOrigin = platform.hasStandardBrowserEnv ? (origin => url => {
  5029. url = new URL(url, document.baseURI || platform.origin);
  5030. return origin.protocol === url.protocol && origin.host === url.host && origin.port === url.port;
  5031. })(new URL(platform.origin)) : () => true;
  5032. function assertParamsAcyclic(params) {
  5033. const pending = [{
  5034. value: params
  5035. }];
  5036. const active = new WeakSet();
  5037. const visited = new WeakSet();
  5038. while (pending.length) {
  5039. const {
  5040. value,
  5041. done
  5042. } = pending.pop();
  5043. if (!utils$1.isPlainObject(value) && !utils$1.isArray(value)) continue;
  5044. if (done) {
  5045. active.delete(value);
  5046. continue;
  5047. }
  5048. if (active.has(value)) {
  5049. throw new AxiosError('Circular reference detected in params', AxiosError.ERR_BAD_OPTION_VALUE);
  5050. }
  5051. if (visited.has(value)) continue;
  5052. visited.add(value);
  5053. active.add(value);
  5054. pending.push({
  5055. value,
  5056. done: true
  5057. });
  5058. const keys = Object.keys(value);
  5059. if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) {
  5060. Object.getOwnPropertySymbols(value).forEach(key => {
  5061. const descriptor = Object.getOwnPropertyDescriptor(value, key);
  5062. if (descriptor && descriptor.enumerable) keys.push(key);
  5063. });
  5064. }
  5065. // Shallow array elements retain fields filtered during plain-object merges.
  5066. // Inspect reserved data properties without evaluating their accessors.
  5067. keys.forEach(key => {
  5068. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  5069. const descriptor = Object.getOwnPropertyDescriptor(value, key);
  5070. if (descriptor && utils$1.hasOwnProp(descriptor, 'value')) {
  5071. pending.push({
  5072. value: descriptor.value
  5073. });
  5074. }
  5075. } else {
  5076. pending.push({
  5077. value: value[key]
  5078. });
  5079. }
  5080. });
  5081. }
  5082. }
  5083. const headersToObject = thing => thing instanceof AxiosHeaders ? {
  5084. ...thing
  5085. } : thing;
  5086. const ownEnumerableKeys = thing => {
  5087. if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) {
  5088. return Object.keys(thing).concat(Object.getOwnPropertySymbols(thing).filter(symbol => {
  5089. const descriptor = Object.getOwnPropertyDescriptor(thing, symbol);
  5090. return descriptor && descriptor.enumerable;
  5091. }));
  5092. }
  5093. return Object.keys(thing);
  5094. };
  5095. // Copy params without recursive merges so the serializer remains responsible
  5096. // for its depth policy. Only visit defaults that contribute to the result.
  5097. function mergeParams(a, b) {
  5098. const pending = [];
  5099. const copies = new WeakMap();
  5100. const empty = {};
  5101. function copy(target, source) {
  5102. if (!utils$1.isPlainObject(source)) {
  5103. return utils$1.isArray(source) ? source.slice() : source;
  5104. }
  5105. const base = utils$1.isPlainObject(target) ? target : empty;
  5106. let bases = copies.get(source);
  5107. if (!bases) {
  5108. bases = new WeakMap();
  5109. copies.set(source, bases);
  5110. }
  5111. if (bases.has(base)) return bases.get(base);
  5112. const result = {};
  5113. bases.set(base, result);
  5114. pending.push({
  5115. base,
  5116. source,
  5117. result
  5118. });
  5119. return result;
  5120. }
  5121. const result = utils$1.isUndefined(b) ? copy(undefined, a) : copy(a, b);
  5122. while (pending.length) {
  5123. const {
  5124. base,
  5125. source,
  5126. result: target
  5127. } = pending.pop();
  5128. const baseKeys = new Set(ownEnumerableKeys(base));
  5129. const sourceKeys = new Set(ownEnumerableKeys(source));
  5130. const keys = new Set([...baseKeys, ...sourceKeys]);
  5131. keys.forEach(key => {
  5132. if (key === '__proto__' || key === 'constructor' || key === 'prototype') return;
  5133. const hasSource = sourceKeys.has(key);
  5134. const value = hasSource ? source[key] : undefined;
  5135. const previous = (!hasSource || utils$1.isPlainObject(value)) && baseKeys.has(key) ? base[key] : undefined;
  5136. target[key] = hasSource ? copy(previous, value) : copy(undefined, previous);
  5137. });
  5138. }
  5139. assertParamsAcyclic(result);
  5140. return result;
  5141. }
  5142. function getMergedValue(target, source, prop, caseless) {
  5143. if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
  5144. return utils$1.merge.call({
  5145. caseless
  5146. }, target, source);
  5147. } else if (utils$1.isPlainObject(source)) {
  5148. return utils$1.merge({}, source);
  5149. } else if (utils$1.isArray(source)) {
  5150. return source.slice();
  5151. }
  5152. return source;
  5153. }
  5154. function mergeDeepProperties(a, b, prop, caseless) {
  5155. if (!utils$1.isUndefined(b)) {
  5156. return getMergedValue(a, b, prop, caseless);
  5157. } else if (!utils$1.isUndefined(a)) {
  5158. return getMergedValue(undefined, a, prop, caseless);
  5159. }
  5160. }
  5161. // eslint-disable-next-line consistent-return
  5162. function valueFromConfig2(a, b) {
  5163. if (!utils$1.isUndefined(b)) {
  5164. return getMergedValue(undefined, b);
  5165. }
  5166. }
  5167. // eslint-disable-next-line consistent-return
  5168. function defaultToConfig2(a, b) {
  5169. if (!utils$1.isUndefined(b)) {
  5170. return getMergedValue(undefined, b);
  5171. } else if (!utils$1.isUndefined(a)) {
  5172. return getMergedValue(undefined, a);
  5173. }
  5174. }
  5175. function getMergedTransitionalOption(config1, config2, prop) {
  5176. const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
  5177. if (!utils$1.isUndefined(transitional2)) {
  5178. if (utils$1.isPlainObject(transitional2)) {
  5179. if (utils$1.hasOwnProp(transitional2, prop)) {
  5180. return transitional2[prop];
  5181. }
  5182. } else {
  5183. return undefined;
  5184. }
  5185. }
  5186. const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
  5187. if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
  5188. return transitional1[prop];
  5189. }
  5190. return undefined;
  5191. }
  5192. // eslint-disable-next-line consistent-return
  5193. function mergeDirectKeys(a, b, prop, config1, config2) {
  5194. if (utils$1.hasOwnProp(config2, prop)) {
  5195. return getMergedValue(a, b);
  5196. } else if (utils$1.hasOwnProp(config1, prop)) {
  5197. return getMergedValue(undefined, a);
  5198. }
  5199. }
  5200. function mergeHeaders(a, b, prop) {
  5201. return mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true);
  5202. }
  5203. // Null-proto, frozen descriptor so a polluted Object.prototype.get cannot turn
  5204. // this data descriptor into an accessor descriptor on the way in.
  5205. // defineProperty only reads it, so one shared instance serves every call.
  5206. const hasOwnPropertyDescriptor = Object.freeze({
  5207. __proto__: null,
  5208. value: Object.prototype.hasOwnProperty,
  5209. enumerable: false,
  5210. writable: true,
  5211. configurable: true
  5212. });
  5213. // The strategy table and the strategies above are stateless, so they are
  5214. // built once at module load instead of on every call: mergeConfig runs at
  5215. // most twice per request (once from a method alias, once from `_request`).
  5216. const mergeMap = {
  5217. url: valueFromConfig2,
  5218. method: valueFromConfig2,
  5219. data: valueFromConfig2,
  5220. baseURL: defaultToConfig2,
  5221. transformRequest: defaultToConfig2,
  5222. transformResponse: defaultToConfig2,
  5223. params: mergeParams,
  5224. paramsSerializer: defaultToConfig2,
  5225. timeout: defaultToConfig2,
  5226. timeoutErrorMessage: defaultToConfig2,
  5227. withCredentials: defaultToConfig2,
  5228. withXSRFToken: defaultToConfig2,
  5229. adapter: defaultToConfig2,
  5230. responseType: defaultToConfig2,
  5231. xsrfCookieName: defaultToConfig2,
  5232. xsrfHeaderName: defaultToConfig2,
  5233. onUploadProgress: defaultToConfig2,
  5234. onDownloadProgress: defaultToConfig2,
  5235. decompress: defaultToConfig2,
  5236. maxContentLength: defaultToConfig2,
  5237. maxBodyLength: defaultToConfig2,
  5238. beforeRedirect: defaultToConfig2,
  5239. transport: defaultToConfig2,
  5240. httpAgent: defaultToConfig2,
  5241. httpsAgent: defaultToConfig2,
  5242. cancelToken: defaultToConfig2,
  5243. socketPath: defaultToConfig2,
  5244. allowedSocketPaths: defaultToConfig2,
  5245. responseEncoding: defaultToConfig2,
  5246. validateStatus: mergeDirectKeys,
  5247. headers: mergeHeaders
  5248. };
  5249. /**
  5250. * Config-specific merge-function which creates a new config-object
  5251. * by merging two configuration objects together.
  5252. *
  5253. * @param {Object} config1
  5254. * @param {Object} config2
  5255. *
  5256. * @returns {Object} New object resulting from merging config2 to config1
  5257. */
  5258. function mergeConfig(config1, config2) {
  5259. // eslint-disable-next-line no-param-reassign
  5260. config1 = config1 || {};
  5261. config2 = config2 || {};
  5262. // Use a null-prototype object so that downstream reads such as `config.auth`
  5263. // or `config.baseURL` cannot inherit polluted values from Object.prototype.
  5264. // `hasOwnProperty` is restored as a non-enumerable own slot to preserve
  5265. // ergonomics for user code that relies on it.
  5266. const config = Object.create(null);
  5267. Object.defineProperty(config, 'hasOwnProperty', hasOwnPropertyDescriptor);
  5268. const keys = ownEnumerableKeys({
  5269. ...config1,
  5270. ...config2
  5271. });
  5272. for (let i = 0, len = keys.length; i < len; i++) {
  5273. const prop = keys[i];
  5274. if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') continue;
  5275. const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
  5276. const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
  5277. const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
  5278. const configValue = merge === mergeDirectKeys ? merge(a, b, prop, config1, config2) : merge(a, b, prop);
  5279. utils$1.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue);
  5280. }
  5281. if (utils$1.hasOwnProp(config2, 'validateStatus') && utils$1.isUndefined(config2.validateStatus) && getMergedTransitionalOption(config1, config2, 'validateStatusUndefinedResolves') === false) {
  5282. if (utils$1.hasOwnProp(config1, 'validateStatus')) {
  5283. config.validateStatus = getMergedValue(undefined, config1.validateStatus);
  5284. } else {
  5285. delete config.validateStatus;
  5286. }
  5287. }
  5288. return config;
  5289. }
  5290. /**
  5291. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  5292. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  5293. *
  5294. * @param {string} str The string to encode
  5295. *
  5296. * @returns {string} UTF-8 bytes as a Latin-1 string
  5297. */
  5298. const encodeUTF8$1 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  5299. const readCookie = name => cookies.read(name);
  5300. function resolveConfig(config, readXsrfCookie = readCookie) {
  5301. const newConfig = mergeConfig({}, config);
  5302. // Read only own properties to prevent prototype pollution gadgets
  5303. // (e.g. Object.prototype.baseURL = 'https://evil.com').
  5304. const own = key => utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined;
  5305. const data = own('data');
  5306. let withXSRFToken = own('withXSRFToken');
  5307. const xsrfHeaderName = own('xsrfHeaderName');
  5308. const xsrfCookieName = own('xsrfCookieName');
  5309. let headers = own('headers');
  5310. const auth = own('auth');
  5311. const baseURL = own('baseURL');
  5312. const allowAbsoluteUrls = own('allowAbsoluteUrls');
  5313. const url = own('url');
  5314. newConfig.headers = headers = AxiosHeaders.from(headers);
  5315. newConfig.url = buildURL(buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), own('params'), own('paramsSerializer'));
  5316. // HTTP basic authentication
  5317. if (auth) {
  5318. const username = utils$1.getSafeProp(auth, 'username') || '';
  5319. const password = utils$1.getSafeProp(auth, 'password') || '';
  5320. const transitional = own('transitional');
  5321. const encodeUsername = transitional && utils$1.hasOwnProp(transitional, 'encodeBasicAuthUsername') && transitional.encodeBasicAuthUsername === true;
  5322. try {
  5323. headers.set('Authorization',
  5324. // Preserve legacy username bytes unless the caller opts in to UTF-8.
  5325. 'Basic ' + btoa((encodeUsername ? encodeUTF8$1(username) : username) + ':' + (password ? encodeUTF8$1(password) : '')));
  5326. } catch (e) {
  5327. throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);
  5328. }
  5329. }
  5330. if (utils$1.isFormData(data)) {
  5331. const getHeaders = utils$1.getSafeProp(data, 'getHeaders');
  5332. if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
  5333. headers.setContentType(undefined); // browser/web worker/RN handles it
  5334. } else if (utils$1.isFunction(getHeaders)) {
  5335. // Node.js FormData (like form-data package)
  5336. setFormDataHeaders(headers, getHeaders.call(data), own('formDataHeaderPolicy'));
  5337. }
  5338. }
  5339. // Add xsrf header
  5340. // This is only done if running in a standard browser environment.
  5341. // Specifically not if we're in a web worker, or react-native.
  5342. if (platform.hasStandardBrowserEnv) {
  5343. if (utils$1.isFunction(withXSRFToken)) {
  5344. withXSRFToken = withXSRFToken(newConfig);
  5345. }
  5346. // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
  5347. // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
  5348. // the XSRF token cross-origin.
  5349. const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
  5350. if (shouldSendXSRF) {
  5351. const xsrfValue = xsrfHeaderName && xsrfCookieName && readXsrfCookie(xsrfCookieName);
  5352. if (xsrfValue) {
  5353. headers.set(xsrfHeaderName, xsrfValue);
  5354. }
  5355. }
  5356. }
  5357. return newConfig;
  5358. }
  5359. const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
  5360. var xhrAdapter = isXHRAdapterSupported && function (config) {
  5361. return new Promise(function dispatchXhrRequest(resolve, reject) {
  5362. let useAsyncXsrf;
  5363. try {
  5364. const store = platform.hasStandardBrowserEnv && typeof window !== 'undefined' && window.cookieStore;
  5365. useAsyncXsrf = store && utils$1.isFunction(store.get);
  5366. } catch (e) {
  5367. // A restricted Cookie Store getter must retain the synchronous fallback.
  5368. }
  5369. let xsrfCookieName;
  5370. const _config = resolveConfig(config, useAsyncXsrf ? name => {
  5371. xsrfCookieName = name;
  5372. return null;
  5373. } : undefined);
  5374. let requestData = _config.data;
  5375. const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
  5376. let {
  5377. responseType,
  5378. onUploadProgress,
  5379. onDownloadProgress
  5380. } = _config;
  5381. let onCanceled;
  5382. let timeoutId;
  5383. let uploadThrottled, downloadThrottled;
  5384. let flushUpload, flushDownload, flushDownloadWithEvent;
  5385. function done() {
  5386. clearTimeout(timeoutId);
  5387. // A final progress callback must not prevent the remaining cleanup.
  5388. // Report errors asynchronously, as onloadend and the throttle timer do.
  5389. try {
  5390. flushUpload && flushUpload(); // flush events
  5391. } catch (err) {
  5392. setTimeout(() => {
  5393. throw err;
  5394. });
  5395. }
  5396. try {
  5397. flushDownload && flushDownload(); // flush events
  5398. } catch (err) {
  5399. setTimeout(() => {
  5400. throw err;
  5401. });
  5402. }
  5403. // A flush can synchronously cancel the request and reenter done().
  5404. // In that case the inner call has already detached these listeners.
  5405. if (request) {
  5406. downloadThrottled && request.removeEventListener('progress', downloadThrottled);
  5407. if (request.upload) {
  5408. uploadThrottled && request.upload.removeEventListener('progress', uploadThrottled);
  5409. flushUpload && request.upload.removeEventListener('loadend', flushUpload);
  5410. }
  5411. }
  5412. _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
  5413. _config.signal && _config.signal.removeEventListener('abort', onCanceled);
  5414. }
  5415. let request = new XMLHttpRequest();
  5416. request.open(_config.method.toUpperCase(), _config.url, true);
  5417. // Set the request timeout in MS
  5418. request.timeout = _config.timeout;
  5419. function onloadend(event) {
  5420. if (!request) {
  5421. return;
  5422. }
  5423. // Status 0 means no response was received, which onerror and onabort normally
  5424. // reject before this runs. Firefox 152 fires only readystatechange and loadend for
  5425. // navigation-canceled requests (https://bugzilla.mozilla.org/show_bug.cgi?id=1505389),
  5426. // leaving settle() to resolve them as an empty success. ECONNABORTED is the error
  5427. // onabort raised on Firefox 151. Reads over file:, which some environments report as
  5428. // status 0 on success, are excluded by the request URL's scheme after browser-style
  5429. // preprocessing, by the page origin's scheme for relative URLs (which inherit it), or
  5430. // by responseURL where implemented.
  5431. if (request.status === 0 && (parseProtocol(normalizeURLForProtocolCheck(_config.url)) || parseProtocol(platform.origin)) !== 'file' && !(request.responseURL && request.responseURL.startsWith('file:'))) {
  5432. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  5433. done();
  5434. // Clean up request
  5435. request = null;
  5436. return;
  5437. }
  5438. // When loadend is still dispatching, flushing with it gives progress
  5439. // listeners a final delivery whose event has a live target. The legacy
  5440. // ready-state fallback has no event, so replay its pending progress.
  5441. // A throwing listener must not block settlement; rethrow asynchronously,
  5442. // matching how listener errors surface on the throttle timer path.
  5443. try {
  5444. if (event) {
  5445. flushDownloadWithEvent && flushDownloadWithEvent(event);
  5446. } else {
  5447. flushDownload && flushDownload();
  5448. }
  5449. } catch (err) {
  5450. setTimeout(() => {
  5451. throw err;
  5452. });
  5453. }
  5454. // A final progress callback can cancel the request synchronously.
  5455. if (!request) {
  5456. return;
  5457. }
  5458. // Prepare the response
  5459. const responseHeaders = AxiosHeaders.from('getAllResponseHeaders' in request && request.getAllResponseHeaders());
  5460. const responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response;
  5461. const response = {
  5462. data: responseData,
  5463. status: request.status,
  5464. statusText: request.statusText,
  5465. headers: responseHeaders,
  5466. config,
  5467. request
  5468. };
  5469. settle(function _resolve(value) {
  5470. resolve(value);
  5471. done();
  5472. }, function _reject(err) {
  5473. reject(err);
  5474. done();
  5475. }, response);
  5476. // Clean up request
  5477. request = null;
  5478. }
  5479. if ('onloadend' in request) {
  5480. // Use onloadend if available
  5481. request.onloadend = onloadend;
  5482. } else {
  5483. // Listen for ready state to emulate onloadend
  5484. request.onreadystatechange = function handleLoad() {
  5485. if (!request || request.readyState !== 4) {
  5486. return;
  5487. }
  5488. // The request errored out and we didn't get a response, this will be
  5489. // handled by onerror instead
  5490. // With one exception: request that using file: protocol, most browsers
  5491. // will return status as 0 even though it's a successful request
  5492. if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith('file:'))) {
  5493. return;
  5494. }
  5495. // readystate handler is calling before onerror or ontimeout handlers,
  5496. // so we should call onloadend on the next 'tick'
  5497. setTimeout(onloadend);
  5498. };
  5499. }
  5500. // Handle browser request cancellation (as opposed to a manual cancellation)
  5501. request.onabort = function handleAbort() {
  5502. if (!request) {
  5503. return;
  5504. }
  5505. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  5506. done();
  5507. // Clean up request
  5508. request = null;
  5509. };
  5510. // Handle low level network errors
  5511. request.onerror = function handleError(event) {
  5512. // Browsers deliver a ProgressEvent in XHR onerror
  5513. // (message may be empty; when present, surface it)
  5514. // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
  5515. const msg = event && event.message ? event.message : 'Network Error';
  5516. const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
  5517. // attach the underlying event for consumers who want details
  5518. err.event = event || null;
  5519. reject(err);
  5520. done();
  5521. request = null;
  5522. };
  5523. // Handle timeout
  5524. request.ontimeout = function handleTimeout() {
  5525. if (!request) return;
  5526. let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
  5527. const transitional = _config.transitional || transitionalDefaults;
  5528. if (_config.timeoutErrorMessage) {
  5529. timeoutErrorMessage = _config.timeoutErrorMessage;
  5530. }
  5531. reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request));
  5532. done();
  5533. // Clean up request
  5534. request = null;
  5535. };
  5536. // Remove Content-Type if data is undefined
  5537. requestData === undefined && requestHeaders.setContentType(null);
  5538. // Add withCredentials to request if needed
  5539. if (!utils$1.isUndefined(_config.withCredentials)) {
  5540. request.withCredentials = !!_config.withCredentials;
  5541. }
  5542. // Add responseType to request if needed
  5543. if (responseType && responseType !== 'json') {
  5544. request.responseType = _config.responseType;
  5545. }
  5546. // Handle progress if needed
  5547. if (onDownloadProgress) {
  5548. [downloadThrottled, flushDownload, flushDownloadWithEvent] = progressEventReducer(onDownloadProgress, true);
  5549. request.addEventListener('progress', downloadThrottled);
  5550. }
  5551. // Not all browsers support upload events
  5552. if (onUploadProgress && request.upload) {
  5553. [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
  5554. request.upload.addEventListener('progress', uploadThrottled);
  5555. request.upload.addEventListener('loadend', flushUpload);
  5556. }
  5557. if (_config.cancelToken || _config.signal) {
  5558. // Handle cancellation
  5559. // eslint-disable-next-line func-names
  5560. onCanceled = cancel => {
  5561. if (!request) {
  5562. return;
  5563. }
  5564. reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
  5565. const xhr = request;
  5566. done();
  5567. request = null;
  5568. xhr.abort();
  5569. };
  5570. _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
  5571. if (!request) return;
  5572. if (_config.signal) {
  5573. _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
  5574. }
  5575. }
  5576. if (!request) return;
  5577. const protocol = parseProtocol(_config.url);
  5578. if (protocol && !platform.protocols.includes(protocol)) {
  5579. reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
  5580. done();
  5581. return;
  5582. }
  5583. const sendRequest = () => {
  5584. if (!request) return;
  5585. // Apply headers after an asynchronous XSRF read so existing headers are
  5586. // replaced through AxiosHeaders rather than appended by the native XHR.
  5587. if ('setRequestHeader' in request) {
  5588. utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
  5589. request.setRequestHeader(key, val);
  5590. });
  5591. }
  5592. request.send(requestData || null);
  5593. };
  5594. if (xsrfCookieName) {
  5595. // Native XHR timeout starts at send(). Cover cookie preparation and the
  5596. // subsequent request with the same budget and existing timeout handler.
  5597. const now = typeof performance !== 'undefined' && utils$1.isFunction(performance.now) ? () => performance.now() : Date.now;
  5598. const deadline = request.timeout > 0 ? now() + Number(request.timeout) : undefined;
  5599. const abortOnTimeout = () => {
  5600. if (!request) return;
  5601. const xhr = request;
  5602. xhr.ontimeout();
  5603. xhr.abort();
  5604. };
  5605. if (deadline !== undefined) {
  5606. const scheduleTimeout = () => {
  5607. const remaining = deadline - now();
  5608. if (remaining > 0) {
  5609. // Browser timers overflow above the signed 32-bit delay limit.
  5610. timeoutId = setTimeout(scheduleTimeout, Math.min(remaining, 0x7fffffff));
  5611. } else {
  5612. abortOnTimeout();
  5613. }
  5614. };
  5615. scheduleTimeout();
  5616. }
  5617. cookies.readAsync(xsrfCookieName).then(value => {
  5618. if (!request) return;
  5619. // Promise callbacks may run before an overdue timer after a busy task.
  5620. if (deadline !== undefined && now() >= deadline) {
  5621. abortOnTimeout();
  5622. return;
  5623. }
  5624. if (value) {
  5625. const headerName = utils$1.hasOwnProp(_config, 'xsrfHeaderName') && _config.xsrfHeaderName;
  5626. requestHeaders.set(headerName, value);
  5627. }
  5628. sendRequest();
  5629. }).catch(error => {
  5630. if (!request) return;
  5631. reject(AxiosError.from(error, null, config, request));
  5632. done();
  5633. request = null;
  5634. });
  5635. } else {
  5636. sendRequest();
  5637. }
  5638. });
  5639. };
  5640. const composeSignals = (signals, timeout) => {
  5641. signals = signals ? signals.filter(Boolean) : [];
  5642. if (!timeout && !signals.length) {
  5643. return;
  5644. }
  5645. const controller = new AbortController();
  5646. let aborted = false;
  5647. const onabort = function (reason) {
  5648. if (!aborted) {
  5649. aborted = true;
  5650. unsubscribe();
  5651. const err = reason instanceof Error ? reason : this.reason;
  5652. controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
  5653. }
  5654. };
  5655. let timer = timeout && setTimeout(() => {
  5656. timer = null;
  5657. onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
  5658. }, timeout);
  5659. const unsubscribe = () => {
  5660. if (!signals) {
  5661. return;
  5662. }
  5663. timer && clearTimeout(timer);
  5664. timer = null;
  5665. signals.forEach(signal => {
  5666. const unsubscribeSignal = utils$1.getSafeProp(signal, 'unsubscribe');
  5667. utils$1.isFunction(unsubscribeSignal) ? unsubscribeSignal.call(signal, onabort) : signal.removeEventListener('abort', onabort);
  5668. });
  5669. signals = null;
  5670. };
  5671. signals.forEach(signal => {
  5672. if (aborted) {
  5673. return;
  5674. }
  5675. if (signal.aborted) {
  5676. onabort.call(signal);
  5677. return;
  5678. }
  5679. signal.addEventListener('abort', onabort, {
  5680. once: true
  5681. });
  5682. });
  5683. const {
  5684. signal
  5685. } = controller;
  5686. signal.unsubscribe = () => utils$1.asap(unsubscribe);
  5687. return signal;
  5688. };
  5689. const streamChunk = function* (chunk, chunkSize) {
  5690. let len = chunk.byteLength;
  5691. if (len < chunkSize) {
  5692. yield chunk;
  5693. return;
  5694. }
  5695. let pos = 0;
  5696. let end;
  5697. while (pos < len) {
  5698. end = pos + chunkSize;
  5699. yield chunk.slice(pos, end);
  5700. pos = end;
  5701. }
  5702. };
  5703. const readBytes = async function* (iterable, chunkSize) {
  5704. for await (const chunk of readStream(iterable)) {
  5705. yield* streamChunk(chunk, chunkSize);
  5706. }
  5707. };
  5708. const readStream = async function* (stream) {
  5709. if (stream[Symbol.asyncIterator]) {
  5710. yield* stream;
  5711. return;
  5712. }
  5713. const reader = stream.getReader();
  5714. try {
  5715. for (;;) {
  5716. const {
  5717. done,
  5718. value
  5719. } = await reader.read();
  5720. if (done) {
  5721. break;
  5722. }
  5723. yield value;
  5724. }
  5725. } finally {
  5726. await reader.cancel();
  5727. }
  5728. };
  5729. const trackStream = (stream, chunkSize, onProgress, onFinish) => {
  5730. const iterator = readBytes(stream, chunkSize);
  5731. let bytes = 0;
  5732. let done;
  5733. let _onFinish = e => {
  5734. if (!done) {
  5735. done = true;
  5736. onFinish && onFinish(e);
  5737. }
  5738. };
  5739. return new ReadableStream({
  5740. async pull(controller) {
  5741. try {
  5742. const {
  5743. done,
  5744. value
  5745. } = await iterator.next();
  5746. if (done) {
  5747. _onFinish();
  5748. controller.close();
  5749. return;
  5750. }
  5751. let len = value.byteLength;
  5752. if (onProgress) {
  5753. let loadedBytes = bytes += len;
  5754. onProgress(loadedBytes);
  5755. }
  5756. controller.enqueue(new Uint8Array(value));
  5757. } catch (err) {
  5758. _onFinish(err);
  5759. throw err;
  5760. }
  5761. },
  5762. cancel(reason) {
  5763. _onFinish(reason);
  5764. return iterator.return();
  5765. }
  5766. }, {
  5767. highWaterMark: 2
  5768. });
  5769. };
  5770. const CRLF = '\r\n';
  5771. const normalizeLines = value => String(value).replace(/\r\n|\r|\n/g, CRLF);
  5772. const escapeName = value => String(value).replace(/[\r\n"]/g, char => char === '\r' ? '%0D' : char === '\n' ? '%0A' : '%22');
  5773. // Count UTF-8 bytes without allocating an encoded copy of a field. FormData
  5774. // string values normalize line endings; Blob/File contents remain unchanged.
  5775. const stringBytes = (value, normalize) => {
  5776. let length = 0;
  5777. for (let i = 0; i < value.length; i++) {
  5778. const code = value.charCodeAt(i);
  5779. if (normalize && (code === 13 || code === 10)) {
  5780. if (code === 13 && value.charCodeAt(i + 1) === 10) i++;
  5781. length += 2;
  5782. } else if (code < 0x80) {
  5783. length++;
  5784. } else if (code < 0x800) {
  5785. length += 2;
  5786. } else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(i + 1) >= 0xdc00 && value.charCodeAt(i + 1) <= 0xdfff) {
  5787. length += 4;
  5788. i++;
  5789. } else {
  5790. length += 3;
  5791. }
  5792. }
  5793. return length;
  5794. };
  5795. // Describe serialization failures independently of any request library.
  5796. class FormDataError extends TypeError {
  5797. constructor(message, reason) {
  5798. super(message);
  5799. this.name = 'FormDataError';
  5800. this.reason = reason;
  5801. }
  5802. }
  5803. // The caller supplies the boundary, Blob implementation, and limit error.
  5804. function formDataToBlob(form, Blob, limit, limitError, boundary) {
  5805. if (!utils$1.isFunction(Blob)) {
  5806. throw new FormDataError('Blob is not supported', 'blob');
  5807. }
  5808. if (!utils$1.isString(boundary) || !/^[A-Za-z0-9'()+_,./:=? -]{1,70}$/.test(boundary) || / $/.test(boundary)) {
  5809. throw new FormDataError('Invalid multipart boundary', 'boundary');
  5810. }
  5811. const footer = '--' + boundary + '--' + CRLF;
  5812. let length = footer.length;
  5813. const parts = [];
  5814. const checkLength = extra => {
  5815. if (length + extra > limit) throw limitError();
  5816. };
  5817. checkLength(0);
  5818. for (const [name, value] of form) {
  5819. const isString = utils$1.isString(value);
  5820. const valueLength = isString ? stringBytes(value, true) : value.size;
  5821. if (!Number.isFinite(valueLength) || valueLength < 0) {
  5822. throw new FormDataError('Unsupported FormData part size', 'part');
  5823. }
  5824. // Reject large values and names before building normalized header strings.
  5825. checkLength(valueLength + stringBytes(name, true) + (!isString && value.name ? stringBytes(value.name, false) : 0) + (!isString && value.type ? stringBytes(value.type, false) : 0));
  5826. let header = '--' + boundary + CRLF + 'Content-Disposition: form-data; name="' + escapeName(normalizeLines(name)) + '"';
  5827. if (!isString) {
  5828. header += '; filename="' + escapeName(utils$1.isString(value.name) ? value.name : 'blob') + '"' + CRLF + 'Content-Type: ' + String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
  5829. }
  5830. header += CRLF + CRLF;
  5831. const partLength = stringBytes(header, false) + valueLength + CRLF.length;
  5832. checkLength(partLength);
  5833. length += partLength;
  5834. parts.push({
  5835. header,
  5836. value,
  5837. isString
  5838. });
  5839. }
  5840. // Native Blob composition retains existing Blob/File data. No file is read
  5841. // and no complete multipart ArrayBuffer is created to determine its length.
  5842. const blobParts = [];
  5843. for (const part of parts) {
  5844. blobParts.push(part.header, part.isString ? normalizeLines(part.value) : part.value, CRLF);
  5845. }
  5846. blobParts.push(footer);
  5847. return new Blob(blobParts, {
  5848. type: 'multipart/form-data; boundary=' + boundary
  5849. });
  5850. }
  5851. function createMultipartBody(form, Blob, limit, limitError, boundary) {
  5852. // Report missing Blob support before trying to select a random source.
  5853. if (!utils$1.isFunction(Blob)) {
  5854. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  5855. }
  5856. if (boundary === undefined) {
  5857. if (utils$1.isFunction(platform.generateString)) {
  5858. boundary = 'axios-' + platform.generateString(36, '0123456789abcdef');
  5859. } else {
  5860. const crypto = utils$1.global.crypto;
  5861. if (!crypto || !utils$1.isFunction(crypto.getRandomValues)) {
  5862. throw new AxiosError('Random byte generation is not supported', AxiosError.ERR_NOT_SUPPORT);
  5863. }
  5864. const random = new Uint8Array(18);
  5865. crypto.getRandomValues(random);
  5866. boundary = 'axios-' + Array.from(random, value => ('0' + value.toString(16)).slice(-2)).join('');
  5867. }
  5868. }
  5869. try {
  5870. return formDataToBlob(form, Blob, limit, limitError, boundary);
  5871. } catch (error) {
  5872. if (error instanceof FormDataError) {
  5873. const code = error.reason === 'boundary' ? AxiosError.ERR_BAD_OPTION_VALUE : AxiosError.ERR_BAD_REQUEST;
  5874. throw new AxiosError(error.message, code);
  5875. }
  5876. throw error;
  5877. }
  5878. }
  5879. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  5880. const DEFAULT_REQUEST_OPTIONS = {
  5881. cache: 'default',
  5882. redirect: 'follow',
  5883. referrer: 'about:client',
  5884. referrerPolicy: '',
  5885. mode: 'cors',
  5886. integrity: '',
  5887. keepalive: false,
  5888. priority: 'auto',
  5889. window: null
  5890. };
  5891. const {
  5892. isFunction
  5893. } = utils$1;
  5894. /**
  5895. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  5896. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  5897. *
  5898. * @param {string} str The string to encode
  5899. *
  5900. * @returns {string} UTF-8 bytes as a Latin-1 string
  5901. */
  5902. const encodeUTF8 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  5903. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  5904. // Decode before composing the `auth` option so credentials such as
  5905. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  5906. // original value for malformed input so a bad encoding never throws.
  5907. const decodeURIComponentSafe = value => {
  5908. if (!utils$1.isString(value)) {
  5909. return value;
  5910. }
  5911. try {
  5912. return decodeURIComponent(value);
  5913. } catch (error) {
  5914. return value;
  5915. }
  5916. };
  5917. const test = (fn, ...args) => {
  5918. try {
  5919. return !!fn(...args);
  5920. } catch (e) {
  5921. return false;
  5922. }
  5923. };
  5924. const maybeWithAuthCredentials = url => {
  5925. const protocolIndex = url.indexOf('://');
  5926. let urlToCheck = url;
  5927. if (protocolIndex !== -1) {
  5928. urlToCheck = urlToCheck.slice(protocolIndex + 3);
  5929. }
  5930. return urlToCheck.includes('@') || urlToCheck.includes(':');
  5931. };
  5932. const factory = env => {
  5933. const globalObject = utils$1.global !== undefined && utils$1.global !== null ? utils$1.global : globalThis;
  5934. const {
  5935. ReadableStream,
  5936. TextEncoder
  5937. } = globalObject;
  5938. env = utils$1.merge.call({
  5939. skipUndefined: true
  5940. }, {
  5941. Request: globalObject.Request,
  5942. Response: globalObject.Response,
  5943. Blob: globalObject.Blob
  5944. }, env);
  5945. const envFetch = utils$1.hasOwnProp(env, 'fetch') ? env.fetch : undefined;
  5946. const {
  5947. Request,
  5948. Response,
  5949. Blob
  5950. } = env;
  5951. const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
  5952. const isRequestSupported = isFunction(Request);
  5953. const isResponseSupported = isFunction(Response);
  5954. if (!isFetchSupported) {
  5955. return false;
  5956. }
  5957. const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
  5958. const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? (encoder => str => encoder.encode(str))(new TextEncoder()) : async str => new Uint8Array(await new Request(str).arrayBuffer()));
  5959. const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
  5960. let duplexAccessed = false;
  5961. const request = new Request(platform.origin, {
  5962. body: new ReadableStream(),
  5963. method: 'POST',
  5964. get duplex() {
  5965. duplexAccessed = true;
  5966. return 'half';
  5967. }
  5968. });
  5969. const hasContentType = request.headers.has('Content-Type');
  5970. if (request.body != null) {
  5971. request.body.cancel();
  5972. }
  5973. return duplexAccessed && !hasContentType;
  5974. });
  5975. const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response('').body));
  5976. // Some runtimes reject every explicit cache mode. Use own defaults for both
  5977. // probes so unrelated polluted options cannot affect cache-mode detection.
  5978. const requestDefaults = Object.assign(Object.create(null), DEFAULT_REQUEST_OPTIONS);
  5979. if (isRequestSupported && !test(() => new Request(platform.origin, requestDefaults))) {
  5980. delete requestDefaults.cache;
  5981. // Only omit cache when that makes Request construction succeed. Otherwise
  5982. // retain the explicit default that protects supporting runtimes from pollution.
  5983. if (!test(() => new Request(platform.origin, requestDefaults))) {
  5984. requestDefaults.cache = DEFAULT_REQUEST_OPTIONS.cache;
  5985. }
  5986. }
  5987. const resolvers = {
  5988. stream: supportsResponseStream && (res => res.body)
  5989. };
  5990. isFetchSupported && (() => {
  5991. ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
  5992. !resolvers[type] && (resolvers[type] = (res, config) => {
  5993. let method = res && res[type];
  5994. if (method) {
  5995. return method.call(res);
  5996. }
  5997. throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
  5998. });
  5999. });
  6000. })();
  6001. const getBodyLength = async body => {
  6002. if (body == null) {
  6003. return 0;
  6004. }
  6005. if (utils$1.isBlob(body)) {
  6006. return body.size;
  6007. }
  6008. if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
  6009. return body.byteLength;
  6010. }
  6011. if (utils$1.isURLSearchParams(body)) {
  6012. body = body + '';
  6013. }
  6014. if (utils$1.isString(body)) {
  6015. return (await encodeText(body)).byteLength;
  6016. }
  6017. };
  6018. const resolveBodyLength = async (headers, body) => {
  6019. const length = utils$1.toFiniteNumber(headers.getContentLength());
  6020. return length == null ? getBodyLength(body) : length;
  6021. };
  6022. return async config => {
  6023. let {
  6024. url,
  6025. method,
  6026. data,
  6027. signal,
  6028. cancelToken,
  6029. timeout,
  6030. onDownloadProgress,
  6031. onUploadProgress,
  6032. responseType,
  6033. headers,
  6034. withCredentials = 'same-origin',
  6035. fetchOptions,
  6036. maxContentLength,
  6037. maxBodyLength,
  6038. maxRedirects
  6039. } = resolveConfig(config);
  6040. const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
  6041. const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
  6042. const own = key => utils$1.hasOwnProp(config, key) ? config[key] : undefined;
  6043. let _fetch = envFetch || fetch;
  6044. responseType = responseType ? (responseType + '').toLowerCase() : 'text';
  6045. let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
  6046. let request = null;
  6047. const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
  6048. composedSignal.unsubscribe();
  6049. });
  6050. let requestContentLength;
  6051. // AxiosErrors we raise while request or response bodies are being streamed. Captured
  6052. // by identity so the catch block can surface it directly, regardless of
  6053. // how the runtime wraps the resulting fetch rejection (undici exposes it
  6054. // as `err.cause`; some browsers drop the original error entirely).
  6055. let pendingBodyError = null;
  6056. let pendingResponseError = null;
  6057. const maxBodyLengthError = () => new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, request);
  6058. try {
  6059. // HTTP basic authentication
  6060. let auth = undefined;
  6061. const configAuth = own('auth');
  6062. if (configAuth) {
  6063. const username = utils$1.getSafeProp(configAuth, 'username') || '';
  6064. const password = utils$1.getSafeProp(configAuth, 'password') || '';
  6065. auth = {
  6066. username,
  6067. password
  6068. };
  6069. }
  6070. let parsedURL;
  6071. if (maybeWithAuthCredentials(url)) {
  6072. parsedURL = new URL(url, platform.origin);
  6073. if (!auth && (parsedURL.username || parsedURL.password)) {
  6074. const urlUsername = decodeURIComponentSafe(parsedURL.username);
  6075. const urlPassword = decodeURIComponentSafe(parsedURL.password);
  6076. auth = {
  6077. username: urlUsername,
  6078. password: urlPassword
  6079. };
  6080. }
  6081. if (parsedURL.username || parsedURL.password) {
  6082. parsedURL.username = '';
  6083. parsedURL.password = '';
  6084. url = parsedURL.href;
  6085. }
  6086. }
  6087. if (auth) {
  6088. headers.delete('authorization');
  6089. headers.set('Authorization', 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || ''))));
  6090. }
  6091. // Enforce maxContentLength for data: URLs up-front so we never materialize
  6092. // an oversized payload. The HTTP adapter applies the same check (see http.js
  6093. // "if (protocol === 'data:')" branch).
  6094. if (hasMaxContentLength && parsedURL && parsedURL.protocol === 'data:') {
  6095. const estimated = estimateDataURLDecodedBytes(parsedURL.href);
  6096. if (estimated > maxContentLength) {
  6097. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  6098. }
  6099. }
  6100. const formContentType = utils$1.isSpecCompliantForm(data) && AxiosHeaders.from(own('headers')).getContentType();
  6101. let formBoundary;
  6102. if (utils$1.isString(formContentType) && /^multipart\/form-data(?:\s*;|$)/i.test(formContentType.trim())) {
  6103. const parameters = AxiosHeaders.parseParameters(formContentType);
  6104. if (utils$1.hasOwnProp(parameters, 'boundary')) formBoundary = parameters.boundary;
  6105. }
  6106. if (utils$1.isSpecCompliantForm(data) && method !== 'get' && method !== 'head' && (hasMaxBodyLength || onUploadProgress && supportsRequestStream || formBoundary !== undefined)) {
  6107. data = createMultipartBody(data, Blob, hasMaxBodyLength ? maxBodyLength : Infinity, maxBodyLengthError, formBoundary);
  6108. // Blob.type lowercases its value, including a case-sensitive boundary.
  6109. // Retain the caller's header when an explicit boundary was serialized.
  6110. headers.setContentType(formBoundary === undefined ? data.type : formContentType);
  6111. requestContentLength = data.size;
  6112. }
  6113. // Enforce maxBodyLength against known-size bodies before dispatch using
  6114. // the body's *actual* size — never a caller-declared Content-Length,
  6115. // which could under-report to slip an oversized body past the check.
  6116. // Unknown-size streams return undefined here and are counted per-chunk
  6117. // below as fetch consumes them.
  6118. if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
  6119. const outboundLength = await getBodyLength(data);
  6120. if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
  6121. requestContentLength = outboundLength;
  6122. if (outboundLength > maxBodyLength) {
  6123. throw maxBodyLengthError();
  6124. }
  6125. }
  6126. }
  6127. // A streamed body under maxBodyLength must be counted as fetch consumes
  6128. // it; its size is never trusted from a caller-declared Content-Length.
  6129. const mustEnforceStreamBody = hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
  6130. const trackRequestStream = (stream, onProgress, flush) => trackStream(stream, DEFAULT_CHUNK_SIZE, loadedBytes => {
  6131. if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
  6132. throw pendingBodyError = maxBodyLengthError();
  6133. }
  6134. onProgress && onProgress(loadedBytes);
  6135. }, flush);
  6136. if (supportsRequestStream && method !== 'get' && method !== 'head' && (onUploadProgress || mustEnforceStreamBody)) {
  6137. requestContentLength = requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
  6138. // A declared length of 0 is only trusted to skip the wrap when we are
  6139. // not enforcing a stream limit (which must not rely on that header).
  6140. if (requestContentLength !== 0 || mustEnforceStreamBody) {
  6141. let _request = new Request(url, {
  6142. method: 'POST',
  6143. body: data,
  6144. duplex: 'half'
  6145. });
  6146. let contentTypeHeader;
  6147. if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
  6148. headers.setContentType(contentTypeHeader);
  6149. }
  6150. if (_request.body) {
  6151. const [onProgress, flush] = onUploadProgress && progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))) || [];
  6152. data = trackRequestStream(_request.body, onProgress, flush);
  6153. }
  6154. }
  6155. } else if (mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== 'get' && method !== 'head') {
  6156. data = trackRequestStream(data);
  6157. } else if (mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== 'get' && method !== 'head') {
  6158. throw new AxiosError('Stream request bodies are not supported by the current fetch implementation', AxiosError.ERR_NOT_SUPPORT, config, request);
  6159. }
  6160. if (!utils$1.isString(withCredentials)) {
  6161. withCredentials = withCredentials ? 'include' : 'omit';
  6162. }
  6163. // Cloudflare Workers throws when credentials are defined
  6164. // see https://github.com/cloudflare/workerd/issues/902
  6165. const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
  6166. // If data is FormData and Content-Type is multipart/form-data without boundary,
  6167. // delete it so fetch can set it correctly with the boundary
  6168. if (utils$1.isFormData(data)) {
  6169. const contentType = headers.getContentType();
  6170. if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) {
  6171. headers.delete('content-type');
  6172. }
  6173. }
  6174. // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
  6175. headers.set('User-Agent', 'axios/' + VERSION, false);
  6176. const safeFetchOptions = fetchOptions == null ? fetchOptions : Object.assign(Object.create(null), fetchOptions);
  6177. if (safeFetchOptions) {
  6178. // These options are owned by Axios and are already reflected in the
  6179. // resolved Request passed to fetch.
  6180. delete safeFetchOptions.body;
  6181. delete safeFetchOptions.headers;
  6182. delete safeFetchOptions.method;
  6183. delete safeFetchOptions.signal;
  6184. delete safeFetchOptions.duplex;
  6185. delete safeFetchOptions.credentials;
  6186. }
  6187. const resolvedOptions = Object.assign(Object.create(null), safeFetchOptions, {
  6188. signal: composedSignal,
  6189. method: method.toUpperCase(),
  6190. headers: toByteStringHeaderObject(headers.normalize()),
  6191. body: data,
  6192. duplex: 'half',
  6193. credentials: isCredentialsSupported ? withCredentials : undefined
  6194. });
  6195. if (isRequestSupported) {
  6196. utils$1.forEach(requestDefaults, (value, key) => {
  6197. if (resolvedOptions[key] === undefined) {
  6198. resolvedOptions[key] = value;
  6199. }
  6200. });
  6201. if (resolvedOptions.signal === undefined) {
  6202. resolvedOptions.signal = null;
  6203. }
  6204. if (resolvedOptions.body === undefined) {
  6205. resolvedOptions.body = null;
  6206. }
  6207. }
  6208. if (maxRedirects === 0) {
  6209. resolvedOptions.redirect = 'manual';
  6210. if (safeFetchOptions) {
  6211. safeFetchOptions.redirect = 'manual';
  6212. }
  6213. }
  6214. request = isRequestSupported && new Request(url, resolvedOptions);
  6215. let response = await (isRequestSupported ? _fetch(request, safeFetchOptions) : _fetch(url, resolvedOptions));
  6216. const responseHeaders = AxiosHeaders.from(response.headers);
  6217. // Cheap pre-check: if the server honestly declares a content-length that
  6218. // already exceeds the cap, reject before we start streaming.
  6219. if (hasMaxContentLength) {
  6220. const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
  6221. if (declaredLength != null && declaredLength > maxContentLength) {
  6222. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  6223. }
  6224. }
  6225. const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
  6226. if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
  6227. const options = {};
  6228. ['status', 'statusText', 'headers'].forEach(prop => {
  6229. options[prop] = response[prop];
  6230. });
  6231. const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
  6232. const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
  6233. let bytesRead = 0;
  6234. const onChunkProgress = loadedBytes => {
  6235. if (hasMaxContentLength) {
  6236. bytesRead = loadedBytes;
  6237. if (bytesRead > maxContentLength) {
  6238. throw pendingResponseError = new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  6239. }
  6240. }
  6241. onProgress && onProgress(loadedBytes);
  6242. };
  6243. response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
  6244. flush && flush();
  6245. unsubscribe && unsubscribe();
  6246. }), options);
  6247. }
  6248. responseType = responseType || 'text';
  6249. let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
  6250. // Fallback enforcement for environments without ReadableStream support
  6251. // (legacy runtimes). Detect materialized size from typed output; skip
  6252. // streams/Response passthrough since the user will read those themselves.
  6253. if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
  6254. let materializedSize;
  6255. if (responseData != null) {
  6256. if (typeof responseData.byteLength === 'number') {
  6257. materializedSize = responseData.byteLength;
  6258. } else if (typeof responseData.size === 'number') {
  6259. materializedSize = responseData.size;
  6260. } else if (typeof responseData === 'string') {
  6261. materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length;
  6262. }
  6263. }
  6264. if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
  6265. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  6266. }
  6267. }
  6268. !isStreamResponse && unsubscribe && unsubscribe();
  6269. return await new Promise((resolve, reject) => {
  6270. settle(resolve, reject, {
  6271. data: responseData,
  6272. headers: AxiosHeaders.from(response.headers),
  6273. status: response.status,
  6274. statusText: response.statusText,
  6275. config,
  6276. request
  6277. });
  6278. });
  6279. } catch (err) {
  6280. unsubscribe && unsubscribe();
  6281. // Safari can surface fetch aborts as a DOMException-like object whose
  6282. // branded getters throw. Prefer our composed signal reason before reading
  6283. // the caught error, preserving timeout vs cancellation semantics.
  6284. if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
  6285. const canceledError = composedSignal.reason;
  6286. canceledError.config = config;
  6287. request && (canceledError.request = request);
  6288. if (err !== canceledError) {
  6289. // Non-enumerable to match native Error `cause` semantics so loggers
  6290. // don't recurse into circular fetch internals (see #7205).
  6291. Object.defineProperty(canceledError, 'cause', {
  6292. __proto__: null,
  6293. value: err,
  6294. writable: true,
  6295. enumerable: false,
  6296. configurable: true
  6297. });
  6298. }
  6299. throw canceledError;
  6300. }
  6301. // Surface a maxBodyLength violation we raised while the request body was
  6302. // being streamed. Keeping the original error (rather than reading
  6303. // `err.cause.isAxiosError`) keeps the error deterministic across runtimes
  6304. // and avoids both prototype-pollution reads and mis-attributing a foreign
  6305. // AxiosError that merely happened to land in `err.cause`.
  6306. if (pendingBodyError) {
  6307. request && !pendingBodyError.request && (pendingBodyError.request = request);
  6308. throw pendingBodyError;
  6309. }
  6310. if (pendingResponseError) {
  6311. throw pendingResponseError;
  6312. }
  6313. // Re-throw AxiosErrors we raised synchronously (data: URL / content-length
  6314. // pre-checks, response size enforcement) without re-wrapping them.
  6315. if (err instanceof AxiosError) {
  6316. request && !err.request && (err.request = request);
  6317. throw err;
  6318. }
  6319. if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
  6320. const networkError = new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, err && err.response);
  6321. // Non-enumerable to match native Error `cause` semantics so loggers
  6322. // don't recurse into circular fetch internals (see #7205).
  6323. Object.defineProperty(networkError, 'cause', {
  6324. __proto__: null,
  6325. value: err.cause || err,
  6326. writable: true,
  6327. enumerable: false,
  6328. configurable: true
  6329. });
  6330. throw networkError;
  6331. }
  6332. throw AxiosError.from(err, err && err.code, config, request, err && err.response);
  6333. }
  6334. };
  6335. };
  6336. const seedCache = new Map();
  6337. const getFetch = config => {
  6338. const env = Object.create(null);
  6339. const configuredEnv = config && utils$1.hasOwnProp(config, 'env') && config.env;
  6340. ['fetch', 'Request', 'Response', 'Blob'].forEach(key => {
  6341. if (configuredEnv && utils$1.hasOwnProp(configuredEnv, key)) {
  6342. env[key] = configuredEnv[key];
  6343. }
  6344. });
  6345. const {
  6346. fetch,
  6347. Request,
  6348. Response,
  6349. Blob
  6350. } = env;
  6351. const seeds = [Request, Response, fetch, Blob];
  6352. let len = seeds.length,
  6353. i = len,
  6354. seed,
  6355. target,
  6356. map = seedCache;
  6357. while (i--) {
  6358. seed = seeds[i];
  6359. target = map.get(seed);
  6360. target === undefined && map.set(seed, target = i ? new Map() : factory(env));
  6361. map = target;
  6362. }
  6363. return target;
  6364. };
  6365. getFetch();
  6366. /**
  6367. * Known adapters mapping.
  6368. * Provides environment-specific adapters for Axios:
  6369. * - `http` for Node.js
  6370. * - `xhr` for browsers
  6371. * - `fetch` for fetch API-based requests
  6372. *
  6373. * @type {Object<string, Function|Object>}
  6374. */
  6375. const knownAdapters = {
  6376. http: httpAdapter,
  6377. xhr: xhrAdapter,
  6378. fetch: {
  6379. get: getFetch
  6380. }
  6381. };
  6382. // Assign adapter names for easier debugging and identification
  6383. utils$1.forEach(knownAdapters, (fn, value) => {
  6384. if (fn) {
  6385. try {
  6386. // Null-proto descriptors so a polluted Object.prototype.get cannot turn
  6387. // these data descriptors into accessor descriptors on the way in.
  6388. Object.defineProperty(fn, 'name', {
  6389. __proto__: null,
  6390. value
  6391. });
  6392. } catch (e) {
  6393. // eslint-disable-next-line no-empty
  6394. }
  6395. Object.defineProperty(fn, 'adapterName', {
  6396. __proto__: null,
  6397. value
  6398. });
  6399. }
  6400. });
  6401. /**
  6402. * Render a rejection reason string for unknown or unsupported adapters
  6403. *
  6404. * @param {string} reason
  6405. * @returns {string}
  6406. */
  6407. const renderReason = reason => `- ${reason}`;
  6408. /**
  6409. * Check if the adapter is resolved (function, null, or false)
  6410. *
  6411. * @param {Function|null|false} adapter
  6412. * @returns {boolean}
  6413. */
  6414. const isResolvedHandle = adapter => utils$1.isFunction(adapter) || adapter === null || adapter === false;
  6415. /**
  6416. * Get the first suitable adapter from the provided list.
  6417. * Tries each adapter in order until a supported one is found.
  6418. * Throws an AxiosError if no adapter is suitable.
  6419. *
  6420. * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
  6421. * @param {Object} config - Axios request configuration
  6422. * @throws {AxiosError} If no suitable adapter is available
  6423. * @returns {Function} The resolved adapter function
  6424. */
  6425. function getAdapter(adapters, config) {
  6426. adapters = utils$1.isArray(adapters) ? adapters : [adapters];
  6427. const {
  6428. length
  6429. } = adapters;
  6430. let nameOrAdapter;
  6431. let adapter;
  6432. const rejectedReasons = {};
  6433. for (let i = 0; i < length; i++) {
  6434. nameOrAdapter = adapters[i];
  6435. let id;
  6436. adapter = nameOrAdapter;
  6437. if (!isResolvedHandle(nameOrAdapter)) {
  6438. adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
  6439. if (adapter === undefined) {
  6440. throw new AxiosError(`Unknown adapter '${id}'`);
  6441. }
  6442. }
  6443. if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
  6444. break;
  6445. }
  6446. rejectedReasons[id || '#' + i] = adapter;
  6447. }
  6448. if (!adapter) {
  6449. const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? 'is not supported by the environment' : 'is not available in the build'));
  6450. let s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified';
  6451. throw new AxiosError(`There is no suitable adapter to dispatch the request ` + s, AxiosError.ERR_NOT_SUPPORT);
  6452. }
  6453. return adapter;
  6454. }
  6455. /**
  6456. * Exports Axios adapters and utility to resolve an adapter
  6457. */
  6458. var adapters = {
  6459. /**
  6460. * Resolve an adapter from a list of adapter names or functions.
  6461. * @type {Function}
  6462. */
  6463. getAdapter,
  6464. /**
  6465. * Exposes all known adapters
  6466. * @type {Object<string, Function|Object>}
  6467. */
  6468. adapters: knownAdapters
  6469. };
  6470. /**
  6471. * Throws a `CanceledError` if cancellation has been requested.
  6472. *
  6473. * @param {Object} config The config that is to be used for the request
  6474. *
  6475. * @returns {void}
  6476. */
  6477. function throwIfCancellationRequested(config) {
  6478. if (config.cancelToken) {
  6479. config.cancelToken.throwIfRequested();
  6480. }
  6481. if (config.signal && config.signal.aborted) {
  6482. throw new CanceledError(null, config);
  6483. }
  6484. }
  6485. /**
  6486. * Resolve the clock used to time adapter execution.
  6487. *
  6488. * Prefers the monotonic `performance.now()` so wall-clock adjustments do not
  6489. * skew the measurement, and so frameworks that forbid reading the current
  6490. * time during prerendering (e.g. Next.js Cache Components) accept it. Falls
  6491. * back to `Date.now()` in runtimes without the High Resolution Time API.
  6492. *
  6493. * @returns {() => number} Millisecond clock
  6494. */
  6495. function resolveClock() {
  6496. return typeof performance !== 'undefined' && utils$1.isFunction(performance.now) ? () => performance.now() : Date.now;
  6497. }
  6498. /**
  6499. * Whole milliseconds elapsed since `start`, floored at zero.
  6500. *
  6501. * Rounded so the value stays an integer as with `Date.now()`. The fallback
  6502. * wall clock can move backwards mid-request, so the result is clamped.
  6503. *
  6504. * @param {() => number} now Clock returned by `resolveClock()`
  6505. * @param {number} start Timestamp read from `now`
  6506. *
  6507. * @returns {number} Non-negative elapsed milliseconds
  6508. */
  6509. function elapsedSince(now, start) {
  6510. return Math.max(0, Math.round(now() - start));
  6511. }
  6512. /**
  6513. * Dispatch a request to the server using the configured adapter.
  6514. *
  6515. * @param {object} config The config that is to be used for the request
  6516. *
  6517. * @returns {Promise} The Promise to be fulfilled
  6518. */
  6519. function dispatchRequest(_config) {
  6520. // Interceptors may replace the merged config with an ordinary object. Flatten
  6521. // it at the dispatch boundary so shared prototype members cannot become
  6522. // request behavior, while preserving intentional template/class members.
  6523. const config = utils$1.toSafeFlatObject(_config);
  6524. throwIfCancellationRequested(config);
  6525. config.headers = AxiosHeaders.from(utils$1.getSafeProp(config, 'headers'));
  6526. // Transform request data
  6527. config.data = transformData.call(config, config.transformRequest);
  6528. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  6529. config.headers.setContentType('application/x-www-form-urlencoded', false);
  6530. }
  6531. const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
  6532. const now = resolveClock();
  6533. const start = now();
  6534. return adapter(config).then(function onAdapterResolution(response) {
  6535. throwIfCancellationRequested(config);
  6536. response.duration = elapsedSince(now, start);
  6537. // Expose the current response on config so that transformResponse can
  6538. // attach it to any AxiosError it throws (e.g. on JSON parse failure).
  6539. // We clean it up afterwards to avoid polluting the config object.
  6540. config.response = response;
  6541. try {
  6542. response.data = transformData.call(config, config.transformResponse, response);
  6543. } finally {
  6544. delete config.response;
  6545. }
  6546. response.headers = AxiosHeaders.from(response.headers);
  6547. return response;
  6548. }, function onAdapterRejection(reason) {
  6549. if (!isCancel(reason)) {
  6550. throwIfCancellationRequested(config);
  6551. // Transform response data
  6552. if (reason && reason.response) {
  6553. reason.response.duration = elapsedSince(now, start);
  6554. config.response = reason.response;
  6555. try {
  6556. reason.response.data = transformData.call(config, config.transformResponse, reason.response);
  6557. } finally {
  6558. delete config.response;
  6559. }
  6560. reason.response.headers = AxiosHeaders.from(reason.response.headers);
  6561. }
  6562. }
  6563. return Promise.reject(reason);
  6564. });
  6565. }
  6566. const validators$1 = {};
  6567. // eslint-disable-next-line func-names
  6568. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  6569. validators$1[type] = function validator(thing) {
  6570. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  6571. };
  6572. });
  6573. const deprecatedWarnings = {};
  6574. /**
  6575. * Transitional option validator
  6576. *
  6577. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  6578. * @param {string?} version - deprecated version / removed since version
  6579. * @param {string?} message - some message with additional info
  6580. *
  6581. * @returns {function}
  6582. */
  6583. validators$1.transitional = function transitional(validator, version, message) {
  6584. function formatMessage(opt, desc) {
  6585. return '[Axios v' + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? '. ' + message : '');
  6586. }
  6587. // eslint-disable-next-line func-names
  6588. return (value, opt, opts) => {
  6589. if (validator === false) {
  6590. throw new AxiosError(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED);
  6591. }
  6592. if (version && !deprecatedWarnings[opt]) {
  6593. deprecatedWarnings[opt] = true;
  6594. // eslint-disable-next-line no-console
  6595. console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future'));
  6596. }
  6597. return validator ? validator(value, opt, opts) : true;
  6598. };
  6599. };
  6600. validators$1.spelling = function spelling(correctSpelling) {
  6601. return (value, opt) => {
  6602. // eslint-disable-next-line no-console
  6603. console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
  6604. return true;
  6605. };
  6606. };
  6607. /**
  6608. * Assert object's properties type
  6609. *
  6610. * @param {object} options
  6611. * @param {object} schema
  6612. * @param {boolean?} allowUnknown
  6613. *
  6614. * @returns {object}
  6615. */
  6616. function assertOptions(options, schema, allowUnknown) {
  6617. if (typeof options !== 'object' || options === null) {
  6618. throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  6619. }
  6620. const keys = Object.keys(options);
  6621. let i = keys.length;
  6622. while (i-- > 0) {
  6623. const opt = keys[i];
  6624. // Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
  6625. // a non-function validator and cause a TypeError.
  6626. const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
  6627. if (validator) {
  6628. const value = options[opt];
  6629. const result = value === undefined || validator(value, opt, options);
  6630. if (result !== true) {
  6631. throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
  6632. }
  6633. continue;
  6634. }
  6635. if (allowUnknown !== true) {
  6636. throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
  6637. }
  6638. }
  6639. }
  6640. var validator = {
  6641. assertOptions,
  6642. validators: validators$1
  6643. };
  6644. const validators = validator.validators;
  6645. // Recognize header maps without consuming objects intended as literal values.
  6646. // AxiosHeaders from other builds share a brand and header-container interface,
  6647. // but not constructor identity. A tag and toJSON alone can describe a literal.
  6648. const isHeadersBucket = value => {
  6649. if (value == null || utils$1.isPlainObject(value) || value instanceof AxiosHeaders) {
  6650. return true;
  6651. }
  6652. try {
  6653. return utils$1.isObject(value) && utils$1.getSafeProp(value, Symbol.toStringTag) === 'AxiosHeaders' && ['toJSON', 'set', 'get', 'has', 'delete', 'clear', 'normalize', 'concat', 'toString', Symbol.iterator].every(method => utils$1.isFunction(utils$1.getSafeProp(value, method)));
  6654. } catch (e) {
  6655. // A failed optional brand probe must not prevent literal header serialization.
  6656. return false;
  6657. }
  6658. };
  6659. /**
  6660. * Create a new instance of Axios
  6661. *
  6662. * @param {Object} instanceConfig The default config for the instance
  6663. *
  6664. * @return {Axios} A new instance of Axios
  6665. */
  6666. class Axios {
  6667. constructor(instanceConfig) {
  6668. this.defaults = instanceConfig || {};
  6669. this.interceptors = {
  6670. request: new InterceptorManager(),
  6671. response: new InterceptorManager()
  6672. };
  6673. }
  6674. /**
  6675. * Dispatch a request
  6676. *
  6677. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  6678. * @param {?Object} config
  6679. *
  6680. * @returns {Promise} The Promise to be fulfilled
  6681. */
  6682. async request(configOrUrl, config) {
  6683. try {
  6684. return await this._request(configOrUrl, config);
  6685. } catch (err) {
  6686. if (err instanceof Error) {
  6687. try {
  6688. let dummy = {};
  6689. Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
  6690. const dummyStack = dummy.stack;
  6691. let stack = '';
  6692. // slice off the Error: ... line
  6693. if (typeof dummyStack === 'string') {
  6694. const firstNewlineIndex = dummyStack.indexOf('\n');
  6695. stack = firstNewlineIndex === -1 ? '' : dummyStack.slice(firstNewlineIndex + 1);
  6696. }
  6697. if (!err.stack) {
  6698. err.stack = stack;
  6699. } else if (stack) {
  6700. // Match a common suffix after the 2 top frames when available,
  6701. // otherwise compare the full reconstructed stack.
  6702. const firstNewlineIndex = stack.indexOf('\n');
  6703. const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
  6704. const duplicateCheckSuffix = secondNewlineIndex === -1 ? stack : stack.slice(secondNewlineIndex + 1);
  6705. // `AxiosError.from()` may have already inlined the wrapped error's
  6706. // stack under a `Caused by:` marker. Keep the reconstructed caller
  6707. // frames ahead of that marker so stack-only reporters do not read
  6708. // them as part of the low-level cause.
  6709. const currentStack = String(err.stack);
  6710. const causeIndex = getCauseStackIndex(err, currentStack);
  6711. const stackHead = causeIndex === -1 ? currentStack : currentStack.slice(0, causeIndex);
  6712. const causeSection = causeIndex === -1 ? '' : currentStack.slice(causeIndex);
  6713. if (!stackHead.endsWith(duplicateCheckSuffix)) {
  6714. err.stack = stackHead + '\n' + stack + causeSection;
  6715. }
  6716. }
  6717. } catch (e) {
  6718. // Ignore failures from custom stack hooks or un-writable stack properties.
  6719. }
  6720. }
  6721. throw err;
  6722. }
  6723. }
  6724. _request(configOrUrl, config) {
  6725. /*eslint no-param-reassign:0*/
  6726. // Allow for axios('example/url'[, config]) a la fetch API
  6727. if (typeof configOrUrl === 'string') {
  6728. config = config || {};
  6729. config.url = configOrUrl;
  6730. } else {
  6731. config = configOrUrl || {};
  6732. }
  6733. config = mergeConfig(this.defaults, config);
  6734. const {
  6735. transitional,
  6736. paramsSerializer,
  6737. headers
  6738. } = config;
  6739. if (transitional !== undefined) {
  6740. validator.assertOptions(transitional, {
  6741. silentJSONParsing: validators.transitional(validators.boolean),
  6742. forcedJSONParsing: validators.transitional(validators.boolean),
  6743. clarifyTimeoutError: validators.transitional(validators.boolean),
  6744. legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
  6745. advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
  6746. validateStatusUndefinedResolves: validators.transitional(validators.boolean),
  6747. encodeBasicAuthUsername: validators.transitional(validators.boolean)
  6748. }, false);
  6749. }
  6750. if (paramsSerializer != null) {
  6751. if (utils$1.isFunction(paramsSerializer)) {
  6752. config.paramsSerializer = {
  6753. serialize: paramsSerializer
  6754. };
  6755. } else {
  6756. validator.assertOptions(paramsSerializer, {
  6757. encode: validators.function,
  6758. serialize: validators.function
  6759. }, true);
  6760. }
  6761. }
  6762. // Set config.allowAbsoluteUrls
  6763. if (config.allowAbsoluteUrls !== undefined) ; else if (utils$1.hasOwnProp(this.defaults, 'allowAbsoluteUrls') && this.defaults.allowAbsoluteUrls !== undefined) {
  6764. config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
  6765. } else {
  6766. config.allowAbsoluteUrls = true;
  6767. }
  6768. validator.assertOptions(config, {
  6769. baseUrl: validators.spelling('baseURL'),
  6770. withXsrfToken: validators.spelling('withXSRFToken')
  6771. }, true);
  6772. // Set config.method
  6773. config.method = (utils$1.getSafeProp(config, 'method') || utils$1.getSafeProp(this.defaults, 'method') || 'get').toLowerCase();
  6774. // Flatten header defaults without consuming literal method-named headers.
  6775. const commonHeaders = utils$1.getSafeProp(headers, 'common');
  6776. const methodHeaders = utils$1.getSafeProp(headers, config.method);
  6777. const contextHeaders = headers && utils$1.merge(isHeadersBucket(commonHeaders) ? commonHeaders : undefined, isHeadersBucket(methodHeaders) ? methodHeaders : undefined);
  6778. headers && utils$1.forEach(methodList.concat('common'), method => {
  6779. if (isHeadersBucket(utils$1.getSafeProp(headers, method))) {
  6780. delete headers[method];
  6781. }
  6782. });
  6783. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  6784. // filter out skipped interceptors
  6785. const requestInterceptorChain = [];
  6786. let synchronousRequestInterceptors = true;
  6787. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  6788. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  6789. return;
  6790. }
  6791. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  6792. const transitional = config.transitional || transitionalDefaults;
  6793. const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;
  6794. if (legacyInterceptorReqResOrdering) {
  6795. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  6796. } else {
  6797. requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  6798. }
  6799. });
  6800. const responseInterceptorChain = [];
  6801. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  6802. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  6803. });
  6804. let promise;
  6805. let i = 0;
  6806. let len;
  6807. if (!synchronousRequestInterceptors) {
  6808. const chain = [dispatchRequest.bind(this), undefined];
  6809. chain.unshift(...requestInterceptorChain);
  6810. chain.push(...responseInterceptorChain);
  6811. len = chain.length;
  6812. promise = Promise.resolve(config);
  6813. while (i < len) {
  6814. promise = promise.then(chain[i++], chain[i++]);
  6815. }
  6816. return promise;
  6817. }
  6818. len = requestInterceptorChain.length;
  6819. let newConfig = config;
  6820. while (i < len) {
  6821. const onFulfilled = requestInterceptorChain[i++];
  6822. const onRejected = requestInterceptorChain[i++];
  6823. try {
  6824. newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig;
  6825. } catch (error) {
  6826. if (!onRejected) {
  6827. promise = Promise.reject(error);
  6828. break;
  6829. }
  6830. try {
  6831. const rejectedResult = onRejected.call(this, error);
  6832. if (utils$1.isThenable(rejectedResult)) {
  6833. promise = Promise.resolve(rejectedResult).then(() => dispatchRequest.call(this, newConfig));
  6834. }
  6835. } catch (rejectedError) {
  6836. promise = Promise.reject(rejectedError);
  6837. }
  6838. break;
  6839. }
  6840. }
  6841. if (!promise) {
  6842. try {
  6843. promise = dispatchRequest.call(this, newConfig);
  6844. } catch (error) {
  6845. promise = Promise.reject(error);
  6846. }
  6847. }
  6848. i = 0;
  6849. len = responseInterceptorChain.length;
  6850. while (i < len) {
  6851. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  6852. }
  6853. return promise;
  6854. }
  6855. getUri(config) {
  6856. config = mergeConfig(this.defaults, config);
  6857. const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
  6858. return buildURL(fullPath, config.params, config.paramsSerializer);
  6859. }
  6860. }
  6861. // Provide aliases for supported request methods
  6862. utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  6863. /*eslint func-names:0*/
  6864. Axios.prototype[method] = async function (url, config) {
  6865. return this.request(mergeConfig(config || {}, {
  6866. method,
  6867. url,
  6868. data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined
  6869. }));
  6870. };
  6871. });
  6872. utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
  6873. function generateHTTPMethod(isForm) {
  6874. return async function httpMethod(url, data, config) {
  6875. return this.request(mergeConfig(config || {}, {
  6876. method,
  6877. headers: isForm ? {
  6878. 'Content-Type': 'multipart/form-data'
  6879. } : {},
  6880. url,
  6881. data
  6882. }));
  6883. };
  6884. }
  6885. Axios.prototype[method] = generateHTTPMethod();
  6886. // QUERY is a safe/idempotent read method; multipart form bodies don't fit
  6887. // its semantics, so no queryForm shorthand is generated.
  6888. if (method !== 'query') {
  6889. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  6890. }
  6891. });
  6892. /**
  6893. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  6894. *
  6895. * @param {Function} executor The executor function.
  6896. *
  6897. * @returns {CancelToken}
  6898. */
  6899. class CancelToken {
  6900. constructor(executor) {
  6901. if (typeof executor !== 'function') {
  6902. throw new TypeError('executor must be a function.');
  6903. }
  6904. let resolvePromise;
  6905. this.promise = new Promise(function promiseExecutor(resolve) {
  6906. resolvePromise = resolve;
  6907. });
  6908. const token = this;
  6909. // eslint-disable-next-line func-names
  6910. this.promise.then(cancel => {
  6911. if (!token._listeners) return;
  6912. let i = token._listeners.length;
  6913. while (i-- > 0) {
  6914. token._listeners[i](cancel);
  6915. }
  6916. token._listeners = null;
  6917. });
  6918. // eslint-disable-next-line func-names
  6919. this.promise.then = onfulfilled => {
  6920. let _resolve;
  6921. // eslint-disable-next-line func-names
  6922. const promise = new Promise(resolve => {
  6923. token.subscribe(resolve);
  6924. _resolve = resolve;
  6925. }).then(onfulfilled);
  6926. promise.cancel = function reject() {
  6927. token.unsubscribe(_resolve);
  6928. };
  6929. return promise;
  6930. };
  6931. executor(function cancel(message, config, request) {
  6932. if (token.reason) {
  6933. // Cancellation has already been requested
  6934. return;
  6935. }
  6936. token.reason = new CanceledError(message, config, request);
  6937. resolvePromise(token.reason);
  6938. });
  6939. }
  6940. /**
  6941. * Throws a `CanceledError` if cancellation has been requested.
  6942. */
  6943. throwIfRequested() {
  6944. if (this.reason) {
  6945. throw this.reason;
  6946. }
  6947. }
  6948. /**
  6949. * Subscribe to the cancel signal
  6950. */
  6951. subscribe(listener) {
  6952. if (this.reason) {
  6953. listener(this.reason);
  6954. return;
  6955. }
  6956. if (this._listeners) {
  6957. this._listeners.push(listener);
  6958. } else {
  6959. this._listeners = [listener];
  6960. }
  6961. }
  6962. /**
  6963. * Unsubscribe from the cancel signal
  6964. */
  6965. unsubscribe(listener) {
  6966. if (!this._listeners) {
  6967. return;
  6968. }
  6969. const index = this._listeners.indexOf(listener);
  6970. if (index !== -1) {
  6971. this._listeners.splice(index, 1);
  6972. }
  6973. }
  6974. toAbortSignal() {
  6975. const controller = new AbortController();
  6976. const abort = err => {
  6977. controller.abort(err);
  6978. };
  6979. this.subscribe(abort);
  6980. controller.signal.unsubscribe = () => this.unsubscribe(abort);
  6981. return controller.signal;
  6982. }
  6983. /**
  6984. * Returns an object that contains a new `CancelToken` and a function that, when called,
  6985. * cancels the `CancelToken`.
  6986. */
  6987. static source() {
  6988. let cancel;
  6989. const token = new CancelToken(function executor(c) {
  6990. cancel = c;
  6991. });
  6992. return {
  6993. token,
  6994. cancel
  6995. };
  6996. }
  6997. }
  6998. /**
  6999. * Syntactic sugar for invoking a function and expanding an array for arguments.
  7000. *
  7001. * Common use case would be to use `Function.prototype.apply`.
  7002. *
  7003. * ```js
  7004. * function f(x, y, z) {}
  7005. * const args = [1, 2, 3];
  7006. * f.apply(null, args);
  7007. * ```
  7008. *
  7009. * With `spread` this example can be re-written.
  7010. *
  7011. * ```js
  7012. * spread(function(x, y, z) {})([1, 2, 3]);
  7013. * ```
  7014. *
  7015. * @param {Function} callback
  7016. *
  7017. * @returns {Function}
  7018. */
  7019. function spread(callback) {
  7020. return function wrap(arr) {
  7021. return callback.apply(null, arr);
  7022. };
  7023. }
  7024. /**
  7025. * Determines whether the payload is an error thrown by Axios
  7026. *
  7027. * @param {*} payload The value to test
  7028. *
  7029. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  7030. */
  7031. function isAxiosError(payload) {
  7032. return utils$1.isObject(payload) && payload.isAxiosError === true;
  7033. }
  7034. const HttpStatusCode = {
  7035. Continue: 100,
  7036. SwitchingProtocols: 101,
  7037. Processing: 102,
  7038. EarlyHints: 103,
  7039. Ok: 200,
  7040. Created: 201,
  7041. Accepted: 202,
  7042. NonAuthoritativeInformation: 203,
  7043. NoContent: 204,
  7044. ResetContent: 205,
  7045. PartialContent: 206,
  7046. MultiStatus: 207,
  7047. AlreadyReported: 208,
  7048. ImUsed: 226,
  7049. MultipleChoices: 300,
  7050. MovedPermanently: 301,
  7051. Found: 302,
  7052. SeeOther: 303,
  7053. NotModified: 304,
  7054. UseProxy: 305,
  7055. Unused: 306,
  7056. TemporaryRedirect: 307,
  7057. PermanentRedirect: 308,
  7058. BadRequest: 400,
  7059. Unauthorized: 401,
  7060. PaymentRequired: 402,
  7061. Forbidden: 403,
  7062. NotFound: 404,
  7063. MethodNotAllowed: 405,
  7064. NotAcceptable: 406,
  7065. ProxyAuthenticationRequired: 407,
  7066. RequestTimeout: 408,
  7067. Conflict: 409,
  7068. Gone: 410,
  7069. LengthRequired: 411,
  7070. PreconditionFailed: 412,
  7071. /**
  7072. * @deprecated Use `ContentTooLarge` instead.
  7073. */
  7074. PayloadTooLarge: 413,
  7075. ContentTooLarge: 413,
  7076. UriTooLong: 414,
  7077. UnsupportedMediaType: 415,
  7078. RangeNotSatisfiable: 416,
  7079. ExpectationFailed: 417,
  7080. ImATeapot: 418,
  7081. MisdirectedRequest: 421,
  7082. /**
  7083. * @deprecated Use `UnprocessableContent` instead.
  7084. */
  7085. UnprocessableEntity: 422,
  7086. UnprocessableContent: 422,
  7087. Locked: 423,
  7088. FailedDependency: 424,
  7089. TooEarly: 425,
  7090. UpgradeRequired: 426,
  7091. PreconditionRequired: 428,
  7092. TooManyRequests: 429,
  7093. RequestHeaderFieldsTooLarge: 431,
  7094. UnavailableForLegalReasons: 451,
  7095. InternalServerError: 500,
  7096. NotImplemented: 501,
  7097. BadGateway: 502,
  7098. ServiceUnavailable: 503,
  7099. GatewayTimeout: 504,
  7100. HttpVersionNotSupported: 505,
  7101. VariantAlsoNegotiates: 506,
  7102. InsufficientStorage: 507,
  7103. LoopDetected: 508,
  7104. NotExtended: 510,
  7105. NetworkAuthenticationRequired: 511,
  7106. WebServerReturnsAnUnknownError: 520,
  7107. WebServerIsDown: 521,
  7108. ConnectionTimedOut: 522,
  7109. OriginIsUnreachable: 523,
  7110. TimeoutOccurred: 524,
  7111. SslHandshakeFailed: 525,
  7112. InvalidSslCertificate: 526
  7113. };
  7114. Object.entries(HttpStatusCode).forEach(([key, value]) => {
  7115. if (HttpStatusCode[value] === undefined) {
  7116. HttpStatusCode[value] = key;
  7117. }
  7118. });
  7119. /**
  7120. * Create an instance of Axios
  7121. *
  7122. * @param {Object} defaultConfig The default config for the instance
  7123. *
  7124. * @returns {Axios} A new instance of Axios
  7125. */
  7126. function createInstance(defaultConfig) {
  7127. const context = new Axios(defaultConfig);
  7128. const instance = bind(Axios.prototype.request, context);
  7129. // Copy axios.prototype to instance
  7130. utils$1.extend(instance, Axios.prototype, context, {
  7131. allOwnKeys: true
  7132. });
  7133. // Copy context to instance
  7134. utils$1.extend(instance, context, null, {
  7135. allOwnKeys: true
  7136. });
  7137. // Factory for creating new instances
  7138. instance.create = function create(instanceConfig) {
  7139. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  7140. };
  7141. return instance;
  7142. }
  7143. // Create the default instance to be exported
  7144. const axios = createInstance(defaults);
  7145. // Expose Axios class to allow class inheritance
  7146. axios.Axios = Axios;
  7147. // Expose Cancel & CancelToken
  7148. axios.CanceledError = CanceledError;
  7149. axios.CancelToken = CancelToken;
  7150. axios.isCancel = isCancel;
  7151. axios.VERSION = VERSION;
  7152. axios.toFormData = toFormData;
  7153. // Expose AxiosError class
  7154. axios.AxiosError = AxiosError;
  7155. // alias for CanceledError for backward compatibility
  7156. axios.Cancel = axios.CanceledError;
  7157. // Expose all/spread
  7158. axios.all = function all(promises) {
  7159. return Promise.all(promises);
  7160. };
  7161. axios.spread = spread;
  7162. // Expose isAxiosError
  7163. axios.isAxiosError = isAxiosError;
  7164. // Expose mergeConfig
  7165. axios.mergeConfig = mergeConfig;
  7166. axios.AxiosHeaders = AxiosHeaders;
  7167. axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
  7168. axios.getAdapter = adapters.getAdapter;
  7169. axios.HttpStatusCode = HttpStatusCode;
  7170. axios.default = axios;
  7171. module.exports = axios;