axios.cjs 126 KB

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