axios.cjs 125 KB

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