智慧水务管理系统 - 精河县供水工程综合管理平台

axios.cjs 195KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906
  1. /*! Axios v1.18.0 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. /**
  44. * Walk the prototype chain (excluding the shared Object.prototype) looking for
  45. * an own `prop`. This distinguishes genuine own/inherited members — including
  46. * class accessors and template prototypes — from members injected via
  47. * Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
  48. * live on Object.prototype itself and are therefore never matched.
  49. *
  50. * @param {*} thing The value whose chain to inspect
  51. * @param {string|symbol} prop The property key to look for
  52. *
  53. * @returns {boolean} True when `prop` is owned below Object.prototype
  54. */
  55. const hasOwnInPrototypeChain = (thing, prop) => {
  56. let obj = thing;
  57. const seen = [];
  58. while (obj != null && obj !== Object.prototype) {
  59. if (seen.indexOf(obj) !== -1) {
  60. return false;
  61. }
  62. seen.push(obj);
  63. if (hasOwnProperty(obj, prop)) {
  64. return true;
  65. }
  66. obj = getPrototypeOf(obj);
  67. }
  68. return false;
  69. };
  70. /**
  71. * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
  72. * properties and members inherited from a non-Object.prototype source (a class
  73. * instance or template object) are honored; a value reachable only through a
  74. * polluted Object.prototype is ignored and `undefined` is returned.
  75. *
  76. * @param {*} obj The source object
  77. * @param {string|symbol} prop The property key to read
  78. *
  79. * @returns {*} The resolved value, or undefined when unsafe/absent
  80. */
  81. const getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
  82. const kindOf = (cache => thing => {
  83. const str = toString.call(thing);
  84. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  85. })(Object.create(null));
  86. const kindOfTest = type => {
  87. type = type.toLowerCase();
  88. return thing => kindOf(thing) === type;
  89. };
  90. const typeOfTest = type => thing => typeof thing === type;
  91. /**
  92. * Determine if a value is a non-null object
  93. *
  94. * @param {Object} val The value to test
  95. *
  96. * @returns {boolean} True if value is an Array, otherwise false
  97. */
  98. const {
  99. isArray
  100. } = Array;
  101. /**
  102. * Determine if a value is undefined
  103. *
  104. * @param {*} val The value to test
  105. *
  106. * @returns {boolean} True if the value is undefined, otherwise false
  107. */
  108. const isUndefined = typeOfTest('undefined');
  109. /**
  110. * Determine if a value is a Buffer
  111. *
  112. * @param {*} val The value to test
  113. *
  114. * @returns {boolean} True if value is a Buffer, otherwise false
  115. */
  116. function isBuffer(val) {
  117. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
  118. }
  119. /**
  120. * Determine if a value is an ArrayBuffer
  121. *
  122. * @param {*} val The value to test
  123. *
  124. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  125. */
  126. const isArrayBuffer = kindOfTest('ArrayBuffer');
  127. /**
  128. * Determine if a value is a view on an ArrayBuffer
  129. *
  130. * @param {*} val The value to test
  131. *
  132. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  133. */
  134. function isArrayBufferView(val) {
  135. let result;
  136. if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
  137. result = ArrayBuffer.isView(val);
  138. } else {
  139. result = val && val.buffer && isArrayBuffer(val.buffer);
  140. }
  141. return result;
  142. }
  143. /**
  144. * Determine if a value is a String
  145. *
  146. * @param {*} val The value to test
  147. *
  148. * @returns {boolean} True if value is a String, otherwise false
  149. */
  150. const isString = typeOfTest('string');
  151. /**
  152. * Determine if a value is a Function
  153. *
  154. * @param {*} val The value to test
  155. * @returns {boolean} True if value is a Function, otherwise false
  156. */
  157. const isFunction$1 = typeOfTest('function');
  158. /**
  159. * Determine if a value is a Number
  160. *
  161. * @param {*} val The value to test
  162. *
  163. * @returns {boolean} True if value is a Number, otherwise false
  164. */
  165. const isNumber = typeOfTest('number');
  166. /**
  167. * Determine if a value is an Object
  168. *
  169. * @param {*} thing The value to test
  170. *
  171. * @returns {boolean} True if value is an Object, otherwise false
  172. */
  173. const isObject = thing => thing !== null && typeof thing === 'object';
  174. /**
  175. * Determine if a value is a Boolean
  176. *
  177. * @param {*} thing The value to test
  178. * @returns {boolean} True if value is a Boolean, otherwise false
  179. */
  180. const isBoolean = thing => thing === true || thing === false;
  181. /**
  182. * Determine if a value is a plain Object
  183. *
  184. * @param {*} val The value to test
  185. *
  186. * @returns {boolean} True if value is a plain Object, otherwise false
  187. */
  188. const isPlainObject = val => {
  189. if (!isObject(val)) {
  190. return false;
  191. }
  192. const prototype = getPrototypeOf(val);
  193. return (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&
  194. // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
  195. // Symbol.iterator as evidence the value is a tagged/iterable type rather
  196. // than a plain object, while ignoring keys injected onto Object.prototype.
  197. !hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator);
  198. };
  199. /**
  200. * Determine if a value is an empty object (safely handles Buffers)
  201. *
  202. * @param {*} val The value to test
  203. *
  204. * @returns {boolean} True if value is an empty object, otherwise false
  205. */
  206. const isEmptyObject = val => {
  207. // Early return for non-objects or Buffers to prevent RangeError
  208. if (!isObject(val) || isBuffer(val)) {
  209. return false;
  210. }
  211. try {
  212. return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  213. } catch (e) {
  214. // Fallback for any other objects that might cause RangeError with Object.keys()
  215. return false;
  216. }
  217. };
  218. /**
  219. * Determine if a value is a Date
  220. *
  221. * @param {*} val The value to test
  222. *
  223. * @returns {boolean} True if value is a Date, otherwise false
  224. */
  225. const isDate = kindOfTest('Date');
  226. /**
  227. * Determine if a value is a File
  228. *
  229. * @param {*} val The value to test
  230. *
  231. * @returns {boolean} True if value is a File, otherwise false
  232. */
  233. const isFile = kindOfTest('File');
  234. /**
  235. * Determine if a value is a React Native Blob
  236. * React Native "blob": an object with a `uri` attribute. Optionally, it can
  237. * also have a `name` and `type` attribute to specify filename and content type
  238. *
  239. * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
  240. *
  241. * @param {*} value The value to test
  242. *
  243. * @returns {boolean} True if value is a React Native Blob, otherwise false
  244. */
  245. const isReactNativeBlob = value => {
  246. return !!(value && typeof value.uri !== 'undefined');
  247. };
  248. /**
  249. * Determine if environment is React Native
  250. * ReactNative `FormData` has a non-standard `getParts()` method
  251. *
  252. * @param {*} formData The formData to test
  253. *
  254. * @returns {boolean} True if environment is React Native, otherwise false
  255. */
  256. const isReactNative = formData => formData && typeof formData.getParts !== 'undefined';
  257. /**
  258. * Determine if a value is a Blob
  259. *
  260. * @param {*} val The value to test
  261. *
  262. * @returns {boolean} True if value is a Blob, otherwise false
  263. */
  264. const isBlob = kindOfTest('Blob');
  265. /**
  266. * Determine if a value is a FileList
  267. *
  268. * @param {*} val The value to test
  269. *
  270. * @returns {boolean} True if value is a FileList, otherwise false
  271. */
  272. const isFileList = kindOfTest('FileList');
  273. /**
  274. * Determine if a value is a Stream
  275. *
  276. * @param {*} val The value to test
  277. *
  278. * @returns {boolean} True if value is a Stream, otherwise false
  279. */
  280. const isStream = val => isObject(val) && isFunction$1(val.pipe);
  281. /**
  282. * Determine if a value is a FormData
  283. *
  284. * @param {*} thing The value to test
  285. *
  286. * @returns {boolean} True if value is an FormData, otherwise false
  287. */
  288. function getGlobal() {
  289. if (typeof globalThis !== 'undefined') return globalThis;
  290. if (typeof self !== 'undefined') return self;
  291. if (typeof window !== 'undefined') return window;
  292. if (typeof global !== 'undefined') return global;
  293. return {};
  294. }
  295. const G = getGlobal();
  296. const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
  297. const isFormData = thing => {
  298. if (!thing) return false;
  299. if (FormDataCtor && thing instanceof FormDataCtor) return true;
  300. // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
  301. const proto = getPrototypeOf(thing);
  302. if (!proto || proto === Object.prototype) return false;
  303. if (!isFunction$1(thing.append)) return false;
  304. const kind = kindOf(thing);
  305. return kind === 'formdata' ||
  306. // detect form-data instance
  307. kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]';
  308. };
  309. /**
  310. * Determine if a value is a URLSearchParams object
  311. *
  312. * @param {*} val The value to test
  313. *
  314. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  315. */
  316. const isURLSearchParams = kindOfTest('URLSearchParams');
  317. const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
  318. /**
  319. * Trim excess whitespace off the beginning and end of a string
  320. *
  321. * @param {String} str The String to trim
  322. *
  323. * @returns {String} The String freed of excess whitespace
  324. */
  325. const trim = str => {
  326. return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  327. };
  328. /**
  329. * Iterate over an Array or an Object invoking a function for each item.
  330. *
  331. * If `obj` is an Array callback will be called passing
  332. * the value, index, and complete array for each item.
  333. *
  334. * If 'obj' is an Object callback will be called passing
  335. * the value, key, and complete object for each property.
  336. *
  337. * @param {Object|Array<unknown>} obj The object to iterate
  338. * @param {Function} fn The callback to invoke for each item
  339. *
  340. * @param {Object} [options]
  341. * @param {Boolean} [options.allOwnKeys = false]
  342. * @returns {any}
  343. */
  344. function forEach(obj, fn, {
  345. allOwnKeys = false
  346. } = {}) {
  347. // Don't bother if no value provided
  348. if (obj === null || typeof obj === 'undefined') {
  349. return;
  350. }
  351. let i;
  352. let l;
  353. // Force an array if not already something iterable
  354. if (typeof obj !== 'object') {
  355. /*eslint no-param-reassign:0*/
  356. obj = [obj];
  357. }
  358. if (isArray(obj)) {
  359. // Iterate over array values
  360. for (i = 0, l = obj.length; i < l; i++) {
  361. fn.call(null, obj[i], i, obj);
  362. }
  363. } else {
  364. // Buffer check
  365. if (isBuffer(obj)) {
  366. return;
  367. }
  368. // Iterate over object keys
  369. const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  370. const len = keys.length;
  371. let key;
  372. for (i = 0; i < len; i++) {
  373. key = keys[i];
  374. fn.call(null, obj[key], key, obj);
  375. }
  376. }
  377. }
  378. /**
  379. * Finds a key in an object, case-insensitive, returning the actual key name.
  380. * Returns null if the object is a Buffer or if no match is found.
  381. *
  382. * @param {Object} obj - The object to search.
  383. * @param {string} key - The key to find (case-insensitive).
  384. * @returns {?string} The actual key name if found, otherwise null.
  385. */
  386. function findKey(obj, key) {
  387. if (isBuffer(obj)) {
  388. return null;
  389. }
  390. key = key.toLowerCase();
  391. const keys = Object.keys(obj);
  392. let i = keys.length;
  393. let _key;
  394. while (i-- > 0) {
  395. _key = keys[i];
  396. if (key === _key.toLowerCase()) {
  397. return _key;
  398. }
  399. }
  400. return null;
  401. }
  402. const _global = (() => {
  403. /*eslint no-undef:0*/
  404. if (typeof globalThis !== 'undefined') return globalThis;
  405. return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
  406. })();
  407. const isContextDefined = context => !isUndefined(context) && context !== _global;
  408. /**
  409. * Accepts varargs expecting each argument to be an object, then
  410. * immutably merges the properties of each object and returns result.
  411. *
  412. * When multiple objects contain the same key the later object in
  413. * the arguments list will take precedence.
  414. *
  415. * Example:
  416. *
  417. * ```js
  418. * const result = merge({foo: 123}, {foo: 456});
  419. * console.log(result.foo); // outputs 456
  420. * ```
  421. *
  422. * @param {Object} obj1 Object to merge
  423. *
  424. * @returns {Object} Result of all merge properties
  425. */
  426. function merge(...objs) {
  427. const {
  428. caseless,
  429. skipUndefined
  430. } = isContextDefined(this) && this || {};
  431. const result = {};
  432. const assignValue = (val, key) => {
  433. // Skip dangerous property names to prevent prototype pollution
  434. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  435. return;
  436. }
  437. // findKey lowercases the key, so caseless lookup only applies to strings —
  438. // symbol keys are identity-matched.
  439. const targetKey = caseless && typeof key === 'string' && findKey(result, key) || key;
  440. // Read via own-prop only — a bare `result[targetKey]` walks the prototype
  441. // chain, so a polluted Object.prototype value could surface here and get
  442. // copied into the merged result.
  443. const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
  444. if (isPlainObject(existing) && isPlainObject(val)) {
  445. result[targetKey] = merge(existing, val);
  446. } else if (isPlainObject(val)) {
  447. result[targetKey] = merge({}, val);
  448. } else if (isArray(val)) {
  449. result[targetKey] = val.slice();
  450. } else if (!skipUndefined || !isUndefined(val)) {
  451. result[targetKey] = val;
  452. }
  453. };
  454. for (let i = 0, l = objs.length; i < l; i++) {
  455. const source = objs[i];
  456. if (!source || isBuffer(source)) {
  457. continue;
  458. }
  459. forEach(source, assignValue);
  460. if (typeof source !== 'object' || isArray(source)) {
  461. continue;
  462. }
  463. const symbols = Object.getOwnPropertySymbols(source);
  464. for (let j = 0; j < symbols.length; j++) {
  465. const symbol = symbols[j];
  466. if (propertyIsEnumerable.call(source, symbol)) {
  467. assignValue(source[symbol], symbol);
  468. }
  469. }
  470. }
  471. return result;
  472. }
  473. /**
  474. * Extends object a by mutably adding to it the properties of object b.
  475. *
  476. * @param {Object} a The object to be extended
  477. * @param {Object} b The object to copy properties from
  478. * @param {Object} thisArg The object to bind function to
  479. *
  480. * @param {Object} [options]
  481. * @param {Boolean} [options.allOwnKeys]
  482. * @returns {Object} The resulting value of object a
  483. */
  484. const extend = (a, b, thisArg, {
  485. allOwnKeys
  486. } = {}) => {
  487. forEach(b, (val, key) => {
  488. if (thisArg && isFunction$1(val)) {
  489. Object.defineProperty(a, key, {
  490. // Null-proto descriptor so a polluted Object.prototype.get cannot
  491. // hijack defineProperty's accessor-vs-data resolution.
  492. __proto__: null,
  493. value: bind(val, thisArg),
  494. writable: true,
  495. enumerable: true,
  496. configurable: true
  497. });
  498. } else {
  499. Object.defineProperty(a, key, {
  500. __proto__: null,
  501. value: val,
  502. writable: true,
  503. enumerable: true,
  504. configurable: true
  505. });
  506. }
  507. }, {
  508. allOwnKeys
  509. });
  510. return a;
  511. };
  512. /**
  513. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  514. *
  515. * @param {string} content with BOM
  516. *
  517. * @returns {string} content value without BOM
  518. */
  519. const stripBOM = content => {
  520. if (content.charCodeAt(0) === 0xfeff) {
  521. content = content.slice(1);
  522. }
  523. return content;
  524. };
  525. /**
  526. * Inherit the prototype methods from one constructor into another
  527. * @param {function} constructor
  528. * @param {function} superConstructor
  529. * @param {object} [props]
  530. * @param {object} [descriptors]
  531. *
  532. * @returns {void}
  533. */
  534. const inherits = (constructor, superConstructor, props, descriptors) => {
  535. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  536. Object.defineProperty(constructor.prototype, 'constructor', {
  537. __proto__: null,
  538. value: constructor,
  539. writable: true,
  540. enumerable: false,
  541. configurable: true
  542. });
  543. Object.defineProperty(constructor, 'super', {
  544. __proto__: null,
  545. value: superConstructor.prototype
  546. });
  547. props && Object.assign(constructor.prototype, props);
  548. };
  549. /**
  550. * Resolve object with deep prototype chain to a flat object
  551. * @param {Object} sourceObj source object
  552. * @param {Object} [destObj]
  553. * @param {Function|Boolean} [filter]
  554. * @param {Function} [propFilter]
  555. *
  556. * @returns {Object}
  557. */
  558. const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  559. let props;
  560. let i;
  561. let prop;
  562. const merged = {};
  563. destObj = destObj || {};
  564. // eslint-disable-next-line no-eq-null,eqeqeq
  565. if (sourceObj == null) return destObj;
  566. do {
  567. props = Object.getOwnPropertyNames(sourceObj);
  568. i = props.length;
  569. while (i-- > 0) {
  570. prop = props[i];
  571. if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
  572. destObj[prop] = sourceObj[prop];
  573. merged[prop] = true;
  574. }
  575. }
  576. sourceObj = filter !== false && getPrototypeOf(sourceObj);
  577. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  578. return destObj;
  579. };
  580. /**
  581. * Determines whether a string ends with the characters of a specified string
  582. *
  583. * @param {String} str
  584. * @param {String} searchString
  585. * @param {Number} [position= 0]
  586. *
  587. * @returns {boolean}
  588. */
  589. const endsWith = (str, searchString, position) => {
  590. str = String(str);
  591. if (position === undefined || position > str.length) {
  592. position = str.length;
  593. }
  594. position -= searchString.length;
  595. const lastIndex = str.indexOf(searchString, position);
  596. return lastIndex !== -1 && lastIndex === position;
  597. };
  598. /**
  599. * Returns new array from array like object or null if failed
  600. *
  601. * @param {*} [thing]
  602. *
  603. * @returns {?Array}
  604. */
  605. const toArray = thing => {
  606. if (!thing) return null;
  607. if (isArray(thing)) return thing;
  608. let i = thing.length;
  609. if (!isNumber(i)) return null;
  610. const arr = new Array(i);
  611. while (i-- > 0) {
  612. arr[i] = thing[i];
  613. }
  614. return arr;
  615. };
  616. /**
  617. * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
  618. * thing passed in is an instance of Uint8Array
  619. *
  620. * @param {TypedArray}
  621. *
  622. * @returns {Array}
  623. */
  624. // eslint-disable-next-line func-names
  625. const isTypedArray = (TypedArray => {
  626. // eslint-disable-next-line func-names
  627. return thing => {
  628. return TypedArray && thing instanceof TypedArray;
  629. };
  630. })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
  631. /**
  632. * For each entry in the object, call the function with the key and value.
  633. *
  634. * @param {Object<any, any>} obj - The object to iterate over.
  635. * @param {Function} fn - The function to call for each entry.
  636. *
  637. * @returns {void}
  638. */
  639. const forEachEntry = (obj, fn) => {
  640. const generator = obj && obj[iterator];
  641. const _iterator = generator.call(obj);
  642. let result;
  643. while ((result = _iterator.next()) && !result.done) {
  644. const pair = result.value;
  645. fn.call(obj, pair[0], pair[1]);
  646. }
  647. };
  648. /**
  649. * It takes a regular expression and a string, and returns an array of all the matches
  650. *
  651. * @param {string} regExp - The regular expression to match against.
  652. * @param {string} str - The string to search.
  653. *
  654. * @returns {Array<boolean>}
  655. */
  656. const matchAll = (regExp, str) => {
  657. let matches;
  658. const arr = [];
  659. while ((matches = regExp.exec(str)) !== null) {
  660. arr.push(matches);
  661. }
  662. return arr;
  663. };
  664. /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
  665. const isHTMLForm = kindOfTest('HTMLFormElement');
  666. const toCamelCase = str => {
  667. return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
  668. return p1.toUpperCase() + p2;
  669. });
  670. };
  671. const {
  672. propertyIsEnumerable
  673. } = Object.prototype;
  674. /**
  675. * Determine if a value is a RegExp object
  676. *
  677. * @param {*} val The value to test
  678. *
  679. * @returns {boolean} True if value is a RegExp object, otherwise false
  680. */
  681. const isRegExp = kindOfTest('RegExp');
  682. const reduceDescriptors = (obj, reducer) => {
  683. const descriptors = Object.getOwnPropertyDescriptors(obj);
  684. const reducedDescriptors = {};
  685. forEach(descriptors, (descriptor, name) => {
  686. let ret;
  687. if ((ret = reducer(descriptor, name, obj)) !== false) {
  688. reducedDescriptors[name] = ret || descriptor;
  689. }
  690. });
  691. Object.defineProperties(obj, reducedDescriptors);
  692. };
  693. /**
  694. * Makes all methods read-only
  695. * @param {Object} obj
  696. */
  697. const freezeMethods = obj => {
  698. reduceDescriptors(obj, (descriptor, name) => {
  699. // skip restricted props in strict mode
  700. if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
  701. return false;
  702. }
  703. const value = obj[name];
  704. if (!isFunction$1(value)) return;
  705. descriptor.enumerable = false;
  706. if ('writable' in descriptor) {
  707. descriptor.writable = false;
  708. return;
  709. }
  710. if (!descriptor.set) {
  711. descriptor.set = () => {
  712. throw Error("Can not rewrite read-only method '" + name + "'");
  713. };
  714. }
  715. });
  716. };
  717. /**
  718. * Converts an array or a delimited string into an object set with values as keys and true as values.
  719. * Useful for fast membership checks.
  720. *
  721. * @param {Array|string} arrayOrString - The array or string to convert.
  722. * @param {string} delimiter - The delimiter to use if input is a string.
  723. * @returns {Object} An object with keys from the array or string, values set to true.
  724. */
  725. const toObjectSet = (arrayOrString, delimiter) => {
  726. const obj = {};
  727. const define = arr => {
  728. arr.forEach(value => {
  729. obj[value] = true;
  730. });
  731. };
  732. isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  733. return obj;
  734. };
  735. const noop = () => {};
  736. const toFiniteNumber = (value, defaultValue) => {
  737. return value != null && Number.isFinite(value = +value) ? value : defaultValue;
  738. };
  739. /**
  740. * If the thing is a FormData object, return true, otherwise return false.
  741. *
  742. * @param {unknown} thing - The thing to check.
  743. *
  744. * @returns {boolean}
  745. */
  746. function isSpecCompliantForm(thing) {
  747. return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
  748. }
  749. /**
  750. * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
  751. *
  752. * @param {Object} obj - The object to convert.
  753. * @returns {Object} The JSON-compatible object.
  754. */
  755. const toJSONObject = obj => {
  756. const visited = new WeakSet();
  757. const visit = source => {
  758. if (isObject(source)) {
  759. if (visited.has(source)) {
  760. return;
  761. }
  762. //Buffer check
  763. if (isBuffer(source)) {
  764. return source;
  765. }
  766. if (!('toJSON' in source)) {
  767. // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
  768. visited.add(source);
  769. const target = isArray(source) ? [] : {};
  770. forEach(source, (value, key) => {
  771. const reducedValue = visit(value);
  772. !isUndefined(reducedValue) && (target[key] = reducedValue);
  773. });
  774. visited.delete(source);
  775. return target;
  776. }
  777. }
  778. return source;
  779. };
  780. return visit(obj);
  781. };
  782. /**
  783. * Determines if a value is an async function.
  784. *
  785. * @param {*} thing - The value to test.
  786. * @returns {boolean} True if value is an async function, otherwise false.
  787. */
  788. const isAsyncFn = kindOfTest('AsyncFunction');
  789. /**
  790. * Determines if a value is thenable (has then and catch methods).
  791. *
  792. * @param {*} thing - The value to test.
  793. * @returns {boolean} True if value is thenable, otherwise false.
  794. */
  795. const isThenable = thing => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
  796. // original code
  797. // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
  798. /**
  799. * Provides a cross-platform setImmediate implementation.
  800. * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
  801. *
  802. * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
  803. * @param {boolean} postMessageSupported - Whether postMessage is supported.
  804. * @returns {Function} A function to schedule a callback asynchronously.
  805. */
  806. const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  807. if (setImmediateSupported) {
  808. return setImmediate;
  809. }
  810. return postMessageSupported ? ((token, callbacks) => {
  811. _global.addEventListener('message', ({
  812. source,
  813. data
  814. }) => {
  815. if (source === _global && data === token) {
  816. callbacks.length && callbacks.shift()();
  817. }
  818. }, false);
  819. return cb => {
  820. callbacks.push(cb);
  821. _global.postMessage(token, '*');
  822. };
  823. })(`axios@${Math.random()}`, []) : cb => setTimeout(cb);
  824. })(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
  825. /**
  826. * Schedules a microtask or asynchronous callback as soon as possible.
  827. * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
  828. *
  829. * @type {Function}
  830. */
  831. const asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : typeof process !== 'undefined' && process.nextTick || _setImmediate;
  832. // *********************
  833. const isIterable = thing => thing != null && isFunction$1(thing[iterator]);
  834. /**
  835. * Determine if a value is iterable via an iterator that is NOT sourced solely
  836. * from a polluted Object.prototype. Use this instead of `isIterable` whenever
  837. * the iterable comes from untrusted input (e.g. user-supplied header sources),
  838. * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
  839. * into an attacker-controlled entries iterator.
  840. *
  841. * @param {*} thing The value to test
  842. *
  843. * @returns {boolean} True if value has a non-polluted iterator
  844. */
  845. const isSafeIterable = thing => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
  846. var utils$1 = {
  847. isArray,
  848. isArrayBuffer,
  849. isBuffer,
  850. isFormData,
  851. isArrayBufferView,
  852. isString,
  853. isNumber,
  854. isBoolean,
  855. isObject,
  856. isPlainObject,
  857. isEmptyObject,
  858. isReadableStream,
  859. isRequest,
  860. isResponse,
  861. isHeaders,
  862. isUndefined,
  863. isDate,
  864. isFile,
  865. isReactNativeBlob,
  866. isReactNative,
  867. isBlob,
  868. isRegExp,
  869. isFunction: isFunction$1,
  870. isStream,
  871. isURLSearchParams,
  872. isTypedArray,
  873. isFileList,
  874. forEach,
  875. merge,
  876. extend,
  877. trim,
  878. stripBOM,
  879. inherits,
  880. toFlatObject,
  881. kindOf,
  882. kindOfTest,
  883. endsWith,
  884. toArray,
  885. forEachEntry,
  886. matchAll,
  887. isHTMLForm,
  888. hasOwnProperty,
  889. hasOwnProp: hasOwnProperty,
  890. // an alias to avoid ESLint no-prototype-builtins detection
  891. hasOwnInPrototypeChain,
  892. getSafeProp,
  893. reduceDescriptors,
  894. freezeMethods,
  895. toObjectSet,
  896. toCamelCase,
  897. noop,
  898. toFiniteNumber,
  899. findKey,
  900. global: _global,
  901. isContextDefined,
  902. isSpecCompliantForm,
  903. toJSONObject,
  904. isAsyncFn,
  905. isThenable,
  906. setImmediate: _setImmediate,
  907. asap,
  908. isIterable,
  909. isSafeIterable
  910. };
  911. // RawAxiosHeaders whose duplicates are ignored by node
  912. // c.f. https://nodejs.org/api/http.html#http_message_headers
  913. 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']);
  914. /**
  915. * Parse headers into an object
  916. *
  917. * ```
  918. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  919. * Content-Type: application/json
  920. * Connection: keep-alive
  921. * Transfer-Encoding: chunked
  922. * ```
  923. *
  924. * @param {String} rawHeaders Headers needing to be parsed
  925. *
  926. * @returns {Object} Headers parsed into an object
  927. */
  928. var parseHeaders = rawHeaders => {
  929. const parsed = {};
  930. let key;
  931. let val;
  932. let i;
  933. rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
  934. i = line.indexOf(':');
  935. key = line.substring(0, i).trim().toLowerCase();
  936. val = line.substring(i + 1).trim();
  937. if (!key || parsed[key] && ignoreDuplicateOf[key]) {
  938. return;
  939. }
  940. if (key === 'set-cookie') {
  941. if (parsed[key]) {
  942. parsed[key].push(val);
  943. } else {
  944. parsed[key] = [val];
  945. }
  946. } else {
  947. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  948. }
  949. });
  950. return parsed;
  951. };
  952. function trimSPorHTAB(str) {
  953. let start = 0;
  954. let end = str.length;
  955. while (start < end) {
  956. const code = str.charCodeAt(start);
  957. if (code !== 0x09 && code !== 0x20) {
  958. break;
  959. }
  960. start += 1;
  961. }
  962. while (end > start) {
  963. const code = str.charCodeAt(end - 1);
  964. if (code !== 0x09 && code !== 0x20) {
  965. break;
  966. }
  967. end -= 1;
  968. }
  969. return start === 0 && end === str.length ? str : str.slice(start, end);
  970. }
  971. // The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
  972. // eslint-disable-next-line no-control-regex
  973. const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
  974. // eslint-disable-next-line no-control-regex
  975. const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
  976. function sanitizeValue(value, invalidChars) {
  977. if (utils$1.isArray(value)) {
  978. return value.map(item => sanitizeValue(item, invalidChars));
  979. }
  980. return trimSPorHTAB(String(value).replace(invalidChars, ''));
  981. }
  982. const sanitizeHeaderValue = value => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
  983. const sanitizeByteStringHeaderValue = value => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
  984. function toByteStringHeaderObject(headers) {
  985. const byteStringHeaders = Object.create(null);
  986. utils$1.forEach(headers.toJSON(), (value, header) => {
  987. byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
  988. });
  989. return byteStringHeaders;
  990. }
  991. const $internals = Symbol('internals');
  992. function normalizeHeader(header) {
  993. return header && String(header).trim().toLowerCase();
  994. }
  995. function normalizeValue(value) {
  996. if (value === false || value == null) {
  997. return value;
  998. }
  999. return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
  1000. }
  1001. function parseTokens(str) {
  1002. const tokens = Object.create(null);
  1003. const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  1004. let match;
  1005. while (match = tokensRE.exec(str)) {
  1006. tokens[match[1]] = match[2];
  1007. }
  1008. return tokens;
  1009. }
  1010. const isValidHeaderName = str => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
  1011. function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  1012. if (utils$1.isFunction(filter)) {
  1013. return filter.call(this, value, header);
  1014. }
  1015. if (isHeaderNameFilter) {
  1016. value = header;
  1017. }
  1018. if (!utils$1.isString(value)) return;
  1019. if (utils$1.isString(filter)) {
  1020. return value.indexOf(filter) !== -1;
  1021. }
  1022. if (utils$1.isRegExp(filter)) {
  1023. return filter.test(value);
  1024. }
  1025. }
  1026. function formatHeader(header) {
  1027. return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
  1028. return char.toUpperCase() + str;
  1029. });
  1030. }
  1031. function buildAccessors(obj, header) {
  1032. const accessorName = utils$1.toCamelCase(' ' + header);
  1033. ['get', 'set', 'has'].forEach(methodName => {
  1034. Object.defineProperty(obj, methodName + accessorName, {
  1035. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  1036. // this data descriptor into an accessor descriptor on the way in.
  1037. __proto__: null,
  1038. value: function (arg1, arg2, arg3) {
  1039. return this[methodName].call(this, header, arg1, arg2, arg3);
  1040. },
  1041. configurable: true
  1042. });
  1043. });
  1044. }
  1045. class AxiosHeaders {
  1046. constructor(headers) {
  1047. headers && this.set(headers);
  1048. }
  1049. set(header, valueOrRewrite, rewrite) {
  1050. const self = this;
  1051. function setHeader(_value, _header, _rewrite) {
  1052. const lHeader = normalizeHeader(_header);
  1053. if (!lHeader) {
  1054. return;
  1055. }
  1056. const key = utils$1.findKey(self, lHeader);
  1057. if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
  1058. self[key || _header] = normalizeValue(_value);
  1059. }
  1060. }
  1061. const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
  1062. if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
  1063. setHeaders(header, valueOrRewrite);
  1064. } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
  1065. setHeaders(parseHeaders(header), valueOrRewrite);
  1066. } else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
  1067. let obj = Object.create(null),
  1068. dest,
  1069. key;
  1070. for (const entry of header) {
  1071. if (!utils$1.isArray(entry)) {
  1072. throw new TypeError('Object iterator must return a key-value pair');
  1073. }
  1074. key = entry[0];
  1075. if (utils$1.hasOwnProp(obj, key)) {
  1076. dest = obj[key];
  1077. obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
  1078. } else {
  1079. obj[key] = entry[1];
  1080. }
  1081. }
  1082. setHeaders(obj, valueOrRewrite);
  1083. } else {
  1084. header != null && setHeader(valueOrRewrite, header, rewrite);
  1085. }
  1086. return this;
  1087. }
  1088. get(header, parser) {
  1089. header = normalizeHeader(header);
  1090. if (header) {
  1091. const key = utils$1.findKey(this, header);
  1092. if (key) {
  1093. const value = this[key];
  1094. if (!parser) {
  1095. return value;
  1096. }
  1097. if (parser === true) {
  1098. return parseTokens(value);
  1099. }
  1100. if (utils$1.isFunction(parser)) {
  1101. return parser.call(this, value, key);
  1102. }
  1103. if (utils$1.isRegExp(parser)) {
  1104. return parser.exec(value);
  1105. }
  1106. throw new TypeError('parser must be boolean|regexp|function');
  1107. }
  1108. }
  1109. }
  1110. has(header, matcher) {
  1111. header = normalizeHeader(header);
  1112. if (header) {
  1113. const key = utils$1.findKey(this, header);
  1114. return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
  1115. }
  1116. return false;
  1117. }
  1118. delete(header, matcher) {
  1119. const self = this;
  1120. let deleted = false;
  1121. function deleteHeader(_header) {
  1122. _header = normalizeHeader(_header);
  1123. if (_header) {
  1124. const key = utils$1.findKey(self, _header);
  1125. if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
  1126. delete self[key];
  1127. deleted = true;
  1128. }
  1129. }
  1130. }
  1131. if (utils$1.isArray(header)) {
  1132. header.forEach(deleteHeader);
  1133. } else {
  1134. deleteHeader(header);
  1135. }
  1136. return deleted;
  1137. }
  1138. clear(matcher) {
  1139. const keys = Object.keys(this);
  1140. let i = keys.length;
  1141. let deleted = false;
  1142. while (i--) {
  1143. const key = keys[i];
  1144. if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
  1145. delete this[key];
  1146. deleted = true;
  1147. }
  1148. }
  1149. return deleted;
  1150. }
  1151. normalize(format) {
  1152. const self = this;
  1153. const headers = {};
  1154. utils$1.forEach(this, (value, header) => {
  1155. const key = utils$1.findKey(headers, header);
  1156. if (key) {
  1157. self[key] = normalizeValue(value);
  1158. delete self[header];
  1159. return;
  1160. }
  1161. const normalized = format ? formatHeader(header) : String(header).trim();
  1162. if (normalized !== header) {
  1163. delete self[header];
  1164. }
  1165. self[normalized] = normalizeValue(value);
  1166. headers[normalized] = true;
  1167. });
  1168. return this;
  1169. }
  1170. concat(...targets) {
  1171. return this.constructor.concat(this, ...targets);
  1172. }
  1173. toJSON(asStrings) {
  1174. const obj = Object.create(null);
  1175. utils$1.forEach(this, (value, header) => {
  1176. value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
  1177. });
  1178. return obj;
  1179. }
  1180. [Symbol.iterator]() {
  1181. return Object.entries(this.toJSON())[Symbol.iterator]();
  1182. }
  1183. toString() {
  1184. return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  1185. }
  1186. getSetCookie() {
  1187. return this.get('set-cookie') || [];
  1188. }
  1189. get [Symbol.toStringTag]() {
  1190. return 'AxiosHeaders';
  1191. }
  1192. static from(thing) {
  1193. return thing instanceof this ? thing : new this(thing);
  1194. }
  1195. static concat(first, ...targets) {
  1196. const computed = new this(first);
  1197. targets.forEach(target => computed.set(target));
  1198. return computed;
  1199. }
  1200. static accessor(header) {
  1201. const internals = this[$internals] = this[$internals] = {
  1202. accessors: {}
  1203. };
  1204. const accessors = internals.accessors;
  1205. const prototype = this.prototype;
  1206. function defineAccessor(_header) {
  1207. const lHeader = normalizeHeader(_header);
  1208. if (!accessors[lHeader]) {
  1209. buildAccessors(prototype, _header);
  1210. accessors[lHeader] = true;
  1211. }
  1212. }
  1213. utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
  1214. return this;
  1215. }
  1216. }
  1217. AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
  1218. // reserved names hotfix
  1219. utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
  1220. value
  1221. }, key) => {
  1222. let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  1223. return {
  1224. get: () => value,
  1225. set(headerValue) {
  1226. this[mapped] = headerValue;
  1227. }
  1228. };
  1229. });
  1230. utils$1.freezeMethods(AxiosHeaders);
  1231. const REDACTED = '[REDACTED ****]';
  1232. function hasOwnOrPrototypeToJSON(source) {
  1233. if (utils$1.hasOwnProp(source, 'toJSON')) {
  1234. return true;
  1235. }
  1236. let prototype = Object.getPrototypeOf(source);
  1237. while (prototype && prototype !== Object.prototype) {
  1238. if (utils$1.hasOwnProp(prototype, 'toJSON')) {
  1239. return true;
  1240. }
  1241. prototype = Object.getPrototypeOf(prototype);
  1242. }
  1243. return false;
  1244. }
  1245. // Build a plain-object snapshot of `config` and replace the value of any key
  1246. // (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
  1247. // and AxiosHeaders, and short-circuits on circular references.
  1248. function redactConfig(config, redactKeys) {
  1249. const lowerKeys = new Set(redactKeys.map(k => String(k).toLowerCase()));
  1250. const seen = [];
  1251. const visit = source => {
  1252. if (source === null || typeof source !== 'object') return source;
  1253. if (utils$1.isBuffer(source)) return source;
  1254. if (seen.indexOf(source) !== -1) return undefined;
  1255. if (source instanceof AxiosHeaders) {
  1256. source = source.toJSON();
  1257. }
  1258. seen.push(source);
  1259. let result;
  1260. if (utils$1.isArray(source)) {
  1261. result = [];
  1262. source.forEach((v, i) => {
  1263. const reducedValue = visit(v);
  1264. if (!utils$1.isUndefined(reducedValue)) {
  1265. result[i] = reducedValue;
  1266. }
  1267. });
  1268. } else {
  1269. if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
  1270. seen.pop();
  1271. return source;
  1272. }
  1273. result = Object.create(null);
  1274. for (const [key, value] of Object.entries(source)) {
  1275. const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
  1276. if (!utils$1.isUndefined(reducedValue)) {
  1277. result[key] = reducedValue;
  1278. }
  1279. }
  1280. }
  1281. seen.pop();
  1282. return result;
  1283. };
  1284. return visit(config);
  1285. }
  1286. class AxiosError extends Error {
  1287. static from(error, code, config, request, response, customProps) {
  1288. const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
  1289. axiosError.cause = error;
  1290. axiosError.name = error.name;
  1291. // Preserve status from the original error if not already set from response
  1292. if (error.status != null && axiosError.status == null) {
  1293. axiosError.status = error.status;
  1294. }
  1295. customProps && Object.assign(axiosError, customProps);
  1296. return axiosError;
  1297. }
  1298. /**
  1299. * Create an Error with the specified message, config, error code, request and response.
  1300. *
  1301. * @param {string} message The error message.
  1302. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1303. * @param {Object} [config] The config.
  1304. * @param {Object} [request] The request.
  1305. * @param {Object} [response] The response.
  1306. *
  1307. * @returns {Error} The created error.
  1308. */
  1309. constructor(message, code, config, request, response) {
  1310. super(message);
  1311. // Make message enumerable to maintain backward compatibility
  1312. // The native Error constructor sets message as non-enumerable,
  1313. // but axios < v1.13.3 had it as enumerable
  1314. Object.defineProperty(this, 'message', {
  1315. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  1316. // this data descriptor into an accessor descriptor on the way in.
  1317. __proto__: null,
  1318. value: message,
  1319. enumerable: true,
  1320. writable: true,
  1321. configurable: true
  1322. });
  1323. this.name = 'AxiosError';
  1324. this.isAxiosError = true;
  1325. code && (this.code = code);
  1326. config && (this.config = config);
  1327. request && (this.request = request);
  1328. if (response) {
  1329. this.response = response;
  1330. this.status = response.status;
  1331. }
  1332. }
  1333. toJSON() {
  1334. // Opt-in redaction: when the request config carries a `redact` array, the
  1335. // value of any matching key (case-insensitive, at any depth) is replaced
  1336. // with REDACTED in the serialized snapshot. Undefined or empty leaves the
  1337. // existing serialization behavior unchanged.
  1338. const config = this.config;
  1339. const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
  1340. const serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils$1.toJSONObject(config);
  1341. return {
  1342. // Standard
  1343. message: this.message,
  1344. name: this.name,
  1345. // Microsoft
  1346. description: this.description,
  1347. number: this.number,
  1348. // Mozilla
  1349. fileName: this.fileName,
  1350. lineNumber: this.lineNumber,
  1351. columnNumber: this.columnNumber,
  1352. stack: this.stack,
  1353. // Axios
  1354. config: serializedConfig,
  1355. code: this.code,
  1356. status: this.status
  1357. };
  1358. }
  1359. }
  1360. // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
  1361. AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
  1362. AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
  1363. AxiosError.ECONNABORTED = 'ECONNABORTED';
  1364. AxiosError.ETIMEDOUT = 'ETIMEDOUT';
  1365. AxiosError.ECONNREFUSED = 'ECONNREFUSED';
  1366. AxiosError.ERR_NETWORK = 'ERR_NETWORK';
  1367. AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
  1368. AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
  1369. AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
  1370. AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
  1371. AxiosError.ERR_CANCELED = 'ERR_CANCELED';
  1372. AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
  1373. AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
  1374. AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
  1375. // Default nesting limit shared with the inverse transform (formDataToJSON) so
  1376. // the FormData <-> JSON round-trip stays symmetric.
  1377. const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
  1378. /**
  1379. * Determines if the given thing is a array or js object.
  1380. *
  1381. * @param {string} thing - The object or array to be visited.
  1382. *
  1383. * @returns {boolean}
  1384. */
  1385. function isVisitable(thing) {
  1386. return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
  1387. }
  1388. /**
  1389. * It removes the brackets from the end of a string
  1390. *
  1391. * @param {string} key - The key of the parameter.
  1392. *
  1393. * @returns {string} the key without the brackets.
  1394. */
  1395. function removeBrackets(key) {
  1396. return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
  1397. }
  1398. /**
  1399. * It takes a path, a key, and a boolean, and returns a string
  1400. *
  1401. * @param {string} path - The path to the current key.
  1402. * @param {string} key - The key of the current object being iterated over.
  1403. * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
  1404. *
  1405. * @returns {string} The path to the current key.
  1406. */
  1407. function renderKey(path, key, dots) {
  1408. if (!path) return key;
  1409. return path.concat(key).map(function each(token, i) {
  1410. // eslint-disable-next-line no-param-reassign
  1411. token = removeBrackets(token);
  1412. return !dots && i ? '[' + token + ']' : token;
  1413. }).join(dots ? '.' : '');
  1414. }
  1415. /**
  1416. * If the array is an array and none of its elements are visitable, then it's a flat array.
  1417. *
  1418. * @param {Array<any>} arr - The array to check
  1419. *
  1420. * @returns {boolean}
  1421. */
  1422. function isFlatArray(arr) {
  1423. return utils$1.isArray(arr) && !arr.some(isVisitable);
  1424. }
  1425. const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
  1426. return /^is[A-Z]/.test(prop);
  1427. });
  1428. /**
  1429. * Convert a data object to FormData
  1430. *
  1431. * @param {Object} obj
  1432. * @param {?Object} [formData]
  1433. * @param {?Object} [options]
  1434. * @param {Function} [options.visitor]
  1435. * @param {Boolean} [options.metaTokens = true]
  1436. * @param {Boolean} [options.dots = false]
  1437. * @param {?Boolean} [options.indexes = false]
  1438. *
  1439. * @returns {Object}
  1440. **/
  1441. /**
  1442. * It converts an object into a FormData object
  1443. *
  1444. * @param {Object<any, any>} obj - The object to convert to form data.
  1445. * @param {string} formData - The FormData object to append to.
  1446. * @param {Object<string, any>} options
  1447. *
  1448. * @returns
  1449. */
  1450. function toFormData(obj, formData, options) {
  1451. if (!utils$1.isObject(obj)) {
  1452. throw new TypeError('target must be an object');
  1453. }
  1454. // eslint-disable-next-line no-param-reassign
  1455. formData = formData || new (FormData$1 || FormData)();
  1456. // eslint-disable-next-line no-param-reassign
  1457. options = utils$1.toFlatObject(options, {
  1458. metaTokens: true,
  1459. dots: false,
  1460. indexes: false
  1461. }, false, function defined(option, source) {
  1462. // eslint-disable-next-line no-eq-null,eqeqeq
  1463. return !utils$1.isUndefined(source[option]);
  1464. });
  1465. const metaTokens = options.metaTokens;
  1466. // eslint-disable-next-line no-use-before-define
  1467. const visitor = options.visitor || defaultVisitor;
  1468. const dots = options.dots;
  1469. const indexes = options.indexes;
  1470. const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  1471. const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
  1472. const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
  1473. const stack = [];
  1474. if (!utils$1.isFunction(visitor)) {
  1475. throw new TypeError('visitor must be a function');
  1476. }
  1477. function convertValue(value) {
  1478. if (value === null) return '';
  1479. if (utils$1.isDate(value)) {
  1480. return value.toISOString();
  1481. }
  1482. if (utils$1.isBoolean(value)) {
  1483. return value.toString();
  1484. }
  1485. if (!useBlob && utils$1.isBlob(value)) {
  1486. throw new AxiosError('Blob is not supported. Use a Buffer instead.');
  1487. }
  1488. if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
  1489. return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  1490. }
  1491. return value;
  1492. }
  1493. function throwIfMaxDepthExceeded(depth) {
  1494. if (depth > maxDepth) {
  1495. throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
  1496. }
  1497. }
  1498. function stringifyWithDepthLimit(value, depth) {
  1499. if (maxDepth === Infinity) {
  1500. return JSON.stringify(value);
  1501. }
  1502. const ancestors = [];
  1503. return JSON.stringify(value, function limitDepth(_key, currentValue) {
  1504. if (!utils$1.isObject(currentValue)) {
  1505. return currentValue;
  1506. }
  1507. while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
  1508. ancestors.pop();
  1509. }
  1510. ancestors.push(currentValue);
  1511. throwIfMaxDepthExceeded(depth + ancestors.length - 1);
  1512. return currentValue;
  1513. });
  1514. }
  1515. /**
  1516. * Default visitor.
  1517. *
  1518. * @param {*} value
  1519. * @param {String|Number} key
  1520. * @param {Array<String|Number>} path
  1521. * @this {FormData}
  1522. *
  1523. * @returns {boolean} return true to visit the each prop of the value recursively
  1524. */
  1525. function defaultVisitor(value, key, path) {
  1526. let arr = value;
  1527. if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
  1528. formData.append(renderKey(path, key, dots), convertValue(value));
  1529. return false;
  1530. }
  1531. if (value && !path && typeof value === 'object') {
  1532. if (utils$1.endsWith(key, '{}')) {
  1533. // eslint-disable-next-line no-param-reassign
  1534. key = metaTokens ? key : key.slice(0, -2);
  1535. // eslint-disable-next-line no-param-reassign
  1536. value = stringifyWithDepthLimit(value, 1);
  1537. } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
  1538. // eslint-disable-next-line no-param-reassign
  1539. key = removeBrackets(key);
  1540. arr.forEach(function each(el, index) {
  1541. !(utils$1.isUndefined(el) || el === null) && formData.append(
  1542. // eslint-disable-next-line no-nested-ternary
  1543. indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
  1544. });
  1545. return false;
  1546. }
  1547. }
  1548. if (isVisitable(value)) {
  1549. return true;
  1550. }
  1551. formData.append(renderKey(path, key, dots), convertValue(value));
  1552. return false;
  1553. }
  1554. const exposedHelpers = Object.assign(predicates, {
  1555. defaultVisitor,
  1556. convertValue,
  1557. isVisitable
  1558. });
  1559. function build(value, path, depth = 0) {
  1560. if (utils$1.isUndefined(value)) return;
  1561. throwIfMaxDepthExceeded(depth);
  1562. if (stack.indexOf(value) !== -1) {
  1563. throw new Error('Circular reference detected in ' + path.join('.'));
  1564. }
  1565. stack.push(value);
  1566. utils$1.forEach(value, function each(el, key) {
  1567. const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
  1568. if (result === true) {
  1569. build(el, path ? path.concat(key) : [key], depth + 1);
  1570. }
  1571. });
  1572. stack.pop();
  1573. }
  1574. if (!utils$1.isObject(obj)) {
  1575. throw new TypeError('data must be an object');
  1576. }
  1577. build(obj);
  1578. return formData;
  1579. }
  1580. /**
  1581. * It encodes a string by replacing all characters that are not in the unreserved set with
  1582. * their percent-encoded equivalents
  1583. *
  1584. * @param {string} str - The string to encode.
  1585. *
  1586. * @returns {string} The encoded string.
  1587. */
  1588. function encode$1(str) {
  1589. const charMap = {
  1590. '!': '%21',
  1591. "'": '%27',
  1592. '(': '%28',
  1593. ')': '%29',
  1594. '~': '%7E',
  1595. '%20': '+'
  1596. };
  1597. return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
  1598. return charMap[match];
  1599. });
  1600. }
  1601. /**
  1602. * It takes a params object and converts it to a FormData object
  1603. *
  1604. * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
  1605. * @param {Object<string, any>} options - The options object passed to the Axios constructor.
  1606. *
  1607. * @returns {void}
  1608. */
  1609. function AxiosURLSearchParams(params, options) {
  1610. this._pairs = [];
  1611. params && toFormData(params, this, options);
  1612. }
  1613. const prototype = AxiosURLSearchParams.prototype;
  1614. prototype.append = function append(name, value) {
  1615. this._pairs.push([name, value]);
  1616. };
  1617. prototype.toString = function toString(encoder) {
  1618. const _encode = encoder ? function (value) {
  1619. return encoder.call(this, value, encode$1);
  1620. } : encode$1;
  1621. return this._pairs.map(function each(pair) {
  1622. return _encode(pair[0]) + '=' + _encode(pair[1]);
  1623. }, '').join('&');
  1624. };
  1625. /**
  1626. * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
  1627. * their plain counterparts (`:`, `$`, `,`, `+`).
  1628. *
  1629. * @param {string} val The value to be encoded.
  1630. *
  1631. * @returns {string} The encoded value.
  1632. */
  1633. function encode(val) {
  1634. return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
  1635. }
  1636. /**
  1637. * Build a URL by appending params to the end
  1638. *
  1639. * @param {string} url The base of the url (e.g., http://www.google.com)
  1640. * @param {object} [params] The params to be appended
  1641. * @param {?(object|Function)} options
  1642. *
  1643. * @returns {string} The formatted url
  1644. */
  1645. function buildURL(url, params, options) {
  1646. if (!params) {
  1647. return url;
  1648. }
  1649. const _options = utils$1.isFunction(options) ? {
  1650. serialize: options
  1651. } : options;
  1652. // Read serializer options pollution-safely: own properties and methods on a
  1653. // class/template prototype are honored, but values injected onto a polluted
  1654. // Object.prototype are ignored.
  1655. const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
  1656. const serializeFn = utils$1.getSafeProp(_options, 'serialize');
  1657. let serializedParams;
  1658. if (serializeFn) {
  1659. serializedParams = serializeFn(params, _options);
  1660. } else {
  1661. serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
  1662. }
  1663. if (serializedParams) {
  1664. const hashmarkIndex = url.indexOf('#');
  1665. if (hashmarkIndex !== -1) {
  1666. url = url.slice(0, hashmarkIndex);
  1667. }
  1668. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  1669. }
  1670. return url;
  1671. }
  1672. class InterceptorManager {
  1673. constructor() {
  1674. this.handlers = [];
  1675. }
  1676. /**
  1677. * Add a new interceptor to the stack
  1678. *
  1679. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  1680. * @param {Function} rejected The function to handle `reject` for a `Promise`
  1681. * @param {Object} options The options for the interceptor, synchronous and runWhen
  1682. *
  1683. * @return {Number} An ID used to remove interceptor later
  1684. */
  1685. use(fulfilled, rejected, options) {
  1686. this.handlers.push({
  1687. fulfilled,
  1688. rejected,
  1689. synchronous: options ? options.synchronous : false,
  1690. runWhen: options ? options.runWhen : null
  1691. });
  1692. return this.handlers.length - 1;
  1693. }
  1694. /**
  1695. * Remove an interceptor from the stack
  1696. *
  1697. * @param {Number} id The ID that was returned by `use`
  1698. *
  1699. * @returns {void}
  1700. */
  1701. eject(id) {
  1702. if (this.handlers[id]) {
  1703. this.handlers[id] = null;
  1704. }
  1705. }
  1706. /**
  1707. * Clear all interceptors from the stack
  1708. *
  1709. * @returns {void}
  1710. */
  1711. clear() {
  1712. if (this.handlers) {
  1713. this.handlers = [];
  1714. }
  1715. }
  1716. /**
  1717. * Iterate over all the registered interceptors
  1718. *
  1719. * This method is particularly useful for skipping over any
  1720. * interceptors that may have become `null` calling `eject`.
  1721. *
  1722. * @param {Function} fn The function to call for each interceptor
  1723. *
  1724. * @returns {void}
  1725. */
  1726. forEach(fn) {
  1727. utils$1.forEach(this.handlers, function forEachHandler(h) {
  1728. if (h !== null) {
  1729. fn(h);
  1730. }
  1731. });
  1732. }
  1733. }
  1734. var transitionalDefaults = {
  1735. silentJSONParsing: true,
  1736. forcedJSONParsing: true,
  1737. clarifyTimeoutError: false,
  1738. legacyInterceptorReqResOrdering: true,
  1739. advertiseZstdAcceptEncoding: false,
  1740. validateStatusUndefinedResolves: true
  1741. };
  1742. var URLSearchParams = url.URLSearchParams;
  1743. const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
  1744. const DIGIT = '0123456789';
  1745. const ALPHABET = {
  1746. DIGIT,
  1747. ALPHA,
  1748. ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
  1749. };
  1750. const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
  1751. let str = '';
  1752. const {
  1753. length
  1754. } = alphabet;
  1755. const randomValues = new Uint32Array(size);
  1756. crypto.randomFillSync(randomValues);
  1757. for (let i = 0; i < size; i++) {
  1758. str += alphabet[randomValues[i] % length];
  1759. }
  1760. return str;
  1761. };
  1762. var platform$1 = {
  1763. isNode: true,
  1764. classes: {
  1765. URLSearchParams,
  1766. FormData: FormData$1,
  1767. Blob: typeof Blob !== 'undefined' && Blob || null
  1768. },
  1769. ALPHABET,
  1770. generateString,
  1771. protocols: ['http', 'https', 'file', 'data']
  1772. };
  1773. const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
  1774. const _navigator = typeof navigator === 'object' && navigator || undefined;
  1775. /**
  1776. * Determine if we're running in a standard browser environment
  1777. *
  1778. * This allows axios to run in a web worker, and react-native.
  1779. * Both environments support XMLHttpRequest, but not fully standard globals.
  1780. *
  1781. * web workers:
  1782. * typeof window -> undefined
  1783. * typeof document -> undefined
  1784. *
  1785. * react-native:
  1786. * navigator.product -> 'ReactNative'
  1787. * nativescript
  1788. * navigator.product -> 'NativeScript' or 'NS'
  1789. *
  1790. * @returns {boolean}
  1791. */
  1792. const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
  1793. /**
  1794. * Determine if we're running in a standard browser webWorker environment
  1795. *
  1796. * Although the `isStandardBrowserEnv` method indicates that
  1797. * `allows axios to run in a web worker`, the WebWorker will still be
  1798. * filtered out due to its judgment standard
  1799. * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
  1800. * This leads to a problem when axios post `FormData` in webWorker
  1801. */
  1802. const hasStandardBrowserWebWorkerEnv = (() => {
  1803. return typeof WorkerGlobalScope !== 'undefined' &&
  1804. // eslint-disable-next-line no-undef
  1805. self instanceof WorkerGlobalScope && typeof self.importScripts === 'function';
  1806. })();
  1807. const origin = hasBrowserEnv && window.location.href || 'http://localhost';
  1808. var utils = /*#__PURE__*/Object.freeze({
  1809. __proto__: null,
  1810. hasBrowserEnv: hasBrowserEnv,
  1811. hasStandardBrowserEnv: hasStandardBrowserEnv,
  1812. hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
  1813. navigator: _navigator,
  1814. origin: origin
  1815. });
  1816. var platform = {
  1817. ...utils,
  1818. ...platform$1
  1819. };
  1820. function toURLEncodedForm(data, options) {
  1821. return toFormData(data, new platform.classes.URLSearchParams(), {
  1822. visitor: function (value, key, path, helpers) {
  1823. if (platform.isNode && utils$1.isBuffer(value)) {
  1824. this.append(key, value.toString('base64'));
  1825. return false;
  1826. }
  1827. return helpers.defaultVisitor.apply(this, arguments);
  1828. },
  1829. ...options
  1830. });
  1831. }
  1832. const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
  1833. function throwIfDepthExceeded(index) {
  1834. if (index > MAX_DEPTH) {
  1835. throw new AxiosError('FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
  1836. }
  1837. }
  1838. /**
  1839. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  1840. *
  1841. * @param {string} name - The name of the property to get.
  1842. *
  1843. * @returns An array of strings.
  1844. */
  1845. function parsePropPath(name) {
  1846. // foo[x][y][z]
  1847. // foo.x.y.z
  1848. // foo-x-y-z
  1849. // foo x y z
  1850. const path = [];
  1851. const pattern = /\w+|\[(\w*)]/g;
  1852. let match;
  1853. while ((match = pattern.exec(name)) !== null) {
  1854. throwIfDepthExceeded(path.length);
  1855. path.push(match[0] === '[]' ? '' : match[1] || match[0]);
  1856. }
  1857. return path;
  1858. }
  1859. /**
  1860. * Convert an array to an object.
  1861. *
  1862. * @param {Array<any>} arr - The array to convert to an object.
  1863. *
  1864. * @returns An object with the same keys and values as the array.
  1865. */
  1866. function arrayToObject(arr) {
  1867. const obj = {};
  1868. const keys = Object.keys(arr);
  1869. let i;
  1870. const len = keys.length;
  1871. let key;
  1872. for (i = 0; i < len; i++) {
  1873. key = keys[i];
  1874. obj[key] = arr[key];
  1875. }
  1876. return obj;
  1877. }
  1878. /**
  1879. * It takes a FormData object and returns a JavaScript object
  1880. *
  1881. * @param {string} formData The FormData object to convert to JSON.
  1882. *
  1883. * @returns {Object<string, any> | null} The converted object.
  1884. */
  1885. function formDataToJSON(formData) {
  1886. function buildPath(path, value, target, index) {
  1887. throwIfDepthExceeded(index);
  1888. let name = path[index++];
  1889. if (name === '__proto__') return true;
  1890. const isNumericKey = Number.isFinite(+name);
  1891. const isLast = index >= path.length;
  1892. name = !name && utils$1.isArray(target) ? target.length : name;
  1893. if (isLast) {
  1894. if (utils$1.hasOwnProp(target, name)) {
  1895. target[name] = utils$1.isArray(target[name]) ? target[name].concat(value) : [target[name], value];
  1896. } else {
  1897. target[name] = value;
  1898. }
  1899. return !isNumericKey;
  1900. }
  1901. if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
  1902. target[name] = [];
  1903. }
  1904. const result = buildPath(path, value, target[name], index);
  1905. if (result && utils$1.isArray(target[name])) {
  1906. target[name] = arrayToObject(target[name]);
  1907. }
  1908. return !isNumericKey;
  1909. }
  1910. if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
  1911. const obj = {};
  1912. utils$1.forEachEntry(formData, (name, value) => {
  1913. buildPath(parsePropPath(name), value, obj, 0);
  1914. });
  1915. return obj;
  1916. }
  1917. return null;
  1918. }
  1919. const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
  1920. /**
  1921. * It takes a string, tries to parse it, and if it fails, it returns the stringified version
  1922. * of the input
  1923. *
  1924. * @param {any} rawValue - The value to be stringified.
  1925. * @param {Function} parser - A function that parses a string into a JavaScript object.
  1926. * @param {Function} encoder - A function that takes a value and returns a string.
  1927. *
  1928. * @returns {string} A stringified version of the rawValue.
  1929. */
  1930. function stringifySafely(rawValue, parser, encoder) {
  1931. if (utils$1.isString(rawValue)) {
  1932. try {
  1933. (parser || JSON.parse)(rawValue);
  1934. return utils$1.trim(rawValue);
  1935. } catch (e) {
  1936. if (e.name !== 'SyntaxError') {
  1937. throw e;
  1938. }
  1939. }
  1940. }
  1941. return (encoder || JSON.stringify)(rawValue);
  1942. }
  1943. const defaults = {
  1944. transitional: transitionalDefaults,
  1945. adapter: ['xhr', 'http', 'fetch'],
  1946. transformRequest: [function transformRequest(data, headers) {
  1947. const contentType = headers.getContentType() || '';
  1948. const hasJSONContentType = contentType.indexOf('application/json') > -1;
  1949. const isObjectPayload = utils$1.isObject(data);
  1950. if (isObjectPayload && utils$1.isHTMLForm(data)) {
  1951. data = new FormData(data);
  1952. }
  1953. const isFormData = utils$1.isFormData(data);
  1954. if (isFormData) {
  1955. return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
  1956. }
  1957. 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)) {
  1958. return data;
  1959. }
  1960. if (utils$1.isArrayBufferView(data)) {
  1961. return data.buffer;
  1962. }
  1963. if (utils$1.isURLSearchParams(data)) {
  1964. headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
  1965. return data.toString();
  1966. }
  1967. let isFileList;
  1968. if (isObjectPayload) {
  1969. const formSerializer = own(this, 'formSerializer');
  1970. if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
  1971. return toURLEncodedForm(data, formSerializer).toString();
  1972. }
  1973. if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
  1974. const env = own(this, 'env');
  1975. const _FormData = env && env.FormData;
  1976. return toFormData(isFileList ? {
  1977. 'files[]': data
  1978. } : data, _FormData && new _FormData(), formSerializer);
  1979. }
  1980. }
  1981. if (isObjectPayload || hasJSONContentType) {
  1982. headers.setContentType('application/json', false);
  1983. return stringifySafely(data);
  1984. }
  1985. return data;
  1986. }],
  1987. transformResponse: [function transformResponse(data) {
  1988. const transitional = own(this, 'transitional') || defaults.transitional;
  1989. const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  1990. const responseType = own(this, 'responseType');
  1991. const JSONRequested = responseType === 'json';
  1992. if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
  1993. return data;
  1994. }
  1995. if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
  1996. const silentJSONParsing = transitional && transitional.silentJSONParsing;
  1997. const strictJSONParsing = !silentJSONParsing && JSONRequested;
  1998. try {
  1999. return JSON.parse(data, own(this, 'parseReviver'));
  2000. } catch (e) {
  2001. if (strictJSONParsing) {
  2002. if (e.name === 'SyntaxError') {
  2003. throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
  2004. }
  2005. throw e;
  2006. }
  2007. }
  2008. }
  2009. return data;
  2010. }],
  2011. /**
  2012. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  2013. * timeout is not created.
  2014. */
  2015. timeout: 0,
  2016. xsrfCookieName: 'XSRF-TOKEN',
  2017. xsrfHeaderName: 'X-XSRF-TOKEN',
  2018. maxContentLength: -1,
  2019. maxBodyLength: -1,
  2020. env: {
  2021. FormData: platform.classes.FormData,
  2022. Blob: platform.classes.Blob
  2023. },
  2024. validateStatus: function validateStatus(status) {
  2025. return status >= 200 && status < 300;
  2026. },
  2027. headers: {
  2028. common: {
  2029. Accept: 'application/json, text/plain, */*',
  2030. 'Content-Type': undefined
  2031. }
  2032. }
  2033. };
  2034. utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], method => {
  2035. defaults.headers[method] = {};
  2036. });
  2037. /**
  2038. * Transform the data for a request or a response
  2039. *
  2040. * @param {Array|Function} fns A single function or Array of functions
  2041. * @param {?Object} response The response object
  2042. *
  2043. * @returns {*} The resulting transformed data
  2044. */
  2045. function transformData(fns, response) {
  2046. const config = this || defaults;
  2047. const context = response || config;
  2048. const headers = AxiosHeaders.from(context.headers);
  2049. let data = context.data;
  2050. utils$1.forEach(fns, function transform(fn) {
  2051. data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  2052. });
  2053. headers.normalize();
  2054. return data;
  2055. }
  2056. function isCancel(value) {
  2057. return !!(value && value.__CANCEL__);
  2058. }
  2059. class CanceledError extends AxiosError {
  2060. /**
  2061. * A `CanceledError` is an object that is thrown when an operation is canceled.
  2062. *
  2063. * @param {string=} message The message.
  2064. * @param {Object=} config The config.
  2065. * @param {Object=} request The request.
  2066. *
  2067. * @returns {CanceledError} The created error.
  2068. */
  2069. constructor(message, config, request) {
  2070. super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
  2071. this.name = 'CanceledError';
  2072. this.__CANCEL__ = true;
  2073. }
  2074. }
  2075. /**
  2076. * Resolve or reject a Promise based on response status.
  2077. *
  2078. * @param {Function} resolve A function that resolves the promise.
  2079. * @param {Function} reject A function that rejects the promise.
  2080. * @param {object} response The response.
  2081. *
  2082. * @returns {object} The response.
  2083. */
  2084. function settle(resolve, reject, response) {
  2085. const validateStatus = response.config.validateStatus;
  2086. if (!response.status || !validateStatus || validateStatus(response.status)) {
  2087. resolve(response);
  2088. } else {
  2089. 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));
  2090. }
  2091. }
  2092. /**
  2093. * Determines whether the specified URL is absolute
  2094. *
  2095. * @param {string} url The URL to test
  2096. *
  2097. * @returns {boolean} True if the specified URL is absolute, otherwise false
  2098. */
  2099. function isAbsoluteURL(url) {
  2100. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  2101. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  2102. // by any combination of letters, digits, plus, period, or hyphen.
  2103. if (typeof url !== 'string') {
  2104. return false;
  2105. }
  2106. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  2107. }
  2108. /**
  2109. * Creates a new URL by combining the specified URLs
  2110. *
  2111. * @param {string} baseURL The base URL
  2112. * @param {string} relativeURL The relative URL
  2113. *
  2114. * @returns {string} The combined URL
  2115. */
  2116. function combineURLs(baseURL, relativeURL) {
  2117. return relativeURL ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL;
  2118. }
  2119. const malformedHttpProtocol = /^https?:(?!\/\/)/i;
  2120. const httpProtocolControlCharacters = /[\t\n\r]/g;
  2121. function stripLeadingC0ControlOrSpace(url) {
  2122. let i = 0;
  2123. while (i < url.length && url.charCodeAt(i) <= 0x20) {
  2124. i++;
  2125. }
  2126. return url.slice(i);
  2127. }
  2128. function normalizeURLForProtocolCheck(url) {
  2129. return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
  2130. }
  2131. function assertValidHttpProtocolURL(url, config) {
  2132. if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
  2133. throw new AxiosError('Invalid URL: missing "//" after protocol', AxiosError.ERR_INVALID_URL, config);
  2134. }
  2135. }
  2136. /**
  2137. * Creates a new URL by combining the baseURL with the requestedURL,
  2138. * only when the requestedURL is not already an absolute URL.
  2139. * If the requestURL is absolute, this function returns the requestedURL untouched.
  2140. *
  2141. * @param {string} baseURL The base URL
  2142. * @param {string} requestedURL Absolute or relative URL to combine
  2143. *
  2144. * @returns {string} The combined full path
  2145. */
  2146. function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
  2147. assertValidHttpProtocolURL(requestedURL, config);
  2148. let isRelativeUrl = !isAbsoluteURL(requestedURL);
  2149. if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
  2150. assertValidHttpProtocolURL(baseURL, config);
  2151. return combineURLs(baseURL, requestedURL);
  2152. }
  2153. return requestedURL;
  2154. }
  2155. var DEFAULT_PORTS$1 = {
  2156. ftp: 21,
  2157. gopher: 70,
  2158. http: 80,
  2159. https: 443,
  2160. ws: 80,
  2161. wss: 443
  2162. };
  2163. function parseUrl(urlString) {
  2164. try {
  2165. return new URL(urlString);
  2166. } catch {
  2167. return null;
  2168. }
  2169. }
  2170. /**
  2171. * @param {string|object|URL} url - The URL as a string or URL instance, or a
  2172. * compatible object (such as the result from legacy url.parse).
  2173. * @return {string} The URL of the proxy that should handle the request to the
  2174. * given URL. If no proxy is set, this will be an empty string.
  2175. */
  2176. function getProxyForUrl(url) {
  2177. var parsedUrl = (typeof url === 'string' ? parseUrl(url) : url) || {};
  2178. var proto = parsedUrl.protocol;
  2179. var hostname = parsedUrl.host;
  2180. var port = parsedUrl.port;
  2181. if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
  2182. return ''; // Don't proxy URLs without a valid scheme or host.
  2183. }
  2184. proto = proto.split(':', 1)[0];
  2185. // Stripping ports in this way instead of using parsedUrl.hostname to make
  2186. // sure that the brackets around IPv6 addresses are kept.
  2187. hostname = hostname.replace(/:\d*$/, '');
  2188. port = parseInt(port) || DEFAULT_PORTS$1[proto] || 0;
  2189. if (!shouldProxy(hostname, port)) {
  2190. return ''; // Don't proxy URLs that match NO_PROXY.
  2191. }
  2192. var proxy = getEnv(proto + '_proxy') || getEnv('all_proxy');
  2193. if (proxy && proxy.indexOf('://') === -1) {
  2194. // Missing scheme in proxy, default to the requested URL's scheme.
  2195. proxy = proto + '://' + proxy;
  2196. }
  2197. return proxy;
  2198. }
  2199. /**
  2200. * Determines whether a given URL should be proxied.
  2201. *
  2202. * @param {string} hostname - The host name of the URL.
  2203. * @param {number} port - The effective port of the URL.
  2204. * @returns {boolean} Whether the given URL should be proxied.
  2205. * @private
  2206. */
  2207. function shouldProxy(hostname, port) {
  2208. var NO_PROXY = getEnv('no_proxy').toLowerCase();
  2209. if (!NO_PROXY) {
  2210. return true; // Always proxy if NO_PROXY is not set.
  2211. }
  2212. if (NO_PROXY === '*') {
  2213. return false; // Never proxy if wildcard is set.
  2214. }
  2215. return NO_PROXY.split(/[,\s]/).every(function (proxy) {
  2216. if (!proxy) {
  2217. return true; // Skip zero-length hosts.
  2218. }
  2219. var parsedProxy = proxy.match(/^(.+):(\d+)$/);
  2220. var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
  2221. var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
  2222. if (parsedProxyPort && parsedProxyPort !== port) {
  2223. return true; // Skip if ports don't match.
  2224. }
  2225. if (!/^[.*]/.test(parsedProxyHostname)) {
  2226. // No wildcards, so stop proxying if there is an exact match.
  2227. return hostname !== parsedProxyHostname;
  2228. }
  2229. if (parsedProxyHostname.charAt(0) === '*') {
  2230. // Remove leading wildcard.
  2231. parsedProxyHostname = parsedProxyHostname.slice(1);
  2232. }
  2233. // Stop proxying if the hostname ends with the no_proxy host.
  2234. return !hostname.endsWith(parsedProxyHostname);
  2235. });
  2236. }
  2237. /**
  2238. * Get the value for an environment variable.
  2239. *
  2240. * @param {string} key - The name of the environment variable.
  2241. * @return {string} The value of the environment variable.
  2242. * @private
  2243. */
  2244. function getEnv(key) {
  2245. return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
  2246. }
  2247. const VERSION = "1.18.0";
  2248. function parseProtocol(url) {
  2249. const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
  2250. return match && match[1] || '';
  2251. }
  2252. // RFC 2397: data:[<mediatype>][;base64],<data>
  2253. // mediatype = type/subtype followed by optional ;name=value parameters
  2254. const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
  2255. /**
  2256. * Parse data uri to a Buffer or Blob
  2257. *
  2258. * @param {String} uri
  2259. * @param {?Boolean} asBlob
  2260. * @param {?Object} options
  2261. * @param {?Function} options.Blob
  2262. *
  2263. * @returns {Buffer|Blob}
  2264. */
  2265. function fromDataURI(uri, asBlob, options) {
  2266. const _Blob = options && options.Blob || platform.classes.Blob;
  2267. const protocol = parseProtocol(uri);
  2268. if (asBlob === undefined && _Blob) {
  2269. asBlob = true;
  2270. }
  2271. if (protocol === 'data') {
  2272. uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
  2273. const match = DATA_URL_PATTERN.exec(uri);
  2274. if (!match) {
  2275. throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
  2276. }
  2277. const type = match[1];
  2278. const params = match[2];
  2279. const encoding = match[3] ? 'base64' : 'utf8';
  2280. const body = match[4];
  2281. // RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
  2282. // Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
  2283. let mime;
  2284. if (type) {
  2285. mime = params ? type + params : type;
  2286. } else if (params) {
  2287. mime = 'text/plain' + params;
  2288. }
  2289. const buffer = Buffer.from(decodeURIComponent(body), encoding);
  2290. if (asBlob) {
  2291. if (!_Blob) {
  2292. throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
  2293. }
  2294. return new _Blob([buffer], {
  2295. type: mime
  2296. });
  2297. }
  2298. return buffer;
  2299. }
  2300. throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
  2301. }
  2302. const kInternals = Symbol('internals');
  2303. class AxiosTransformStream extends stream.Transform {
  2304. constructor(options) {
  2305. options = utils$1.toFlatObject(options, {
  2306. maxRate: 0,
  2307. chunkSize: 64 * 1024,
  2308. minChunkSize: 100,
  2309. timeWindow: 500,
  2310. ticksRate: 2,
  2311. samplesCount: 15
  2312. }, null, (prop, source) => {
  2313. return !utils$1.isUndefined(source[prop]);
  2314. });
  2315. super({
  2316. readableHighWaterMark: options.chunkSize
  2317. });
  2318. const internals = this[kInternals] = {
  2319. timeWindow: options.timeWindow,
  2320. chunkSize: options.chunkSize,
  2321. maxRate: options.maxRate,
  2322. minChunkSize: options.minChunkSize,
  2323. bytesSeen: 0,
  2324. isCaptured: false,
  2325. notifiedBytesLoaded: 0,
  2326. ts: Date.now(),
  2327. bytes: 0,
  2328. onReadCallback: null
  2329. };
  2330. this.on('newListener', event => {
  2331. if (event === 'progress') {
  2332. if (!internals.isCaptured) {
  2333. internals.isCaptured = true;
  2334. }
  2335. }
  2336. });
  2337. }
  2338. _read(size) {
  2339. const internals = this[kInternals];
  2340. if (internals.onReadCallback) {
  2341. internals.onReadCallback();
  2342. }
  2343. return super._read(size);
  2344. }
  2345. _transform(chunk, encoding, callback) {
  2346. const internals = this[kInternals];
  2347. const maxRate = internals.maxRate;
  2348. const readableHighWaterMark = this.readableHighWaterMark;
  2349. const timeWindow = internals.timeWindow;
  2350. const divider = 1000 / timeWindow;
  2351. const bytesThreshold = maxRate / divider;
  2352. const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
  2353. const pushChunk = (_chunk, _callback) => {
  2354. const bytes = Buffer.byteLength(_chunk);
  2355. internals.bytesSeen += bytes;
  2356. internals.bytes += bytes;
  2357. internals.isCaptured && this.emit('progress', internals.bytesSeen);
  2358. if (this.push(_chunk)) {
  2359. process.nextTick(_callback);
  2360. } else {
  2361. internals.onReadCallback = () => {
  2362. internals.onReadCallback = null;
  2363. process.nextTick(_callback);
  2364. };
  2365. }
  2366. };
  2367. const transformChunk = (_chunk, _callback) => {
  2368. const chunkSize = Buffer.byteLength(_chunk);
  2369. let chunkRemainder = null;
  2370. let maxChunkSize = readableHighWaterMark;
  2371. let bytesLeft;
  2372. let passed = 0;
  2373. if (maxRate) {
  2374. const now = Date.now();
  2375. if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
  2376. internals.ts = now;
  2377. bytesLeft = bytesThreshold - internals.bytes;
  2378. internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
  2379. passed = 0;
  2380. }
  2381. bytesLeft = bytesThreshold - internals.bytes;
  2382. }
  2383. if (maxRate) {
  2384. if (bytesLeft <= 0) {
  2385. // next time window
  2386. return setTimeout(() => {
  2387. _callback(null, _chunk);
  2388. }, timeWindow - passed);
  2389. }
  2390. if (bytesLeft < maxChunkSize) {
  2391. maxChunkSize = bytesLeft;
  2392. }
  2393. }
  2394. if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
  2395. chunkRemainder = _chunk.subarray(maxChunkSize);
  2396. _chunk = _chunk.subarray(0, maxChunkSize);
  2397. }
  2398. pushChunk(_chunk, chunkRemainder ? () => {
  2399. process.nextTick(_callback, null, chunkRemainder);
  2400. } : _callback);
  2401. };
  2402. transformChunk(chunk, function transformNextChunk(err, _chunk) {
  2403. if (err) {
  2404. return callback(err);
  2405. }
  2406. if (_chunk) {
  2407. transformChunk(_chunk, transformNextChunk);
  2408. } else {
  2409. callback(null);
  2410. }
  2411. });
  2412. }
  2413. }
  2414. const {
  2415. asyncIterator
  2416. } = Symbol;
  2417. const readBlob = async function* (blob) {
  2418. if (blob.stream) {
  2419. yield* blob.stream();
  2420. } else if (blob.arrayBuffer) {
  2421. yield await blob.arrayBuffer();
  2422. } else if (blob[asyncIterator]) {
  2423. yield* blob[asyncIterator]();
  2424. } else {
  2425. yield blob;
  2426. }
  2427. };
  2428. const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_';
  2429. const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder();
  2430. const CRLF = '\r\n';
  2431. const CRLF_BYTES = textEncoder.encode(CRLF);
  2432. const CRLF_BYTES_COUNT = 2;
  2433. class FormDataPart {
  2434. constructor(name, value) {
  2435. const {
  2436. escapeName
  2437. } = this.constructor;
  2438. const isStringValue = utils$1.isString(value);
  2439. let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''}${CRLF}`;
  2440. if (isStringValue) {
  2441. value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
  2442. } else {
  2443. const safeType = String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
  2444. headers += `Content-Type: ${safeType}${CRLF}`;
  2445. }
  2446. this.headers = textEncoder.encode(headers + CRLF);
  2447. this.contentLength = isStringValue ? value.byteLength : value.size;
  2448. this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
  2449. this.name = name;
  2450. this.value = value;
  2451. }
  2452. async *encode() {
  2453. yield this.headers;
  2454. const {
  2455. value
  2456. } = this;
  2457. if (utils$1.isTypedArray(value)) {
  2458. yield value;
  2459. } else {
  2460. yield* readBlob(value);
  2461. }
  2462. yield CRLF_BYTES;
  2463. }
  2464. static escapeName(name) {
  2465. return String(name).replace(/[\r\n"]/g, match => ({
  2466. '\r': '%0D',
  2467. '\n': '%0A',
  2468. '"': '%22'
  2469. })[match]);
  2470. }
  2471. }
  2472. const formDataToStream = (form, headersHandler, options) => {
  2473. const {
  2474. tag = 'form-data-boundary',
  2475. size = 25,
  2476. boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET)
  2477. } = options || {};
  2478. if (!utils$1.isFormData(form)) {
  2479. throw new TypeError('FormData instance required');
  2480. }
  2481. if (boundary.length < 1 || boundary.length > 70) {
  2482. throw new Error('boundary must be 1-70 characters long');
  2483. }
  2484. const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
  2485. const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF);
  2486. let contentLength = footerBytes.byteLength;
  2487. const parts = Array.from(form.entries()).map(([name, value]) => {
  2488. const part = new FormDataPart(name, value);
  2489. contentLength += part.size;
  2490. return part;
  2491. });
  2492. contentLength += boundaryBytes.byteLength * parts.length;
  2493. contentLength = utils$1.toFiniteNumber(contentLength);
  2494. const computedHeaders = {
  2495. 'Content-Type': `multipart/form-data; boundary=${boundary}`
  2496. };
  2497. if (Number.isFinite(contentLength)) {
  2498. computedHeaders['Content-Length'] = contentLength;
  2499. }
  2500. headersHandler && headersHandler(computedHeaders);
  2501. return stream.Readable.from(async function* () {
  2502. for (const part of parts) {
  2503. yield boundaryBytes;
  2504. yield* part.encode();
  2505. }
  2506. yield footerBytes;
  2507. }());
  2508. };
  2509. class ZlibHeaderTransformStream extends stream.Transform {
  2510. __transform(chunk, encoding, callback) {
  2511. this.push(chunk);
  2512. callback();
  2513. }
  2514. _transform(chunk, encoding, callback) {
  2515. if (chunk.length !== 0) {
  2516. this._transform = this.__transform;
  2517. // Add Default Compression headers if no zlib headers are present
  2518. if (chunk[0] !== 120) {
  2519. // Hex: 78
  2520. const header = Buffer.alloc(2);
  2521. header[0] = 120; // Hex: 78
  2522. header[1] = 156; // Hex: 9C
  2523. this.push(header, encoding);
  2524. }
  2525. }
  2526. this.__transform(chunk, encoding, callback);
  2527. }
  2528. }
  2529. class Http2Sessions {
  2530. constructor() {
  2531. this.sessions = Object.create(null);
  2532. }
  2533. getSession(authority, options) {
  2534. options = Object.assign({
  2535. sessionTimeout: 1000
  2536. }, options);
  2537. let authoritySessions = this.sessions[authority];
  2538. if (authoritySessions) {
  2539. let len = authoritySessions.length;
  2540. for (let i = 0; i < len; i++) {
  2541. const [sessionHandle, sessionOptions] = authoritySessions[i];
  2542. if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) {
  2543. return sessionHandle;
  2544. }
  2545. }
  2546. }
  2547. const session = http2.connect(authority, options);
  2548. let removed;
  2549. let timer;
  2550. const removeSession = () => {
  2551. if (removed) {
  2552. return;
  2553. }
  2554. removed = true;
  2555. if (timer) {
  2556. clearTimeout(timer);
  2557. timer = null;
  2558. }
  2559. let entries = authoritySessions,
  2560. len = entries.length,
  2561. i = len;
  2562. while (i--) {
  2563. if (entries[i][0] === session) {
  2564. if (len === 1) {
  2565. delete this.sessions[authority];
  2566. } else {
  2567. entries.splice(i, 1);
  2568. }
  2569. if (!session.closed) {
  2570. session.close();
  2571. }
  2572. return;
  2573. }
  2574. }
  2575. };
  2576. const originalRequestFn = session.request;
  2577. const {
  2578. sessionTimeout
  2579. } = options;
  2580. if (sessionTimeout != null) {
  2581. let streamsCount = 0;
  2582. session.request = function () {
  2583. const stream = originalRequestFn.apply(this, arguments);
  2584. streamsCount++;
  2585. if (timer) {
  2586. clearTimeout(timer);
  2587. timer = null;
  2588. }
  2589. stream.once('close', () => {
  2590. if (! --streamsCount) {
  2591. timer = setTimeout(() => {
  2592. timer = null;
  2593. removeSession();
  2594. }, sessionTimeout);
  2595. }
  2596. });
  2597. return stream;
  2598. };
  2599. }
  2600. session.once('close', removeSession);
  2601. let entry = [session, options];
  2602. authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
  2603. return session;
  2604. }
  2605. }
  2606. const callbackify = (fn, reducer) => {
  2607. return utils$1.isAsyncFn(fn) ? function (...args) {
  2608. const cb = args.pop();
  2609. fn.apply(this, args).then(value => {
  2610. try {
  2611. reducer ? cb(null, ...reducer(value)) : cb(null, value);
  2612. } catch (err) {
  2613. cb(err);
  2614. }
  2615. }, cb);
  2616. } : fn;
  2617. };
  2618. const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']);
  2619. const isIPv4Loopback = host => {
  2620. const parts = host.split('.');
  2621. if (parts.length !== 4) return false;
  2622. if (parts[0] !== '127') return false;
  2623. return parts.every(p => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
  2624. };
  2625. const isIPv6ZeroGroup = group => /^0{1,4}$/.test(group);
  2626. // The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host
  2627. // for outbound connections, so treat it as loopback-equivalent for NO_PROXY
  2628. // matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed
  2629. // and full IPv6 all-zero forms so both families bypass symmetrically.
  2630. const isIPv6Unspecified = host => {
  2631. if (host === '::') return true;
  2632. const compressionIndex = host.indexOf('::');
  2633. if (compressionIndex !== -1) {
  2634. if (compressionIndex !== host.lastIndexOf('::')) return false;
  2635. const left = host.slice(0, compressionIndex);
  2636. const right = host.slice(compressionIndex + 2);
  2637. const leftGroups = left ? left.split(':') : [];
  2638. const rightGroups = right ? right.split(':') : [];
  2639. const explicitGroups = leftGroups.length + rightGroups.length;
  2640. return explicitGroups < 8 && leftGroups.every(isIPv6ZeroGroup) && rightGroups.every(isIPv6ZeroGroup);
  2641. }
  2642. const groups = host.split(':');
  2643. return groups.length === 8 && groups.every(isIPv6ZeroGroup);
  2644. };
  2645. const isIPv6Loopback = host => {
  2646. // Collapse all-zero groups: any form of ::1 / 0:0:...:0:1
  2647. // First, strip any leading "::" by normalising with Set lookup of common forms,
  2648. // then fall back to structural check.
  2649. if (host === '::1') return true;
  2650. // Check IPv4-mapped IPv6 loopback: ::ffff:<v4-loopback> or ::ffff:<hex-v4-loopback>
  2651. // Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1
  2652. const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
  2653. if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]);
  2654. const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
  2655. if (v4MappedHex) {
  2656. const high = parseInt(v4MappedHex[1], 16);
  2657. // High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff
  2658. return high >= 0x7f00 && high <= 0x7fff;
  2659. }
  2660. // Full-form ::1 variants: any number of zero groups followed by trailing 1
  2661. // e.g. 0:0:0:0:0:0:0:1, 0000:...:0001
  2662. const groups = host.split(':');
  2663. if (groups.length === 8) {
  2664. for (let i = 0; i < 7; i++) {
  2665. if (!/^0+$/.test(groups[i])) return false;
  2666. }
  2667. return /^0*1$/.test(groups[7]);
  2668. }
  2669. return false;
  2670. };
  2671. const isLoopback = host => {
  2672. if (!host) return false;
  2673. if (LOOPBACK_HOSTNAMES.has(host)) return true;
  2674. if (isIPv4Loopback(host)) return true;
  2675. if (isIPv6Unspecified(host)) return true;
  2676. return isIPv6Loopback(host);
  2677. };
  2678. const DEFAULT_PORTS = {
  2679. http: 80,
  2680. https: 443,
  2681. ws: 80,
  2682. wss: 443,
  2683. ftp: 21
  2684. };
  2685. const parseNoProxyEntry = entry => {
  2686. let entryHost = entry;
  2687. let entryPort = 0;
  2688. if (entryHost.charAt(0) === '[') {
  2689. const bracketIndex = entryHost.indexOf(']');
  2690. if (bracketIndex !== -1) {
  2691. const host = entryHost.slice(1, bracketIndex);
  2692. const rest = entryHost.slice(bracketIndex + 1);
  2693. if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
  2694. entryPort = Number.parseInt(rest.slice(1), 10);
  2695. }
  2696. return [host, entryPort];
  2697. }
  2698. }
  2699. const firstColon = entryHost.indexOf(':');
  2700. const lastColon = entryHost.lastIndexOf(':');
  2701. if (firstColon !== -1 && firstColon === lastColon && /^\d+$/.test(entryHost.slice(lastColon + 1))) {
  2702. entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
  2703. entryHost = entryHost.slice(0, lastColon);
  2704. }
  2705. return [entryHost, entryPort];
  2706. };
  2707. // Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
  2708. // sides of a NO_PROXY comparison see the same canonical address. Without this,
  2709. // `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
  2710. // (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
  2711. // allowing the proxy-bypass policy to be circumvented by using the alternate
  2712. // representation. Returns the input unchanged when not IPv4-mapped.
  2713. const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
  2714. 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;
  2715. const unmapIPv4MappedIPv6 = host => {
  2716. if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
  2717. const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
  2718. if (dotted) return dotted[1];
  2719. const hex = host.match(IPV4_MAPPED_HEX_RE);
  2720. if (hex) {
  2721. const high = parseInt(hex[1], 16);
  2722. const low = parseInt(hex[2], 16);
  2723. return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
  2724. }
  2725. return host;
  2726. };
  2727. const normalizeNoProxyHost = hostname => {
  2728. if (!hostname) {
  2729. return hostname;
  2730. }
  2731. if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
  2732. hostname = hostname.slice(1, -1);
  2733. }
  2734. return unmapIPv4MappedIPv6(hostname.replace(/\.+$/, ''));
  2735. };
  2736. function shouldBypassProxy(location) {
  2737. let parsed;
  2738. try {
  2739. parsed = new URL(location);
  2740. } catch (_err) {
  2741. return false;
  2742. }
  2743. const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
  2744. if (!noProxy) {
  2745. return false;
  2746. }
  2747. if (noProxy === '*') {
  2748. return true;
  2749. }
  2750. const port = Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
  2751. const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
  2752. return noProxy.split(/[\s,]+/).some(entry => {
  2753. if (!entry) {
  2754. return false;
  2755. }
  2756. let [entryHost, entryPort] = parseNoProxyEntry(entry);
  2757. entryHost = normalizeNoProxyHost(entryHost);
  2758. if (!entryHost) {
  2759. return false;
  2760. }
  2761. if (entryPort && entryPort !== port) {
  2762. return false;
  2763. }
  2764. if (entryHost.charAt(0) === '*') {
  2765. entryHost = entryHost.slice(1);
  2766. }
  2767. if (entryHost.charAt(0) === '.') {
  2768. return hostname.endsWith(entryHost);
  2769. }
  2770. return hostname === entryHost || isLoopback(hostname) && isLoopback(entryHost);
  2771. });
  2772. }
  2773. /**
  2774. * Calculate data maxRate
  2775. * @param {Number} [samplesCount= 10]
  2776. * @param {Number} [min= 1000]
  2777. * @returns {Function}
  2778. */
  2779. function speedometer(samplesCount, min) {
  2780. samplesCount = samplesCount || 10;
  2781. const bytes = new Array(samplesCount);
  2782. const timestamps = new Array(samplesCount);
  2783. let head = 0;
  2784. let tail = 0;
  2785. let firstSampleTS;
  2786. min = min !== undefined ? min : 1000;
  2787. return function push(chunkLength) {
  2788. const now = Date.now();
  2789. const startedAt = timestamps[tail];
  2790. if (!firstSampleTS) {
  2791. firstSampleTS = now;
  2792. }
  2793. bytes[head] = chunkLength;
  2794. timestamps[head] = now;
  2795. let i = tail;
  2796. let bytesCount = 0;
  2797. while (i !== head) {
  2798. bytesCount += bytes[i++];
  2799. i = i % samplesCount;
  2800. }
  2801. head = (head + 1) % samplesCount;
  2802. if (head === tail) {
  2803. tail = (tail + 1) % samplesCount;
  2804. }
  2805. if (now - firstSampleTS < min) {
  2806. return;
  2807. }
  2808. const passed = startedAt && now - startedAt;
  2809. return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  2810. };
  2811. }
  2812. /**
  2813. * Throttle decorator
  2814. * @param {Function} fn
  2815. * @param {Number} freq
  2816. * @return {Function}
  2817. */
  2818. function throttle(fn, freq) {
  2819. let timestamp = 0;
  2820. let threshold = 1000 / freq;
  2821. let lastArgs;
  2822. let timer;
  2823. const invoke = (args, now = Date.now()) => {
  2824. timestamp = now;
  2825. lastArgs = null;
  2826. if (timer) {
  2827. clearTimeout(timer);
  2828. timer = null;
  2829. }
  2830. fn(...args);
  2831. };
  2832. const throttled = (...args) => {
  2833. const now = Date.now();
  2834. const passed = now - timestamp;
  2835. if (passed >= threshold) {
  2836. invoke(args, now);
  2837. } else {
  2838. lastArgs = args;
  2839. if (!timer) {
  2840. timer = setTimeout(() => {
  2841. timer = null;
  2842. invoke(lastArgs);
  2843. }, threshold - passed);
  2844. }
  2845. }
  2846. };
  2847. const flush = () => lastArgs && invoke(lastArgs);
  2848. return [throttled, flush];
  2849. }
  2850. const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  2851. let bytesNotified = 0;
  2852. const _speedometer = speedometer(50, 250);
  2853. return throttle(e => {
  2854. if (!e || typeof e.loaded !== 'number') {
  2855. return;
  2856. }
  2857. const rawLoaded = e.loaded;
  2858. const total = e.lengthComputable ? e.total : undefined;
  2859. const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
  2860. const progressBytes = Math.max(0, loaded - bytesNotified);
  2861. const rate = _speedometer(progressBytes);
  2862. bytesNotified = Math.max(bytesNotified, loaded);
  2863. const data = {
  2864. loaded,
  2865. total,
  2866. progress: total ? loaded / total : undefined,
  2867. bytes: progressBytes,
  2868. rate: rate ? rate : undefined,
  2869. estimated: rate && total ? (total - loaded) / rate : undefined,
  2870. event: e,
  2871. lengthComputable: total != null,
  2872. [isDownloadStream ? 'download' : 'upload']: true
  2873. };
  2874. listener(data);
  2875. }, freq);
  2876. };
  2877. const progressEventDecorator = (total, throttled) => {
  2878. const lengthComputable = total != null;
  2879. return [loaded => throttled[0]({
  2880. lengthComputable,
  2881. total,
  2882. loaded
  2883. }), throttled[1]];
  2884. };
  2885. const asyncDecorator = fn => (...args) => utils$1.asap(() => fn(...args));
  2886. /**
  2887. * Estimate decoded byte length of a data:// URL *without* allocating large buffers.
  2888. * - For base64: compute exact decoded size using length and padding;
  2889. * handle %XX at the character-count level (no string allocation).
  2890. * - For non-base64: compute the exact percent-decoded UTF-8 byte length.
  2891. *
  2892. * @param {string} url
  2893. * @returns {number}
  2894. */
  2895. const isHexDigit = charCode => charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102;
  2896. const isPercentEncodedByte = (str, i, len) => i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
  2897. function estimateDataURLDecodedBytes(url) {
  2898. if (!url || typeof url !== 'string') return 0;
  2899. if (!url.startsWith('data:')) return 0;
  2900. const comma = url.indexOf(',');
  2901. if (comma < 0) return 0;
  2902. const meta = url.slice(5, comma);
  2903. const body = url.slice(comma + 1);
  2904. const isBase64 = /;base64/i.test(meta);
  2905. if (isBase64) {
  2906. let effectiveLen = body.length;
  2907. const len = body.length; // cache length
  2908. for (let i = 0; i < len; i++) {
  2909. if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
  2910. const a = body.charCodeAt(i + 1);
  2911. const b = body.charCodeAt(i + 2);
  2912. const isHex = isHexDigit(a) && isHexDigit(b);
  2913. if (isHex) {
  2914. effectiveLen -= 2;
  2915. i += 2;
  2916. }
  2917. }
  2918. }
  2919. let pad = 0;
  2920. let idx = len - 1;
  2921. const tailIsPct3D = j => j >= 2 && body.charCodeAt(j - 2) === 37 &&
  2922. // '%'
  2923. body.charCodeAt(j - 1) === 51 && (
  2924. // '3'
  2925. body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
  2926. if (idx >= 0) {
  2927. if (body.charCodeAt(idx) === 61 /* '=' */) {
  2928. pad++;
  2929. idx--;
  2930. } else if (tailIsPct3D(idx)) {
  2931. pad++;
  2932. idx -= 3;
  2933. }
  2934. }
  2935. if (pad === 1 && idx >= 0) {
  2936. if (body.charCodeAt(idx) === 61 /* '=' */) {
  2937. pad++;
  2938. } else if (tailIsPct3D(idx)) {
  2939. pad++;
  2940. }
  2941. }
  2942. const groups = Math.floor(effectiveLen / 4);
  2943. const bytes = groups * 3 - (pad || 0);
  2944. return bytes > 0 ? bytes : 0;
  2945. }
  2946. // Compute UTF-8 byte length directly from UTF-16 code units without allocating
  2947. // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
  2948. // Valid %XX triplets count as one decoded byte; this matches the bytes that
  2949. // decodeURIComponent(body) would produce before Buffer re-encodes the string.
  2950. let bytes = 0;
  2951. for (let i = 0, len = body.length; i < len; i++) {
  2952. const c = body.charCodeAt(i);
  2953. if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
  2954. bytes += 1;
  2955. i += 2;
  2956. } else if (c < 0x80) {
  2957. bytes += 1;
  2958. } else if (c < 0x800) {
  2959. bytes += 2;
  2960. } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
  2961. const next = body.charCodeAt(i + 1);
  2962. if (next >= 0xdc00 && next <= 0xdfff) {
  2963. bytes += 4;
  2964. i++;
  2965. } else {
  2966. bytes += 3;
  2967. }
  2968. } else {
  2969. bytes += 3;
  2970. }
  2971. }
  2972. return bytes;
  2973. }
  2974. const zlibOptions = {
  2975. flush: zlib.constants.Z_SYNC_FLUSH,
  2976. finishFlush: zlib.constants.Z_SYNC_FLUSH
  2977. };
  2978. const brotliOptions = {
  2979. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  2980. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  2981. };
  2982. const zstdOptions = {
  2983. flush: zlib.constants.ZSTD_e_flush,
  2984. finishFlush: zlib.constants.ZSTD_e_flush
  2985. };
  2986. const isBrotliSupported = utils$1.isFunction(zlib.createBrotliDecompress);
  2987. const isZstdSupported = utils$1.isFunction(zlib.createZstdDecompress);
  2988. const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
  2989. const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
  2990. const {
  2991. http: httpFollow,
  2992. https: httpsFollow
  2993. } = followRedirects;
  2994. const isHttps = /https:?/;
  2995. const FORM_DATA_CONTENT_HEADERS$1 = ['content-type', 'content-length'];
  2996. function setFormDataHeaders$1(headers, formHeaders, policy) {
  2997. if (policy !== 'content-only') {
  2998. headers.set(formHeaders);
  2999. return;
  3000. }
  3001. Object.entries(formHeaders).forEach(([key, val]) => {
  3002. if (FORM_DATA_CONTENT_HEADERS$1.includes(key.toLowerCase())) {
  3003. headers.set(key, val);
  3004. }
  3005. });
  3006. }
  3007. // Symbols used to bind a single 'error' listener to a pooled socket and track
  3008. // the request currently owning that socket across keep-alive reuse (issue #10780).
  3009. const kAxiosSocketListener = Symbol('axios.http.socketListener');
  3010. const kAxiosCurrentReq = Symbol('axios.http.currentReq');
  3011. // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
  3012. // can strip them without clobbering a user-supplied agent that happens to be
  3013. // an HttpsProxyAgent.
  3014. const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
  3015. // Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
  3016. // through the same proxy reuse a single agent (and its socket pool). The
  3017. // keyspace is bounded by the set of distinct proxy configs the process uses,
  3018. // so unbounded growth is not a concern in practice.
  3019. const tunnelingAgentCache = new Map();
  3020. const tunnelingAgentCacheUser = new WeakMap();
  3021. function getTunnelingAgent(agentOptions, userHttpsAgent) {
  3022. const key = agentOptions.protocol + '//' + agentOptions.hostname + ':' + (agentOptions.port || '') + '#' + (agentOptions.auth || '');
  3023. const cache = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent) : tunnelingAgentCache;
  3024. let agent = cache.get(key);
  3025. if (agent) return agent;
  3026. // Forward the user's TLS options (custom CA, rejectUnauthorized, client cert,
  3027. // etc.) into the tunneling agent so they apply to the origin TLS upgrade
  3028. // performed after CONNECT. Our proxy fields take precedence on conflict.
  3029. const merged = userHttpsAgent && userHttpsAgent.options ? {
  3030. ...userHttpsAgent.options,
  3031. ...agentOptions
  3032. } : agentOptions;
  3033. agent = new HttpsProxyAgent(merged);
  3034. if (userHttpsAgent && userHttpsAgent.options) {
  3035. const originTLSOptions = {
  3036. ...userHttpsAgent.options
  3037. };
  3038. const callback = agent.callback;
  3039. agent.callback = function axiosTunnelingAgentCallback(req, opts) {
  3040. // HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
  3041. return callback.call(this, req, {
  3042. ...originTLSOptions,
  3043. ...opts
  3044. });
  3045. };
  3046. }
  3047. agent[kAxiosInstalledTunnel] = true;
  3048. cache.set(key, agent);
  3049. return agent;
  3050. }
  3051. const supportedProtocols = platform.protocols.map(protocol => {
  3052. return protocol + ':';
  3053. });
  3054. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  3055. // Decode before composing the `auth` option so credentials such as
  3056. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  3057. // original value for malformed input so a bad encoding never throws.
  3058. const decodeURIComponentSafe$1 = value => {
  3059. if (!utils$1.isString(value)) {
  3060. return value;
  3061. }
  3062. try {
  3063. return decodeURIComponent(value);
  3064. } catch (error) {
  3065. return value;
  3066. }
  3067. };
  3068. const flushOnFinish = (stream, [throttled, flush]) => {
  3069. stream.on('end', flush).on('error', flush);
  3070. return throttled;
  3071. };
  3072. const http2Sessions = new Http2Sessions();
  3073. /**
  3074. * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
  3075. * call them with the options object.
  3076. *
  3077. * @param {Object<string, any>} options - The options object that was passed to the request.
  3078. *
  3079. * @returns {Object<string, any>}
  3080. */
  3081. function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
  3082. if (options.beforeRedirects.proxy) {
  3083. options.beforeRedirects.proxy(options);
  3084. }
  3085. if (options.beforeRedirects.auth) {
  3086. options.beforeRedirects.auth(options);
  3087. }
  3088. if (options.beforeRedirects.sensitiveHeaders) {
  3089. options.beforeRedirects.sensitiveHeaders(options, requestDetails);
  3090. }
  3091. if (options.beforeRedirects.config) {
  3092. options.beforeRedirects.config(options, responseDetails, requestDetails);
  3093. }
  3094. }
  3095. function stripMatchingHeaders(headers, sensitiveSet) {
  3096. if (!headers) {
  3097. return;
  3098. }
  3099. Object.keys(headers).forEach(header => {
  3100. if (sensitiveSet.has(header.toLowerCase())) {
  3101. delete headers[header];
  3102. }
  3103. });
  3104. }
  3105. function isSameOriginRedirect(redirectOptions, requestDetails) {
  3106. if (!requestDetails) {
  3107. return false;
  3108. }
  3109. try {
  3110. return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
  3111. } catch (e) {
  3112. // If origin comparison fails, treat the redirect as unsafe.
  3113. return false;
  3114. }
  3115. }
  3116. /**
  3117. * If the proxy or config afterRedirects functions are defined, call them with the options
  3118. *
  3119. * @param {http.ClientRequestArgs} options
  3120. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  3121. * @param {string} location
  3122. *
  3123. * @returns {http.ClientRequestArgs}
  3124. */
  3125. function setProxy(options, configProxy, location, isRedirect, configHttpsAgent) {
  3126. let proxy = configProxy;
  3127. if (!proxy && proxy !== false) {
  3128. const proxyUrl = getProxyForUrl(location);
  3129. if (proxyUrl) {
  3130. if (!shouldBypassProxy(location)) {
  3131. proxy = new URL(proxyUrl);
  3132. }
  3133. }
  3134. }
  3135. // On redirect re-invocation, strip any stale Proxy-Authorization header carried
  3136. // over from the prior request (e.g. new target no longer uses a proxy, or uses
  3137. // a different proxy). Skip on the initial request so user-supplied headers are
  3138. // preserved. Header names are case-insensitive, so remove every case variant.
  3139. if (isRedirect && options.headers) {
  3140. for (const name of Object.keys(options.headers)) {
  3141. if (name.toLowerCase() === 'proxy-authorization') {
  3142. delete options.headers[name];
  3143. }
  3144. }
  3145. }
  3146. // Strip any tunneling agent we installed for the previous hop so a redirect
  3147. // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
  3148. // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
  3149. // (which won't carry the marker) is left alone.
  3150. if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
  3151. options.agent = undefined;
  3152. }
  3153. if (proxy) {
  3154. // Read proxy fields without traversing the prototype chain. URL instances expose
  3155. // username/password/hostname/host/port/protocol via getters on URL.prototype (so
  3156. // direct reads are shielded), but plain object proxies — and the `auth` field
  3157. // (which URL does not expose) — must be guarded so a polluted Object.prototype
  3158. // (e.g. Object.prototype.auth = { username, password }) cannot inject
  3159. // attacker-controlled credentials into the Proxy-Authorization header or
  3160. // redirect proxying to an attacker-controlled host.
  3161. const isProxyURL = proxy instanceof URL;
  3162. const readProxyField = key => isProxyURL || utils$1.hasOwnProp(proxy, key) ? proxy[key] : undefined;
  3163. const proxyUsername = readProxyField('username');
  3164. const proxyPassword = readProxyField('password');
  3165. let proxyAuth = utils$1.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
  3166. // Basic proxy authorization
  3167. if (proxyUsername) {
  3168. proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
  3169. }
  3170. if (proxyAuth) {
  3171. // Support proxy auth object form. Read sub-fields via own-prop checks so a
  3172. // plain object inheriting from polluted Object.prototype cannot leak creds.
  3173. const authIsObject = typeof proxyAuth === 'object';
  3174. const authUsername = authIsObject && utils$1.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
  3175. const authPassword = authIsObject && utils$1.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
  3176. const validProxyAuth = Boolean(authUsername || authPassword);
  3177. if (validProxyAuth) {
  3178. proxyAuth = (authUsername || '') + ':' + (authPassword || '');
  3179. } else if (authIsObject) {
  3180. throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, {
  3181. proxy
  3182. });
  3183. }
  3184. }
  3185. const targetIsHttps = isHttps.test(options.protocol);
  3186. if (targetIsHttps) {
  3187. // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
  3188. // the origin so the proxy cannot inspect the URL, headers, or body — the
  3189. // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
  3190. // sends Proxy-Authorization on the CONNECT request only, never on the
  3191. // wrapped TLS request, which is why we don't stamp it onto
  3192. // options.headers here. If the user already supplied an HttpsProxyAgent,
  3193. // they own tunneling end-to-end and we leave them alone; otherwise we
  3194. // install our own tunneling agent and forward their TLS options (if any)
  3195. // so a custom httpsAgent for cert pinning / rejectUnauthorized still
  3196. // applies to the origin TLS upgrade.
  3197. if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
  3198. const proxyHost = readProxyField('hostname') || readProxyField('host');
  3199. const proxyPort = readProxyField('port');
  3200. const rawProxyProtocol = readProxyField('protocol');
  3201. const normalizedProtocol = rawProxyProtocol ? rawProxyProtocol.includes(':') ? rawProxyProtocol : `${rawProxyProtocol}:` : 'http:';
  3202. // Bracket IPv6 literals for URL parsing; URL.hostname strips the
  3203. // brackets again on read so the agent receives the raw form.
  3204. const proxyHostForURL = proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[') ? `[${proxyHost}]` : proxyHost;
  3205. const proxyURL = new URL(`${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`);
  3206. const agentOptions = {
  3207. protocol: proxyURL.protocol,
  3208. hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
  3209. port: proxyURL.port,
  3210. auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined
  3211. };
  3212. if (proxyURL.protocol === 'https:') {
  3213. agentOptions.ALPNProtocols = ['http/1.1'];
  3214. }
  3215. const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
  3216. // Set both: `options.agent` is consumed by the native https.request path
  3217. // (maxRedirects === 0); `options.agents.https` is consumed by
  3218. // follow-redirects, which ignores `options.agent` when `options.agents`
  3219. // is present.
  3220. options.agent = tunnelingAgent;
  3221. if (options.agents) {
  3222. options.agents.https = tunnelingAgent;
  3223. }
  3224. }
  3225. } else {
  3226. // Forward-proxy mode for plaintext HTTP targets. The request line carries
  3227. // the absolute URL and the proxy sees everything — acceptable for plain
  3228. // HTTP since the wire was already plaintext.
  3229. if (proxyAuth) {
  3230. const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
  3231. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  3232. }
  3233. // Preserve a user-supplied Host header (case-insensitive) so callers can override
  3234. // the value forwarded to the proxy; otherwise default to the request URL's host.
  3235. let hasUserHostHeader = false;
  3236. for (const name of Object.keys(options.headers)) {
  3237. if (name.toLowerCase() === 'host') {
  3238. hasUserHostHeader = true;
  3239. break;
  3240. }
  3241. }
  3242. if (!hasUserHostHeader) {
  3243. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  3244. }
  3245. const proxyHost = readProxyField('hostname') || readProxyField('host');
  3246. options.hostname = proxyHost;
  3247. // Replace 'host' since options is not a URL object
  3248. options.host = proxyHost;
  3249. options.port = readProxyField('port');
  3250. options.path = location;
  3251. const proxyProtocol = readProxyField('protocol');
  3252. if (proxyProtocol) {
  3253. options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
  3254. }
  3255. }
  3256. }
  3257. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  3258. // Configure proxy for redirected request, passing the original config proxy to apply
  3259. // the exact same logic as if the redirected request was performed by axios directly.
  3260. setProxy(redirectOptions, configProxy, redirectOptions.href, true, configHttpsAgent);
  3261. };
  3262. }
  3263. const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
  3264. // temporary hotfix
  3265. const wrapAsync = asyncExecutor => {
  3266. return new Promise((resolve, reject) => {
  3267. let onDone;
  3268. let isDone;
  3269. const done = (value, isRejected) => {
  3270. if (isDone) return;
  3271. isDone = true;
  3272. onDone && onDone(value, isRejected);
  3273. };
  3274. const _resolve = value => {
  3275. done(value);
  3276. resolve(value);
  3277. };
  3278. const _reject = reason => {
  3279. done(reason, true);
  3280. reject(reason);
  3281. };
  3282. asyncExecutor(_resolve, _reject, onDoneHandler => onDone = onDoneHandler).catch(_reject);
  3283. });
  3284. };
  3285. const resolveFamily = ({
  3286. address,
  3287. family
  3288. }) => {
  3289. if (!utils$1.isString(address)) {
  3290. throw TypeError('address must be a string');
  3291. }
  3292. return {
  3293. address,
  3294. family: family || (address.indexOf('.') < 0 ? 6 : 4)
  3295. };
  3296. };
  3297. const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {
  3298. address,
  3299. family
  3300. });
  3301. const http2Transport = {
  3302. request(options, cb) {
  3303. const authority = options.protocol + '//' + options.hostname + ':' + (options.port || (options.protocol === 'https:' ? 443 : 80));
  3304. const {
  3305. http2Options,
  3306. headers
  3307. } = options;
  3308. const session = http2Sessions.getSession(authority, http2Options);
  3309. const {
  3310. HTTP2_HEADER_SCHEME,
  3311. HTTP2_HEADER_METHOD,
  3312. HTTP2_HEADER_PATH,
  3313. HTTP2_HEADER_STATUS
  3314. } = http2.constants;
  3315. const http2Headers = {
  3316. [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
  3317. [HTTP2_HEADER_METHOD]: options.method,
  3318. [HTTP2_HEADER_PATH]: options.path
  3319. };
  3320. utils$1.forEach(headers, (header, name) => {
  3321. name.charAt(0) !== ':' && (http2Headers[name] = header);
  3322. });
  3323. const req = session.request(http2Headers);
  3324. req.once('response', responseHeaders => {
  3325. const response = req; //duplex
  3326. responseHeaders = Object.assign({}, responseHeaders);
  3327. const status = responseHeaders[HTTP2_HEADER_STATUS];
  3328. delete responseHeaders[HTTP2_HEADER_STATUS];
  3329. response.headers = responseHeaders;
  3330. response.statusCode = +status;
  3331. cb(response);
  3332. });
  3333. return req;
  3334. }
  3335. };
  3336. /*eslint consistent-return:0*/
  3337. var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
  3338. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  3339. // Read config pollution-safely: own properties and members inherited from
  3340. // a non-Object.prototype source (e.g. an Object.create(defaults) template)
  3341. // are honored, but values injected onto a polluted Object.prototype are
  3342. // ignored. All behavior-affecting reads in this adapter go through own()
  3343. // so the protection boundary stays consistent.
  3344. const own = key => utils$1.getSafeProp(config, key);
  3345. const transitional = own('transitional') || transitionalDefaults;
  3346. let data = own('data');
  3347. let lookup = own('lookup');
  3348. let family = own('family');
  3349. let httpVersion = own('httpVersion');
  3350. if (httpVersion === undefined) httpVersion = 1;
  3351. let http2Options = own('http2Options');
  3352. const responseType = own('responseType');
  3353. const responseEncoding = own('responseEncoding');
  3354. const httpAgent = own('httpAgent');
  3355. const httpsAgent = own('httpsAgent');
  3356. const method = own('method').toUpperCase();
  3357. const maxRedirects = own('maxRedirects');
  3358. const maxBodyLength = own('maxBodyLength');
  3359. const maxContentLength = own('maxContentLength');
  3360. const decompress = own('decompress');
  3361. let isDone;
  3362. let rejected = false;
  3363. let req;
  3364. let connectPhaseTimer;
  3365. httpVersion = +httpVersion;
  3366. if (Number.isNaN(httpVersion)) {
  3367. throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
  3368. }
  3369. if (httpVersion !== 1 && httpVersion !== 2) {
  3370. throw TypeError(`Unsupported protocol version '${httpVersion}'`);
  3371. }
  3372. const isHttp2 = httpVersion === 2;
  3373. if (lookup) {
  3374. const _lookup = callbackify(lookup, value => utils$1.isArray(value) ? value : [value]);
  3375. // hotfix to support opt.all option which is required for node 20.x
  3376. lookup = (hostname, opt, cb) => {
  3377. _lookup(hostname, opt, (err, arg0, arg1) => {
  3378. if (err) {
  3379. return cb(err);
  3380. }
  3381. const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
  3382. opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
  3383. });
  3384. };
  3385. }
  3386. const abortEmitter = new events.EventEmitter();
  3387. function abort(reason) {
  3388. try {
  3389. abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
  3390. } catch (err) {
  3391. // ignore emit errors
  3392. }
  3393. }
  3394. function clearConnectPhaseTimer() {
  3395. if (connectPhaseTimer) {
  3396. clearTimeout(connectPhaseTimer);
  3397. connectPhaseTimer = null;
  3398. }
  3399. }
  3400. function createTimeoutError() {
  3401. const configTimeout = own('timeout');
  3402. let timeoutErrorMessage = configTimeout ? 'timeout of ' + configTimeout + 'ms exceeded' : 'timeout exceeded';
  3403. const configTimeoutErrorMessage = own('timeoutErrorMessage');
  3404. if (configTimeoutErrorMessage) {
  3405. timeoutErrorMessage = configTimeoutErrorMessage;
  3406. }
  3407. return new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, req);
  3408. }
  3409. abortEmitter.once('abort', reject);
  3410. const onFinished = () => {
  3411. clearConnectPhaseTimer();
  3412. if (config.cancelToken) {
  3413. config.cancelToken.unsubscribe(abort);
  3414. }
  3415. if (config.signal) {
  3416. config.signal.removeEventListener('abort', abort);
  3417. }
  3418. abortEmitter.removeAllListeners();
  3419. };
  3420. if (config.cancelToken || config.signal) {
  3421. config.cancelToken && config.cancelToken.subscribe(abort);
  3422. if (config.signal) {
  3423. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  3424. }
  3425. }
  3426. onDone((response, isRejected) => {
  3427. isDone = true;
  3428. clearConnectPhaseTimer();
  3429. if (isRejected) {
  3430. rejected = true;
  3431. onFinished();
  3432. return;
  3433. }
  3434. const {
  3435. data
  3436. } = response;
  3437. if (data instanceof stream.Readable || data instanceof stream.Duplex) {
  3438. const offListeners = stream.finished(data, () => {
  3439. offListeners();
  3440. onFinished();
  3441. });
  3442. } else {
  3443. onFinished();
  3444. }
  3445. });
  3446. // Parse url
  3447. const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
  3448. const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined);
  3449. const protocol = parsed.protocol || supportedProtocols[0];
  3450. if (protocol === 'data:') {
  3451. // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
  3452. if (maxContentLength > -1) {
  3453. // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
  3454. const dataUrl = String(own('url') || fullPath || '');
  3455. const estimated = estimateDataURLDecodedBytes(dataUrl);
  3456. if (estimated > maxContentLength) {
  3457. return reject(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config));
  3458. }
  3459. }
  3460. let convertedData;
  3461. if (method !== 'GET') {
  3462. return settle(resolve, reject, {
  3463. status: 405,
  3464. statusText: 'method not allowed',
  3465. headers: {},
  3466. config
  3467. });
  3468. }
  3469. try {
  3470. convertedData = fromDataURI(own('url'), responseType === 'blob', {
  3471. Blob: config.env && config.env.Blob
  3472. });
  3473. } catch (err) {
  3474. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  3475. }
  3476. if (responseType === 'text') {
  3477. convertedData = convertedData.toString(responseEncoding);
  3478. if (!responseEncoding || responseEncoding === 'utf8') {
  3479. convertedData = utils$1.stripBOM(convertedData);
  3480. }
  3481. } else if (responseType === 'stream') {
  3482. convertedData = stream.Readable.from(convertedData);
  3483. }
  3484. return settle(resolve, reject, {
  3485. data: convertedData,
  3486. status: 200,
  3487. statusText: 'OK',
  3488. headers: new AxiosHeaders(),
  3489. config
  3490. });
  3491. }
  3492. if (supportedProtocols.indexOf(protocol) === -1) {
  3493. return reject(new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config));
  3494. }
  3495. const headers = AxiosHeaders.from(config.headers).normalize();
  3496. // Set User-Agent (required by some servers)
  3497. // See https://github.com/axios/axios/issues/69
  3498. // User-Agent is specified; handle case where no UA header is desired
  3499. // Only set header if it hasn't been set in config
  3500. headers.set('User-Agent', 'axios/' + VERSION, false);
  3501. const {
  3502. onUploadProgress,
  3503. onDownloadProgress
  3504. } = config;
  3505. const maxRate = config.maxRate;
  3506. let maxUploadRate = undefined;
  3507. let maxDownloadRate = undefined;
  3508. // support for spec compliant FormData objects
  3509. if (utils$1.isSpecCompliantForm(data)) {
  3510. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  3511. data = formDataToStream(data, formHeaders => {
  3512. headers.set(formHeaders);
  3513. }, {
  3514. tag: `axios-${VERSION}-boundary`,
  3515. boundary: userBoundary && userBoundary[1] || undefined
  3516. });
  3517. // support for https://www.npmjs.com/package/form-data api
  3518. } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders) && data.getHeaders !== Object.prototype.getHeaders) {
  3519. setFormDataHeaders$1(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  3520. if (!headers.hasContentLength()) {
  3521. try {
  3522. const knownLength = await util.promisify(data.getLength).call(data);
  3523. Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
  3524. /*eslint no-empty:0*/
  3525. } catch (e) {}
  3526. }
  3527. } else if (utils$1.isBlob(data) || utils$1.isFile(data)) {
  3528. data.size && headers.setContentType(data.type || 'application/octet-stream');
  3529. headers.setContentLength(data.size || 0);
  3530. data = stream.Readable.from(readBlob(data));
  3531. } else if (data && !utils$1.isStream(data)) {
  3532. if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) {
  3533. data = Buffer.from(new Uint8Array(data));
  3534. } else if (utils$1.isString(data)) {
  3535. data = Buffer.from(data, 'utf-8');
  3536. } else {
  3537. return reject(new AxiosError('Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', AxiosError.ERR_BAD_REQUEST, config));
  3538. }
  3539. // Add Content-Length header if data exists
  3540. headers.setContentLength(data.length, false);
  3541. if (maxBodyLength > -1 && data.length > maxBodyLength) {
  3542. return reject(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config));
  3543. }
  3544. }
  3545. const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
  3546. if (utils$1.isArray(maxRate)) {
  3547. maxUploadRate = maxRate[0];
  3548. maxDownloadRate = maxRate[1];
  3549. } else {
  3550. maxUploadRate = maxDownloadRate = maxRate;
  3551. }
  3552. if (data && (onUploadProgress || maxUploadRate)) {
  3553. if (!utils$1.isStream(data)) {
  3554. data = stream.Readable.from(data, {
  3555. objectMode: false
  3556. });
  3557. }
  3558. data = stream.pipeline([data, new AxiosTransformStream({
  3559. maxRate: utils$1.toFiniteNumber(maxUploadRate)
  3560. })], utils$1.noop);
  3561. onUploadProgress && data.on('progress', flushOnFinish(data, progressEventDecorator(contentLength, progressEventReducer(asyncDecorator(onUploadProgress), false, 3))));
  3562. }
  3563. // HTTP basic authentication
  3564. let auth = undefined;
  3565. const configAuth = own('auth');
  3566. if (configAuth) {
  3567. const username = utils$1.getSafeProp(configAuth, 'username') || '';
  3568. const password = utils$1.getSafeProp(configAuth, 'password') || '';
  3569. auth = username + ':' + password;
  3570. }
  3571. if (!auth && (parsed.username || parsed.password)) {
  3572. const urlUsername = decodeURIComponentSafe$1(parsed.username);
  3573. const urlPassword = decodeURIComponentSafe$1(parsed.password);
  3574. auth = urlUsername + ':' + urlPassword;
  3575. }
  3576. auth && headers.delete('authorization');
  3577. let path$1;
  3578. try {
  3579. path$1 = buildURL(parsed.pathname + parsed.search, own('params'), own('paramsSerializer')).replace(/^\?/, '');
  3580. } catch (err) {
  3581. const customErr = new Error(err.message);
  3582. customErr.config = config;
  3583. customErr.url = own('url');
  3584. customErr.exists = true;
  3585. return reject(customErr);
  3586. }
  3587. headers.set('Accept-Encoding', utils$1.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') && transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING, false);
  3588. // Null-prototype to block prototype pollution gadgets on properties read
  3589. // directly by Node's http.request (e.g. insecureHTTPParser, lookup).
  3590. const options = Object.assign(Object.create(null), {
  3591. path: path$1,
  3592. method: method,
  3593. headers: toByteStringHeaderObject(headers),
  3594. agents: {
  3595. http: httpAgent,
  3596. https: httpsAgent
  3597. },
  3598. auth,
  3599. protocol,
  3600. family,
  3601. beforeRedirect: dispatchBeforeRedirect,
  3602. beforeRedirects: Object.create(null),
  3603. http2Options
  3604. });
  3605. // cacheable-lookup integration hotfix
  3606. !utils$1.isUndefined(lookup) && (options.lookup = lookup);
  3607. const socketPath = own('socketPath');
  3608. if (socketPath) {
  3609. if (typeof socketPath !== 'string') {
  3610. return reject(new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config));
  3611. }
  3612. const allowedSocketPaths = own('allowedSocketPaths');
  3613. if (allowedSocketPaths != null) {
  3614. const allowed = Array.isArray(allowedSocketPaths) ? allowedSocketPaths : [allowedSocketPaths];
  3615. const resolvedSocket = path.resolve(socketPath);
  3616. const isAllowed = allowed.some(entry => typeof entry === 'string' && path.resolve(entry) === resolvedSocket);
  3617. if (!isAllowed) {
  3618. return reject(new AxiosError(`socketPath "${socketPath}" is not permitted by allowedSocketPaths`, AxiosError.ERR_BAD_OPTION_VALUE, config));
  3619. }
  3620. }
  3621. options.socketPath = socketPath;
  3622. } else {
  3623. options.hostname = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
  3624. options.port = parsed.port;
  3625. setProxy(options, own('proxy'), protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, false, httpsAgent);
  3626. }
  3627. let transport;
  3628. let isNativeTransport = false;
  3629. // True only for the follow-redirects transport, which applies
  3630. // options.maxBodyLength itself. Every other transport (http2, native
  3631. // http/https, a user-supplied custom transport) needs the explicit
  3632. // byte-counting pipeline below to enforce maxBodyLength on streamed uploads.
  3633. let transportEnforcesMaxBodyLength = false;
  3634. const isHttpsRequest = isHttps.test(options.protocol);
  3635. // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
  3636. // HTTPS target.
  3637. if (options.agent == null) {
  3638. options.agent = isHttpsRequest ? httpsAgent : httpAgent;
  3639. }
  3640. if (isHttp2) {
  3641. transport = http2Transport;
  3642. } else {
  3643. const configTransport = own('transport');
  3644. if (configTransport) {
  3645. transport = configTransport;
  3646. } else if (maxRedirects === 0) {
  3647. transport = isHttpsRequest ? https : http;
  3648. isNativeTransport = true;
  3649. } else {
  3650. transportEnforcesMaxBodyLength = true;
  3651. options.sensitiveHeaders = [];
  3652. if (maxRedirects) {
  3653. options.maxRedirects = maxRedirects;
  3654. }
  3655. const configBeforeRedirect = own('beforeRedirect');
  3656. if (configBeforeRedirect) {
  3657. options.beforeRedirects.config = configBeforeRedirect;
  3658. }
  3659. if (auth) {
  3660. // Restore HTTP Basic credentials on same-origin redirects only.
  3661. // follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
  3662. // cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
  3663. // and is preserved by deliberately not restoring on origin change.
  3664. const requestOrigin = parsed.origin;
  3665. const authToRestore = auth;
  3666. options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
  3667. try {
  3668. if (new URL(redirectOptions.href).origin === requestOrigin) {
  3669. redirectOptions.auth = authToRestore;
  3670. }
  3671. } catch (e) {
  3672. // ignore malformed URL: leaving auth stripped is fail-safe
  3673. }
  3674. };
  3675. }
  3676. const sensitiveHeaders = own('sensitiveHeaders');
  3677. if (sensitiveHeaders != null) {
  3678. if (!utils$1.isArray(sensitiveHeaders)) {
  3679. return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
  3680. }
  3681. const sensitiveSet = new Set();
  3682. for (const header of sensitiveHeaders) {
  3683. if (!utils$1.isString(header)) {
  3684. return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
  3685. }
  3686. sensitiveSet.add(header.toLowerCase());
  3687. }
  3688. if (sensitiveSet.size) {
  3689. options.sensitiveHeaders = Array.from(sensitiveSet);
  3690. options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(redirectOptions, requestDetails) {
  3691. if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
  3692. stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
  3693. }
  3694. };
  3695. }
  3696. }
  3697. transport = isHttpsRequest ? httpsFollow : httpFollow;
  3698. }
  3699. }
  3700. if (maxBodyLength > -1) {
  3701. options.maxBodyLength = maxBodyLength;
  3702. } else {
  3703. // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
  3704. options.maxBodyLength = Infinity;
  3705. }
  3706. // Always set an explicit own value so a polluted
  3707. // Object.prototype.insecureHTTPParser cannot enable the lenient parser
  3708. // through Node's internal options copy
  3709. options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
  3710. // Create the request
  3711. req = transport.request(options, function handleResponse(res) {
  3712. clearConnectPhaseTimer();
  3713. if (req.destroyed) return;
  3714. const streams = [res];
  3715. const responseLength = utils$1.toFiniteNumber(res.headers['content-length']);
  3716. if (onDownloadProgress || maxDownloadRate) {
  3717. const transformStream = new AxiosTransformStream({
  3718. maxRate: utils$1.toFiniteNumber(maxDownloadRate)
  3719. });
  3720. onDownloadProgress && transformStream.on('progress', flushOnFinish(transformStream, progressEventDecorator(responseLength, progressEventReducer(asyncDecorator(onDownloadProgress), true, 3))));
  3721. streams.push(transformStream);
  3722. }
  3723. // decompress the response body transparently if required
  3724. let responseStream = res;
  3725. // return the last request in case of redirects
  3726. const lastRequest = res.req || req;
  3727. // if decompress disabled we should not decompress
  3728. if (decompress !== false && res.headers['content-encoding']) {
  3729. // if no content, but headers still say that it is encoded,
  3730. // remove the header not confuse downstream operations
  3731. if (method === 'HEAD' || res.statusCode === 204) {
  3732. delete res.headers['content-encoding'];
  3733. }
  3734. switch ((res.headers['content-encoding'] || '').toLowerCase()) {
  3735. /*eslint default-case:0*/
  3736. case 'gzip':
  3737. case 'x-gzip':
  3738. case 'compress':
  3739. case 'x-compress':
  3740. // add the unzipper to the body stream processing pipeline
  3741. streams.push(zlib.createUnzip(zlibOptions));
  3742. // remove the content-encoding in order to not confuse downstream operations
  3743. delete res.headers['content-encoding'];
  3744. break;
  3745. case 'deflate':
  3746. streams.push(new ZlibHeaderTransformStream());
  3747. // add the unzipper to the body stream processing pipeline
  3748. streams.push(zlib.createUnzip(zlibOptions));
  3749. // remove the content-encoding in order to not confuse downstream operations
  3750. delete res.headers['content-encoding'];
  3751. break;
  3752. case 'br':
  3753. if (isBrotliSupported) {
  3754. streams.push(zlib.createBrotliDecompress(brotliOptions));
  3755. delete res.headers['content-encoding'];
  3756. }
  3757. break;
  3758. case 'zstd':
  3759. if (isZstdSupported) {
  3760. streams.push(zlib.createZstdDecompress(zstdOptions));
  3761. delete res.headers['content-encoding'];
  3762. }
  3763. break;
  3764. }
  3765. }
  3766. responseStream = streams.length > 1 ? stream.pipeline(streams, utils$1.noop) : streams[0];
  3767. const response = {
  3768. status: res.statusCode,
  3769. statusText: res.statusMessage,
  3770. headers: new AxiosHeaders(res.headers),
  3771. config,
  3772. request: lastRequest
  3773. };
  3774. if (responseType === 'stream') {
  3775. // Enforce maxContentLength on streamed responses; previously this
  3776. // was applied only to buffered responses.
  3777. if (maxContentLength > -1) {
  3778. const limit = maxContentLength;
  3779. const source = responseStream;
  3780. async function* enforceMaxContentLength() {
  3781. let totalResponseBytes = 0;
  3782. for await (const chunk of source) {
  3783. totalResponseBytes += chunk.length;
  3784. if (totalResponseBytes > limit) {
  3785. throw new AxiosError('maxContentLength size of ' + limit + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest);
  3786. }
  3787. yield chunk;
  3788. }
  3789. }
  3790. responseStream = stream.Readable.from(enforceMaxContentLength(), {
  3791. objectMode: false
  3792. });
  3793. }
  3794. response.data = responseStream;
  3795. settle(resolve, reject, response);
  3796. } else {
  3797. const responseBuffer = [];
  3798. let totalResponseBytes = 0;
  3799. responseStream.on('data', function handleStreamData(chunk) {
  3800. responseBuffer.push(chunk);
  3801. totalResponseBytes += chunk.length;
  3802. // make sure the content length is not over the maxContentLength if specified
  3803. if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
  3804. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  3805. rejected = true;
  3806. responseStream.destroy();
  3807. abort(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
  3808. }
  3809. });
  3810. responseStream.on('aborted', function handlerStreamAborted() {
  3811. if (rejected) {
  3812. return;
  3813. }
  3814. const err = new AxiosError('stream has been aborted', AxiosError.ERR_BAD_RESPONSE, config, lastRequest, response);
  3815. responseStream.destroy(err);
  3816. reject(err);
  3817. });
  3818. responseStream.on('error', function handleStreamError(err) {
  3819. if (rejected) return;
  3820. reject(AxiosError.from(err, null, config, lastRequest, response));
  3821. });
  3822. responseStream.on('end', function handleStreamEnd() {
  3823. try {
  3824. let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  3825. if (responseType !== 'arraybuffer') {
  3826. responseData = responseData.toString(responseEncoding);
  3827. if (!responseEncoding || responseEncoding === 'utf8') {
  3828. responseData = utils$1.stripBOM(responseData);
  3829. }
  3830. }
  3831. response.data = responseData;
  3832. } catch (err) {
  3833. return reject(AxiosError.from(err, null, config, response.request, response));
  3834. }
  3835. settle(resolve, reject, response);
  3836. });
  3837. }
  3838. abortEmitter.once('abort', err => {
  3839. if (!responseStream.destroyed) {
  3840. responseStream.emit('error', err);
  3841. responseStream.destroy();
  3842. }
  3843. });
  3844. });
  3845. abortEmitter.once('abort', err => {
  3846. if (req.close) {
  3847. req.close();
  3848. } else {
  3849. req.destroy(err);
  3850. }
  3851. });
  3852. // Handle errors
  3853. req.on('error', function handleRequestError(err) {
  3854. reject(AxiosError.from(err, null, config, req));
  3855. });
  3856. // set tcp keep alive to prevent drop connection by peer
  3857. // Track every socket bound to this outer RedirectableRequest so a single
  3858. // 'close' listener can release ownership on all of them. follow-redirects
  3859. // re-emits the 'socket' event for each hop's native request onto the same
  3860. // outer request, so attaching per-request listeners inside this handler
  3861. // would accumulate across hops and trigger MaxListenersExceededWarning at
  3862. // >= 11 redirects. Clearing only the last-bound socket would leave stale
  3863. // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
  3864. // pool, causing an idle-pool 'error' to be attributed to a closed req.
  3865. const boundSockets = new Set();
  3866. req.on('socket', function handleRequestSocket(socket) {
  3867. // default interval of sending ack packet is 1 minute
  3868. socket.setKeepAlive(true, 1000 * 60);
  3869. // Install a single 'error' listener per socket (not per request) to avoid
  3870. // accumulating listeners on pooled keep-alive sockets that get reassigned
  3871. // to new requests before the previous request's 'close' fires (issue #10780).
  3872. // The listener is bound to the socket's currently-active request via a
  3873. // symbol, which is swapped as the socket is reassigned.
  3874. if (!socket[kAxiosSocketListener]) {
  3875. socket.on('error', function handleSocketError(err) {
  3876. const current = socket[kAxiosCurrentReq];
  3877. if (current && !current.destroyed) {
  3878. current.destroy(err);
  3879. }
  3880. });
  3881. socket[kAxiosSocketListener] = true;
  3882. }
  3883. socket[kAxiosCurrentReq] = req;
  3884. boundSockets.add(socket);
  3885. });
  3886. req.once('close', function clearCurrentReq() {
  3887. clearConnectPhaseTimer();
  3888. for (const socket of boundSockets) {
  3889. if (socket[kAxiosCurrentReq] === req) {
  3890. socket[kAxiosCurrentReq] = null;
  3891. }
  3892. }
  3893. boundSockets.clear();
  3894. });
  3895. // Handle request timeout
  3896. if (own('timeout')) {
  3897. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  3898. const timeout = parseInt(own('timeout'), 10);
  3899. if (Number.isNaN(timeout)) {
  3900. abort(new AxiosError('error trying to parse `config.timeout` to int', AxiosError.ERR_BAD_OPTION_VALUE, config, req));
  3901. return;
  3902. }
  3903. const handleTimeout = function handleTimeout() {
  3904. if (isDone) return;
  3905. abort(createTimeoutError());
  3906. };
  3907. if (isNativeTransport && timeout > 0) {
  3908. // Native ClientRequest#setTimeout starts from the socket lifecycle and
  3909. // may not fire while TCP connect is still pending. Mirror the
  3910. // follow-redirects wall-clock timer for the maxRedirects === 0 path.
  3911. connectPhaseTimer = setTimeout(handleTimeout, timeout);
  3912. }
  3913. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  3914. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  3915. // 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.
  3916. // And then these socket which be hang up will devouring CPU little by little.
  3917. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  3918. req.setTimeout(timeout, handleTimeout);
  3919. } else {
  3920. // explicitly reset the socket timeout value for a possible `keep-alive` request
  3921. req.setTimeout(0);
  3922. }
  3923. // Send the request
  3924. if (utils$1.isStream(data)) {
  3925. let ended = false;
  3926. let errored = false;
  3927. data.on('end', () => {
  3928. ended = true;
  3929. });
  3930. data.once('error', err => {
  3931. errored = true;
  3932. req.destroy(err);
  3933. });
  3934. data.on('close', () => {
  3935. if (!ended && !errored) {
  3936. abort(new CanceledError('Request stream has been aborted', config, req));
  3937. }
  3938. });
  3939. // Enforce maxBodyLength for streamed uploads on every transport that
  3940. // does not apply options.maxBodyLength itself (native http/https, http2,
  3941. // and user-supplied custom transports). The follow-redirects transport
  3942. // enforces it on the redirected HTTP/1 path.
  3943. let uploadStream = data;
  3944. if (maxBodyLength > -1 && !transportEnforcesMaxBodyLength) {
  3945. const limit = maxBodyLength;
  3946. let bytesSent = 0;
  3947. uploadStream = stream.pipeline([data, new stream.Transform({
  3948. transform(chunk, _enc, cb) {
  3949. bytesSent += chunk.length;
  3950. if (bytesSent > limit) {
  3951. return cb(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, req));
  3952. }
  3953. cb(null, chunk);
  3954. }
  3955. })], utils$1.noop);
  3956. uploadStream.on('error', err => {
  3957. if (!req.destroyed) req.destroy(err);
  3958. });
  3959. }
  3960. uploadStream.pipe(req);
  3961. } else {
  3962. data && req.write(data);
  3963. req.end();
  3964. }
  3965. });
  3966. };
  3967. var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => url => {
  3968. url = new URL(url, platform.origin);
  3969. return origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port);
  3970. })(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
  3971. var cookies = platform.hasStandardBrowserEnv ?
  3972. // Standard browser envs support document.cookie
  3973. {
  3974. write(name, value, expires, path, domain, secure, sameSite) {
  3975. if (typeof document === 'undefined') return;
  3976. const cookie = [`${name}=${encodeURIComponent(value)}`];
  3977. if (utils$1.isNumber(expires)) {
  3978. cookie.push(`expires=${new Date(expires).toUTCString()}`);
  3979. }
  3980. if (utils$1.isString(path)) {
  3981. cookie.push(`path=${path}`);
  3982. }
  3983. if (utils$1.isString(domain)) {
  3984. cookie.push(`domain=${domain}`);
  3985. }
  3986. if (secure === true) {
  3987. cookie.push('secure');
  3988. }
  3989. if (utils$1.isString(sameSite)) {
  3990. cookie.push(`SameSite=${sameSite}`);
  3991. }
  3992. document.cookie = cookie.join('; ');
  3993. },
  3994. read(name) {
  3995. if (typeof document === 'undefined') return null;
  3996. // Match name=value by splitting on the semicolon separator instead of building a
  3997. // RegExp from `name` — interpolating an unescaped string into a RegExp would let
  3998. // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
  3999. // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
  4000. // "; ", so ignore optional whitespace before each cookie name.
  4001. const cookies = document.cookie.split(';');
  4002. for (let i = 0; i < cookies.length; i++) {
  4003. const cookie = cookies[i].replace(/^\s+/, '');
  4004. const eq = cookie.indexOf('=');
  4005. if (eq !== -1 && cookie.slice(0, eq) === name) {
  4006. return decodeURIComponent(cookie.slice(eq + 1));
  4007. }
  4008. }
  4009. return null;
  4010. },
  4011. remove(name) {
  4012. this.write(name, '', Date.now() - 86400000, '/');
  4013. }
  4014. } :
  4015. // Non-standard browser env (web workers, react-native) lack needed support.
  4016. {
  4017. write() {},
  4018. read() {
  4019. return null;
  4020. },
  4021. remove() {}
  4022. };
  4023. const headersToObject = thing => thing instanceof AxiosHeaders ? {
  4024. ...thing
  4025. } : thing;
  4026. /**
  4027. * Config-specific merge-function which creates a new config-object
  4028. * by merging two configuration objects together.
  4029. *
  4030. * @param {Object} config1
  4031. * @param {Object} config2
  4032. *
  4033. * @returns {Object} New object resulting from merging config2 to config1
  4034. */
  4035. function mergeConfig(config1, config2) {
  4036. // eslint-disable-next-line no-param-reassign
  4037. config2 = config2 || {};
  4038. // Use a null-prototype object so that downstream reads such as `config.auth`
  4039. // or `config.baseURL` cannot inherit polluted values from Object.prototype.
  4040. // `hasOwnProperty` is restored as a non-enumerable own slot to preserve
  4041. // ergonomics for user code that relies on it.
  4042. const config = Object.create(null);
  4043. Object.defineProperty(config, 'hasOwnProperty', {
  4044. // Null-proto descriptor so a polluted Object.prototype.get cannot turn
  4045. // this data descriptor into an accessor descriptor on the way in.
  4046. __proto__: null,
  4047. value: Object.prototype.hasOwnProperty,
  4048. enumerable: false,
  4049. writable: true,
  4050. configurable: true
  4051. });
  4052. function getMergedValue(target, source, prop, caseless) {
  4053. if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
  4054. return utils$1.merge.call({
  4055. caseless
  4056. }, target, source);
  4057. } else if (utils$1.isPlainObject(source)) {
  4058. return utils$1.merge({}, source);
  4059. } else if (utils$1.isArray(source)) {
  4060. return source.slice();
  4061. }
  4062. return source;
  4063. }
  4064. function mergeDeepProperties(a, b, prop, caseless) {
  4065. if (!utils$1.isUndefined(b)) {
  4066. return getMergedValue(a, b, prop, caseless);
  4067. } else if (!utils$1.isUndefined(a)) {
  4068. return getMergedValue(undefined, a, prop, caseless);
  4069. }
  4070. }
  4071. // eslint-disable-next-line consistent-return
  4072. function valueFromConfig2(a, b) {
  4073. if (!utils$1.isUndefined(b)) {
  4074. return getMergedValue(undefined, b);
  4075. }
  4076. }
  4077. // eslint-disable-next-line consistent-return
  4078. function defaultToConfig2(a, b) {
  4079. if (!utils$1.isUndefined(b)) {
  4080. return getMergedValue(undefined, b);
  4081. } else if (!utils$1.isUndefined(a)) {
  4082. return getMergedValue(undefined, a);
  4083. }
  4084. }
  4085. function getMergedTransitionalOption(prop) {
  4086. const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
  4087. if (!utils$1.isUndefined(transitional2)) {
  4088. if (utils$1.isPlainObject(transitional2)) {
  4089. if (utils$1.hasOwnProp(transitional2, prop)) {
  4090. return transitional2[prop];
  4091. }
  4092. } else {
  4093. return undefined;
  4094. }
  4095. }
  4096. const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
  4097. if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
  4098. return transitional1[prop];
  4099. }
  4100. return undefined;
  4101. }
  4102. // eslint-disable-next-line consistent-return
  4103. function mergeDirectKeys(a, b, prop) {
  4104. if (utils$1.hasOwnProp(config2, prop)) {
  4105. return getMergedValue(a, b);
  4106. } else if (utils$1.hasOwnProp(config1, prop)) {
  4107. return getMergedValue(undefined, a);
  4108. }
  4109. }
  4110. const mergeMap = {
  4111. url: valueFromConfig2,
  4112. method: valueFromConfig2,
  4113. data: valueFromConfig2,
  4114. baseURL: defaultToConfig2,
  4115. transformRequest: defaultToConfig2,
  4116. transformResponse: defaultToConfig2,
  4117. paramsSerializer: defaultToConfig2,
  4118. timeout: defaultToConfig2,
  4119. timeoutMessage: defaultToConfig2,
  4120. withCredentials: defaultToConfig2,
  4121. withXSRFToken: defaultToConfig2,
  4122. adapter: defaultToConfig2,
  4123. responseType: defaultToConfig2,
  4124. xsrfCookieName: defaultToConfig2,
  4125. xsrfHeaderName: defaultToConfig2,
  4126. onUploadProgress: defaultToConfig2,
  4127. onDownloadProgress: defaultToConfig2,
  4128. decompress: defaultToConfig2,
  4129. maxContentLength: defaultToConfig2,
  4130. maxBodyLength: defaultToConfig2,
  4131. beforeRedirect: defaultToConfig2,
  4132. transport: defaultToConfig2,
  4133. httpAgent: defaultToConfig2,
  4134. httpsAgent: defaultToConfig2,
  4135. cancelToken: defaultToConfig2,
  4136. socketPath: defaultToConfig2,
  4137. allowedSocketPaths: defaultToConfig2,
  4138. responseEncoding: defaultToConfig2,
  4139. validateStatus: mergeDirectKeys,
  4140. headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
  4141. };
  4142. utils$1.forEach(Object.keys({
  4143. ...config1,
  4144. ...config2
  4145. }), function computeConfigValue(prop) {
  4146. if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
  4147. const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
  4148. const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
  4149. const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
  4150. const configValue = merge(a, b, prop);
  4151. utils$1.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue);
  4152. });
  4153. if (utils$1.hasOwnProp(config2, 'validateStatus') && utils$1.isUndefined(config2.validateStatus) && getMergedTransitionalOption('validateStatusUndefinedResolves') === false) {
  4154. if (utils$1.hasOwnProp(config1, 'validateStatus')) {
  4155. config.validateStatus = getMergedValue(undefined, config1.validateStatus);
  4156. } else {
  4157. delete config.validateStatus;
  4158. }
  4159. }
  4160. return config;
  4161. }
  4162. const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
  4163. function setFormDataHeaders(headers, formHeaders, policy) {
  4164. if (policy !== 'content-only') {
  4165. headers.set(formHeaders);
  4166. return;
  4167. }
  4168. Object.entries(formHeaders).forEach(([key, val]) => {
  4169. if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
  4170. headers.set(key, val);
  4171. }
  4172. });
  4173. }
  4174. /**
  4175. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  4176. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  4177. *
  4178. * @param {string} str The string to encode
  4179. *
  4180. * @returns {string} UTF-8 bytes as a Latin-1 string
  4181. */
  4182. const encodeUTF8$1 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  4183. function resolveConfig(config) {
  4184. const newConfig = mergeConfig({}, config);
  4185. // Read only own properties to prevent prototype pollution gadgets
  4186. // (e.g. Object.prototype.baseURL = 'https://evil.com').
  4187. const own = key => utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined;
  4188. const data = own('data');
  4189. let withXSRFToken = own('withXSRFToken');
  4190. const xsrfHeaderName = own('xsrfHeaderName');
  4191. const xsrfCookieName = own('xsrfCookieName');
  4192. let headers = own('headers');
  4193. const auth = own('auth');
  4194. const baseURL = own('baseURL');
  4195. const allowAbsoluteUrls = own('allowAbsoluteUrls');
  4196. const url = own('url');
  4197. newConfig.headers = headers = AxiosHeaders.from(headers);
  4198. newConfig.url = buildURL(buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), own('params'), own('paramsSerializer'));
  4199. // HTTP basic authentication
  4200. if (auth) {
  4201. const username = utils$1.getSafeProp(auth, 'username') || '';
  4202. const password = utils$1.getSafeProp(auth, 'password') || '';
  4203. headers.set('Authorization', 'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : '')));
  4204. }
  4205. if (utils$1.isFormData(data)) {
  4206. if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
  4207. headers.setContentType(undefined); // browser/web worker/RN handles it
  4208. } else if (utils$1.isFunction(data.getHeaders)) {
  4209. // Node.js FormData (like form-data package)
  4210. setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  4211. }
  4212. }
  4213. // Add xsrf header
  4214. // This is only done if running in a standard browser environment.
  4215. // Specifically not if we're in a web worker, or react-native.
  4216. if (platform.hasStandardBrowserEnv) {
  4217. if (utils$1.isFunction(withXSRFToken)) {
  4218. withXSRFToken = withXSRFToken(newConfig);
  4219. }
  4220. // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
  4221. // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
  4222. // the XSRF token cross-origin.
  4223. const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
  4224. if (shouldSendXSRF) {
  4225. const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
  4226. if (xsrfValue) {
  4227. headers.set(xsrfHeaderName, xsrfValue);
  4228. }
  4229. }
  4230. }
  4231. return newConfig;
  4232. }
  4233. const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
  4234. var xhrAdapter = isXHRAdapterSupported && function (config) {
  4235. return new Promise(function dispatchXhrRequest(resolve, reject) {
  4236. const _config = resolveConfig(config);
  4237. let requestData = _config.data;
  4238. const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
  4239. let {
  4240. responseType,
  4241. onUploadProgress,
  4242. onDownloadProgress
  4243. } = _config;
  4244. let onCanceled;
  4245. let uploadThrottled, downloadThrottled;
  4246. let flushUpload, flushDownload;
  4247. function done() {
  4248. flushUpload && flushUpload(); // flush events
  4249. flushDownload && flushDownload(); // flush events
  4250. _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
  4251. _config.signal && _config.signal.removeEventListener('abort', onCanceled);
  4252. }
  4253. let request = new XMLHttpRequest();
  4254. request.open(_config.method.toUpperCase(), _config.url, true);
  4255. // Set the request timeout in MS
  4256. request.timeout = _config.timeout;
  4257. function onloadend() {
  4258. if (!request) {
  4259. return;
  4260. }
  4261. // Prepare the response
  4262. const responseHeaders = AxiosHeaders.from('getAllResponseHeaders' in request && request.getAllResponseHeaders());
  4263. const responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response;
  4264. const response = {
  4265. data: responseData,
  4266. status: request.status,
  4267. statusText: request.statusText,
  4268. headers: responseHeaders,
  4269. config,
  4270. request
  4271. };
  4272. settle(function _resolve(value) {
  4273. resolve(value);
  4274. done();
  4275. }, function _reject(err) {
  4276. reject(err);
  4277. done();
  4278. }, response);
  4279. // Clean up request
  4280. request = null;
  4281. }
  4282. if ('onloadend' in request) {
  4283. // Use onloadend if available
  4284. request.onloadend = onloadend;
  4285. } else {
  4286. // Listen for ready state to emulate onloadend
  4287. request.onreadystatechange = function handleLoad() {
  4288. if (!request || request.readyState !== 4) {
  4289. return;
  4290. }
  4291. // The request errored out and we didn't get a response, this will be
  4292. // handled by onerror instead
  4293. // With one exception: request that using file: protocol, most browsers
  4294. // will return status as 0 even though it's a successful request
  4295. if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith('file:'))) {
  4296. return;
  4297. }
  4298. // readystate handler is calling before onerror or ontimeout handlers,
  4299. // so we should call onloadend on the next 'tick'
  4300. setTimeout(onloadend);
  4301. };
  4302. }
  4303. // Handle browser request cancellation (as opposed to a manual cancellation)
  4304. request.onabort = function handleAbort() {
  4305. if (!request) {
  4306. return;
  4307. }
  4308. reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
  4309. done();
  4310. // Clean up request
  4311. request = null;
  4312. };
  4313. // Handle low level network errors
  4314. request.onerror = function handleError(event) {
  4315. // Browsers deliver a ProgressEvent in XHR onerror
  4316. // (message may be empty; when present, surface it)
  4317. // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
  4318. const msg = event && event.message ? event.message : 'Network Error';
  4319. const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
  4320. // attach the underlying event for consumers who want details
  4321. err.event = event || null;
  4322. reject(err);
  4323. done();
  4324. request = null;
  4325. };
  4326. // Handle timeout
  4327. request.ontimeout = function handleTimeout() {
  4328. let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
  4329. const transitional = _config.transitional || transitionalDefaults;
  4330. if (_config.timeoutErrorMessage) {
  4331. timeoutErrorMessage = _config.timeoutErrorMessage;
  4332. }
  4333. reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request));
  4334. done();
  4335. // Clean up request
  4336. request = null;
  4337. };
  4338. // Remove Content-Type if data is undefined
  4339. requestData === undefined && requestHeaders.setContentType(null);
  4340. // Add headers to the request
  4341. if ('setRequestHeader' in request) {
  4342. utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
  4343. request.setRequestHeader(key, val);
  4344. });
  4345. }
  4346. // Add withCredentials to request if needed
  4347. if (!utils$1.isUndefined(_config.withCredentials)) {
  4348. request.withCredentials = !!_config.withCredentials;
  4349. }
  4350. // Add responseType to request if needed
  4351. if (responseType && responseType !== 'json') {
  4352. request.responseType = _config.responseType;
  4353. }
  4354. // Handle progress if needed
  4355. if (onDownloadProgress) {
  4356. [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
  4357. request.addEventListener('progress', downloadThrottled);
  4358. }
  4359. // Not all browsers support upload events
  4360. if (onUploadProgress && request.upload) {
  4361. [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
  4362. request.upload.addEventListener('progress', uploadThrottled);
  4363. request.upload.addEventListener('loadend', flushUpload);
  4364. }
  4365. if (_config.cancelToken || _config.signal) {
  4366. // Handle cancellation
  4367. // eslint-disable-next-line func-names
  4368. onCanceled = cancel => {
  4369. if (!request) {
  4370. return;
  4371. }
  4372. reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
  4373. request.abort();
  4374. done();
  4375. request = null;
  4376. };
  4377. _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
  4378. if (_config.signal) {
  4379. _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
  4380. }
  4381. }
  4382. const protocol = parseProtocol(_config.url);
  4383. if (protocol && !platform.protocols.includes(protocol)) {
  4384. reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
  4385. return;
  4386. }
  4387. // Send the request
  4388. request.send(requestData || null);
  4389. });
  4390. };
  4391. const composeSignals = (signals, timeout) => {
  4392. signals = signals ? signals.filter(Boolean) : [];
  4393. if (!timeout && !signals.length) {
  4394. return;
  4395. }
  4396. const controller = new AbortController();
  4397. let aborted = false;
  4398. const onabort = function (reason) {
  4399. if (!aborted) {
  4400. aborted = true;
  4401. unsubscribe();
  4402. const err = reason instanceof Error ? reason : this.reason;
  4403. controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
  4404. }
  4405. };
  4406. let timer = timeout && setTimeout(() => {
  4407. timer = null;
  4408. onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
  4409. }, timeout);
  4410. const unsubscribe = () => {
  4411. if (!signals) {
  4412. return;
  4413. }
  4414. timer && clearTimeout(timer);
  4415. timer = null;
  4416. signals.forEach(signal => {
  4417. signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
  4418. });
  4419. signals = null;
  4420. };
  4421. signals.forEach(signal => signal.addEventListener('abort', onabort));
  4422. const {
  4423. signal
  4424. } = controller;
  4425. signal.unsubscribe = () => utils$1.asap(unsubscribe);
  4426. return signal;
  4427. };
  4428. const streamChunk = function* (chunk, chunkSize) {
  4429. let len = chunk.byteLength;
  4430. if (len < chunkSize) {
  4431. yield chunk;
  4432. return;
  4433. }
  4434. let pos = 0;
  4435. let end;
  4436. while (pos < len) {
  4437. end = pos + chunkSize;
  4438. yield chunk.slice(pos, end);
  4439. pos = end;
  4440. }
  4441. };
  4442. const readBytes = async function* (iterable, chunkSize) {
  4443. for await (const chunk of readStream(iterable)) {
  4444. yield* streamChunk(chunk, chunkSize);
  4445. }
  4446. };
  4447. const readStream = async function* (stream) {
  4448. if (stream[Symbol.asyncIterator]) {
  4449. yield* stream;
  4450. return;
  4451. }
  4452. const reader = stream.getReader();
  4453. try {
  4454. for (;;) {
  4455. const {
  4456. done,
  4457. value
  4458. } = await reader.read();
  4459. if (done) {
  4460. break;
  4461. }
  4462. yield value;
  4463. }
  4464. } finally {
  4465. await reader.cancel();
  4466. }
  4467. };
  4468. const trackStream = (stream, chunkSize, onProgress, onFinish) => {
  4469. const iterator = readBytes(stream, chunkSize);
  4470. let bytes = 0;
  4471. let done;
  4472. let _onFinish = e => {
  4473. if (!done) {
  4474. done = true;
  4475. onFinish && onFinish(e);
  4476. }
  4477. };
  4478. return new ReadableStream({
  4479. async pull(controller) {
  4480. try {
  4481. const {
  4482. done,
  4483. value
  4484. } = await iterator.next();
  4485. if (done) {
  4486. _onFinish();
  4487. controller.close();
  4488. return;
  4489. }
  4490. let len = value.byteLength;
  4491. if (onProgress) {
  4492. let loadedBytes = bytes += len;
  4493. onProgress(loadedBytes);
  4494. }
  4495. controller.enqueue(new Uint8Array(value));
  4496. } catch (err) {
  4497. _onFinish(err);
  4498. throw err;
  4499. }
  4500. },
  4501. cancel(reason) {
  4502. _onFinish(reason);
  4503. return iterator.return();
  4504. }
  4505. }, {
  4506. highWaterMark: 2
  4507. });
  4508. };
  4509. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  4510. const {
  4511. isFunction
  4512. } = utils$1;
  4513. /**
  4514. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  4515. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  4516. *
  4517. * @param {string} str The string to encode
  4518. *
  4519. * @returns {string} UTF-8 bytes as a Latin-1 string
  4520. */
  4521. const encodeUTF8 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
  4522. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  4523. // Decode before composing the `auth` option so credentials such as
  4524. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  4525. // original value for malformed input so a bad encoding never throws.
  4526. const decodeURIComponentSafe = value => {
  4527. if (!utils$1.isString(value)) {
  4528. return value;
  4529. }
  4530. try {
  4531. return decodeURIComponent(value);
  4532. } catch (error) {
  4533. return value;
  4534. }
  4535. };
  4536. const test = (fn, ...args) => {
  4537. try {
  4538. return !!fn(...args);
  4539. } catch (e) {
  4540. return false;
  4541. }
  4542. };
  4543. const maybeWithAuthCredentials = url => {
  4544. const protocolIndex = url.indexOf('://');
  4545. let urlToCheck = url;
  4546. if (protocolIndex !== -1) {
  4547. urlToCheck = urlToCheck.slice(protocolIndex + 3);
  4548. }
  4549. return urlToCheck.includes('@') || urlToCheck.includes(':');
  4550. };
  4551. const factory = env => {
  4552. const globalObject = utils$1.global !== undefined && utils$1.global !== null ? utils$1.global : globalThis;
  4553. const {
  4554. ReadableStream,
  4555. TextEncoder
  4556. } = globalObject;
  4557. env = utils$1.merge.call({
  4558. skipUndefined: true
  4559. }, {
  4560. Request: globalObject.Request,
  4561. Response: globalObject.Response
  4562. }, env);
  4563. const {
  4564. fetch: envFetch,
  4565. Request,
  4566. Response
  4567. } = env;
  4568. const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
  4569. const isRequestSupported = isFunction(Request);
  4570. const isResponseSupported = isFunction(Response);
  4571. if (!isFetchSupported) {
  4572. return false;
  4573. }
  4574. const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
  4575. const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? (encoder => str => encoder.encode(str))(new TextEncoder()) : async str => new Uint8Array(await new Request(str).arrayBuffer()));
  4576. const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
  4577. let duplexAccessed = false;
  4578. const request = new Request(platform.origin, {
  4579. body: new ReadableStream(),
  4580. method: 'POST',
  4581. get duplex() {
  4582. duplexAccessed = true;
  4583. return 'half';
  4584. }
  4585. });
  4586. const hasContentType = request.headers.has('Content-Type');
  4587. if (request.body != null) {
  4588. request.body.cancel();
  4589. }
  4590. return duplexAccessed && !hasContentType;
  4591. });
  4592. const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response('').body));
  4593. const resolvers = {
  4594. stream: supportsResponseStream && (res => res.body)
  4595. };
  4596. isFetchSupported && (() => {
  4597. ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
  4598. !resolvers[type] && (resolvers[type] = (res, config) => {
  4599. let method = res && res[type];
  4600. if (method) {
  4601. return method.call(res);
  4602. }
  4603. throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
  4604. });
  4605. });
  4606. })();
  4607. const getBodyLength = async body => {
  4608. if (body == null) {
  4609. return 0;
  4610. }
  4611. if (utils$1.isBlob(body)) {
  4612. return body.size;
  4613. }
  4614. if (utils$1.isSpecCompliantForm(body)) {
  4615. const _request = new Request(platform.origin, {
  4616. method: 'POST',
  4617. body
  4618. });
  4619. return (await _request.arrayBuffer()).byteLength;
  4620. }
  4621. if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
  4622. return body.byteLength;
  4623. }
  4624. if (utils$1.isURLSearchParams(body)) {
  4625. body = body + '';
  4626. }
  4627. if (utils$1.isString(body)) {
  4628. return (await encodeText(body)).byteLength;
  4629. }
  4630. };
  4631. const resolveBodyLength = async (headers, body) => {
  4632. const length = utils$1.toFiniteNumber(headers.getContentLength());
  4633. return length == null ? getBodyLength(body) : length;
  4634. };
  4635. return async config => {
  4636. let {
  4637. url,
  4638. method,
  4639. data,
  4640. signal,
  4641. cancelToken,
  4642. timeout,
  4643. onDownloadProgress,
  4644. onUploadProgress,
  4645. responseType,
  4646. headers,
  4647. withCredentials = 'same-origin',
  4648. fetchOptions,
  4649. maxContentLength,
  4650. maxBodyLength
  4651. } = resolveConfig(config);
  4652. const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
  4653. const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
  4654. const own = key => utils$1.hasOwnProp(config, key) ? config[key] : undefined;
  4655. let _fetch = envFetch || fetch;
  4656. responseType = responseType ? (responseType + '').toLowerCase() : 'text';
  4657. let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
  4658. let request = null;
  4659. const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
  4660. composedSignal.unsubscribe();
  4661. });
  4662. let requestContentLength;
  4663. // AxiosError we raise while the request body is being streamed. Captured
  4664. // by identity so the catch block can surface it directly, regardless of
  4665. // how the runtime wraps the resulting fetch rejection (undici exposes it
  4666. // as `err.cause`; some browsers drop the original error entirely).
  4667. let pendingBodyError = null;
  4668. const maxBodyLengthError = () => new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, request);
  4669. try {
  4670. // HTTP basic authentication
  4671. let auth = undefined;
  4672. const configAuth = own('auth');
  4673. if (configAuth) {
  4674. const username = utils$1.getSafeProp(configAuth, 'username') || '';
  4675. const password = utils$1.getSafeProp(configAuth, 'password') || '';
  4676. auth = {
  4677. username,
  4678. password
  4679. };
  4680. }
  4681. if (maybeWithAuthCredentials(url)) {
  4682. const parsedURL = new URL(url, platform.origin);
  4683. if (!auth && (parsedURL.username || parsedURL.password)) {
  4684. const urlUsername = decodeURIComponentSafe(parsedURL.username);
  4685. const urlPassword = decodeURIComponentSafe(parsedURL.password);
  4686. auth = {
  4687. username: urlUsername,
  4688. password: urlPassword
  4689. };
  4690. }
  4691. if (parsedURL.username || parsedURL.password) {
  4692. parsedURL.username = '';
  4693. parsedURL.password = '';
  4694. url = parsedURL.href;
  4695. }
  4696. }
  4697. if (auth) {
  4698. headers.delete('authorization');
  4699. headers.set('Authorization', 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || ''))));
  4700. }
  4701. // Enforce maxContentLength for data: URLs up-front so we never materialize
  4702. // an oversized payload. The HTTP adapter applies the same check (see http.js
  4703. // "if (protocol === 'data:')" branch).
  4704. if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
  4705. const estimated = estimateDataURLDecodedBytes(url);
  4706. if (estimated > maxContentLength) {
  4707. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  4708. }
  4709. }
  4710. // Enforce maxBodyLength against known-size bodies before dispatch using
  4711. // the body's *actual* size — never a caller-declared Content-Length,
  4712. // which could under-report to slip an oversized body past the check.
  4713. // Unknown-size streams return undefined here and are counted per-chunk
  4714. // below as fetch consumes them.
  4715. if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
  4716. const outboundLength = await getBodyLength(data);
  4717. if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
  4718. requestContentLength = outboundLength;
  4719. if (outboundLength > maxBodyLength) {
  4720. throw maxBodyLengthError();
  4721. }
  4722. }
  4723. }
  4724. // A streamed body under maxBodyLength must be counted as fetch consumes
  4725. // it; its size is never trusted from a caller-declared Content-Length.
  4726. const mustEnforceStreamBody = hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
  4727. const trackRequestStream = (stream, onProgress, flush) => trackStream(stream, DEFAULT_CHUNK_SIZE, loadedBytes => {
  4728. if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
  4729. throw pendingBodyError = maxBodyLengthError();
  4730. }
  4731. onProgress && onProgress(loadedBytes);
  4732. }, flush);
  4733. if (supportsRequestStream && method !== 'get' && method !== 'head' && (onUploadProgress || mustEnforceStreamBody)) {
  4734. requestContentLength = requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
  4735. // A declared length of 0 is only trusted to skip the wrap when we are
  4736. // not enforcing a stream limit (which must not rely on that header).
  4737. if (requestContentLength !== 0 || mustEnforceStreamBody) {
  4738. let _request = new Request(url, {
  4739. method: 'POST',
  4740. body: data,
  4741. duplex: 'half'
  4742. });
  4743. let contentTypeHeader;
  4744. if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
  4745. headers.setContentType(contentTypeHeader);
  4746. }
  4747. if (_request.body) {
  4748. const [onProgress, flush] = onUploadProgress && progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))) || [];
  4749. data = trackRequestStream(_request.body, onProgress, flush);
  4750. }
  4751. }
  4752. } else if (mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== 'get' && method !== 'head') {
  4753. data = trackRequestStream(data);
  4754. } else if (mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== 'get' && method !== 'head') {
  4755. throw new AxiosError('Stream request bodies are not supported by the current fetch implementation', AxiosError.ERR_NOT_SUPPORT, config, request);
  4756. }
  4757. if (!utils$1.isString(withCredentials)) {
  4758. withCredentials = withCredentials ? 'include' : 'omit';
  4759. }
  4760. // Cloudflare Workers throws when credentials are defined
  4761. // see https://github.com/cloudflare/workerd/issues/902
  4762. const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
  4763. // If data is FormData and Content-Type is multipart/form-data without boundary,
  4764. // delete it so fetch can set it correctly with the boundary
  4765. if (utils$1.isFormData(data)) {
  4766. const contentType = headers.getContentType();
  4767. if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) {
  4768. headers.delete('content-type');
  4769. }
  4770. }
  4771. // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
  4772. headers.set('User-Agent', 'axios/' + VERSION, false);
  4773. const resolvedOptions = {
  4774. ...fetchOptions,
  4775. signal: composedSignal,
  4776. method: method.toUpperCase(),
  4777. headers: toByteStringHeaderObject(headers.normalize()),
  4778. body: data,
  4779. duplex: 'half',
  4780. credentials: isCredentialsSupported ? withCredentials : undefined
  4781. };
  4782. request = isRequestSupported && new Request(url, resolvedOptions);
  4783. let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
  4784. const responseHeaders = AxiosHeaders.from(response.headers);
  4785. // Cheap pre-check: if the server honestly declares a content-length that
  4786. // already exceeds the cap, reject before we start streaming.
  4787. if (hasMaxContentLength) {
  4788. const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
  4789. if (declaredLength != null && declaredLength > maxContentLength) {
  4790. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  4791. }
  4792. }
  4793. const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
  4794. if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
  4795. const options = {};
  4796. ['status', 'statusText', 'headers'].forEach(prop => {
  4797. options[prop] = response[prop];
  4798. });
  4799. const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
  4800. const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
  4801. let bytesRead = 0;
  4802. const onChunkProgress = loadedBytes => {
  4803. if (hasMaxContentLength) {
  4804. bytesRead = loadedBytes;
  4805. if (bytesRead > maxContentLength) {
  4806. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  4807. }
  4808. }
  4809. onProgress && onProgress(loadedBytes);
  4810. };
  4811. response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
  4812. flush && flush();
  4813. unsubscribe && unsubscribe();
  4814. }), options);
  4815. }
  4816. responseType = responseType || 'text';
  4817. let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
  4818. // Fallback enforcement for environments without ReadableStream support
  4819. // (legacy runtimes). Detect materialized size from typed output; skip
  4820. // streams/Response passthrough since the user will read those themselves.
  4821. if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
  4822. let materializedSize;
  4823. if (responseData != null) {
  4824. if (typeof responseData.byteLength === 'number') {
  4825. materializedSize = responseData.byteLength;
  4826. } else if (typeof responseData.size === 'number') {
  4827. materializedSize = responseData.size;
  4828. } else if (typeof responseData === 'string') {
  4829. materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length;
  4830. }
  4831. }
  4832. if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
  4833. throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
  4834. }
  4835. }
  4836. !isStreamResponse && unsubscribe && unsubscribe();
  4837. return await new Promise((resolve, reject) => {
  4838. settle(resolve, reject, {
  4839. data: responseData,
  4840. headers: AxiosHeaders.from(response.headers),
  4841. status: response.status,
  4842. statusText: response.statusText,
  4843. config,
  4844. request
  4845. });
  4846. });
  4847. } catch (err) {
  4848. unsubscribe && unsubscribe();
  4849. // Safari can surface fetch aborts as a DOMException-like object whose
  4850. // branded getters throw. Prefer our composed signal reason before reading
  4851. // the caught error, preserving timeout vs cancellation semantics.
  4852. if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
  4853. const canceledError = composedSignal.reason;
  4854. canceledError.config = config;
  4855. request && (canceledError.request = request);
  4856. err !== canceledError && (canceledError.cause = err);
  4857. throw canceledError;
  4858. }
  4859. // Surface a maxBodyLength violation we raised while the request body was
  4860. // being streamed. Matching by identity (rather than reading
  4861. // `err.cause.isAxiosError`) keeps the error deterministic across runtimes
  4862. // and avoids both prototype-pollution reads and mis-attributing a foreign
  4863. // AxiosError that merely happened to land in `err.cause`.
  4864. if (pendingBodyError) {
  4865. request && !pendingBodyError.request && (pendingBodyError.request = request);
  4866. throw pendingBodyError;
  4867. }
  4868. // Re-throw AxiosErrors we raised synchronously (data: URL / content-length
  4869. // pre-checks, response size enforcement) without re-wrapping them.
  4870. if (err instanceof AxiosError) {
  4871. request && !err.request && (err.request = request);
  4872. throw err;
  4873. }
  4874. if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
  4875. throw Object.assign(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, err && err.response), {
  4876. cause: err.cause || err
  4877. });
  4878. }
  4879. throw AxiosError.from(err, err && err.code, config, request, err && err.response);
  4880. }
  4881. };
  4882. };
  4883. const seedCache = new Map();
  4884. const getFetch = config => {
  4885. let env = config && config.env || {};
  4886. const {
  4887. fetch,
  4888. Request,
  4889. Response
  4890. } = env;
  4891. const seeds = [Request, Response, fetch];
  4892. let len = seeds.length,
  4893. i = len,
  4894. seed,
  4895. target,
  4896. map = seedCache;
  4897. while (i--) {
  4898. seed = seeds[i];
  4899. target = map.get(seed);
  4900. target === undefined && map.set(seed, target = i ? new Map() : factory(env));
  4901. map = target;
  4902. }
  4903. return target;
  4904. };
  4905. getFetch();
  4906. /**
  4907. * Known adapters mapping.
  4908. * Provides environment-specific adapters for Axios:
  4909. * - `http` for Node.js
  4910. * - `xhr` for browsers
  4911. * - `fetch` for fetch API-based requests
  4912. *
  4913. * @type {Object<string, Function|Object>}
  4914. */
  4915. const knownAdapters = {
  4916. http: httpAdapter,
  4917. xhr: xhrAdapter,
  4918. fetch: {
  4919. get: getFetch
  4920. }
  4921. };
  4922. // Assign adapter names for easier debugging and identification
  4923. utils$1.forEach(knownAdapters, (fn, value) => {
  4924. if (fn) {
  4925. try {
  4926. // Null-proto descriptors so a polluted Object.prototype.get cannot turn
  4927. // these data descriptors into accessor descriptors on the way in.
  4928. Object.defineProperty(fn, 'name', {
  4929. __proto__: null,
  4930. value
  4931. });
  4932. } catch (e) {
  4933. // eslint-disable-next-line no-empty
  4934. }
  4935. Object.defineProperty(fn, 'adapterName', {
  4936. __proto__: null,
  4937. value
  4938. });
  4939. }
  4940. });
  4941. /**
  4942. * Render a rejection reason string for unknown or unsupported adapters
  4943. *
  4944. * @param {string} reason
  4945. * @returns {string}
  4946. */
  4947. const renderReason = reason => `- ${reason}`;
  4948. /**
  4949. * Check if the adapter is resolved (function, null, or false)
  4950. *
  4951. * @param {Function|null|false} adapter
  4952. * @returns {boolean}
  4953. */
  4954. const isResolvedHandle = adapter => utils$1.isFunction(adapter) || adapter === null || adapter === false;
  4955. /**
  4956. * Get the first suitable adapter from the provided list.
  4957. * Tries each adapter in order until a supported one is found.
  4958. * Throws an AxiosError if no adapter is suitable.
  4959. *
  4960. * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
  4961. * @param {Object} config - Axios request configuration
  4962. * @throws {AxiosError} If no suitable adapter is available
  4963. * @returns {Function} The resolved adapter function
  4964. */
  4965. function getAdapter(adapters, config) {
  4966. adapters = utils$1.isArray(adapters) ? adapters : [adapters];
  4967. const {
  4968. length
  4969. } = adapters;
  4970. let nameOrAdapter;
  4971. let adapter;
  4972. const rejectedReasons = {};
  4973. for (let i = 0; i < length; i++) {
  4974. nameOrAdapter = adapters[i];
  4975. let id;
  4976. adapter = nameOrAdapter;
  4977. if (!isResolvedHandle(nameOrAdapter)) {
  4978. adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
  4979. if (adapter === undefined) {
  4980. throw new AxiosError(`Unknown adapter '${id}'`);
  4981. }
  4982. }
  4983. if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
  4984. break;
  4985. }
  4986. rejectedReasons[id || '#' + i] = adapter;
  4987. }
  4988. if (!adapter) {
  4989. const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? 'is not supported by the environment' : 'is not available in the build'));
  4990. let s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified';
  4991. throw new AxiosError(`There is no suitable adapter to dispatch the request ` + s, 'ERR_NOT_SUPPORT');
  4992. }
  4993. return adapter;
  4994. }
  4995. /**
  4996. * Exports Axios adapters and utility to resolve an adapter
  4997. */
  4998. var adapters = {
  4999. /**
  5000. * Resolve an adapter from a list of adapter names or functions.
  5001. * @type {Function}
  5002. */
  5003. getAdapter,
  5004. /**
  5005. * Exposes all known adapters
  5006. * @type {Object<string, Function|Object>}
  5007. */
  5008. adapters: knownAdapters
  5009. };
  5010. /**
  5011. * Throws a `CanceledError` if cancellation has been requested.
  5012. *
  5013. * @param {Object} config The config that is to be used for the request
  5014. *
  5015. * @returns {void}
  5016. */
  5017. function throwIfCancellationRequested(config) {
  5018. if (config.cancelToken) {
  5019. config.cancelToken.throwIfRequested();
  5020. }
  5021. if (config.signal && config.signal.aborted) {
  5022. throw new CanceledError(null, config);
  5023. }
  5024. }
  5025. /**
  5026. * Dispatch a request to the server using the configured adapter.
  5027. *
  5028. * @param {object} config The config that is to be used for the request
  5029. *
  5030. * @returns {Promise} The Promise to be fulfilled
  5031. */
  5032. function dispatchRequest(config) {
  5033. throwIfCancellationRequested(config);
  5034. config.headers = AxiosHeaders.from(config.headers);
  5035. // Transform request data
  5036. config.data = transformData.call(config, config.transformRequest);
  5037. if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
  5038. config.headers.setContentType('application/x-www-form-urlencoded', false);
  5039. }
  5040. const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
  5041. return adapter(config).then(function onAdapterResolution(response) {
  5042. throwIfCancellationRequested(config);
  5043. // Expose the current response on config so that transformResponse can
  5044. // attach it to any AxiosError it throws (e.g. on JSON parse failure).
  5045. // We clean it up afterwards to avoid polluting the config object.
  5046. config.response = response;
  5047. try {
  5048. response.data = transformData.call(config, config.transformResponse, response);
  5049. } finally {
  5050. delete config.response;
  5051. }
  5052. response.headers = AxiosHeaders.from(response.headers);
  5053. return response;
  5054. }, function onAdapterRejection(reason) {
  5055. if (!isCancel(reason)) {
  5056. throwIfCancellationRequested(config);
  5057. // Transform response data
  5058. if (reason && reason.response) {
  5059. config.response = reason.response;
  5060. try {
  5061. reason.response.data = transformData.call(config, config.transformResponse, reason.response);
  5062. } finally {
  5063. delete config.response;
  5064. }
  5065. reason.response.headers = AxiosHeaders.from(reason.response.headers);
  5066. }
  5067. }
  5068. return Promise.reject(reason);
  5069. });
  5070. }
  5071. const validators$1 = {};
  5072. // eslint-disable-next-line func-names
  5073. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  5074. validators$1[type] = function validator(thing) {
  5075. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  5076. };
  5077. });
  5078. const deprecatedWarnings = {};
  5079. /**
  5080. * Transitional option validator
  5081. *
  5082. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  5083. * @param {string?} version - deprecated version / removed since version
  5084. * @param {string?} message - some message with additional info
  5085. *
  5086. * @returns {function}
  5087. */
  5088. validators$1.transitional = function transitional(validator, version, message) {
  5089. function formatMessage(opt, desc) {
  5090. return '[Axios v' + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? '. ' + message : '');
  5091. }
  5092. // eslint-disable-next-line func-names
  5093. return (value, opt, opts) => {
  5094. if (validator === false) {
  5095. throw new AxiosError(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED);
  5096. }
  5097. if (version && !deprecatedWarnings[opt]) {
  5098. deprecatedWarnings[opt] = true;
  5099. // eslint-disable-next-line no-console
  5100. console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future'));
  5101. }
  5102. return validator ? validator(value, opt, opts) : true;
  5103. };
  5104. };
  5105. validators$1.spelling = function spelling(correctSpelling) {
  5106. return (value, opt) => {
  5107. // eslint-disable-next-line no-console
  5108. console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
  5109. return true;
  5110. };
  5111. };
  5112. /**
  5113. * Assert object's properties type
  5114. *
  5115. * @param {object} options
  5116. * @param {object} schema
  5117. * @param {boolean?} allowUnknown
  5118. *
  5119. * @returns {object}
  5120. */
  5121. function assertOptions(options, schema, allowUnknown) {
  5122. if (typeof options !== 'object') {
  5123. throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  5124. }
  5125. const keys = Object.keys(options);
  5126. let i = keys.length;
  5127. while (i-- > 0) {
  5128. const opt = keys[i];
  5129. // Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
  5130. // a non-function validator and cause a TypeError.
  5131. const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
  5132. if (validator) {
  5133. const value = options[opt];
  5134. const result = value === undefined || validator(value, opt, options);
  5135. if (result !== true) {
  5136. throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
  5137. }
  5138. continue;
  5139. }
  5140. if (allowUnknown !== true) {
  5141. throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
  5142. }
  5143. }
  5144. }
  5145. var validator = {
  5146. assertOptions,
  5147. validators: validators$1
  5148. };
  5149. const validators = validator.validators;
  5150. /**
  5151. * Create a new instance of Axios
  5152. *
  5153. * @param {Object} instanceConfig The default config for the instance
  5154. *
  5155. * @return {Axios} A new instance of Axios
  5156. */
  5157. class Axios {
  5158. constructor(instanceConfig) {
  5159. this.defaults = instanceConfig || {};
  5160. this.interceptors = {
  5161. request: new InterceptorManager(),
  5162. response: new InterceptorManager()
  5163. };
  5164. }
  5165. /**
  5166. * Dispatch a request
  5167. *
  5168. * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
  5169. * @param {?Object} config
  5170. *
  5171. * @returns {Promise} The Promise to be fulfilled
  5172. */
  5173. async request(configOrUrl, config) {
  5174. try {
  5175. return await this._request(configOrUrl, config);
  5176. } catch (err) {
  5177. if (err instanceof Error) {
  5178. let dummy = {};
  5179. Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
  5180. // slice off the Error: ... line
  5181. const stack = (() => {
  5182. if (!dummy.stack) {
  5183. return '';
  5184. }
  5185. const firstNewlineIndex = dummy.stack.indexOf('\n');
  5186. return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
  5187. })();
  5188. try {
  5189. if (!err.stack) {
  5190. err.stack = stack;
  5191. // match without the 2 top stack lines
  5192. } else if (stack) {
  5193. const firstNewlineIndex = stack.indexOf('\n');
  5194. const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
  5195. const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
  5196. if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
  5197. err.stack += '\n' + stack;
  5198. }
  5199. }
  5200. } catch (e) {
  5201. // ignore the case where "stack" is an un-writable property
  5202. }
  5203. }
  5204. throw err;
  5205. }
  5206. }
  5207. _request(configOrUrl, config) {
  5208. /*eslint no-param-reassign:0*/
  5209. // Allow for axios('example/url'[, config]) a la fetch API
  5210. if (typeof configOrUrl === 'string') {
  5211. config = config || {};
  5212. config.url = configOrUrl;
  5213. } else {
  5214. config = configOrUrl || {};
  5215. }
  5216. config = mergeConfig(this.defaults, config);
  5217. const {
  5218. transitional,
  5219. paramsSerializer,
  5220. headers
  5221. } = config;
  5222. if (transitional !== undefined) {
  5223. validator.assertOptions(transitional, {
  5224. silentJSONParsing: validators.transitional(validators.boolean),
  5225. forcedJSONParsing: validators.transitional(validators.boolean),
  5226. clarifyTimeoutError: validators.transitional(validators.boolean),
  5227. legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
  5228. advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
  5229. validateStatusUndefinedResolves: validators.transitional(validators.boolean)
  5230. }, false);
  5231. }
  5232. if (paramsSerializer != null) {
  5233. if (utils$1.isFunction(paramsSerializer)) {
  5234. config.paramsSerializer = {
  5235. serialize: paramsSerializer
  5236. };
  5237. } else {
  5238. validator.assertOptions(paramsSerializer, {
  5239. encode: validators.function,
  5240. serialize: validators.function
  5241. }, true);
  5242. }
  5243. }
  5244. // Set config.allowAbsoluteUrls
  5245. if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
  5246. config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
  5247. } else {
  5248. config.allowAbsoluteUrls = true;
  5249. }
  5250. validator.assertOptions(config, {
  5251. baseUrl: validators.spelling('baseURL'),
  5252. withXsrfToken: validators.spelling('withXSRFToken')
  5253. }, true);
  5254. // Set config.method
  5255. config.method = (config.method || this.defaults.method || 'get').toLowerCase();
  5256. // Flatten headers
  5257. let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
  5258. headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], method => {
  5259. delete headers[method];
  5260. });
  5261. config.headers = AxiosHeaders.concat(contextHeaders, headers);
  5262. // filter out skipped interceptors
  5263. const requestInterceptorChain = [];
  5264. let synchronousRequestInterceptors = true;
  5265. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  5266. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  5267. return;
  5268. }
  5269. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  5270. const transitional = config.transitional || transitionalDefaults;
  5271. const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;
  5272. if (legacyInterceptorReqResOrdering) {
  5273. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  5274. } else {
  5275. requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  5276. }
  5277. });
  5278. const responseInterceptorChain = [];
  5279. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  5280. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  5281. });
  5282. let promise;
  5283. let i = 0;
  5284. let len;
  5285. if (!synchronousRequestInterceptors) {
  5286. const chain = [dispatchRequest.bind(this), undefined];
  5287. chain.unshift(...requestInterceptorChain);
  5288. chain.push(...responseInterceptorChain);
  5289. len = chain.length;
  5290. promise = Promise.resolve(config);
  5291. while (i < len) {
  5292. promise = promise.then(chain[i++], chain[i++]);
  5293. }
  5294. return promise;
  5295. }
  5296. len = requestInterceptorChain.length;
  5297. let newConfig = config;
  5298. while (i < len) {
  5299. const onFulfilled = requestInterceptorChain[i++];
  5300. const onRejected = requestInterceptorChain[i++];
  5301. try {
  5302. newConfig = onFulfilled(newConfig);
  5303. } catch (error) {
  5304. onRejected.call(this, error);
  5305. break;
  5306. }
  5307. }
  5308. try {
  5309. promise = dispatchRequest.call(this, newConfig);
  5310. } catch (error) {
  5311. return Promise.reject(error);
  5312. }
  5313. i = 0;
  5314. len = responseInterceptorChain.length;
  5315. while (i < len) {
  5316. promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
  5317. }
  5318. return promise;
  5319. }
  5320. getUri(config) {
  5321. config = mergeConfig(this.defaults, config);
  5322. const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
  5323. return buildURL(fullPath, config.params, config.paramsSerializer);
  5324. }
  5325. }
  5326. // Provide aliases for supported request methods
  5327. utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  5328. /*eslint func-names:0*/
  5329. Axios.prototype[method] = function (url, config) {
  5330. return this.request(mergeConfig(config || {}, {
  5331. method,
  5332. url,
  5333. data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined
  5334. }));
  5335. };
  5336. });
  5337. utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
  5338. function generateHTTPMethod(isForm) {
  5339. return function httpMethod(url, data, config) {
  5340. return this.request(mergeConfig(config || {}, {
  5341. method,
  5342. headers: isForm ? {
  5343. 'Content-Type': 'multipart/form-data'
  5344. } : {},
  5345. url,
  5346. data
  5347. }));
  5348. };
  5349. }
  5350. Axios.prototype[method] = generateHTTPMethod();
  5351. // QUERY is a safe/idempotent read method; multipart form bodies don't fit
  5352. // its semantics, so no queryForm shorthand is generated.
  5353. if (method !== 'query') {
  5354. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  5355. }
  5356. });
  5357. /**
  5358. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  5359. *
  5360. * @param {Function} executor The executor function.
  5361. *
  5362. * @returns {CancelToken}
  5363. */
  5364. class CancelToken {
  5365. constructor(executor) {
  5366. if (typeof executor !== 'function') {
  5367. throw new TypeError('executor must be a function.');
  5368. }
  5369. let resolvePromise;
  5370. this.promise = new Promise(function promiseExecutor(resolve) {
  5371. resolvePromise = resolve;
  5372. });
  5373. const token = this;
  5374. // eslint-disable-next-line func-names
  5375. this.promise.then(cancel => {
  5376. if (!token._listeners) return;
  5377. let i = token._listeners.length;
  5378. while (i-- > 0) {
  5379. token._listeners[i](cancel);
  5380. }
  5381. token._listeners = null;
  5382. });
  5383. // eslint-disable-next-line func-names
  5384. this.promise.then = onfulfilled => {
  5385. let _resolve;
  5386. // eslint-disable-next-line func-names
  5387. const promise = new Promise(resolve => {
  5388. token.subscribe(resolve);
  5389. _resolve = resolve;
  5390. }).then(onfulfilled);
  5391. promise.cancel = function reject() {
  5392. token.unsubscribe(_resolve);
  5393. };
  5394. return promise;
  5395. };
  5396. executor(function cancel(message, config, request) {
  5397. if (token.reason) {
  5398. // Cancellation has already been requested
  5399. return;
  5400. }
  5401. token.reason = new CanceledError(message, config, request);
  5402. resolvePromise(token.reason);
  5403. });
  5404. }
  5405. /**
  5406. * Throws a `CanceledError` if cancellation has been requested.
  5407. */
  5408. throwIfRequested() {
  5409. if (this.reason) {
  5410. throw this.reason;
  5411. }
  5412. }
  5413. /**
  5414. * Subscribe to the cancel signal
  5415. */
  5416. subscribe(listener) {
  5417. if (this.reason) {
  5418. listener(this.reason);
  5419. return;
  5420. }
  5421. if (this._listeners) {
  5422. this._listeners.push(listener);
  5423. } else {
  5424. this._listeners = [listener];
  5425. }
  5426. }
  5427. /**
  5428. * Unsubscribe from the cancel signal
  5429. */
  5430. unsubscribe(listener) {
  5431. if (!this._listeners) {
  5432. return;
  5433. }
  5434. const index = this._listeners.indexOf(listener);
  5435. if (index !== -1) {
  5436. this._listeners.splice(index, 1);
  5437. }
  5438. }
  5439. toAbortSignal() {
  5440. const controller = new AbortController();
  5441. const abort = err => {
  5442. controller.abort(err);
  5443. };
  5444. this.subscribe(abort);
  5445. controller.signal.unsubscribe = () => this.unsubscribe(abort);
  5446. return controller.signal;
  5447. }
  5448. /**
  5449. * Returns an object that contains a new `CancelToken` and a function that, when called,
  5450. * cancels the `CancelToken`.
  5451. */
  5452. static source() {
  5453. let cancel;
  5454. const token = new CancelToken(function executor(c) {
  5455. cancel = c;
  5456. });
  5457. return {
  5458. token,
  5459. cancel
  5460. };
  5461. }
  5462. }
  5463. /**
  5464. * Syntactic sugar for invoking a function and expanding an array for arguments.
  5465. *
  5466. * Common use case would be to use `Function.prototype.apply`.
  5467. *
  5468. * ```js
  5469. * function f(x, y, z) {}
  5470. * const args = [1, 2, 3];
  5471. * f.apply(null, args);
  5472. * ```
  5473. *
  5474. * With `spread` this example can be re-written.
  5475. *
  5476. * ```js
  5477. * spread(function(x, y, z) {})([1, 2, 3]);
  5478. * ```
  5479. *
  5480. * @param {Function} callback
  5481. *
  5482. * @returns {Function}
  5483. */
  5484. function spread(callback) {
  5485. return function wrap(arr) {
  5486. return callback.apply(null, arr);
  5487. };
  5488. }
  5489. /**
  5490. * Determines whether the payload is an error thrown by Axios
  5491. *
  5492. * @param {*} payload The value to test
  5493. *
  5494. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  5495. */
  5496. function isAxiosError(payload) {
  5497. return utils$1.isObject(payload) && payload.isAxiosError === true;
  5498. }
  5499. const HttpStatusCode = {
  5500. Continue: 100,
  5501. SwitchingProtocols: 101,
  5502. Processing: 102,
  5503. EarlyHints: 103,
  5504. Ok: 200,
  5505. Created: 201,
  5506. Accepted: 202,
  5507. NonAuthoritativeInformation: 203,
  5508. NoContent: 204,
  5509. ResetContent: 205,
  5510. PartialContent: 206,
  5511. MultiStatus: 207,
  5512. AlreadyReported: 208,
  5513. ImUsed: 226,
  5514. MultipleChoices: 300,
  5515. MovedPermanently: 301,
  5516. Found: 302,
  5517. SeeOther: 303,
  5518. NotModified: 304,
  5519. UseProxy: 305,
  5520. Unused: 306,
  5521. TemporaryRedirect: 307,
  5522. PermanentRedirect: 308,
  5523. BadRequest: 400,
  5524. Unauthorized: 401,
  5525. PaymentRequired: 402,
  5526. Forbidden: 403,
  5527. NotFound: 404,
  5528. MethodNotAllowed: 405,
  5529. NotAcceptable: 406,
  5530. ProxyAuthenticationRequired: 407,
  5531. RequestTimeout: 408,
  5532. Conflict: 409,
  5533. Gone: 410,
  5534. LengthRequired: 411,
  5535. PreconditionFailed: 412,
  5536. PayloadTooLarge: 413,
  5537. UriTooLong: 414,
  5538. UnsupportedMediaType: 415,
  5539. RangeNotSatisfiable: 416,
  5540. ExpectationFailed: 417,
  5541. ImATeapot: 418,
  5542. MisdirectedRequest: 421,
  5543. UnprocessableEntity: 422,
  5544. Locked: 423,
  5545. FailedDependency: 424,
  5546. TooEarly: 425,
  5547. UpgradeRequired: 426,
  5548. PreconditionRequired: 428,
  5549. TooManyRequests: 429,
  5550. RequestHeaderFieldsTooLarge: 431,
  5551. UnavailableForLegalReasons: 451,
  5552. InternalServerError: 500,
  5553. NotImplemented: 501,
  5554. BadGateway: 502,
  5555. ServiceUnavailable: 503,
  5556. GatewayTimeout: 504,
  5557. HttpVersionNotSupported: 505,
  5558. VariantAlsoNegotiates: 506,
  5559. InsufficientStorage: 507,
  5560. LoopDetected: 508,
  5561. NotExtended: 510,
  5562. NetworkAuthenticationRequired: 511,
  5563. WebServerIsDown: 521,
  5564. ConnectionTimedOut: 522,
  5565. OriginIsUnreachable: 523,
  5566. TimeoutOccurred: 524,
  5567. SslHandshakeFailed: 525,
  5568. InvalidSslCertificate: 526
  5569. };
  5570. Object.entries(HttpStatusCode).forEach(([key, value]) => {
  5571. HttpStatusCode[value] = key;
  5572. });
  5573. /**
  5574. * Create an instance of Axios
  5575. *
  5576. * @param {Object} defaultConfig The default config for the instance
  5577. *
  5578. * @returns {Axios} A new instance of Axios
  5579. */
  5580. function createInstance(defaultConfig) {
  5581. const context = new Axios(defaultConfig);
  5582. const instance = bind(Axios.prototype.request, context);
  5583. // Copy axios.prototype to instance
  5584. utils$1.extend(instance, Axios.prototype, context, {
  5585. allOwnKeys: true
  5586. });
  5587. // Copy context to instance
  5588. utils$1.extend(instance, context, null, {
  5589. allOwnKeys: true
  5590. });
  5591. // Factory for creating new instances
  5592. instance.create = function create(instanceConfig) {
  5593. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  5594. };
  5595. return instance;
  5596. }
  5597. // Create the default instance to be exported
  5598. const axios = createInstance(defaults);
  5599. // Expose Axios class to allow class inheritance
  5600. axios.Axios = Axios;
  5601. // Expose Cancel & CancelToken
  5602. axios.CanceledError = CanceledError;
  5603. axios.CancelToken = CancelToken;
  5604. axios.isCancel = isCancel;
  5605. axios.VERSION = VERSION;
  5606. axios.toFormData = toFormData;
  5607. // Expose AxiosError class
  5608. axios.AxiosError = AxiosError;
  5609. // alias for CanceledError for backward compatibility
  5610. axios.Cancel = axios.CanceledError;
  5611. // Expose all/spread
  5612. axios.all = function all(promises) {
  5613. return Promise.all(promises);
  5614. };
  5615. axios.spread = spread;
  5616. // Expose isAxiosError
  5617. axios.isAxiosError = isAxiosError;
  5618. // Expose mergeConfig
  5619. axios.mergeConfig = mergeConfig;
  5620. axios.AxiosHeaders = AxiosHeaders;
  5621. axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
  5622. axios.getAdapter = adapters.getAdapter;
  5623. axios.HttpStatusCode = HttpStatusCode;
  5624. axios.default = axios;
  5625. module.exports = axios;
  5626. //# sourceMappingURL=axios.cjs.map