axios.js 183 KB

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