axios.cjs 116 KB

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