axios.cjs 113 KB

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