axios.cjs 138 KB

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