axios.cjs 148 KB

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