axios.cjs 154 KB

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