智慧水务管理系统 - 精河县供水工程综合管理平台

axios.js 138KB

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