axios.cjs 126 KB

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