axios.cjs 111 KB

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