dep-827b23df.js 2.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713
  1. import fs$l from 'node:fs';
  2. import fsp from 'node:fs/promises';
  3. import path$o, { dirname as dirname$2, join as join$2, posix as posix$1, isAbsolute as isAbsolute$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path';
  4. import { fileURLToPath, URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url';
  5. import { promisify as promisify$4, format as format$2, inspect } from 'node:util';
  6. import { performance } from 'node:perf_hooks';
  7. import { createRequire as createRequire$1, builtinModules } from 'node:module';
  8. import crypto$2, { createHash as createHash$2 } from 'node:crypto';
  9. import require$$0$3 from 'tty';
  10. import esbuild, { transform as transform$1, formatMessages, build as build$3 } from 'esbuild';
  11. import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep as sep$1, normalize } from 'path';
  12. import * as require$$0$2 from 'fs';
  13. import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdir as readdir$4, readdirSync } from 'fs';
  14. import require$$0$5 from 'events';
  15. import require$$5 from 'assert';
  16. import require$$0$6 from 'util';
  17. import require$$3$2 from 'net';
  18. import require$$0$9 from 'url';
  19. import require$$1$1 from 'http';
  20. import require$$0$7 from 'stream';
  21. import require$$2 from 'os';
  22. import require$$2$1 from 'child_process';
  23. import os$4 from 'node:os';
  24. import { exec } from 'node:child_process';
  25. import { promises } from 'node:dns';
  26. import { CLIENT_ENTRY, OPTIMIZABLE_ENTRY_RE, wildcardHosts, loopbackHosts, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, FS_PREFIX, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEP_VERSION_RE, DEFAULT_MAIN_FIELDS, DEFAULT_EXTENSIONS as DEFAULT_EXTENSIONS$1, SPECIAL_QUERY_RE, CSS_LANGS_RE, ESBUILD_MODULES_TARGET, KNOWN_ASSET_TYPES, CLIENT_DIR, JS_TYPES_RE, VERSION as VERSION$1, VITE_PACKAGE_DIR, defaultAllowedOrigins, DEFAULT_DEV_PORT, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js';
  27. import require$$3$1 from 'crypto';
  28. import { Buffer as Buffer$1 } from 'node:buffer';
  29. import require$$0$8, { createRequire as createRequire$2 } from 'module';
  30. import assert$1 from 'node:assert';
  31. import process$1 from 'node:process';
  32. import v8 from 'node:v8';
  33. import { VERSION } from 'rollup';
  34. import require$$1 from 'worker_threads';
  35. import { createServer as createServer$3, STATUS_CODES } from 'node:http';
  36. import { createServer as createServer$2 } from 'node:https';
  37. import require$$0$a from 'zlib';
  38. import require$$0$b from 'buffer';
  39. import require$$1$2 from 'https';
  40. import require$$4$1 from 'tls';
  41. import net$1 from 'node:net';
  42. import * as qs from 'querystring';
  43. import readline from 'node:readline';
  44. import zlib$1, { gzip } from 'node:zlib';
  45. import { fileURLToPath as __cjs_fileURLToPath } from 'node:url';
  46. import { dirname as __cjs_dirname } from 'node:path';
  47. import { createRequire as __cjs_createRequire } from 'node:module';
  48. const __filename = __cjs_fileURLToPath(import.meta.url);
  49. const __dirname = __cjs_dirname(__filename);
  50. const require = __cjs_createRequire(import.meta.url);
  51. const __require = require;
  52. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  53. function getDefaultExportFromCjs (x) {
  54. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  55. }
  56. function getAugmentedNamespace(n) {
  57. if (n.__esModule) return n;
  58. var f = n.default;
  59. if (typeof f == "function") {
  60. var a = function a () {
  61. if (this instanceof a) {
  62. return Reflect.construct(f, arguments, this.constructor);
  63. }
  64. return f.apply(this, arguments);
  65. };
  66. a.prototype = f.prototype;
  67. } else a = {};
  68. Object.defineProperty(a, '__esModule', {value: true});
  69. Object.keys(n).forEach(function (k) {
  70. var d = Object.getOwnPropertyDescriptor(n, k);
  71. Object.defineProperty(a, k, d.get ? d : {
  72. enumerable: true,
  73. get: function () {
  74. return n[k];
  75. }
  76. });
  77. });
  78. return a;
  79. }
  80. var picocolors = {exports: {}};
  81. let tty = require$$0$3;
  82. let isColorSupported =
  83. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  84. ("FORCE_COLOR" in process.env ||
  85. process.argv.includes("--color") ||
  86. process.platform === "win32" ||
  87. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  88. "CI" in process.env);
  89. let formatter =
  90. (open, close, replace = open) =>
  91. input => {
  92. let string = "" + input;
  93. let index = string.indexOf(close, open.length);
  94. return ~index
  95. ? open + replaceClose(string, close, replace, index) + close
  96. : open + string + close
  97. };
  98. let replaceClose = (string, close, replace, index) => {
  99. let start = string.substring(0, index) + replace;
  100. let end = string.substring(index + close.length);
  101. let nextIndex = end.indexOf(close);
  102. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  103. };
  104. let createColors = (enabled = isColorSupported) => ({
  105. isColorSupported: enabled,
  106. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  107. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  108. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  109. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  110. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  111. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  112. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  113. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  114. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  115. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  116. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  117. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  118. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  119. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  120. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  121. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  122. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  123. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  124. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  125. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  126. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  127. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  128. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  129. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  130. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  131. });
  132. picocolors.exports = createColors();
  133. picocolors.exports.createColors = createColors;
  134. var picocolorsExports = picocolors.exports;
  135. var colors$1 = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  136. function matches$1(pattern, importee) {
  137. if (pattern instanceof RegExp) {
  138. return pattern.test(importee);
  139. }
  140. if (importee.length < pattern.length) {
  141. return false;
  142. }
  143. if (importee === pattern) {
  144. return true;
  145. }
  146. // eslint-disable-next-line prefer-template
  147. return importee.startsWith(pattern + '/');
  148. }
  149. function getEntries({ entries, customResolver }) {
  150. if (!entries) {
  151. return [];
  152. }
  153. const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
  154. if (Array.isArray(entries)) {
  155. return entries.map((entry) => {
  156. return {
  157. find: entry.find,
  158. replacement: entry.replacement,
  159. resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
  160. };
  161. });
  162. }
  163. return Object.entries(entries).map(([key, value]) => {
  164. return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
  165. });
  166. }
  167. function getHookFunction(hook) {
  168. if (typeof hook === 'function') {
  169. return hook;
  170. }
  171. if (hook && 'handler' in hook && typeof hook.handler === 'function') {
  172. return hook.handler;
  173. }
  174. return null;
  175. }
  176. function resolveCustomResolver(customResolver) {
  177. if (typeof customResolver === 'function') {
  178. return customResolver;
  179. }
  180. if (customResolver) {
  181. return getHookFunction(customResolver.resolveId);
  182. }
  183. return null;
  184. }
  185. function alias$1(options = {}) {
  186. const entries = getEntries(options);
  187. if (entries.length === 0) {
  188. return {
  189. name: 'alias',
  190. resolveId: () => null
  191. };
  192. }
  193. return {
  194. name: 'alias',
  195. async buildStart(inputOptions) {
  196. await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); }));
  197. },
  198. resolveId(importee, importer, resolveOptions) {
  199. if (!importer) {
  200. return null;
  201. }
  202. // First match is supposed to be the correct one
  203. const matchedEntry = entries.find((entry) => matches$1(entry.find, importee));
  204. if (!matchedEntry) {
  205. return null;
  206. }
  207. const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
  208. if (matchedEntry.resolverFunction) {
  209. return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
  210. }
  211. return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => resolved || { id: updatedId });
  212. }
  213. };
  214. }
  215. // @ts-check
  216. /** @typedef { import('estree').BaseNode} BaseNode */
  217. /** @typedef {{
  218. skip: () => void;
  219. remove: () => void;
  220. replace: (node: BaseNode) => void;
  221. }} WalkerContext */
  222. let WalkerBase$1 = class WalkerBase {
  223. constructor() {
  224. /** @type {boolean} */
  225. this.should_skip = false;
  226. /** @type {boolean} */
  227. this.should_remove = false;
  228. /** @type {BaseNode | null} */
  229. this.replacement = null;
  230. /** @type {WalkerContext} */
  231. this.context = {
  232. skip: () => (this.should_skip = true),
  233. remove: () => (this.should_remove = true),
  234. replace: (node) => (this.replacement = node)
  235. };
  236. }
  237. /**
  238. *
  239. * @param {any} parent
  240. * @param {string} prop
  241. * @param {number} index
  242. * @param {BaseNode} node
  243. */
  244. replace(parent, prop, index, node) {
  245. if (parent) {
  246. if (index !== null) {
  247. parent[prop][index] = node;
  248. } else {
  249. parent[prop] = node;
  250. }
  251. }
  252. }
  253. /**
  254. *
  255. * @param {any} parent
  256. * @param {string} prop
  257. * @param {number} index
  258. */
  259. remove(parent, prop, index) {
  260. if (parent) {
  261. if (index !== null) {
  262. parent[prop].splice(index, 1);
  263. } else {
  264. delete parent[prop];
  265. }
  266. }
  267. }
  268. };
  269. // @ts-check
  270. /** @typedef { import('estree').BaseNode} BaseNode */
  271. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  272. /** @typedef {(
  273. * this: WalkerContext,
  274. * node: BaseNode,
  275. * parent: BaseNode,
  276. * key: string,
  277. * index: number
  278. * ) => void} SyncHandler */
  279. let SyncWalker$1 = class SyncWalker extends WalkerBase$1 {
  280. /**
  281. *
  282. * @param {SyncHandler} enter
  283. * @param {SyncHandler} leave
  284. */
  285. constructor(enter, leave) {
  286. super();
  287. /** @type {SyncHandler} */
  288. this.enter = enter;
  289. /** @type {SyncHandler} */
  290. this.leave = leave;
  291. }
  292. /**
  293. *
  294. * @param {BaseNode} node
  295. * @param {BaseNode} parent
  296. * @param {string} [prop]
  297. * @param {number} [index]
  298. * @returns {BaseNode}
  299. */
  300. visit(node, parent, prop, index) {
  301. if (node) {
  302. if (this.enter) {
  303. const _should_skip = this.should_skip;
  304. const _should_remove = this.should_remove;
  305. const _replacement = this.replacement;
  306. this.should_skip = false;
  307. this.should_remove = false;
  308. this.replacement = null;
  309. this.enter.call(this.context, node, parent, prop, index);
  310. if (this.replacement) {
  311. node = this.replacement;
  312. this.replace(parent, prop, index, node);
  313. }
  314. if (this.should_remove) {
  315. this.remove(parent, prop, index);
  316. }
  317. const skipped = this.should_skip;
  318. const removed = this.should_remove;
  319. this.should_skip = _should_skip;
  320. this.should_remove = _should_remove;
  321. this.replacement = _replacement;
  322. if (skipped) return node;
  323. if (removed) return null;
  324. }
  325. for (const key in node) {
  326. const value = node[key];
  327. if (typeof value !== "object") {
  328. continue;
  329. } else if (Array.isArray(value)) {
  330. for (let i = 0; i < value.length; i += 1) {
  331. if (value[i] !== null && typeof value[i].type === 'string') {
  332. if (!this.visit(value[i], node, key, i)) {
  333. // removed
  334. i--;
  335. }
  336. }
  337. }
  338. } else if (value !== null && typeof value.type === "string") {
  339. this.visit(value, node, key, null);
  340. }
  341. }
  342. if (this.leave) {
  343. const _replacement = this.replacement;
  344. const _should_remove = this.should_remove;
  345. this.replacement = null;
  346. this.should_remove = false;
  347. this.leave.call(this.context, node, parent, prop, index);
  348. if (this.replacement) {
  349. node = this.replacement;
  350. this.replace(parent, prop, index, node);
  351. }
  352. if (this.should_remove) {
  353. this.remove(parent, prop, index);
  354. }
  355. const removed = this.should_remove;
  356. this.replacement = _replacement;
  357. this.should_remove = _should_remove;
  358. if (removed) return null;
  359. }
  360. }
  361. return node;
  362. }
  363. };
  364. // @ts-check
  365. /** @typedef { import('estree').BaseNode} BaseNode */
  366. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  367. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  368. /**
  369. *
  370. * @param {BaseNode} ast
  371. * @param {{
  372. * enter?: SyncHandler
  373. * leave?: SyncHandler
  374. * }} walker
  375. * @returns {BaseNode}
  376. */
  377. function walk$4(ast, { enter, leave }) {
  378. const instance = new SyncWalker$1(enter, leave);
  379. return instance.visit(ast, null);
  380. }
  381. var utils$k = {};
  382. const path$n = require$$0$4;
  383. const WIN_SLASH = '\\\\/';
  384. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  385. /**
  386. * Posix glob regex
  387. */
  388. const DOT_LITERAL = '\\.';
  389. const PLUS_LITERAL = '\\+';
  390. const QMARK_LITERAL = '\\?';
  391. const SLASH_LITERAL = '\\/';
  392. const ONE_CHAR = '(?=.)';
  393. const QMARK = '[^/]';
  394. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  395. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  396. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  397. const NO_DOT = `(?!${DOT_LITERAL})`;
  398. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  399. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  400. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  401. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  402. const STAR$1 = `${QMARK}*?`;
  403. const POSIX_CHARS = {
  404. DOT_LITERAL,
  405. PLUS_LITERAL,
  406. QMARK_LITERAL,
  407. SLASH_LITERAL,
  408. ONE_CHAR,
  409. QMARK,
  410. END_ANCHOR,
  411. DOTS_SLASH,
  412. NO_DOT,
  413. NO_DOTS,
  414. NO_DOT_SLASH,
  415. NO_DOTS_SLASH,
  416. QMARK_NO_DOT,
  417. STAR: STAR$1,
  418. START_ANCHOR
  419. };
  420. /**
  421. * Windows glob regex
  422. */
  423. const WINDOWS_CHARS = {
  424. ...POSIX_CHARS,
  425. SLASH_LITERAL: `[${WIN_SLASH}]`,
  426. QMARK: WIN_NO_SLASH,
  427. STAR: `${WIN_NO_SLASH}*?`,
  428. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  429. NO_DOT: `(?!${DOT_LITERAL})`,
  430. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  431. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  432. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  433. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  434. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  435. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  436. };
  437. /**
  438. * POSIX Bracket Regex
  439. */
  440. const POSIX_REGEX_SOURCE$1 = {
  441. alnum: 'a-zA-Z0-9',
  442. alpha: 'a-zA-Z',
  443. ascii: '\\x00-\\x7F',
  444. blank: ' \\t',
  445. cntrl: '\\x00-\\x1F\\x7F',
  446. digit: '0-9',
  447. graph: '\\x21-\\x7E',
  448. lower: 'a-z',
  449. print: '\\x20-\\x7E ',
  450. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  451. space: ' \\t\\r\\n\\v\\f',
  452. upper: 'A-Z',
  453. word: 'A-Za-z0-9_',
  454. xdigit: 'A-Fa-f0-9'
  455. };
  456. var constants$6 = {
  457. MAX_LENGTH: 1024 * 64,
  458. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  459. // regular expressions
  460. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  461. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  462. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  463. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  464. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  465. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  466. // Replace globs with equivalent patterns to reduce parsing time.
  467. REPLACEMENTS: {
  468. '***': '*',
  469. '**/**': '**',
  470. '**/**/**': '**'
  471. },
  472. // Digits
  473. CHAR_0: 48, /* 0 */
  474. CHAR_9: 57, /* 9 */
  475. // Alphabet chars.
  476. CHAR_UPPERCASE_A: 65, /* A */
  477. CHAR_LOWERCASE_A: 97, /* a */
  478. CHAR_UPPERCASE_Z: 90, /* Z */
  479. CHAR_LOWERCASE_Z: 122, /* z */
  480. CHAR_LEFT_PARENTHESES: 40, /* ( */
  481. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  482. CHAR_ASTERISK: 42, /* * */
  483. // Non-alphabetic chars.
  484. CHAR_AMPERSAND: 38, /* & */
  485. CHAR_AT: 64, /* @ */
  486. CHAR_BACKWARD_SLASH: 92, /* \ */
  487. CHAR_CARRIAGE_RETURN: 13, /* \r */
  488. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  489. CHAR_COLON: 58, /* : */
  490. CHAR_COMMA: 44, /* , */
  491. CHAR_DOT: 46, /* . */
  492. CHAR_DOUBLE_QUOTE: 34, /* " */
  493. CHAR_EQUAL: 61, /* = */
  494. CHAR_EXCLAMATION_MARK: 33, /* ! */
  495. CHAR_FORM_FEED: 12, /* \f */
  496. CHAR_FORWARD_SLASH: 47, /* / */
  497. CHAR_GRAVE_ACCENT: 96, /* ` */
  498. CHAR_HASH: 35, /* # */
  499. CHAR_HYPHEN_MINUS: 45, /* - */
  500. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  501. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  502. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  503. CHAR_LINE_FEED: 10, /* \n */
  504. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  505. CHAR_PERCENT: 37, /* % */
  506. CHAR_PLUS: 43, /* + */
  507. CHAR_QUESTION_MARK: 63, /* ? */
  508. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  509. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  510. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  511. CHAR_SEMICOLON: 59, /* ; */
  512. CHAR_SINGLE_QUOTE: 39, /* ' */
  513. CHAR_SPACE: 32, /* */
  514. CHAR_TAB: 9, /* \t */
  515. CHAR_UNDERSCORE: 95, /* _ */
  516. CHAR_VERTICAL_LINE: 124, /* | */
  517. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  518. SEP: path$n.sep,
  519. /**
  520. * Create EXTGLOB_CHARS
  521. */
  522. extglobChars(chars) {
  523. return {
  524. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  525. '?': { type: 'qmark', open: '(?:', close: ')?' },
  526. '+': { type: 'plus', open: '(?:', close: ')+' },
  527. '*': { type: 'star', open: '(?:', close: ')*' },
  528. '@': { type: 'at', open: '(?:', close: ')' }
  529. };
  530. },
  531. /**
  532. * Create GLOB_CHARS
  533. */
  534. globChars(win32) {
  535. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  536. }
  537. };
  538. (function (exports) {
  539. const path = require$$0$4;
  540. const win32 = process.platform === 'win32';
  541. const {
  542. REGEX_BACKSLASH,
  543. REGEX_REMOVE_BACKSLASH,
  544. REGEX_SPECIAL_CHARS,
  545. REGEX_SPECIAL_CHARS_GLOBAL
  546. } = constants$6;
  547. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  548. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  549. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  550. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  551. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  552. exports.removeBackslashes = str => {
  553. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  554. return match === '\\' ? '' : match;
  555. });
  556. };
  557. exports.supportsLookbehinds = () => {
  558. const segs = process.version.slice(1).split('.').map(Number);
  559. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  560. return true;
  561. }
  562. return false;
  563. };
  564. exports.isWindows = options => {
  565. if (options && typeof options.windows === 'boolean') {
  566. return options.windows;
  567. }
  568. return win32 === true || path.sep === '\\';
  569. };
  570. exports.escapeLast = (input, char, lastIdx) => {
  571. const idx = input.lastIndexOf(char, lastIdx);
  572. if (idx === -1) return input;
  573. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  574. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  575. };
  576. exports.removePrefix = (input, state = {}) => {
  577. let output = input;
  578. if (output.startsWith('./')) {
  579. output = output.slice(2);
  580. state.prefix = './';
  581. }
  582. return output;
  583. };
  584. exports.wrapOutput = (input, state = {}, options = {}) => {
  585. const prepend = options.contains ? '' : '^';
  586. const append = options.contains ? '' : '$';
  587. let output = `${prepend}(?:${input})${append}`;
  588. if (state.negated === true) {
  589. output = `(?:^(?!${output}).*$)`;
  590. }
  591. return output;
  592. };
  593. } (utils$k));
  594. const utils$j = utils$k;
  595. const {
  596. CHAR_ASTERISK, /* * */
  597. CHAR_AT, /* @ */
  598. CHAR_BACKWARD_SLASH, /* \ */
  599. CHAR_COMMA: CHAR_COMMA$1, /* , */
  600. CHAR_DOT: CHAR_DOT$1, /* . */
  601. CHAR_EXCLAMATION_MARK, /* ! */
  602. CHAR_FORWARD_SLASH, /* / */
  603. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  604. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  605. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  606. CHAR_PLUS, /* + */
  607. CHAR_QUESTION_MARK, /* ? */
  608. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  609. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  610. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */
  611. } = constants$6;
  612. const isPathSeparator = code => {
  613. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  614. };
  615. const depth = token => {
  616. if (token.isPrefix !== true) {
  617. token.depth = token.isGlobstar ? Infinity : 1;
  618. }
  619. };
  620. /**
  621. * Quickly scans a glob pattern and returns an object with a handful of
  622. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  623. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  624. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  625. *
  626. * ```js
  627. * const pm = require('picomatch');
  628. * console.log(pm.scan('foo/bar/*.js'));
  629. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  630. * ```
  631. * @param {String} `str`
  632. * @param {Object} `options`
  633. * @return {Object} Returns an object with tokens and regex source string.
  634. * @api public
  635. */
  636. const scan$2 = (input, options) => {
  637. const opts = options || {};
  638. const length = input.length - 1;
  639. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  640. const slashes = [];
  641. const tokens = [];
  642. const parts = [];
  643. let str = input;
  644. let index = -1;
  645. let start = 0;
  646. let lastIndex = 0;
  647. let isBrace = false;
  648. let isBracket = false;
  649. let isGlob = false;
  650. let isExtglob = false;
  651. let isGlobstar = false;
  652. let braceEscaped = false;
  653. let backslashes = false;
  654. let negated = false;
  655. let negatedExtglob = false;
  656. let finished = false;
  657. let braces = 0;
  658. let prev;
  659. let code;
  660. let token = { value: '', depth: 0, isGlob: false };
  661. const eos = () => index >= length;
  662. const peek = () => str.charCodeAt(index + 1);
  663. const advance = () => {
  664. prev = code;
  665. return str.charCodeAt(++index);
  666. };
  667. while (index < length) {
  668. code = advance();
  669. let next;
  670. if (code === CHAR_BACKWARD_SLASH) {
  671. backslashes = token.backslashes = true;
  672. code = advance();
  673. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  674. braceEscaped = true;
  675. }
  676. continue;
  677. }
  678. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  679. braces++;
  680. while (eos() !== true && (code = advance())) {
  681. if (code === CHAR_BACKWARD_SLASH) {
  682. backslashes = token.backslashes = true;
  683. advance();
  684. continue;
  685. }
  686. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  687. braces++;
  688. continue;
  689. }
  690. if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
  691. isBrace = token.isBrace = true;
  692. isGlob = token.isGlob = true;
  693. finished = true;
  694. if (scanToEnd === true) {
  695. continue;
  696. }
  697. break;
  698. }
  699. if (braceEscaped !== true && code === CHAR_COMMA$1) {
  700. isBrace = token.isBrace = true;
  701. isGlob = token.isGlob = true;
  702. finished = true;
  703. if (scanToEnd === true) {
  704. continue;
  705. }
  706. break;
  707. }
  708. if (code === CHAR_RIGHT_CURLY_BRACE$1) {
  709. braces--;
  710. if (braces === 0) {
  711. braceEscaped = false;
  712. isBrace = token.isBrace = true;
  713. finished = true;
  714. break;
  715. }
  716. }
  717. }
  718. if (scanToEnd === true) {
  719. continue;
  720. }
  721. break;
  722. }
  723. if (code === CHAR_FORWARD_SLASH) {
  724. slashes.push(index);
  725. tokens.push(token);
  726. token = { value: '', depth: 0, isGlob: false };
  727. if (finished === true) continue;
  728. if (prev === CHAR_DOT$1 && index === (start + 1)) {
  729. start += 2;
  730. continue;
  731. }
  732. lastIndex = index + 1;
  733. continue;
  734. }
  735. if (opts.noext !== true) {
  736. const isExtglobChar = code === CHAR_PLUS
  737. || code === CHAR_AT
  738. || code === CHAR_ASTERISK
  739. || code === CHAR_QUESTION_MARK
  740. || code === CHAR_EXCLAMATION_MARK;
  741. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
  742. isGlob = token.isGlob = true;
  743. isExtglob = token.isExtglob = true;
  744. finished = true;
  745. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  746. negatedExtglob = true;
  747. }
  748. if (scanToEnd === true) {
  749. while (eos() !== true && (code = advance())) {
  750. if (code === CHAR_BACKWARD_SLASH) {
  751. backslashes = token.backslashes = true;
  752. code = advance();
  753. continue;
  754. }
  755. if (code === CHAR_RIGHT_PARENTHESES$1) {
  756. isGlob = token.isGlob = true;
  757. finished = true;
  758. break;
  759. }
  760. }
  761. continue;
  762. }
  763. break;
  764. }
  765. }
  766. if (code === CHAR_ASTERISK) {
  767. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  768. isGlob = token.isGlob = true;
  769. finished = true;
  770. if (scanToEnd === true) {
  771. continue;
  772. }
  773. break;
  774. }
  775. if (code === CHAR_QUESTION_MARK) {
  776. isGlob = token.isGlob = true;
  777. finished = true;
  778. if (scanToEnd === true) {
  779. continue;
  780. }
  781. break;
  782. }
  783. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  784. while (eos() !== true && (next = advance())) {
  785. if (next === CHAR_BACKWARD_SLASH) {
  786. backslashes = token.backslashes = true;
  787. advance();
  788. continue;
  789. }
  790. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  791. isBracket = token.isBracket = true;
  792. isGlob = token.isGlob = true;
  793. finished = true;
  794. break;
  795. }
  796. }
  797. if (scanToEnd === true) {
  798. continue;
  799. }
  800. break;
  801. }
  802. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  803. negated = token.negated = true;
  804. start++;
  805. continue;
  806. }
  807. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
  808. isGlob = token.isGlob = true;
  809. if (scanToEnd === true) {
  810. while (eos() !== true && (code = advance())) {
  811. if (code === CHAR_LEFT_PARENTHESES$1) {
  812. backslashes = token.backslashes = true;
  813. code = advance();
  814. continue;
  815. }
  816. if (code === CHAR_RIGHT_PARENTHESES$1) {
  817. finished = true;
  818. break;
  819. }
  820. }
  821. continue;
  822. }
  823. break;
  824. }
  825. if (isGlob === true) {
  826. finished = true;
  827. if (scanToEnd === true) {
  828. continue;
  829. }
  830. break;
  831. }
  832. }
  833. if (opts.noext === true) {
  834. isExtglob = false;
  835. isGlob = false;
  836. }
  837. let base = str;
  838. let prefix = '';
  839. let glob = '';
  840. if (start > 0) {
  841. prefix = str.slice(0, start);
  842. str = str.slice(start);
  843. lastIndex -= start;
  844. }
  845. if (base && isGlob === true && lastIndex > 0) {
  846. base = str.slice(0, lastIndex);
  847. glob = str.slice(lastIndex);
  848. } else if (isGlob === true) {
  849. base = '';
  850. glob = str;
  851. } else {
  852. base = str;
  853. }
  854. if (base && base !== '' && base !== '/' && base !== str) {
  855. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  856. base = base.slice(0, -1);
  857. }
  858. }
  859. if (opts.unescape === true) {
  860. if (glob) glob = utils$j.removeBackslashes(glob);
  861. if (base && backslashes === true) {
  862. base = utils$j.removeBackslashes(base);
  863. }
  864. }
  865. const state = {
  866. prefix,
  867. input,
  868. start,
  869. base,
  870. glob,
  871. isBrace,
  872. isBracket,
  873. isGlob,
  874. isExtglob,
  875. isGlobstar,
  876. negated,
  877. negatedExtglob
  878. };
  879. if (opts.tokens === true) {
  880. state.maxDepth = 0;
  881. if (!isPathSeparator(code)) {
  882. tokens.push(token);
  883. }
  884. state.tokens = tokens;
  885. }
  886. if (opts.parts === true || opts.tokens === true) {
  887. let prevIndex;
  888. for (let idx = 0; idx < slashes.length; idx++) {
  889. const n = prevIndex ? prevIndex + 1 : start;
  890. const i = slashes[idx];
  891. const value = input.slice(n, i);
  892. if (opts.tokens) {
  893. if (idx === 0 && start !== 0) {
  894. tokens[idx].isPrefix = true;
  895. tokens[idx].value = prefix;
  896. } else {
  897. tokens[idx].value = value;
  898. }
  899. depth(tokens[idx]);
  900. state.maxDepth += tokens[idx].depth;
  901. }
  902. if (idx !== 0 || value !== '') {
  903. parts.push(value);
  904. }
  905. prevIndex = i;
  906. }
  907. if (prevIndex && prevIndex + 1 < input.length) {
  908. const value = input.slice(prevIndex + 1);
  909. parts.push(value);
  910. if (opts.tokens) {
  911. tokens[tokens.length - 1].value = value;
  912. depth(tokens[tokens.length - 1]);
  913. state.maxDepth += tokens[tokens.length - 1].depth;
  914. }
  915. }
  916. state.slashes = slashes;
  917. state.parts = parts;
  918. }
  919. return state;
  920. };
  921. var scan_1 = scan$2;
  922. const constants$5 = constants$6;
  923. const utils$i = utils$k;
  924. /**
  925. * Constants
  926. */
  927. const {
  928. MAX_LENGTH: MAX_LENGTH$1,
  929. POSIX_REGEX_SOURCE,
  930. REGEX_NON_SPECIAL_CHARS,
  931. REGEX_SPECIAL_CHARS_BACKREF,
  932. REPLACEMENTS
  933. } = constants$5;
  934. /**
  935. * Helpers
  936. */
  937. const expandRange = (args, options) => {
  938. if (typeof options.expandRange === 'function') {
  939. return options.expandRange(...args, options);
  940. }
  941. args.sort();
  942. const value = `[${args.join('-')}]`;
  943. return value;
  944. };
  945. /**
  946. * Create the message for a syntax error
  947. */
  948. const syntaxError = (type, char) => {
  949. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  950. };
  951. /**
  952. * Parse the given input string.
  953. * @param {String} input
  954. * @param {Object} options
  955. * @return {Object}
  956. */
  957. const parse$h = (input, options) => {
  958. if (typeof input !== 'string') {
  959. throw new TypeError('Expected a string');
  960. }
  961. input = REPLACEMENTS[input] || input;
  962. const opts = { ...options };
  963. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  964. let len = input.length;
  965. if (len > max) {
  966. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  967. }
  968. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  969. const tokens = [bos];
  970. const capture = opts.capture ? '' : '?:';
  971. const win32 = utils$i.isWindows(options);
  972. // create constants based on platform, for windows or posix
  973. const PLATFORM_CHARS = constants$5.globChars(win32);
  974. const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS);
  975. const {
  976. DOT_LITERAL,
  977. PLUS_LITERAL,
  978. SLASH_LITERAL,
  979. ONE_CHAR,
  980. DOTS_SLASH,
  981. NO_DOT,
  982. NO_DOT_SLASH,
  983. NO_DOTS_SLASH,
  984. QMARK,
  985. QMARK_NO_DOT,
  986. STAR,
  987. START_ANCHOR
  988. } = PLATFORM_CHARS;
  989. const globstar = opts => {
  990. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  991. };
  992. const nodot = opts.dot ? '' : NO_DOT;
  993. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  994. let star = opts.bash === true ? globstar(opts) : STAR;
  995. if (opts.capture) {
  996. star = `(${star})`;
  997. }
  998. // minimatch options support
  999. if (typeof opts.noext === 'boolean') {
  1000. opts.noextglob = opts.noext;
  1001. }
  1002. const state = {
  1003. input,
  1004. index: -1,
  1005. start: 0,
  1006. dot: opts.dot === true,
  1007. consumed: '',
  1008. output: '',
  1009. prefix: '',
  1010. backtrack: false,
  1011. negated: false,
  1012. brackets: 0,
  1013. braces: 0,
  1014. parens: 0,
  1015. quotes: 0,
  1016. globstar: false,
  1017. tokens
  1018. };
  1019. input = utils$i.removePrefix(input, state);
  1020. len = input.length;
  1021. const extglobs = [];
  1022. const braces = [];
  1023. const stack = [];
  1024. let prev = bos;
  1025. let value;
  1026. /**
  1027. * Tokenizing helpers
  1028. */
  1029. const eos = () => state.index === len - 1;
  1030. const peek = state.peek = (n = 1) => input[state.index + n];
  1031. const advance = state.advance = () => input[++state.index] || '';
  1032. const remaining = () => input.slice(state.index + 1);
  1033. const consume = (value = '', num = 0) => {
  1034. state.consumed += value;
  1035. state.index += num;
  1036. };
  1037. const append = token => {
  1038. state.output += token.output != null ? token.output : token.value;
  1039. consume(token.value);
  1040. };
  1041. const negate = () => {
  1042. let count = 1;
  1043. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1044. advance();
  1045. state.start++;
  1046. count++;
  1047. }
  1048. if (count % 2 === 0) {
  1049. return false;
  1050. }
  1051. state.negated = true;
  1052. state.start++;
  1053. return true;
  1054. };
  1055. const increment = type => {
  1056. state[type]++;
  1057. stack.push(type);
  1058. };
  1059. const decrement = type => {
  1060. state[type]--;
  1061. stack.pop();
  1062. };
  1063. /**
  1064. * Push tokens onto the tokens array. This helper speeds up
  1065. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1066. * and 2) helping us avoid creating extra tokens when consecutive
  1067. * characters are plain text. This improves performance and simplifies
  1068. * lookbehinds.
  1069. */
  1070. const push = tok => {
  1071. if (prev.type === 'globstar') {
  1072. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1073. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1074. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1075. state.output = state.output.slice(0, -prev.output.length);
  1076. prev.type = 'star';
  1077. prev.value = '*';
  1078. prev.output = star;
  1079. state.output += prev.output;
  1080. }
  1081. }
  1082. if (extglobs.length && tok.type !== 'paren') {
  1083. extglobs[extglobs.length - 1].inner += tok.value;
  1084. }
  1085. if (tok.value || tok.output) append(tok);
  1086. if (prev && prev.type === 'text' && tok.type === 'text') {
  1087. prev.value += tok.value;
  1088. prev.output = (prev.output || '') + tok.value;
  1089. return;
  1090. }
  1091. tok.prev = prev;
  1092. tokens.push(tok);
  1093. prev = tok;
  1094. };
  1095. const extglobOpen = (type, value) => {
  1096. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1097. token.prev = prev;
  1098. token.parens = state.parens;
  1099. token.output = state.output;
  1100. const output = (opts.capture ? '(' : '') + token.open;
  1101. increment('parens');
  1102. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1103. push({ type: 'paren', extglob: true, value: advance(), output });
  1104. extglobs.push(token);
  1105. };
  1106. const extglobClose = token => {
  1107. let output = token.close + (opts.capture ? ')' : '');
  1108. let rest;
  1109. if (token.type === 'negate') {
  1110. let extglobStar = star;
  1111. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1112. extglobStar = globstar(opts);
  1113. }
  1114. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1115. output = token.close = `)$))${extglobStar}`;
  1116. }
  1117. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1118. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1119. // In this case, we need to parse the string and use it in the output of the original pattern.
  1120. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1121. //
  1122. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1123. const expression = parse$h(rest, { ...options, fastpaths: false }).output;
  1124. output = token.close = `)${expression})${extglobStar})`;
  1125. }
  1126. if (token.prev.type === 'bos') {
  1127. state.negatedExtglob = true;
  1128. }
  1129. }
  1130. push({ type: 'paren', extglob: true, value, output });
  1131. decrement('parens');
  1132. };
  1133. /**
  1134. * Fast paths
  1135. */
  1136. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1137. let backslashes = false;
  1138. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1139. if (first === '\\') {
  1140. backslashes = true;
  1141. return m;
  1142. }
  1143. if (first === '?') {
  1144. if (esc) {
  1145. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1146. }
  1147. if (index === 0) {
  1148. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1149. }
  1150. return QMARK.repeat(chars.length);
  1151. }
  1152. if (first === '.') {
  1153. return DOT_LITERAL.repeat(chars.length);
  1154. }
  1155. if (first === '*') {
  1156. if (esc) {
  1157. return esc + first + (rest ? star : '');
  1158. }
  1159. return star;
  1160. }
  1161. return esc ? m : `\\${m}`;
  1162. });
  1163. if (backslashes === true) {
  1164. if (opts.unescape === true) {
  1165. output = output.replace(/\\/g, '');
  1166. } else {
  1167. output = output.replace(/\\+/g, m => {
  1168. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1169. });
  1170. }
  1171. }
  1172. if (output === input && opts.contains === true) {
  1173. state.output = input;
  1174. return state;
  1175. }
  1176. state.output = utils$i.wrapOutput(output, state, options);
  1177. return state;
  1178. }
  1179. /**
  1180. * Tokenize input until we reach end-of-string
  1181. */
  1182. while (!eos()) {
  1183. value = advance();
  1184. if (value === '\u0000') {
  1185. continue;
  1186. }
  1187. /**
  1188. * Escaped characters
  1189. */
  1190. if (value === '\\') {
  1191. const next = peek();
  1192. if (next === '/' && opts.bash !== true) {
  1193. continue;
  1194. }
  1195. if (next === '.' || next === ';') {
  1196. continue;
  1197. }
  1198. if (!next) {
  1199. value += '\\';
  1200. push({ type: 'text', value });
  1201. continue;
  1202. }
  1203. // collapse slashes to reduce potential for exploits
  1204. const match = /^\\+/.exec(remaining());
  1205. let slashes = 0;
  1206. if (match && match[0].length > 2) {
  1207. slashes = match[0].length;
  1208. state.index += slashes;
  1209. if (slashes % 2 !== 0) {
  1210. value += '\\';
  1211. }
  1212. }
  1213. if (opts.unescape === true) {
  1214. value = advance();
  1215. } else {
  1216. value += advance();
  1217. }
  1218. if (state.brackets === 0) {
  1219. push({ type: 'text', value });
  1220. continue;
  1221. }
  1222. }
  1223. /**
  1224. * If we're inside a regex character class, continue
  1225. * until we reach the closing bracket.
  1226. */
  1227. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1228. if (opts.posix !== false && value === ':') {
  1229. const inner = prev.value.slice(1);
  1230. if (inner.includes('[')) {
  1231. prev.posix = true;
  1232. if (inner.includes(':')) {
  1233. const idx = prev.value.lastIndexOf('[');
  1234. const pre = prev.value.slice(0, idx);
  1235. const rest = prev.value.slice(idx + 2);
  1236. const posix = POSIX_REGEX_SOURCE[rest];
  1237. if (posix) {
  1238. prev.value = pre + posix;
  1239. state.backtrack = true;
  1240. advance();
  1241. if (!bos.output && tokens.indexOf(prev) === 1) {
  1242. bos.output = ONE_CHAR;
  1243. }
  1244. continue;
  1245. }
  1246. }
  1247. }
  1248. }
  1249. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1250. value = `\\${value}`;
  1251. }
  1252. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1253. value = `\\${value}`;
  1254. }
  1255. if (opts.posix === true && value === '!' && prev.value === '[') {
  1256. value = '^';
  1257. }
  1258. prev.value += value;
  1259. append({ value });
  1260. continue;
  1261. }
  1262. /**
  1263. * If we're inside a quoted string, continue
  1264. * until we reach the closing double quote.
  1265. */
  1266. if (state.quotes === 1 && value !== '"') {
  1267. value = utils$i.escapeRegex(value);
  1268. prev.value += value;
  1269. append({ value });
  1270. continue;
  1271. }
  1272. /**
  1273. * Double quotes
  1274. */
  1275. if (value === '"') {
  1276. state.quotes = state.quotes === 1 ? 0 : 1;
  1277. if (opts.keepQuotes === true) {
  1278. push({ type: 'text', value });
  1279. }
  1280. continue;
  1281. }
  1282. /**
  1283. * Parentheses
  1284. */
  1285. if (value === '(') {
  1286. increment('parens');
  1287. push({ type: 'paren', value });
  1288. continue;
  1289. }
  1290. if (value === ')') {
  1291. if (state.parens === 0 && opts.strictBrackets === true) {
  1292. throw new SyntaxError(syntaxError('opening', '('));
  1293. }
  1294. const extglob = extglobs[extglobs.length - 1];
  1295. if (extglob && state.parens === extglob.parens + 1) {
  1296. extglobClose(extglobs.pop());
  1297. continue;
  1298. }
  1299. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1300. decrement('parens');
  1301. continue;
  1302. }
  1303. /**
  1304. * Square brackets
  1305. */
  1306. if (value === '[') {
  1307. if (opts.nobracket === true || !remaining().includes(']')) {
  1308. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1309. throw new SyntaxError(syntaxError('closing', ']'));
  1310. }
  1311. value = `\\${value}`;
  1312. } else {
  1313. increment('brackets');
  1314. }
  1315. push({ type: 'bracket', value });
  1316. continue;
  1317. }
  1318. if (value === ']') {
  1319. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1320. push({ type: 'text', value, output: `\\${value}` });
  1321. continue;
  1322. }
  1323. if (state.brackets === 0) {
  1324. if (opts.strictBrackets === true) {
  1325. throw new SyntaxError(syntaxError('opening', '['));
  1326. }
  1327. push({ type: 'text', value, output: `\\${value}` });
  1328. continue;
  1329. }
  1330. decrement('brackets');
  1331. const prevValue = prev.value.slice(1);
  1332. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1333. value = `/${value}`;
  1334. }
  1335. prev.value += value;
  1336. append({ value });
  1337. // when literal brackets are explicitly disabled
  1338. // assume we should match with a regex character class
  1339. if (opts.literalBrackets === false || utils$i.hasRegexChars(prevValue)) {
  1340. continue;
  1341. }
  1342. const escaped = utils$i.escapeRegex(prev.value);
  1343. state.output = state.output.slice(0, -prev.value.length);
  1344. // when literal brackets are explicitly enabled
  1345. // assume we should escape the brackets to match literal characters
  1346. if (opts.literalBrackets === true) {
  1347. state.output += escaped;
  1348. prev.value = escaped;
  1349. continue;
  1350. }
  1351. // when the user specifies nothing, try to match both
  1352. prev.value = `(${capture}${escaped}|${prev.value})`;
  1353. state.output += prev.value;
  1354. continue;
  1355. }
  1356. /**
  1357. * Braces
  1358. */
  1359. if (value === '{' && opts.nobrace !== true) {
  1360. increment('braces');
  1361. const open = {
  1362. type: 'brace',
  1363. value,
  1364. output: '(',
  1365. outputIndex: state.output.length,
  1366. tokensIndex: state.tokens.length
  1367. };
  1368. braces.push(open);
  1369. push(open);
  1370. continue;
  1371. }
  1372. if (value === '}') {
  1373. const brace = braces[braces.length - 1];
  1374. if (opts.nobrace === true || !brace) {
  1375. push({ type: 'text', value, output: value });
  1376. continue;
  1377. }
  1378. let output = ')';
  1379. if (brace.dots === true) {
  1380. const arr = tokens.slice();
  1381. const range = [];
  1382. for (let i = arr.length - 1; i >= 0; i--) {
  1383. tokens.pop();
  1384. if (arr[i].type === 'brace') {
  1385. break;
  1386. }
  1387. if (arr[i].type !== 'dots') {
  1388. range.unshift(arr[i].value);
  1389. }
  1390. }
  1391. output = expandRange(range, opts);
  1392. state.backtrack = true;
  1393. }
  1394. if (brace.comma !== true && brace.dots !== true) {
  1395. const out = state.output.slice(0, brace.outputIndex);
  1396. const toks = state.tokens.slice(brace.tokensIndex);
  1397. brace.value = brace.output = '\\{';
  1398. value = output = '\\}';
  1399. state.output = out;
  1400. for (const t of toks) {
  1401. state.output += (t.output || t.value);
  1402. }
  1403. }
  1404. push({ type: 'brace', value, output });
  1405. decrement('braces');
  1406. braces.pop();
  1407. continue;
  1408. }
  1409. /**
  1410. * Pipes
  1411. */
  1412. if (value === '|') {
  1413. if (extglobs.length > 0) {
  1414. extglobs[extglobs.length - 1].conditions++;
  1415. }
  1416. push({ type: 'text', value });
  1417. continue;
  1418. }
  1419. /**
  1420. * Commas
  1421. */
  1422. if (value === ',') {
  1423. let output = value;
  1424. const brace = braces[braces.length - 1];
  1425. if (brace && stack[stack.length - 1] === 'braces') {
  1426. brace.comma = true;
  1427. output = '|';
  1428. }
  1429. push({ type: 'comma', value, output });
  1430. continue;
  1431. }
  1432. /**
  1433. * Slashes
  1434. */
  1435. if (value === '/') {
  1436. // if the beginning of the glob is "./", advance the start
  1437. // to the current index, and don't add the "./" characters
  1438. // to the state. This greatly simplifies lookbehinds when
  1439. // checking for BOS characters like "!" and "." (not "./")
  1440. if (prev.type === 'dot' && state.index === state.start + 1) {
  1441. state.start = state.index + 1;
  1442. state.consumed = '';
  1443. state.output = '';
  1444. tokens.pop();
  1445. prev = bos; // reset "prev" to the first token
  1446. continue;
  1447. }
  1448. push({ type: 'slash', value, output: SLASH_LITERAL });
  1449. continue;
  1450. }
  1451. /**
  1452. * Dots
  1453. */
  1454. if (value === '.') {
  1455. if (state.braces > 0 && prev.type === 'dot') {
  1456. if (prev.value === '.') prev.output = DOT_LITERAL;
  1457. const brace = braces[braces.length - 1];
  1458. prev.type = 'dots';
  1459. prev.output += value;
  1460. prev.value += value;
  1461. brace.dots = true;
  1462. continue;
  1463. }
  1464. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  1465. push({ type: 'text', value, output: DOT_LITERAL });
  1466. continue;
  1467. }
  1468. push({ type: 'dot', value, output: DOT_LITERAL });
  1469. continue;
  1470. }
  1471. /**
  1472. * Question marks
  1473. */
  1474. if (value === '?') {
  1475. const isGroup = prev && prev.value === '(';
  1476. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1477. extglobOpen('qmark', value);
  1478. continue;
  1479. }
  1480. if (prev && prev.type === 'paren') {
  1481. const next = peek();
  1482. let output = value;
  1483. if (next === '<' && !utils$i.supportsLookbehinds()) {
  1484. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  1485. }
  1486. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  1487. output = `\\${value}`;
  1488. }
  1489. push({ type: 'text', value, output });
  1490. continue;
  1491. }
  1492. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  1493. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  1494. continue;
  1495. }
  1496. push({ type: 'qmark', value, output: QMARK });
  1497. continue;
  1498. }
  1499. /**
  1500. * Exclamation
  1501. */
  1502. if (value === '!') {
  1503. if (opts.noextglob !== true && peek() === '(') {
  1504. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  1505. extglobOpen('negate', value);
  1506. continue;
  1507. }
  1508. }
  1509. if (opts.nonegate !== true && state.index === 0) {
  1510. negate();
  1511. continue;
  1512. }
  1513. }
  1514. /**
  1515. * Plus
  1516. */
  1517. if (value === '+') {
  1518. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1519. extglobOpen('plus', value);
  1520. continue;
  1521. }
  1522. if ((prev && prev.value === '(') || opts.regex === false) {
  1523. push({ type: 'plus', value, output: PLUS_LITERAL });
  1524. continue;
  1525. }
  1526. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  1527. push({ type: 'plus', value });
  1528. continue;
  1529. }
  1530. push({ type: 'plus', value: PLUS_LITERAL });
  1531. continue;
  1532. }
  1533. /**
  1534. * Plain text
  1535. */
  1536. if (value === '@') {
  1537. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1538. push({ type: 'at', extglob: true, value, output: '' });
  1539. continue;
  1540. }
  1541. push({ type: 'text', value });
  1542. continue;
  1543. }
  1544. /**
  1545. * Plain text
  1546. */
  1547. if (value !== '*') {
  1548. if (value === '$' || value === '^') {
  1549. value = `\\${value}`;
  1550. }
  1551. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  1552. if (match) {
  1553. value += match[0];
  1554. state.index += match[0].length;
  1555. }
  1556. push({ type: 'text', value });
  1557. continue;
  1558. }
  1559. /**
  1560. * Stars
  1561. */
  1562. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  1563. prev.type = 'star';
  1564. prev.star = true;
  1565. prev.value += value;
  1566. prev.output = star;
  1567. state.backtrack = true;
  1568. state.globstar = true;
  1569. consume(value);
  1570. continue;
  1571. }
  1572. let rest = remaining();
  1573. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  1574. extglobOpen('star', value);
  1575. continue;
  1576. }
  1577. if (prev.type === 'star') {
  1578. if (opts.noglobstar === true) {
  1579. consume(value);
  1580. continue;
  1581. }
  1582. const prior = prev.prev;
  1583. const before = prior.prev;
  1584. const isStart = prior.type === 'slash' || prior.type === 'bos';
  1585. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  1586. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  1587. push({ type: 'star', value, output: '' });
  1588. continue;
  1589. }
  1590. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  1591. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  1592. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  1593. push({ type: 'star', value, output: '' });
  1594. continue;
  1595. }
  1596. // strip consecutive `/**/`
  1597. while (rest.slice(0, 3) === '/**') {
  1598. const after = input[state.index + 4];
  1599. if (after && after !== '/') {
  1600. break;
  1601. }
  1602. rest = rest.slice(3);
  1603. consume('/**', 3);
  1604. }
  1605. if (prior.type === 'bos' && eos()) {
  1606. prev.type = 'globstar';
  1607. prev.value += value;
  1608. prev.output = globstar(opts);
  1609. state.output = prev.output;
  1610. state.globstar = true;
  1611. consume(value);
  1612. continue;
  1613. }
  1614. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  1615. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1616. prior.output = `(?:${prior.output}`;
  1617. prev.type = 'globstar';
  1618. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  1619. prev.value += value;
  1620. state.globstar = true;
  1621. state.output += prior.output + prev.output;
  1622. consume(value);
  1623. continue;
  1624. }
  1625. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  1626. const end = rest[1] !== void 0 ? '|$' : '';
  1627. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1628. prior.output = `(?:${prior.output}`;
  1629. prev.type = 'globstar';
  1630. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  1631. prev.value += value;
  1632. state.output += prior.output + prev.output;
  1633. state.globstar = true;
  1634. consume(value + advance());
  1635. push({ type: 'slash', value: '/', output: '' });
  1636. continue;
  1637. }
  1638. if (prior.type === 'bos' && rest[0] === '/') {
  1639. prev.type = 'globstar';
  1640. prev.value += value;
  1641. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  1642. state.output = prev.output;
  1643. state.globstar = true;
  1644. consume(value + advance());
  1645. push({ type: 'slash', value: '/', output: '' });
  1646. continue;
  1647. }
  1648. // remove single star from output
  1649. state.output = state.output.slice(0, -prev.output.length);
  1650. // reset previous token to globstar
  1651. prev.type = 'globstar';
  1652. prev.output = globstar(opts);
  1653. prev.value += value;
  1654. // reset output with globstar
  1655. state.output += prev.output;
  1656. state.globstar = true;
  1657. consume(value);
  1658. continue;
  1659. }
  1660. const token = { type: 'star', value, output: star };
  1661. if (opts.bash === true) {
  1662. token.output = '.*?';
  1663. if (prev.type === 'bos' || prev.type === 'slash') {
  1664. token.output = nodot + token.output;
  1665. }
  1666. push(token);
  1667. continue;
  1668. }
  1669. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  1670. token.output = value;
  1671. push(token);
  1672. continue;
  1673. }
  1674. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  1675. if (prev.type === 'dot') {
  1676. state.output += NO_DOT_SLASH;
  1677. prev.output += NO_DOT_SLASH;
  1678. } else if (opts.dot === true) {
  1679. state.output += NO_DOTS_SLASH;
  1680. prev.output += NO_DOTS_SLASH;
  1681. } else {
  1682. state.output += nodot;
  1683. prev.output += nodot;
  1684. }
  1685. if (peek() !== '*') {
  1686. state.output += ONE_CHAR;
  1687. prev.output += ONE_CHAR;
  1688. }
  1689. }
  1690. push(token);
  1691. }
  1692. while (state.brackets > 0) {
  1693. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  1694. state.output = utils$i.escapeLast(state.output, '[');
  1695. decrement('brackets');
  1696. }
  1697. while (state.parens > 0) {
  1698. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  1699. state.output = utils$i.escapeLast(state.output, '(');
  1700. decrement('parens');
  1701. }
  1702. while (state.braces > 0) {
  1703. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  1704. state.output = utils$i.escapeLast(state.output, '{');
  1705. decrement('braces');
  1706. }
  1707. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  1708. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  1709. }
  1710. // rebuild the output if we had to backtrack at any point
  1711. if (state.backtrack === true) {
  1712. state.output = '';
  1713. for (const token of state.tokens) {
  1714. state.output += token.output != null ? token.output : token.value;
  1715. if (token.suffix) {
  1716. state.output += token.suffix;
  1717. }
  1718. }
  1719. }
  1720. return state;
  1721. };
  1722. /**
  1723. * Fast paths for creating regular expressions for common glob patterns.
  1724. * This can significantly speed up processing and has very little downside
  1725. * impact when none of the fast paths match.
  1726. */
  1727. parse$h.fastpaths = (input, options) => {
  1728. const opts = { ...options };
  1729. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  1730. const len = input.length;
  1731. if (len > max) {
  1732. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1733. }
  1734. input = REPLACEMENTS[input] || input;
  1735. const win32 = utils$i.isWindows(options);
  1736. // create constants based on platform, for windows or posix
  1737. const {
  1738. DOT_LITERAL,
  1739. SLASH_LITERAL,
  1740. ONE_CHAR,
  1741. DOTS_SLASH,
  1742. NO_DOT,
  1743. NO_DOTS,
  1744. NO_DOTS_SLASH,
  1745. STAR,
  1746. START_ANCHOR
  1747. } = constants$5.globChars(win32);
  1748. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  1749. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  1750. const capture = opts.capture ? '' : '?:';
  1751. const state = { negated: false, prefix: '' };
  1752. let star = opts.bash === true ? '.*?' : STAR;
  1753. if (opts.capture) {
  1754. star = `(${star})`;
  1755. }
  1756. const globstar = opts => {
  1757. if (opts.noglobstar === true) return star;
  1758. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1759. };
  1760. const create = str => {
  1761. switch (str) {
  1762. case '*':
  1763. return `${nodot}${ONE_CHAR}${star}`;
  1764. case '.*':
  1765. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  1766. case '*.*':
  1767. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1768. case '*/*':
  1769. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  1770. case '**':
  1771. return nodot + globstar(opts);
  1772. case '**/*':
  1773. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  1774. case '**/*.*':
  1775. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1776. case '**/.*':
  1777. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  1778. default: {
  1779. const match = /^(.*?)\.(\w+)$/.exec(str);
  1780. if (!match) return;
  1781. const source = create(match[1]);
  1782. if (!source) return;
  1783. return source + DOT_LITERAL + match[2];
  1784. }
  1785. }
  1786. };
  1787. const output = utils$i.removePrefix(input, state);
  1788. let source = create(output);
  1789. if (source && opts.strictSlashes !== true) {
  1790. source += `${SLASH_LITERAL}?`;
  1791. }
  1792. return source;
  1793. };
  1794. var parse_1$3 = parse$h;
  1795. const path$m = require$$0$4;
  1796. const scan$1 = scan_1;
  1797. const parse$g = parse_1$3;
  1798. const utils$h = utils$k;
  1799. const constants$4 = constants$6;
  1800. const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val);
  1801. /**
  1802. * Creates a matcher function from one or more glob patterns. The
  1803. * returned function takes a string to match as its first argument,
  1804. * and returns true if the string is a match. The returned matcher
  1805. * function also takes a boolean as the second argument that, when true,
  1806. * returns an object with additional information.
  1807. *
  1808. * ```js
  1809. * const picomatch = require('picomatch');
  1810. * // picomatch(glob[, options]);
  1811. *
  1812. * const isMatch = picomatch('*.!(*a)');
  1813. * console.log(isMatch('a.a')); //=> false
  1814. * console.log(isMatch('a.b')); //=> true
  1815. * ```
  1816. * @name picomatch
  1817. * @param {String|Array} `globs` One or more glob patterns.
  1818. * @param {Object=} `options`
  1819. * @return {Function=} Returns a matcher function.
  1820. * @api public
  1821. */
  1822. const picomatch$5 = (glob, options, returnState = false) => {
  1823. if (Array.isArray(glob)) {
  1824. const fns = glob.map(input => picomatch$5(input, options, returnState));
  1825. const arrayMatcher = str => {
  1826. for (const isMatch of fns) {
  1827. const state = isMatch(str);
  1828. if (state) return state;
  1829. }
  1830. return false;
  1831. };
  1832. return arrayMatcher;
  1833. }
  1834. const isState = isObject$4(glob) && glob.tokens && glob.input;
  1835. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  1836. throw new TypeError('Expected pattern to be a non-empty string');
  1837. }
  1838. const opts = options || {};
  1839. const posix = utils$h.isWindows(options);
  1840. const regex = isState
  1841. ? picomatch$5.compileRe(glob, options)
  1842. : picomatch$5.makeRe(glob, options, false, true);
  1843. const state = regex.state;
  1844. delete regex.state;
  1845. let isIgnored = () => false;
  1846. if (opts.ignore) {
  1847. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  1848. isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState);
  1849. }
  1850. const matcher = (input, returnObject = false) => {
  1851. const { isMatch, match, output } = picomatch$5.test(input, regex, options, { glob, posix });
  1852. const result = { glob, state, regex, posix, input, output, match, isMatch };
  1853. if (typeof opts.onResult === 'function') {
  1854. opts.onResult(result);
  1855. }
  1856. if (isMatch === false) {
  1857. result.isMatch = false;
  1858. return returnObject ? result : false;
  1859. }
  1860. if (isIgnored(input)) {
  1861. if (typeof opts.onIgnore === 'function') {
  1862. opts.onIgnore(result);
  1863. }
  1864. result.isMatch = false;
  1865. return returnObject ? result : false;
  1866. }
  1867. if (typeof opts.onMatch === 'function') {
  1868. opts.onMatch(result);
  1869. }
  1870. return returnObject ? result : true;
  1871. };
  1872. if (returnState) {
  1873. matcher.state = state;
  1874. }
  1875. return matcher;
  1876. };
  1877. /**
  1878. * Test `input` with the given `regex`. This is used by the main
  1879. * `picomatch()` function to test the input string.
  1880. *
  1881. * ```js
  1882. * const picomatch = require('picomatch');
  1883. * // picomatch.test(input, regex[, options]);
  1884. *
  1885. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  1886. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  1887. * ```
  1888. * @param {String} `input` String to test.
  1889. * @param {RegExp} `regex`
  1890. * @return {Object} Returns an object with matching info.
  1891. * @api public
  1892. */
  1893. picomatch$5.test = (input, regex, options, { glob, posix } = {}) => {
  1894. if (typeof input !== 'string') {
  1895. throw new TypeError('Expected input to be a string');
  1896. }
  1897. if (input === '') {
  1898. return { isMatch: false, output: '' };
  1899. }
  1900. const opts = options || {};
  1901. const format = opts.format || (posix ? utils$h.toPosixSlashes : null);
  1902. let match = input === glob;
  1903. let output = (match && format) ? format(input) : input;
  1904. if (match === false) {
  1905. output = format ? format(input) : input;
  1906. match = output === glob;
  1907. }
  1908. if (match === false || opts.capture === true) {
  1909. if (opts.matchBase === true || opts.basename === true) {
  1910. match = picomatch$5.matchBase(input, regex, options, posix);
  1911. } else {
  1912. match = regex.exec(output);
  1913. }
  1914. }
  1915. return { isMatch: Boolean(match), match, output };
  1916. };
  1917. /**
  1918. * Match the basename of a filepath.
  1919. *
  1920. * ```js
  1921. * const picomatch = require('picomatch');
  1922. * // picomatch.matchBase(input, glob[, options]);
  1923. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  1924. * ```
  1925. * @param {String} `input` String to test.
  1926. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  1927. * @return {Boolean}
  1928. * @api public
  1929. */
  1930. picomatch$5.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => {
  1931. const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options);
  1932. return regex.test(path$m.basename(input));
  1933. };
  1934. /**
  1935. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  1936. *
  1937. * ```js
  1938. * const picomatch = require('picomatch');
  1939. * // picomatch.isMatch(string, patterns[, options]);
  1940. *
  1941. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  1942. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  1943. * ```
  1944. * @param {String|Array} str The string to test.
  1945. * @param {String|Array} patterns One or more glob patterns to use for matching.
  1946. * @param {Object} [options] See available [options](#options).
  1947. * @return {Boolean} Returns true if any patterns match `str`
  1948. * @api public
  1949. */
  1950. picomatch$5.isMatch = (str, patterns, options) => picomatch$5(patterns, options)(str);
  1951. /**
  1952. * Parse a glob pattern to create the source string for a regular
  1953. * expression.
  1954. *
  1955. * ```js
  1956. * const picomatch = require('picomatch');
  1957. * const result = picomatch.parse(pattern[, options]);
  1958. * ```
  1959. * @param {String} `pattern`
  1960. * @param {Object} `options`
  1961. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  1962. * @api public
  1963. */
  1964. picomatch$5.parse = (pattern, options) => {
  1965. if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options));
  1966. return parse$g(pattern, { ...options, fastpaths: false });
  1967. };
  1968. /**
  1969. * Scan a glob pattern to separate the pattern into segments.
  1970. *
  1971. * ```js
  1972. * const picomatch = require('picomatch');
  1973. * // picomatch.scan(input[, options]);
  1974. *
  1975. * const result = picomatch.scan('!./foo/*.js');
  1976. * console.log(result);
  1977. * { prefix: '!./',
  1978. * input: '!./foo/*.js',
  1979. * start: 3,
  1980. * base: 'foo',
  1981. * glob: '*.js',
  1982. * isBrace: false,
  1983. * isBracket: false,
  1984. * isGlob: true,
  1985. * isExtglob: false,
  1986. * isGlobstar: false,
  1987. * negated: true }
  1988. * ```
  1989. * @param {String} `input` Glob pattern to scan.
  1990. * @param {Object} `options`
  1991. * @return {Object} Returns an object with
  1992. * @api public
  1993. */
  1994. picomatch$5.scan = (input, options) => scan$1(input, options);
  1995. /**
  1996. * Compile a regular expression from the `state` object returned by the
  1997. * [parse()](#parse) method.
  1998. *
  1999. * @param {Object} `state`
  2000. * @param {Object} `options`
  2001. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2002. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2003. * @return {RegExp}
  2004. * @api public
  2005. */
  2006. picomatch$5.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2007. if (returnOutput === true) {
  2008. return state.output;
  2009. }
  2010. const opts = options || {};
  2011. const prepend = opts.contains ? '' : '^';
  2012. const append = opts.contains ? '' : '$';
  2013. let source = `${prepend}(?:${state.output})${append}`;
  2014. if (state && state.negated === true) {
  2015. source = `^(?!${source}).*$`;
  2016. }
  2017. const regex = picomatch$5.toRegex(source, options);
  2018. if (returnState === true) {
  2019. regex.state = state;
  2020. }
  2021. return regex;
  2022. };
  2023. /**
  2024. * Create a regular expression from a parsed glob pattern.
  2025. *
  2026. * ```js
  2027. * const picomatch = require('picomatch');
  2028. * const state = picomatch.parse('*.js');
  2029. * // picomatch.compileRe(state[, options]);
  2030. *
  2031. * console.log(picomatch.compileRe(state));
  2032. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2033. * ```
  2034. * @param {String} `state` The object returned from the `.parse` method.
  2035. * @param {Object} `options`
  2036. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  2037. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2038. * @return {RegExp} Returns a regex created from the given pattern.
  2039. * @api public
  2040. */
  2041. picomatch$5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2042. if (!input || typeof input !== 'string') {
  2043. throw new TypeError('Expected a non-empty string');
  2044. }
  2045. let parsed = { negated: false, fastpaths: true };
  2046. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2047. parsed.output = parse$g.fastpaths(input, options);
  2048. }
  2049. if (!parsed.output) {
  2050. parsed = parse$g(input, options);
  2051. }
  2052. return picomatch$5.compileRe(parsed, options, returnOutput, returnState);
  2053. };
  2054. /**
  2055. * Create a regular expression from the given regex source string.
  2056. *
  2057. * ```js
  2058. * const picomatch = require('picomatch');
  2059. * // picomatch.toRegex(source[, options]);
  2060. *
  2061. * const { output } = picomatch.parse('*.js');
  2062. * console.log(picomatch.toRegex(output));
  2063. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2064. * ```
  2065. * @param {String} `source` Regular expression source string.
  2066. * @param {Object} `options`
  2067. * @return {RegExp}
  2068. * @api public
  2069. */
  2070. picomatch$5.toRegex = (source, options) => {
  2071. try {
  2072. const opts = options || {};
  2073. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2074. } catch (err) {
  2075. if (options && options.debug === true) throw err;
  2076. return /$^/;
  2077. }
  2078. };
  2079. /**
  2080. * Picomatch constants.
  2081. * @return {Object}
  2082. */
  2083. picomatch$5.constants = constants$4;
  2084. /**
  2085. * Expose "picomatch"
  2086. */
  2087. var picomatch_1 = picomatch$5;
  2088. var picomatch$3 = picomatch_1;
  2089. var picomatch$4 = /*@__PURE__*/getDefaultExportFromCjs(picomatch$3);
  2090. const extractors = {
  2091. ArrayPattern(names, param) {
  2092. for (const element of param.elements) {
  2093. if (element)
  2094. extractors[element.type](names, element);
  2095. }
  2096. },
  2097. AssignmentPattern(names, param) {
  2098. extractors[param.left.type](names, param.left);
  2099. },
  2100. Identifier(names, param) {
  2101. names.push(param.name);
  2102. },
  2103. MemberExpression() { },
  2104. ObjectPattern(names, param) {
  2105. for (const prop of param.properties) {
  2106. // @ts-ignore Typescript reports that this is not a valid type
  2107. if (prop.type === 'RestElement') {
  2108. extractors.RestElement(names, prop);
  2109. }
  2110. else {
  2111. extractors[prop.value.type](names, prop.value);
  2112. }
  2113. }
  2114. },
  2115. RestElement(names, param) {
  2116. extractors[param.argument.type](names, param.argument);
  2117. }
  2118. };
  2119. const extractAssignedNames = function extractAssignedNames(param) {
  2120. const names = [];
  2121. extractors[param.type](names, param);
  2122. return names;
  2123. };
  2124. const blockDeclarations = {
  2125. const: true,
  2126. let: true
  2127. };
  2128. let Scope$1 = class Scope {
  2129. constructor(options = {}) {
  2130. this.parent = options.parent;
  2131. this.isBlockScope = !!options.block;
  2132. this.declarations = Object.create(null);
  2133. if (options.params) {
  2134. options.params.forEach((param) => {
  2135. extractAssignedNames(param).forEach((name) => {
  2136. this.declarations[name] = true;
  2137. });
  2138. });
  2139. }
  2140. }
  2141. addDeclaration(node, isBlockDeclaration, isVar) {
  2142. if (!isBlockDeclaration && this.isBlockScope) {
  2143. // it's a `var` or function node, and this
  2144. // is a block scope, so we need to go up
  2145. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  2146. }
  2147. else if (node.id) {
  2148. extractAssignedNames(node.id).forEach((name) => {
  2149. this.declarations[name] = true;
  2150. });
  2151. }
  2152. }
  2153. contains(name) {
  2154. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  2155. }
  2156. };
  2157. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  2158. let scope = new Scope$1();
  2159. walk$4(ast, {
  2160. enter(n, parent) {
  2161. const node = n;
  2162. // function foo () {...}
  2163. // class Foo {...}
  2164. if (/(Function|Class)Declaration/.test(node.type)) {
  2165. scope.addDeclaration(node, false, false);
  2166. }
  2167. // var foo = 1
  2168. if (node.type === 'VariableDeclaration') {
  2169. const { kind } = node;
  2170. const isBlockDeclaration = blockDeclarations[kind];
  2171. node.declarations.forEach((declaration) => {
  2172. scope.addDeclaration(declaration, isBlockDeclaration, true);
  2173. });
  2174. }
  2175. let newScope;
  2176. // create new function scope
  2177. if (/Function/.test(node.type)) {
  2178. const func = node;
  2179. newScope = new Scope$1({
  2180. parent: scope,
  2181. block: false,
  2182. params: func.params
  2183. });
  2184. // named function expressions - the name is considered
  2185. // part of the function's scope
  2186. if (func.type === 'FunctionExpression' && func.id) {
  2187. newScope.addDeclaration(func, false, false);
  2188. }
  2189. }
  2190. // create new for scope
  2191. if (/For(In|Of)?Statement/.test(node.type)) {
  2192. newScope = new Scope$1({
  2193. parent: scope,
  2194. block: true
  2195. });
  2196. }
  2197. // create new block scope
  2198. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  2199. newScope = new Scope$1({
  2200. parent: scope,
  2201. block: true
  2202. });
  2203. }
  2204. // catch clause has its own block scope
  2205. if (node.type === 'CatchClause') {
  2206. newScope = new Scope$1({
  2207. parent: scope,
  2208. params: node.param ? [node.param] : [],
  2209. block: true
  2210. });
  2211. }
  2212. if (newScope) {
  2213. Object.defineProperty(node, propertyName, {
  2214. value: newScope,
  2215. configurable: true
  2216. });
  2217. scope = newScope;
  2218. }
  2219. },
  2220. leave(n) {
  2221. const node = n;
  2222. if (node[propertyName])
  2223. scope = scope.parent;
  2224. }
  2225. });
  2226. return scope;
  2227. };
  2228. // Helper since Typescript can't detect readonly arrays with Array.isArray
  2229. function isArray$2(arg) {
  2230. return Array.isArray(arg);
  2231. }
  2232. function ensureArray(thing) {
  2233. if (isArray$2(thing))
  2234. return thing;
  2235. if (thing == null)
  2236. return [];
  2237. return [thing];
  2238. }
  2239. const normalizePath$5 = function normalizePath(filename) {
  2240. return filename.split(win32.sep).join(posix.sep);
  2241. };
  2242. function getMatcherString(id, resolutionBase) {
  2243. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
  2244. return normalizePath$5(id);
  2245. }
  2246. // resolve('') is valid and will default to process.cwd()
  2247. const basePath = normalizePath$5(resolve$3(resolutionBase || ''))
  2248. // escape all possible (posix + win) path characters that might interfere with regex
  2249. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  2250. // Note that we use posix.join because:
  2251. // 1. the basePath has been normalized to use /
  2252. // 2. the incoming glob (id) matcher, also uses /
  2253. // otherwise Node will force backslash (\) on windows
  2254. return posix.join(basePath, normalizePath$5(id));
  2255. }
  2256. const createFilter$1 = function createFilter(include, exclude, options) {
  2257. const resolutionBase = options && options.resolve;
  2258. const getMatcher = (id) => id instanceof RegExp
  2259. ? id
  2260. : {
  2261. test: (what) => {
  2262. // this refactor is a tad overly verbose but makes for easy debugging
  2263. const pattern = getMatcherString(id, resolutionBase);
  2264. const fn = picomatch$4(pattern, { dot: true });
  2265. const result = fn(what);
  2266. return result;
  2267. }
  2268. };
  2269. const includeMatchers = ensureArray(include).map(getMatcher);
  2270. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  2271. return function result(id) {
  2272. if (typeof id !== 'string')
  2273. return false;
  2274. if (/\0/.test(id))
  2275. return false;
  2276. const pathId = normalizePath$5(id);
  2277. for (let i = 0; i < excludeMatchers.length; ++i) {
  2278. const matcher = excludeMatchers[i];
  2279. if (matcher.test(pathId))
  2280. return false;
  2281. }
  2282. for (let i = 0; i < includeMatchers.length; ++i) {
  2283. const matcher = includeMatchers[i];
  2284. if (matcher.test(pathId))
  2285. return true;
  2286. }
  2287. return !includeMatchers.length;
  2288. };
  2289. };
  2290. const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  2291. const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  2292. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  2293. forbiddenIdentifiers.add('');
  2294. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  2295. let identifier = str
  2296. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2297. .replace(/[^$_a-zA-Z0-9]/g, '_');
  2298. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  2299. identifier = `_${identifier}`;
  2300. }
  2301. return identifier || '_';
  2302. };
  2303. function stringify$8(obj) {
  2304. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  2305. }
  2306. function serializeArray(arr, indent, baseIndent) {
  2307. let output = '[';
  2308. const separator = indent ? `\n${baseIndent}${indent}` : '';
  2309. for (let i = 0; i < arr.length; i++) {
  2310. const key = arr[i];
  2311. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  2312. }
  2313. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  2314. }
  2315. function serializeObject(obj, indent, baseIndent) {
  2316. let output = '{';
  2317. const separator = indent ? `\n${baseIndent}${indent}` : '';
  2318. const entries = Object.entries(obj);
  2319. for (let i = 0; i < entries.length; i++) {
  2320. const [key, value] = entries[i];
  2321. const stringKey = makeLegalIdentifier(key) === key ? key : stringify$8(key);
  2322. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  2323. }
  2324. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  2325. }
  2326. function serialize(obj, indent, baseIndent) {
  2327. if (typeof obj === 'object' && obj !== null) {
  2328. if (Array.isArray(obj))
  2329. return serializeArray(obj, indent, baseIndent);
  2330. if (obj instanceof Date)
  2331. return `new Date(${obj.getTime()})`;
  2332. if (obj instanceof RegExp)
  2333. return obj.toString();
  2334. return serializeObject(obj, indent, baseIndent);
  2335. }
  2336. if (typeof obj === 'number') {
  2337. if (obj === Infinity)
  2338. return 'Infinity';
  2339. if (obj === -Infinity)
  2340. return '-Infinity';
  2341. if (obj === 0)
  2342. return 1 / obj === Infinity ? '0' : '-0';
  2343. if (obj !== obj)
  2344. return 'NaN'; // eslint-disable-line no-self-compare
  2345. }
  2346. if (typeof obj === 'symbol') {
  2347. const key = Symbol.keyFor(obj);
  2348. // eslint-disable-next-line no-undefined
  2349. if (key !== undefined)
  2350. return `Symbol.for(${stringify$8(key)})`;
  2351. }
  2352. if (typeof obj === 'bigint')
  2353. return `${obj}n`;
  2354. return stringify$8(obj);
  2355. }
  2356. const dataToEsm = function dataToEsm(data, options = {}) {
  2357. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  2358. const _ = options.compact ? '' : ' ';
  2359. const n = options.compact ? '' : '\n';
  2360. const declarationType = options.preferConst ? 'const' : 'var';
  2361. if (options.namedExports === false ||
  2362. typeof data !== 'object' ||
  2363. Array.isArray(data) ||
  2364. data instanceof Date ||
  2365. data instanceof RegExp ||
  2366. data === null) {
  2367. const code = serialize(data, options.compact ? null : t, '');
  2368. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  2369. return `export default${magic}${code};`;
  2370. }
  2371. let namedExportCode = '';
  2372. const defaultExportRows = [];
  2373. for (const [key, value] of Object.entries(data)) {
  2374. if (key === makeLegalIdentifier(key)) {
  2375. if (options.objectShorthand)
  2376. defaultExportRows.push(key);
  2377. else
  2378. defaultExportRows.push(`${key}:${_}${key}`);
  2379. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  2380. }
  2381. else {
  2382. defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  2383. }
  2384. }
  2385. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  2386. };
  2387. var path$l = require$$0$4;
  2388. var commondir = function (basedir, relfiles) {
  2389. if (relfiles) {
  2390. var files = relfiles.map(function (r) {
  2391. return path$l.resolve(basedir, r);
  2392. });
  2393. }
  2394. else {
  2395. var files = basedir;
  2396. }
  2397. var res = files.slice(1).reduce(function (ps, file) {
  2398. if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
  2399. throw new Error('relative path without a basedir');
  2400. }
  2401. var xs = file.split(/\/+|\\+/);
  2402. for (
  2403. var i = 0;
  2404. ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
  2405. i++
  2406. );
  2407. return ps.slice(0, i);
  2408. }, files[0].split(/\/+|\\+/));
  2409. // Windows correctly handles paths with forward-slashes
  2410. return res.length > 1 ? res.join('/') : '/'
  2411. };
  2412. var getCommonDir = /*@__PURE__*/getDefaultExportFromCjs(commondir);
  2413. var old$1 = {};
  2414. // Copyright Joyent, Inc. and other Node contributors.
  2415. //
  2416. // Permission is hereby granted, free of charge, to any person obtaining a
  2417. // copy of this software and associated documentation files (the
  2418. // "Software"), to deal in the Software without restriction, including
  2419. // without limitation the rights to use, copy, modify, merge, publish,
  2420. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2421. // persons to whom the Software is furnished to do so, subject to the
  2422. // following conditions:
  2423. //
  2424. // The above copyright notice and this permission notice shall be included
  2425. // in all copies or substantial portions of the Software.
  2426. //
  2427. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2428. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2429. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2430. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2431. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2432. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2433. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2434. var pathModule = require$$0$4;
  2435. var isWindows$6 = process.platform === 'win32';
  2436. var fs$k = require$$0__default;
  2437. // JavaScript implementation of realpath, ported from node pre-v6
  2438. var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  2439. function rethrow() {
  2440. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  2441. // is fairly slow to generate.
  2442. var callback;
  2443. if (DEBUG$1) {
  2444. var backtrace = new Error;
  2445. callback = debugCallback;
  2446. } else
  2447. callback = missingCallback;
  2448. return callback;
  2449. function debugCallback(err) {
  2450. if (err) {
  2451. backtrace.message = err.message;
  2452. err = backtrace;
  2453. missingCallback(err);
  2454. }
  2455. }
  2456. function missingCallback(err) {
  2457. if (err) {
  2458. if (process.throwDeprecation)
  2459. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  2460. else if (!process.noDeprecation) {
  2461. var msg = 'fs: missing callback ' + (err.stack || err.message);
  2462. if (process.traceDeprecation)
  2463. console.trace(msg);
  2464. else
  2465. console.error(msg);
  2466. }
  2467. }
  2468. }
  2469. }
  2470. function maybeCallback(cb) {
  2471. return typeof cb === 'function' ? cb : rethrow();
  2472. }
  2473. // Regexp that finds the next partion of a (partial) path
  2474. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  2475. if (isWindows$6) {
  2476. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  2477. } else {
  2478. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  2479. }
  2480. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  2481. if (isWindows$6) {
  2482. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  2483. } else {
  2484. var splitRootRe = /^[\/]*/;
  2485. }
  2486. old$1.realpathSync = function realpathSync(p, cache) {
  2487. // make p is absolute
  2488. p = pathModule.resolve(p);
  2489. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  2490. return cache[p];
  2491. }
  2492. var original = p,
  2493. seenLinks = {},
  2494. knownHard = {};
  2495. // current character position in p
  2496. var pos;
  2497. // the partial path so far, including a trailing slash if any
  2498. var current;
  2499. // the partial path without a trailing slash (except when pointing at a root)
  2500. var base;
  2501. // the partial path scanned in the previous round, with slash
  2502. var previous;
  2503. start();
  2504. function start() {
  2505. // Skip over roots
  2506. var m = splitRootRe.exec(p);
  2507. pos = m[0].length;
  2508. current = m[0];
  2509. base = m[0];
  2510. previous = '';
  2511. // On windows, check that the root exists. On unix there is no need.
  2512. if (isWindows$6 && !knownHard[base]) {
  2513. fs$k.lstatSync(base);
  2514. knownHard[base] = true;
  2515. }
  2516. }
  2517. // walk down the path, swapping out linked pathparts for their real
  2518. // values
  2519. // NB: p.length changes.
  2520. while (pos < p.length) {
  2521. // find the next part
  2522. nextPartRe.lastIndex = pos;
  2523. var result = nextPartRe.exec(p);
  2524. previous = current;
  2525. current += result[0];
  2526. base = previous + result[1];
  2527. pos = nextPartRe.lastIndex;
  2528. // continue if not a symlink
  2529. if (knownHard[base] || (cache && cache[base] === base)) {
  2530. continue;
  2531. }
  2532. var resolvedLink;
  2533. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  2534. // some known symbolic link. no need to stat again.
  2535. resolvedLink = cache[base];
  2536. } else {
  2537. var stat = fs$k.lstatSync(base);
  2538. if (!stat.isSymbolicLink()) {
  2539. knownHard[base] = true;
  2540. if (cache) cache[base] = base;
  2541. continue;
  2542. }
  2543. // read the link if it wasn't read before
  2544. // dev/ino always return 0 on windows, so skip the check.
  2545. var linkTarget = null;
  2546. if (!isWindows$6) {
  2547. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  2548. if (seenLinks.hasOwnProperty(id)) {
  2549. linkTarget = seenLinks[id];
  2550. }
  2551. }
  2552. if (linkTarget === null) {
  2553. fs$k.statSync(base);
  2554. linkTarget = fs$k.readlinkSync(base);
  2555. }
  2556. resolvedLink = pathModule.resolve(previous, linkTarget);
  2557. // track this, if given a cache.
  2558. if (cache) cache[base] = resolvedLink;
  2559. if (!isWindows$6) seenLinks[id] = linkTarget;
  2560. }
  2561. // resolve the link, then start over
  2562. p = pathModule.resolve(resolvedLink, p.slice(pos));
  2563. start();
  2564. }
  2565. if (cache) cache[original] = p;
  2566. return p;
  2567. };
  2568. old$1.realpath = function realpath(p, cache, cb) {
  2569. if (typeof cb !== 'function') {
  2570. cb = maybeCallback(cache);
  2571. cache = null;
  2572. }
  2573. // make p is absolute
  2574. p = pathModule.resolve(p);
  2575. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  2576. return process.nextTick(cb.bind(null, null, cache[p]));
  2577. }
  2578. var original = p,
  2579. seenLinks = {},
  2580. knownHard = {};
  2581. // current character position in p
  2582. var pos;
  2583. // the partial path so far, including a trailing slash if any
  2584. var current;
  2585. // the partial path without a trailing slash (except when pointing at a root)
  2586. var base;
  2587. // the partial path scanned in the previous round, with slash
  2588. var previous;
  2589. start();
  2590. function start() {
  2591. // Skip over roots
  2592. var m = splitRootRe.exec(p);
  2593. pos = m[0].length;
  2594. current = m[0];
  2595. base = m[0];
  2596. previous = '';
  2597. // On windows, check that the root exists. On unix there is no need.
  2598. if (isWindows$6 && !knownHard[base]) {
  2599. fs$k.lstat(base, function(err) {
  2600. if (err) return cb(err);
  2601. knownHard[base] = true;
  2602. LOOP();
  2603. });
  2604. } else {
  2605. process.nextTick(LOOP);
  2606. }
  2607. }
  2608. // walk down the path, swapping out linked pathparts for their real
  2609. // values
  2610. function LOOP() {
  2611. // stop if scanned past end of path
  2612. if (pos >= p.length) {
  2613. if (cache) cache[original] = p;
  2614. return cb(null, p);
  2615. }
  2616. // find the next part
  2617. nextPartRe.lastIndex = pos;
  2618. var result = nextPartRe.exec(p);
  2619. previous = current;
  2620. current += result[0];
  2621. base = previous + result[1];
  2622. pos = nextPartRe.lastIndex;
  2623. // continue if not a symlink
  2624. if (knownHard[base] || (cache && cache[base] === base)) {
  2625. return process.nextTick(LOOP);
  2626. }
  2627. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  2628. // known symbolic link. no need to stat again.
  2629. return gotResolvedLink(cache[base]);
  2630. }
  2631. return fs$k.lstat(base, gotStat);
  2632. }
  2633. function gotStat(err, stat) {
  2634. if (err) return cb(err);
  2635. // if not a symlink, skip to the next path part
  2636. if (!stat.isSymbolicLink()) {
  2637. knownHard[base] = true;
  2638. if (cache) cache[base] = base;
  2639. return process.nextTick(LOOP);
  2640. }
  2641. // stat & read the link if not read before
  2642. // call gotTarget as soon as the link target is known
  2643. // dev/ino always return 0 on windows, so skip the check.
  2644. if (!isWindows$6) {
  2645. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  2646. if (seenLinks.hasOwnProperty(id)) {
  2647. return gotTarget(null, seenLinks[id], base);
  2648. }
  2649. }
  2650. fs$k.stat(base, function(err) {
  2651. if (err) return cb(err);
  2652. fs$k.readlink(base, function(err, target) {
  2653. if (!isWindows$6) seenLinks[id] = target;
  2654. gotTarget(err, target);
  2655. });
  2656. });
  2657. }
  2658. function gotTarget(err, target, base) {
  2659. if (err) return cb(err);
  2660. var resolvedLink = pathModule.resolve(previous, target);
  2661. if (cache) cache[base] = resolvedLink;
  2662. gotResolvedLink(resolvedLink);
  2663. }
  2664. function gotResolvedLink(resolvedLink) {
  2665. // resolve the link, then start over
  2666. p = pathModule.resolve(resolvedLink, p.slice(pos));
  2667. start();
  2668. }
  2669. };
  2670. var fs_realpath = realpath$2;
  2671. realpath$2.realpath = realpath$2;
  2672. realpath$2.sync = realpathSync;
  2673. realpath$2.realpathSync = realpathSync;
  2674. realpath$2.monkeypatch = monkeypatch;
  2675. realpath$2.unmonkeypatch = unmonkeypatch;
  2676. var fs$j = require$$0__default;
  2677. var origRealpath = fs$j.realpath;
  2678. var origRealpathSync = fs$j.realpathSync;
  2679. var version$4 = process.version;
  2680. var ok = /^v[0-5]\./.test(version$4);
  2681. var old = old$1;
  2682. function newError (er) {
  2683. return er && er.syscall === 'realpath' && (
  2684. er.code === 'ELOOP' ||
  2685. er.code === 'ENOMEM' ||
  2686. er.code === 'ENAMETOOLONG'
  2687. )
  2688. }
  2689. function realpath$2 (p, cache, cb) {
  2690. if (ok) {
  2691. return origRealpath(p, cache, cb)
  2692. }
  2693. if (typeof cache === 'function') {
  2694. cb = cache;
  2695. cache = null;
  2696. }
  2697. origRealpath(p, cache, function (er, result) {
  2698. if (newError(er)) {
  2699. old.realpath(p, cache, cb);
  2700. } else {
  2701. cb(er, result);
  2702. }
  2703. });
  2704. }
  2705. function realpathSync (p, cache) {
  2706. if (ok) {
  2707. return origRealpathSync(p, cache)
  2708. }
  2709. try {
  2710. return origRealpathSync(p, cache)
  2711. } catch (er) {
  2712. if (newError(er)) {
  2713. return old.realpathSync(p, cache)
  2714. } else {
  2715. throw er
  2716. }
  2717. }
  2718. }
  2719. function monkeypatch () {
  2720. fs$j.realpath = realpath$2;
  2721. fs$j.realpathSync = realpathSync;
  2722. }
  2723. function unmonkeypatch () {
  2724. fs$j.realpath = origRealpath;
  2725. fs$j.realpathSync = origRealpathSync;
  2726. }
  2727. const isWindows$5 = typeof process === 'object' &&
  2728. process &&
  2729. process.platform === 'win32';
  2730. var path$k = isWindows$5 ? { sep: '\\' } : { sep: '/' };
  2731. var balancedMatch = balanced$1;
  2732. function balanced$1(a, b, str) {
  2733. if (a instanceof RegExp) a = maybeMatch(a, str);
  2734. if (b instanceof RegExp) b = maybeMatch(b, str);
  2735. var r = range$1(a, b, str);
  2736. return r && {
  2737. start: r[0],
  2738. end: r[1],
  2739. pre: str.slice(0, r[0]),
  2740. body: str.slice(r[0] + a.length, r[1]),
  2741. post: str.slice(r[1] + b.length)
  2742. };
  2743. }
  2744. function maybeMatch(reg, str) {
  2745. var m = str.match(reg);
  2746. return m ? m[0] : null;
  2747. }
  2748. balanced$1.range = range$1;
  2749. function range$1(a, b, str) {
  2750. var begs, beg, left, right, result;
  2751. var ai = str.indexOf(a);
  2752. var bi = str.indexOf(b, ai + 1);
  2753. var i = ai;
  2754. if (ai >= 0 && bi > 0) {
  2755. if(a===b) {
  2756. return [ai, bi];
  2757. }
  2758. begs = [];
  2759. left = str.length;
  2760. while (i >= 0 && !result) {
  2761. if (i == ai) {
  2762. begs.push(i);
  2763. ai = str.indexOf(a, i + 1);
  2764. } else if (begs.length == 1) {
  2765. result = [ begs.pop(), bi ];
  2766. } else {
  2767. beg = begs.pop();
  2768. if (beg < left) {
  2769. left = beg;
  2770. right = bi;
  2771. }
  2772. bi = str.indexOf(b, i + 1);
  2773. }
  2774. i = ai < bi && ai >= 0 ? ai : bi;
  2775. }
  2776. if (begs.length) {
  2777. result = [ left, right ];
  2778. }
  2779. }
  2780. return result;
  2781. }
  2782. var balanced = balancedMatch;
  2783. var braceExpansion = expandTop;
  2784. var escSlash = '\0SLASH'+Math.random()+'\0';
  2785. var escOpen = '\0OPEN'+Math.random()+'\0';
  2786. var escClose = '\0CLOSE'+Math.random()+'\0';
  2787. var escComma = '\0COMMA'+Math.random()+'\0';
  2788. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  2789. function numeric(str) {
  2790. return parseInt(str, 10) == str
  2791. ? parseInt(str, 10)
  2792. : str.charCodeAt(0);
  2793. }
  2794. function escapeBraces(str) {
  2795. return str.split('\\\\').join(escSlash)
  2796. .split('\\{').join(escOpen)
  2797. .split('\\}').join(escClose)
  2798. .split('\\,').join(escComma)
  2799. .split('\\.').join(escPeriod);
  2800. }
  2801. function unescapeBraces(str) {
  2802. return str.split(escSlash).join('\\')
  2803. .split(escOpen).join('{')
  2804. .split(escClose).join('}')
  2805. .split(escComma).join(',')
  2806. .split(escPeriod).join('.');
  2807. }
  2808. // Basically just str.split(","), but handling cases
  2809. // where we have nested braced sections, which should be
  2810. // treated as individual members, like {a,{b,c},d}
  2811. function parseCommaParts(str) {
  2812. if (!str)
  2813. return [''];
  2814. var parts = [];
  2815. var m = balanced('{', '}', str);
  2816. if (!m)
  2817. return str.split(',');
  2818. var pre = m.pre;
  2819. var body = m.body;
  2820. var post = m.post;
  2821. var p = pre.split(',');
  2822. p[p.length-1] += '{' + body + '}';
  2823. var postParts = parseCommaParts(post);
  2824. if (post.length) {
  2825. p[p.length-1] += postParts.shift();
  2826. p.push.apply(p, postParts);
  2827. }
  2828. parts.push.apply(parts, p);
  2829. return parts;
  2830. }
  2831. function expandTop(str) {
  2832. if (!str)
  2833. return [];
  2834. // I don't know why Bash 4.3 does this, but it does.
  2835. // Anything starting with {} will have the first two bytes preserved
  2836. // but *only* at the top level, so {},a}b will not expand to anything,
  2837. // but a{},b}c will be expanded to [a}c,abc].
  2838. // One could argue that this is a bug in Bash, but since the goal of
  2839. // this module is to match Bash's rules, we escape a leading {}
  2840. if (str.substr(0, 2) === '{}') {
  2841. str = '\\{\\}' + str.substr(2);
  2842. }
  2843. return expand$4(escapeBraces(str), true).map(unescapeBraces);
  2844. }
  2845. function embrace(str) {
  2846. return '{' + str + '}';
  2847. }
  2848. function isPadded(el) {
  2849. return /^-?0\d/.test(el);
  2850. }
  2851. function lte(i, y) {
  2852. return i <= y;
  2853. }
  2854. function gte(i, y) {
  2855. return i >= y;
  2856. }
  2857. function expand$4(str, isTop) {
  2858. var expansions = [];
  2859. var m = balanced('{', '}', str);
  2860. if (!m) return [str];
  2861. // no need to expand pre, since it is guaranteed to be free of brace-sets
  2862. var pre = m.pre;
  2863. var post = m.post.length
  2864. ? expand$4(m.post, false)
  2865. : [''];
  2866. if (/\$$/.test(m.pre)) {
  2867. for (var k = 0; k < post.length; k++) {
  2868. var expansion = pre+ '{' + m.body + '}' + post[k];
  2869. expansions.push(expansion);
  2870. }
  2871. } else {
  2872. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  2873. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  2874. var isSequence = isNumericSequence || isAlphaSequence;
  2875. var isOptions = m.body.indexOf(',') >= 0;
  2876. if (!isSequence && !isOptions) {
  2877. // {a},b}
  2878. if (m.post.match(/,.*\}/)) {
  2879. str = m.pre + '{' + m.body + escClose + m.post;
  2880. return expand$4(str);
  2881. }
  2882. return [str];
  2883. }
  2884. var n;
  2885. if (isSequence) {
  2886. n = m.body.split(/\.\./);
  2887. } else {
  2888. n = parseCommaParts(m.body);
  2889. if (n.length === 1) {
  2890. // x{{a,b}}y ==> x{a}y x{b}y
  2891. n = expand$4(n[0], false).map(embrace);
  2892. if (n.length === 1) {
  2893. return post.map(function(p) {
  2894. return m.pre + n[0] + p;
  2895. });
  2896. }
  2897. }
  2898. }
  2899. // at this point, n is the parts, and we know it's not a comma set
  2900. // with a single entry.
  2901. var N;
  2902. if (isSequence) {
  2903. var x = numeric(n[0]);
  2904. var y = numeric(n[1]);
  2905. var width = Math.max(n[0].length, n[1].length);
  2906. var incr = n.length == 3
  2907. ? Math.abs(numeric(n[2]))
  2908. : 1;
  2909. var test = lte;
  2910. var reverse = y < x;
  2911. if (reverse) {
  2912. incr *= -1;
  2913. test = gte;
  2914. }
  2915. var pad = n.some(isPadded);
  2916. N = [];
  2917. for (var i = x; test(i, y); i += incr) {
  2918. var c;
  2919. if (isAlphaSequence) {
  2920. c = String.fromCharCode(i);
  2921. if (c === '\\')
  2922. c = '';
  2923. } else {
  2924. c = String(i);
  2925. if (pad) {
  2926. var need = width - c.length;
  2927. if (need > 0) {
  2928. var z = new Array(need + 1).join('0');
  2929. if (i < 0)
  2930. c = '-' + z + c.slice(1);
  2931. else
  2932. c = z + c;
  2933. }
  2934. }
  2935. }
  2936. N.push(c);
  2937. }
  2938. } else {
  2939. N = [];
  2940. for (var j = 0; j < n.length; j++) {
  2941. N.push.apply(N, expand$4(n[j], false));
  2942. }
  2943. }
  2944. for (var j = 0; j < N.length; j++) {
  2945. for (var k = 0; k < post.length; k++) {
  2946. var expansion = pre + N[j] + post[k];
  2947. if (!isTop || isSequence || expansion)
  2948. expansions.push(expansion);
  2949. }
  2950. }
  2951. }
  2952. return expansions;
  2953. }
  2954. const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => {
  2955. assertValidPattern(pattern);
  2956. // shortcut: comments match nothing.
  2957. if (!options.nocomment && pattern.charAt(0) === '#') {
  2958. return false
  2959. }
  2960. return new Minimatch$1(pattern, options).match(p)
  2961. };
  2962. var minimatch_1 = minimatch$1;
  2963. const path$j = path$k;
  2964. minimatch$1.sep = path$j.sep;
  2965. const GLOBSTAR$2 = Symbol('globstar **');
  2966. minimatch$1.GLOBSTAR = GLOBSTAR$2;
  2967. const expand$3 = braceExpansion;
  2968. const plTypes = {
  2969. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  2970. '?': { open: '(?:', close: ')?' },
  2971. '+': { open: '(?:', close: ')+' },
  2972. '*': { open: '(?:', close: ')*' },
  2973. '@': { open: '(?:', close: ')' }
  2974. };
  2975. // any single thing other than /
  2976. // don't need to escape / when using new RegExp()
  2977. const qmark = '[^/]';
  2978. // * => any number of characters
  2979. const star = qmark + '*?';
  2980. // ** when dots are allowed. Anything goes, except .. and .
  2981. // not (^ or / followed by one or two dots followed by $ or /),
  2982. // followed by anything, any number of times.
  2983. const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  2984. // not a ^ or / followed by a dot,
  2985. // followed by anything, any number of times.
  2986. const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  2987. // "abc" -> { a:true, b:true, c:true }
  2988. const charSet = s => s.split('').reduce((set, c) => {
  2989. set[c] = true;
  2990. return set
  2991. }, {});
  2992. // characters that need to be escaped in RegExp.
  2993. const reSpecials = charSet('().*{}+?[]^$\\!');
  2994. // characters that indicate we have to add the pattern start
  2995. const addPatternStartSet = charSet('[.(');
  2996. // normalizes slashes.
  2997. const slashSplit = /\/+/;
  2998. minimatch$1.filter = (pattern, options = {}) =>
  2999. (p, i, list) => minimatch$1(p, pattern, options);
  3000. const ext = (a, b = {}) => {
  3001. const t = {};
  3002. Object.keys(a).forEach(k => t[k] = a[k]);
  3003. Object.keys(b).forEach(k => t[k] = b[k]);
  3004. return t
  3005. };
  3006. minimatch$1.defaults = def => {
  3007. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  3008. return minimatch$1
  3009. }
  3010. const orig = minimatch$1;
  3011. const m = (p, pattern, options) => orig(p, pattern, ext(def, options));
  3012. m.Minimatch = class Minimatch extends orig.Minimatch {
  3013. constructor (pattern, options) {
  3014. super(pattern, ext(def, options));
  3015. }
  3016. };
  3017. m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch;
  3018. m.filter = (pattern, options) => orig.filter(pattern, ext(def, options));
  3019. m.defaults = options => orig.defaults(ext(def, options));
  3020. m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options));
  3021. m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options));
  3022. m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options));
  3023. return m
  3024. };
  3025. // Brace expansion:
  3026. // a{b,c}d -> abd acd
  3027. // a{b,}c -> abc ac
  3028. // a{0..3}d -> a0d a1d a2d a3d
  3029. // a{b,c{d,e}f}g -> abg acdfg acefg
  3030. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  3031. //
  3032. // Invalid sets are not expanded.
  3033. // a{2..}b -> a{2..}b
  3034. // a{b}c -> a{b}c
  3035. minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options);
  3036. const braceExpand = (pattern, options = {}) => {
  3037. assertValidPattern(pattern);
  3038. // Thanks to Yeting Li <https://github.com/yetingli> for
  3039. // improving this regexp to avoid a ReDOS vulnerability.
  3040. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  3041. // shortcut. no need to expand.
  3042. return [pattern]
  3043. }
  3044. return expand$3(pattern)
  3045. };
  3046. const MAX_PATTERN_LENGTH = 1024 * 64;
  3047. const assertValidPattern = pattern => {
  3048. if (typeof pattern !== 'string') {
  3049. throw new TypeError('invalid pattern')
  3050. }
  3051. if (pattern.length > MAX_PATTERN_LENGTH) {
  3052. throw new TypeError('pattern is too long')
  3053. }
  3054. };
  3055. // parse a component of the expanded set.
  3056. // At this point, no pattern may contain "/" in it
  3057. // so we're going to return a 2d array, where each entry is the full
  3058. // pattern, split on '/', and then turned into a regular expression.
  3059. // A regexp is made at the end which joins each array with an
  3060. // escaped /, and another full one which joins each regexp with |.
  3061. //
  3062. // Following the lead of Bash 4.1, note that "**" only has special meaning
  3063. // when it is the *only* thing in a path portion. Otherwise, any series
  3064. // of * is equivalent to a single *. Globstar behavior is enabled by
  3065. // default, and can be disabled by setting options.noglobstar.
  3066. const SUBPARSE = Symbol('subparse');
  3067. minimatch$1.makeRe = (pattern, options) =>
  3068. new Minimatch$1(pattern, options || {}).makeRe();
  3069. minimatch$1.match = (list, pattern, options = {}) => {
  3070. const mm = new Minimatch$1(pattern, options);
  3071. list = list.filter(f => mm.match(f));
  3072. if (mm.options.nonull && !list.length) {
  3073. list.push(pattern);
  3074. }
  3075. return list
  3076. };
  3077. // replace stuff like \* with *
  3078. const globUnescape = s => s.replace(/\\(.)/g, '$1');
  3079. const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  3080. let Minimatch$1 = class Minimatch {
  3081. constructor (pattern, options) {
  3082. assertValidPattern(pattern);
  3083. if (!options) options = {};
  3084. this.options = options;
  3085. this.set = [];
  3086. this.pattern = pattern;
  3087. this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
  3088. options.allowWindowsEscape === false;
  3089. if (this.windowsPathsNoEscape) {
  3090. this.pattern = this.pattern.replace(/\\/g, '/');
  3091. }
  3092. this.regexp = null;
  3093. this.negate = false;
  3094. this.comment = false;
  3095. this.empty = false;
  3096. this.partial = !!options.partial;
  3097. // make the set of regexps etc.
  3098. this.make();
  3099. }
  3100. debug () {}
  3101. make () {
  3102. const pattern = this.pattern;
  3103. const options = this.options;
  3104. // empty patterns and comments match nothing.
  3105. if (!options.nocomment && pattern.charAt(0) === '#') {
  3106. this.comment = true;
  3107. return
  3108. }
  3109. if (!pattern) {
  3110. this.empty = true;
  3111. return
  3112. }
  3113. // step 1: figure out negation, etc.
  3114. this.parseNegate();
  3115. // step 2: expand braces
  3116. let set = this.globSet = this.braceExpand();
  3117. if (options.debug) this.debug = (...args) => console.error(...args);
  3118. this.debug(this.pattern, set);
  3119. // step 3: now we have a set, so turn each one into a series of path-portion
  3120. // matching patterns.
  3121. // These will be regexps, except in the case of "**", which is
  3122. // set to the GLOBSTAR object for globstar behavior,
  3123. // and will not contain any / characters
  3124. set = this.globParts = set.map(s => s.split(slashSplit));
  3125. this.debug(this.pattern, set);
  3126. // glob --> regexps
  3127. set = set.map((s, si, set) => s.map(this.parse, this));
  3128. this.debug(this.pattern, set);
  3129. // filter out everything that didn't compile properly.
  3130. set = set.filter(s => s.indexOf(false) === -1);
  3131. this.debug(this.pattern, set);
  3132. this.set = set;
  3133. }
  3134. parseNegate () {
  3135. if (this.options.nonegate) return
  3136. const pattern = this.pattern;
  3137. let negate = false;
  3138. let negateOffset = 0;
  3139. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  3140. negate = !negate;
  3141. negateOffset++;
  3142. }
  3143. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  3144. this.negate = negate;
  3145. }
  3146. // set partial to true to test if, for example,
  3147. // "/a/b" matches the start of "/*/b/*/d"
  3148. // Partial means, if you run out of file before you run
  3149. // out of pattern, then that's fine, as long as all
  3150. // the parts match.
  3151. matchOne (file, pattern, partial) {
  3152. var options = this.options;
  3153. this.debug('matchOne',
  3154. { 'this': this, file: file, pattern: pattern });
  3155. this.debug('matchOne', file.length, pattern.length);
  3156. for (var fi = 0,
  3157. pi = 0,
  3158. fl = file.length,
  3159. pl = pattern.length
  3160. ; (fi < fl) && (pi < pl)
  3161. ; fi++, pi++) {
  3162. this.debug('matchOne loop');
  3163. var p = pattern[pi];
  3164. var f = file[fi];
  3165. this.debug(pattern, p, f);
  3166. // should be impossible.
  3167. // some invalid regexp stuff in the set.
  3168. /* istanbul ignore if */
  3169. if (p === false) return false
  3170. if (p === GLOBSTAR$2) {
  3171. this.debug('GLOBSTAR', [pattern, p, f]);
  3172. // "**"
  3173. // a/**/b/**/c would match the following:
  3174. // a/b/x/y/z/c
  3175. // a/x/y/z/b/c
  3176. // a/b/x/b/x/c
  3177. // a/b/c
  3178. // To do this, take the rest of the pattern after
  3179. // the **, and see if it would match the file remainder.
  3180. // If so, return success.
  3181. // If not, the ** "swallows" a segment, and try again.
  3182. // This is recursively awful.
  3183. //
  3184. // a/**/b/**/c matching a/b/x/y/z/c
  3185. // - a matches a
  3186. // - doublestar
  3187. // - matchOne(b/x/y/z/c, b/**/c)
  3188. // - b matches b
  3189. // - doublestar
  3190. // - matchOne(x/y/z/c, c) -> no
  3191. // - matchOne(y/z/c, c) -> no
  3192. // - matchOne(z/c, c) -> no
  3193. // - matchOne(c, c) yes, hit
  3194. var fr = fi;
  3195. var pr = pi + 1;
  3196. if (pr === pl) {
  3197. this.debug('** at the end');
  3198. // a ** at the end will just swallow the rest.
  3199. // We have found a match.
  3200. // however, it will not swallow /.x, unless
  3201. // options.dot is set.
  3202. // . and .. are *never* matched by **, for explosively
  3203. // exponential reasons.
  3204. for (; fi < fl; fi++) {
  3205. if (file[fi] === '.' || file[fi] === '..' ||
  3206. (!options.dot && file[fi].charAt(0) === '.')) return false
  3207. }
  3208. return true
  3209. }
  3210. // ok, let's see if we can swallow whatever we can.
  3211. while (fr < fl) {
  3212. var swallowee = file[fr];
  3213. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  3214. // XXX remove this slice. Just pass the start index.
  3215. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  3216. this.debug('globstar found match!', fr, fl, swallowee);
  3217. // found a match.
  3218. return true
  3219. } else {
  3220. // can't swallow "." or ".." ever.
  3221. // can only swallow ".foo" when explicitly asked.
  3222. if (swallowee === '.' || swallowee === '..' ||
  3223. (!options.dot && swallowee.charAt(0) === '.')) {
  3224. this.debug('dot detected!', file, fr, pattern, pr);
  3225. break
  3226. }
  3227. // ** swallows a segment, and continue.
  3228. this.debug('globstar swallow a segment, and continue');
  3229. fr++;
  3230. }
  3231. }
  3232. // no match was found.
  3233. // However, in partial mode, we can't say this is necessarily over.
  3234. // If there's more *pattern* left, then
  3235. /* istanbul ignore if */
  3236. if (partial) {
  3237. // ran out of file
  3238. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  3239. if (fr === fl) return true
  3240. }
  3241. return false
  3242. }
  3243. // something other than **
  3244. // non-magic patterns just have to match exactly
  3245. // patterns with magic have been turned into regexps.
  3246. var hit;
  3247. if (typeof p === 'string') {
  3248. hit = f === p;
  3249. this.debug('string match', p, f, hit);
  3250. } else {
  3251. hit = f.match(p);
  3252. this.debug('pattern match', p, f, hit);
  3253. }
  3254. if (!hit) return false
  3255. }
  3256. // Note: ending in / means that we'll get a final ""
  3257. // at the end of the pattern. This can only match a
  3258. // corresponding "" at the end of the file.
  3259. // If the file ends in /, then it can only match a
  3260. // a pattern that ends in /, unless the pattern just
  3261. // doesn't have any more for it. But, a/b/ should *not*
  3262. // match "a/b/*", even though "" matches against the
  3263. // [^/]*? pattern, except in partial mode, where it might
  3264. // simply not be reached yet.
  3265. // However, a/b/ should still satisfy a/*
  3266. // now either we fell off the end of the pattern, or we're done.
  3267. if (fi === fl && pi === pl) {
  3268. // ran out of pattern and filename at the same time.
  3269. // an exact hit!
  3270. return true
  3271. } else if (fi === fl) {
  3272. // ran out of file, but still had pattern left.
  3273. // this is ok if we're doing the match as part of
  3274. // a glob fs traversal.
  3275. return partial
  3276. } else /* istanbul ignore else */ if (pi === pl) {
  3277. // ran out of pattern, still have file left.
  3278. // this is only acceptable if we're on the very last
  3279. // empty segment of a file with a trailing slash.
  3280. // a/* should match a/b/
  3281. return (fi === fl - 1) && (file[fi] === '')
  3282. }
  3283. // should be unreachable.
  3284. /* istanbul ignore next */
  3285. throw new Error('wtf?')
  3286. }
  3287. braceExpand () {
  3288. return braceExpand(this.pattern, this.options)
  3289. }
  3290. parse (pattern, isSub) {
  3291. assertValidPattern(pattern);
  3292. const options = this.options;
  3293. // shortcuts
  3294. if (pattern === '**') {
  3295. if (!options.noglobstar)
  3296. return GLOBSTAR$2
  3297. else
  3298. pattern = '*';
  3299. }
  3300. if (pattern === '') return ''
  3301. let re = '';
  3302. let hasMagic = !!options.nocase;
  3303. let escaping = false;
  3304. // ? => one single character
  3305. const patternListStack = [];
  3306. const negativeLists = [];
  3307. let stateChar;
  3308. let inClass = false;
  3309. let reClassStart = -1;
  3310. let classStart = -1;
  3311. let cs;
  3312. let pl;
  3313. let sp;
  3314. // . and .. never match anything that doesn't start with .,
  3315. // even when options.dot is set.
  3316. const patternStart = pattern.charAt(0) === '.' ? '' // anything
  3317. // not (start or / followed by . or .. followed by / or end)
  3318. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  3319. : '(?!\\.)';
  3320. const clearStateChar = () => {
  3321. if (stateChar) {
  3322. // we had some state-tracking character
  3323. // that wasn't consumed by this pass.
  3324. switch (stateChar) {
  3325. case '*':
  3326. re += star;
  3327. hasMagic = true;
  3328. break
  3329. case '?':
  3330. re += qmark;
  3331. hasMagic = true;
  3332. break
  3333. default:
  3334. re += '\\' + stateChar;
  3335. break
  3336. }
  3337. this.debug('clearStateChar %j %j', stateChar, re);
  3338. stateChar = false;
  3339. }
  3340. };
  3341. for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
  3342. this.debug('%s\t%s %s %j', pattern, i, re, c);
  3343. // skip over any that are escaped.
  3344. if (escaping) {
  3345. /* istanbul ignore next - completely not allowed, even escaped. */
  3346. if (c === '/') {
  3347. return false
  3348. }
  3349. if (reSpecials[c]) {
  3350. re += '\\';
  3351. }
  3352. re += c;
  3353. escaping = false;
  3354. continue
  3355. }
  3356. switch (c) {
  3357. /* istanbul ignore next */
  3358. case '/': {
  3359. // Should already be path-split by now.
  3360. return false
  3361. }
  3362. case '\\':
  3363. clearStateChar();
  3364. escaping = true;
  3365. continue
  3366. // the various stateChar values
  3367. // for the "extglob" stuff.
  3368. case '?':
  3369. case '*':
  3370. case '+':
  3371. case '@':
  3372. case '!':
  3373. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  3374. // all of those are literals inside a class, except that
  3375. // the glob [!a] means [^a] in regexp
  3376. if (inClass) {
  3377. this.debug(' in class');
  3378. if (c === '!' && i === classStart + 1) c = '^';
  3379. re += c;
  3380. continue
  3381. }
  3382. // if we already have a stateChar, then it means
  3383. // that there was something like ** or +? in there.
  3384. // Handle the stateChar, then proceed with this one.
  3385. this.debug('call clearStateChar %j', stateChar);
  3386. clearStateChar();
  3387. stateChar = c;
  3388. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  3389. // just clear the statechar *now*, rather than even diving into
  3390. // the patternList stuff.
  3391. if (options.noext) clearStateChar();
  3392. continue
  3393. case '(':
  3394. if (inClass) {
  3395. re += '(';
  3396. continue
  3397. }
  3398. if (!stateChar) {
  3399. re += '\\(';
  3400. continue
  3401. }
  3402. patternListStack.push({
  3403. type: stateChar,
  3404. start: i - 1,
  3405. reStart: re.length,
  3406. open: plTypes[stateChar].open,
  3407. close: plTypes[stateChar].close
  3408. });
  3409. // negation is (?:(?!js)[^/]*)
  3410. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  3411. this.debug('plType %j %j', stateChar, re);
  3412. stateChar = false;
  3413. continue
  3414. case ')':
  3415. if (inClass || !patternListStack.length) {
  3416. re += '\\)';
  3417. continue
  3418. }
  3419. clearStateChar();
  3420. hasMagic = true;
  3421. pl = patternListStack.pop();
  3422. // negation is (?:(?!js)[^/]*)
  3423. // The others are (?:<pattern>)<type>
  3424. re += pl.close;
  3425. if (pl.type === '!') {
  3426. negativeLists.push(pl);
  3427. }
  3428. pl.reEnd = re.length;
  3429. continue
  3430. case '|':
  3431. if (inClass || !patternListStack.length) {
  3432. re += '\\|';
  3433. continue
  3434. }
  3435. clearStateChar();
  3436. re += '|';
  3437. continue
  3438. // these are mostly the same in regexp and glob
  3439. case '[':
  3440. // swallow any state-tracking char before the [
  3441. clearStateChar();
  3442. if (inClass) {
  3443. re += '\\' + c;
  3444. continue
  3445. }
  3446. inClass = true;
  3447. classStart = i;
  3448. reClassStart = re.length;
  3449. re += c;
  3450. continue
  3451. case ']':
  3452. // a right bracket shall lose its special
  3453. // meaning and represent itself in
  3454. // a bracket expression if it occurs
  3455. // first in the list. -- POSIX.2 2.8.3.2
  3456. if (i === classStart + 1 || !inClass) {
  3457. re += '\\' + c;
  3458. continue
  3459. }
  3460. // handle the case where we left a class open.
  3461. // "[z-a]" is valid, equivalent to "\[z-a\]"
  3462. // split where the last [ was, make sure we don't have
  3463. // an invalid re. if so, re-walk the contents of the
  3464. // would-be class to re-translate any characters that
  3465. // were passed through as-is
  3466. // TODO: It would probably be faster to determine this
  3467. // without a try/catch and a new RegExp, but it's tricky
  3468. // to do safely. For now, this is safe and works.
  3469. cs = pattern.substring(classStart + 1, i);
  3470. // finish up the class.
  3471. hasMagic = true;
  3472. inClass = false;
  3473. re += c;
  3474. continue
  3475. default:
  3476. // swallow any state char that wasn't consumed
  3477. clearStateChar();
  3478. if (reSpecials[c] && !(c === '^' && inClass)) {
  3479. re += '\\';
  3480. }
  3481. re += c;
  3482. break
  3483. } // switch
  3484. } // for
  3485. // handle the case where we left a class open.
  3486. // "[abc" is valid, equivalent to "\[abc"
  3487. if (inClass) {
  3488. // split where the last [ was, and escape it
  3489. // this is a huge pita. We now have to re-walk
  3490. // the contents of the would-be class to re-translate
  3491. // any characters that were passed through as-is
  3492. cs = pattern.substr(classStart + 1);
  3493. sp = this.parse(cs, SUBPARSE);
  3494. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  3495. hasMagic = hasMagic || sp[1];
  3496. }
  3497. // handle the case where we had a +( thing at the *end*
  3498. // of the pattern.
  3499. // each pattern list stack adds 3 chars, and we need to go through
  3500. // and escape any | chars that were passed through as-is for the regexp.
  3501. // Go through and escape them, taking care not to double-escape any
  3502. // | chars that were already escaped.
  3503. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  3504. let tail;
  3505. tail = re.slice(pl.reStart + pl.open.length);
  3506. this.debug('setting tail', re, pl);
  3507. // maybe some even number of \, then maybe 1 \, followed by a |
  3508. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
  3509. /* istanbul ignore else - should already be done */
  3510. if (!$2) {
  3511. // the | isn't already escaped, so escape it.
  3512. $2 = '\\';
  3513. }
  3514. // need to escape all those slashes *again*, without escaping the
  3515. // one that we need for escaping the | character. As it works out,
  3516. // escaping an even number of slashes can be done by simply repeating
  3517. // it exactly after itself. That's why this trick works.
  3518. //
  3519. // I am sorry that you have to see this.
  3520. return $1 + $1 + $2 + '|'
  3521. });
  3522. this.debug('tail=%j\n %s', tail, tail, pl, re);
  3523. const t = pl.type === '*' ? star
  3524. : pl.type === '?' ? qmark
  3525. : '\\' + pl.type;
  3526. hasMagic = true;
  3527. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  3528. }
  3529. // handle trailing things that only matter at the very end.
  3530. clearStateChar();
  3531. if (escaping) {
  3532. // trailing \\
  3533. re += '\\\\';
  3534. }
  3535. // only need to apply the nodot start if the re starts with
  3536. // something that could conceivably capture a dot
  3537. const addPatternStart = addPatternStartSet[re.charAt(0)];
  3538. // Hack to work around lack of negative lookbehind in JS
  3539. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  3540. // like 'a.xyz.yz' doesn't match. So, the first negative
  3541. // lookahead, has to look ALL the way ahead, to the end of
  3542. // the pattern.
  3543. for (let n = negativeLists.length - 1; n > -1; n--) {
  3544. const nl = negativeLists[n];
  3545. const nlBefore = re.slice(0, nl.reStart);
  3546. const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  3547. let nlAfter = re.slice(nl.reEnd);
  3548. const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
  3549. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  3550. // mean that we should *not* include the ) in the bit that is considered
  3551. // "after" the negated section.
  3552. const openParensBefore = nlBefore.split('(').length - 1;
  3553. let cleanAfter = nlAfter;
  3554. for (let i = 0; i < openParensBefore; i++) {
  3555. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  3556. }
  3557. nlAfter = cleanAfter;
  3558. const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : '';
  3559. re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  3560. }
  3561. // if the re is not "" at this point, then we need to make sure
  3562. // it doesn't match against an empty path part.
  3563. // Otherwise a/* will match a/, which it should not.
  3564. if (re !== '' && hasMagic) {
  3565. re = '(?=.)' + re;
  3566. }
  3567. if (addPatternStart) {
  3568. re = patternStart + re;
  3569. }
  3570. // parsing just a piece of a larger pattern.
  3571. if (isSub === SUBPARSE) {
  3572. return [re, hasMagic]
  3573. }
  3574. // skip the regexp for non-magical patterns
  3575. // unescape anything in it, though, so that it'll be
  3576. // an exact match against a file etc.
  3577. if (!hasMagic) {
  3578. return globUnescape(pattern)
  3579. }
  3580. const flags = options.nocase ? 'i' : '';
  3581. try {
  3582. return Object.assign(new RegExp('^' + re + '$', flags), {
  3583. _glob: pattern,
  3584. _src: re,
  3585. })
  3586. } catch (er) /* istanbul ignore next - should be impossible */ {
  3587. // If it was an invalid regular expression, then it can't match
  3588. // anything. This trick looks for a character after the end of
  3589. // the string, which is of course impossible, except in multi-line
  3590. // mode, but it's not a /m regex.
  3591. return new RegExp('$.')
  3592. }
  3593. }
  3594. makeRe () {
  3595. if (this.regexp || this.regexp === false) return this.regexp
  3596. // at this point, this.set is a 2d array of partial
  3597. // pattern strings, or "**".
  3598. //
  3599. // It's better to use .match(). This function shouldn't
  3600. // be used, really, but it's pretty convenient sometimes,
  3601. // when you just want to work with a regex.
  3602. const set = this.set;
  3603. if (!set.length) {
  3604. this.regexp = false;
  3605. return this.regexp
  3606. }
  3607. const options = this.options;
  3608. const twoStar = options.noglobstar ? star
  3609. : options.dot ? twoStarDot
  3610. : twoStarNoDot;
  3611. const flags = options.nocase ? 'i' : '';
  3612. // coalesce globstars and regexpify non-globstar patterns
  3613. // if it's the only item, then we just do one twoStar
  3614. // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
  3615. // if it's the last, append (\/twoStar|) to previous
  3616. // if it's in the middle, append (\/|\/twoStar\/) to previous
  3617. // then filter out GLOBSTAR symbols
  3618. let re = set.map(pattern => {
  3619. pattern = pattern.map(p =>
  3620. typeof p === 'string' ? regExpEscape(p)
  3621. : p === GLOBSTAR$2 ? GLOBSTAR$2
  3622. : p._src
  3623. ).reduce((set, p) => {
  3624. if (!(set[set.length - 1] === GLOBSTAR$2 && p === GLOBSTAR$2)) {
  3625. set.push(p);
  3626. }
  3627. return set
  3628. }, []);
  3629. pattern.forEach((p, i) => {
  3630. if (p !== GLOBSTAR$2 || pattern[i-1] === GLOBSTAR$2) {
  3631. return
  3632. }
  3633. if (i === 0) {
  3634. if (pattern.length > 1) {
  3635. pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1];
  3636. } else {
  3637. pattern[i] = twoStar;
  3638. }
  3639. } else if (i === pattern.length - 1) {
  3640. pattern[i-1] += '(?:\\\/|' + twoStar + ')?';
  3641. } else {
  3642. pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1];
  3643. pattern[i+1] = GLOBSTAR$2;
  3644. }
  3645. });
  3646. return pattern.filter(p => p !== GLOBSTAR$2).join('/')
  3647. }).join('|');
  3648. // must match entire pattern
  3649. // ending in a * or ** will make it less strict.
  3650. re = '^(?:' + re + ')$';
  3651. // can match anything, as long as it's not this.
  3652. if (this.negate) re = '^(?!' + re + ').*$';
  3653. try {
  3654. this.regexp = new RegExp(re, flags);
  3655. } catch (ex) /* istanbul ignore next - should be impossible */ {
  3656. this.regexp = false;
  3657. }
  3658. return this.regexp
  3659. }
  3660. match (f, partial = this.partial) {
  3661. this.debug('match', f, this.pattern);
  3662. // short-circuit in the case of busted things.
  3663. // comments, etc.
  3664. if (this.comment) return false
  3665. if (this.empty) return f === ''
  3666. if (f === '/' && partial) return true
  3667. const options = this.options;
  3668. // windows: need to use /, not \
  3669. if (path$j.sep !== '/') {
  3670. f = f.split(path$j.sep).join('/');
  3671. }
  3672. // treat the test path as a set of pathparts.
  3673. f = f.split(slashSplit);
  3674. this.debug(this.pattern, 'split', f);
  3675. // just ONE of the pattern sets in this.set needs to match
  3676. // in order for it to be valid. If negating, then just one
  3677. // match means that we have failed.
  3678. // Either way, return on the first hit.
  3679. const set = this.set;
  3680. this.debug(this.pattern, 'set', set);
  3681. // Find the basename of the path by looking for the last non-empty segment
  3682. let filename;
  3683. for (let i = f.length - 1; i >= 0; i--) {
  3684. filename = f[i];
  3685. if (filename) break
  3686. }
  3687. for (let i = 0; i < set.length; i++) {
  3688. const pattern = set[i];
  3689. let file = f;
  3690. if (options.matchBase && pattern.length === 1) {
  3691. file = [filename];
  3692. }
  3693. const hit = this.matchOne(file, pattern, partial);
  3694. if (hit) {
  3695. if (options.flipNegate) return true
  3696. return !this.negate
  3697. }
  3698. }
  3699. // didn't get any hits. this is success if it's a negative
  3700. // pattern, failure otherwise.
  3701. if (options.flipNegate) return false
  3702. return this.negate
  3703. }
  3704. static defaults (def) {
  3705. return minimatch$1.defaults(def).Minimatch
  3706. }
  3707. };
  3708. minimatch$1.Minimatch = Minimatch$1;
  3709. var inherits = {exports: {}};
  3710. var inherits_browser = {exports: {}};
  3711. var hasRequiredInherits_browser;
  3712. function requireInherits_browser () {
  3713. if (hasRequiredInherits_browser) return inherits_browser.exports;
  3714. hasRequiredInherits_browser = 1;
  3715. if (typeof Object.create === 'function') {
  3716. // implementation from standard node.js 'util' module
  3717. inherits_browser.exports = function inherits(ctor, superCtor) {
  3718. if (superCtor) {
  3719. ctor.super_ = superCtor;
  3720. ctor.prototype = Object.create(superCtor.prototype, {
  3721. constructor: {
  3722. value: ctor,
  3723. enumerable: false,
  3724. writable: true,
  3725. configurable: true
  3726. }
  3727. });
  3728. }
  3729. };
  3730. } else {
  3731. // old school shim for old browsers
  3732. inherits_browser.exports = function inherits(ctor, superCtor) {
  3733. if (superCtor) {
  3734. ctor.super_ = superCtor;
  3735. var TempCtor = function () {};
  3736. TempCtor.prototype = superCtor.prototype;
  3737. ctor.prototype = new TempCtor();
  3738. ctor.prototype.constructor = ctor;
  3739. }
  3740. };
  3741. }
  3742. return inherits_browser.exports;
  3743. }
  3744. try {
  3745. var util$2 = require('util');
  3746. /* istanbul ignore next */
  3747. if (typeof util$2.inherits !== 'function') throw '';
  3748. inherits.exports = util$2.inherits;
  3749. } catch (e) {
  3750. /* istanbul ignore next */
  3751. inherits.exports = requireInherits_browser();
  3752. }
  3753. var inheritsExports = inherits.exports;
  3754. var common$c = {};
  3755. common$c.setopts = setopts;
  3756. common$c.ownProp = ownProp;
  3757. common$c.makeAbs = makeAbs;
  3758. common$c.finish = finish;
  3759. common$c.mark = mark;
  3760. common$c.isIgnored = isIgnored;
  3761. common$c.childrenIgnored = childrenIgnored;
  3762. function ownProp (obj, field) {
  3763. return Object.prototype.hasOwnProperty.call(obj, field)
  3764. }
  3765. var fs$i = require$$0__default;
  3766. var path$i = require$$0$4;
  3767. var minimatch = minimatch_1;
  3768. var isAbsolute = require$$0$4.isAbsolute;
  3769. var Minimatch = minimatch.Minimatch;
  3770. function alphasort (a, b) {
  3771. return a.localeCompare(b, 'en')
  3772. }
  3773. function setupIgnores (self, options) {
  3774. self.ignore = options.ignore || [];
  3775. if (!Array.isArray(self.ignore))
  3776. self.ignore = [self.ignore];
  3777. if (self.ignore.length) {
  3778. self.ignore = self.ignore.map(ignoreMap);
  3779. }
  3780. }
  3781. // ignore patterns are always in dot:true mode.
  3782. function ignoreMap (pattern) {
  3783. var gmatcher = null;
  3784. if (pattern.slice(-3) === '/**') {
  3785. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  3786. gmatcher = new Minimatch(gpattern, { dot: true });
  3787. }
  3788. return {
  3789. matcher: new Minimatch(pattern, { dot: true }),
  3790. gmatcher: gmatcher
  3791. }
  3792. }
  3793. function setopts (self, pattern, options) {
  3794. if (!options)
  3795. options = {};
  3796. // base-matching: just use globstar for that.
  3797. if (options.matchBase && -1 === pattern.indexOf("/")) {
  3798. if (options.noglobstar) {
  3799. throw new Error("base matching requires globstar")
  3800. }
  3801. pattern = "**/" + pattern;
  3802. }
  3803. self.silent = !!options.silent;
  3804. self.pattern = pattern;
  3805. self.strict = options.strict !== false;
  3806. self.realpath = !!options.realpath;
  3807. self.realpathCache = options.realpathCache || Object.create(null);
  3808. self.follow = !!options.follow;
  3809. self.dot = !!options.dot;
  3810. self.mark = !!options.mark;
  3811. self.nodir = !!options.nodir;
  3812. if (self.nodir)
  3813. self.mark = true;
  3814. self.sync = !!options.sync;
  3815. self.nounique = !!options.nounique;
  3816. self.nonull = !!options.nonull;
  3817. self.nosort = !!options.nosort;
  3818. self.nocase = !!options.nocase;
  3819. self.stat = !!options.stat;
  3820. self.noprocess = !!options.noprocess;
  3821. self.absolute = !!options.absolute;
  3822. self.fs = options.fs || fs$i;
  3823. self.maxLength = options.maxLength || Infinity;
  3824. self.cache = options.cache || Object.create(null);
  3825. self.statCache = options.statCache || Object.create(null);
  3826. self.symlinks = options.symlinks || Object.create(null);
  3827. setupIgnores(self, options);
  3828. self.changedCwd = false;
  3829. var cwd = process.cwd();
  3830. if (!ownProp(options, "cwd"))
  3831. self.cwd = path$i.resolve(cwd);
  3832. else {
  3833. self.cwd = path$i.resolve(options.cwd);
  3834. self.changedCwd = self.cwd !== cwd;
  3835. }
  3836. self.root = options.root || path$i.resolve(self.cwd, "/");
  3837. self.root = path$i.resolve(self.root);
  3838. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  3839. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  3840. self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  3841. self.nomount = !!options.nomount;
  3842. if (process.platform === "win32") {
  3843. self.root = self.root.replace(/\\/g, "/");
  3844. self.cwd = self.cwd.replace(/\\/g, "/");
  3845. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  3846. }
  3847. // disable comments and negation in Minimatch.
  3848. // Note that they are not supported in Glob itself anyway.
  3849. options.nonegate = true;
  3850. options.nocomment = true;
  3851. // always treat \ in patterns as escapes, not path separators
  3852. options.allowWindowsEscape = true;
  3853. self.minimatch = new Minimatch(pattern, options);
  3854. self.options = self.minimatch.options;
  3855. }
  3856. function finish (self) {
  3857. var nou = self.nounique;
  3858. var all = nou ? [] : Object.create(null);
  3859. for (var i = 0, l = self.matches.length; i < l; i ++) {
  3860. var matches = self.matches[i];
  3861. if (!matches || Object.keys(matches).length === 0) {
  3862. if (self.nonull) {
  3863. // do like the shell, and spit out the literal glob
  3864. var literal = self.minimatch.globSet[i];
  3865. if (nou)
  3866. all.push(literal);
  3867. else
  3868. all[literal] = true;
  3869. }
  3870. } else {
  3871. // had matches
  3872. var m = Object.keys(matches);
  3873. if (nou)
  3874. all.push.apply(all, m);
  3875. else
  3876. m.forEach(function (m) {
  3877. all[m] = true;
  3878. });
  3879. }
  3880. }
  3881. if (!nou)
  3882. all = Object.keys(all);
  3883. if (!self.nosort)
  3884. all = all.sort(alphasort);
  3885. // at *some* point we statted all of these
  3886. if (self.mark) {
  3887. for (var i = 0; i < all.length; i++) {
  3888. all[i] = self._mark(all[i]);
  3889. }
  3890. if (self.nodir) {
  3891. all = all.filter(function (e) {
  3892. var notDir = !(/\/$/.test(e));
  3893. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  3894. if (notDir && c)
  3895. notDir = c !== 'DIR' && !Array.isArray(c);
  3896. return notDir
  3897. });
  3898. }
  3899. }
  3900. if (self.ignore.length)
  3901. all = all.filter(function(m) {
  3902. return !isIgnored(self, m)
  3903. });
  3904. self.found = all;
  3905. }
  3906. function mark (self, p) {
  3907. var abs = makeAbs(self, p);
  3908. var c = self.cache[abs];
  3909. var m = p;
  3910. if (c) {
  3911. var isDir = c === 'DIR' || Array.isArray(c);
  3912. var slash = p.slice(-1) === '/';
  3913. if (isDir && !slash)
  3914. m += '/';
  3915. else if (!isDir && slash)
  3916. m = m.slice(0, -1);
  3917. if (m !== p) {
  3918. var mabs = makeAbs(self, m);
  3919. self.statCache[mabs] = self.statCache[abs];
  3920. self.cache[mabs] = self.cache[abs];
  3921. }
  3922. }
  3923. return m
  3924. }
  3925. // lotta situps...
  3926. function makeAbs (self, f) {
  3927. var abs = f;
  3928. if (f.charAt(0) === '/') {
  3929. abs = path$i.join(self.root, f);
  3930. } else if (isAbsolute(f) || f === '') {
  3931. abs = f;
  3932. } else if (self.changedCwd) {
  3933. abs = path$i.resolve(self.cwd, f);
  3934. } else {
  3935. abs = path$i.resolve(f);
  3936. }
  3937. if (process.platform === 'win32')
  3938. abs = abs.replace(/\\/g, '/');
  3939. return abs
  3940. }
  3941. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  3942. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  3943. function isIgnored (self, path) {
  3944. if (!self.ignore.length)
  3945. return false
  3946. return self.ignore.some(function(item) {
  3947. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  3948. })
  3949. }
  3950. function childrenIgnored (self, path) {
  3951. if (!self.ignore.length)
  3952. return false
  3953. return self.ignore.some(function(item) {
  3954. return !!(item.gmatcher && item.gmatcher.match(path))
  3955. })
  3956. }
  3957. var sync$9;
  3958. var hasRequiredSync;
  3959. function requireSync () {
  3960. if (hasRequiredSync) return sync$9;
  3961. hasRequiredSync = 1;
  3962. sync$9 = globSync;
  3963. globSync.GlobSync = GlobSync;
  3964. var rp = fs_realpath;
  3965. var minimatch = minimatch_1;
  3966. requireGlob().Glob;
  3967. var path = require$$0$4;
  3968. var assert = require$$5;
  3969. var isAbsolute = require$$0$4.isAbsolute;
  3970. var common = common$c;
  3971. var setopts = common.setopts;
  3972. var ownProp = common.ownProp;
  3973. var childrenIgnored = common.childrenIgnored;
  3974. var isIgnored = common.isIgnored;
  3975. function globSync (pattern, options) {
  3976. if (typeof options === 'function' || arguments.length === 3)
  3977. throw new TypeError('callback provided to sync glob\n'+
  3978. 'See: https://github.com/isaacs/node-glob/issues/167')
  3979. return new GlobSync(pattern, options).found
  3980. }
  3981. function GlobSync (pattern, options) {
  3982. if (!pattern)
  3983. throw new Error('must provide pattern')
  3984. if (typeof options === 'function' || arguments.length === 3)
  3985. throw new TypeError('callback provided to sync glob\n'+
  3986. 'See: https://github.com/isaacs/node-glob/issues/167')
  3987. if (!(this instanceof GlobSync))
  3988. return new GlobSync(pattern, options)
  3989. setopts(this, pattern, options);
  3990. if (this.noprocess)
  3991. return this
  3992. var n = this.minimatch.set.length;
  3993. this.matches = new Array(n);
  3994. for (var i = 0; i < n; i ++) {
  3995. this._process(this.minimatch.set[i], i, false);
  3996. }
  3997. this._finish();
  3998. }
  3999. GlobSync.prototype._finish = function () {
  4000. assert.ok(this instanceof GlobSync);
  4001. if (this.realpath) {
  4002. var self = this;
  4003. this.matches.forEach(function (matchset, index) {
  4004. var set = self.matches[index] = Object.create(null);
  4005. for (var p in matchset) {
  4006. try {
  4007. p = self._makeAbs(p);
  4008. var real = rp.realpathSync(p, self.realpathCache);
  4009. set[real] = true;
  4010. } catch (er) {
  4011. if (er.syscall === 'stat')
  4012. set[self._makeAbs(p)] = true;
  4013. else
  4014. throw er
  4015. }
  4016. }
  4017. });
  4018. }
  4019. common.finish(this);
  4020. };
  4021. GlobSync.prototype._process = function (pattern, index, inGlobStar) {
  4022. assert.ok(this instanceof GlobSync);
  4023. // Get the first [n] parts of pattern that are all strings.
  4024. var n = 0;
  4025. while (typeof pattern[n] === 'string') {
  4026. n ++;
  4027. }
  4028. // now n is the index of the first one that is *not* a string.
  4029. // See if there's anything else
  4030. var prefix;
  4031. switch (n) {
  4032. // if not, then this is rather simple
  4033. case pattern.length:
  4034. this._processSimple(pattern.join('/'), index);
  4035. return
  4036. case 0:
  4037. // pattern *starts* with some non-trivial item.
  4038. // going to readdir(cwd), but not include the prefix in matches.
  4039. prefix = null;
  4040. break
  4041. default:
  4042. // pattern has some string bits in the front.
  4043. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  4044. // or 'relative' like '../baz'
  4045. prefix = pattern.slice(0, n).join('/');
  4046. break
  4047. }
  4048. var remain = pattern.slice(n);
  4049. // get the list of entries.
  4050. var read;
  4051. if (prefix === null)
  4052. read = '.';
  4053. else if (isAbsolute(prefix) ||
  4054. isAbsolute(pattern.map(function (p) {
  4055. return typeof p === 'string' ? p : '[*]'
  4056. }).join('/'))) {
  4057. if (!prefix || !isAbsolute(prefix))
  4058. prefix = '/' + prefix;
  4059. read = prefix;
  4060. } else
  4061. read = prefix;
  4062. var abs = this._makeAbs(read);
  4063. //if ignored, skip processing
  4064. if (childrenIgnored(this, read))
  4065. return
  4066. var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  4067. if (isGlobStar)
  4068. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  4069. else
  4070. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  4071. };
  4072. GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  4073. var entries = this._readdir(abs, inGlobStar);
  4074. // if the abs isn't a dir, then nothing can match!
  4075. if (!entries)
  4076. return
  4077. // It will only match dot entries if it starts with a dot, or if
  4078. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  4079. var pn = remain[0];
  4080. var negate = !!this.minimatch.negate;
  4081. var rawGlob = pn._glob;
  4082. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  4083. var matchedEntries = [];
  4084. for (var i = 0; i < entries.length; i++) {
  4085. var e = entries[i];
  4086. if (e.charAt(0) !== '.' || dotOk) {
  4087. var m;
  4088. if (negate && !prefix) {
  4089. m = !e.match(pn);
  4090. } else {
  4091. m = e.match(pn);
  4092. }
  4093. if (m)
  4094. matchedEntries.push(e);
  4095. }
  4096. }
  4097. var len = matchedEntries.length;
  4098. // If there are no matched entries, then nothing matches.
  4099. if (len === 0)
  4100. return
  4101. // if this is the last remaining pattern bit, then no need for
  4102. // an additional stat *unless* the user has specified mark or
  4103. // stat explicitly. We know they exist, since readdir returned
  4104. // them.
  4105. if (remain.length === 1 && !this.mark && !this.stat) {
  4106. if (!this.matches[index])
  4107. this.matches[index] = Object.create(null);
  4108. for (var i = 0; i < len; i ++) {
  4109. var e = matchedEntries[i];
  4110. if (prefix) {
  4111. if (prefix.slice(-1) !== '/')
  4112. e = prefix + '/' + e;
  4113. else
  4114. e = prefix + e;
  4115. }
  4116. if (e.charAt(0) === '/' && !this.nomount) {
  4117. e = path.join(this.root, e);
  4118. }
  4119. this._emitMatch(index, e);
  4120. }
  4121. // This was the last one, and no stats were needed
  4122. return
  4123. }
  4124. // now test all matched entries as stand-ins for that part
  4125. // of the pattern.
  4126. remain.shift();
  4127. for (var i = 0; i < len; i ++) {
  4128. var e = matchedEntries[i];
  4129. var newPattern;
  4130. if (prefix)
  4131. newPattern = [prefix, e];
  4132. else
  4133. newPattern = [e];
  4134. this._process(newPattern.concat(remain), index, inGlobStar);
  4135. }
  4136. };
  4137. GlobSync.prototype._emitMatch = function (index, e) {
  4138. if (isIgnored(this, e))
  4139. return
  4140. var abs = this._makeAbs(e);
  4141. if (this.mark)
  4142. e = this._mark(e);
  4143. if (this.absolute) {
  4144. e = abs;
  4145. }
  4146. if (this.matches[index][e])
  4147. return
  4148. if (this.nodir) {
  4149. var c = this.cache[abs];
  4150. if (c === 'DIR' || Array.isArray(c))
  4151. return
  4152. }
  4153. this.matches[index][e] = true;
  4154. if (this.stat)
  4155. this._stat(e);
  4156. };
  4157. GlobSync.prototype._readdirInGlobStar = function (abs) {
  4158. // follow all symlinked directories forever
  4159. // just proceed as if this is a non-globstar situation
  4160. if (this.follow)
  4161. return this._readdir(abs, false)
  4162. var entries;
  4163. var lstat;
  4164. try {
  4165. lstat = this.fs.lstatSync(abs);
  4166. } catch (er) {
  4167. if (er.code === 'ENOENT') {
  4168. // lstat failed, doesn't exist
  4169. return null
  4170. }
  4171. }
  4172. var isSym = lstat && lstat.isSymbolicLink();
  4173. this.symlinks[abs] = isSym;
  4174. // If it's not a symlink or a dir, then it's definitely a regular file.
  4175. // don't bother doing a readdir in that case.
  4176. if (!isSym && lstat && !lstat.isDirectory())
  4177. this.cache[abs] = 'FILE';
  4178. else
  4179. entries = this._readdir(abs, false);
  4180. return entries
  4181. };
  4182. GlobSync.prototype._readdir = function (abs, inGlobStar) {
  4183. if (inGlobStar && !ownProp(this.symlinks, abs))
  4184. return this._readdirInGlobStar(abs)
  4185. if (ownProp(this.cache, abs)) {
  4186. var c = this.cache[abs];
  4187. if (!c || c === 'FILE')
  4188. return null
  4189. if (Array.isArray(c))
  4190. return c
  4191. }
  4192. try {
  4193. return this._readdirEntries(abs, this.fs.readdirSync(abs))
  4194. } catch (er) {
  4195. this._readdirError(abs, er);
  4196. return null
  4197. }
  4198. };
  4199. GlobSync.prototype._readdirEntries = function (abs, entries) {
  4200. // if we haven't asked to stat everything, then just
  4201. // assume that everything in there exists, so we can avoid
  4202. // having to stat it a second time.
  4203. if (!this.mark && !this.stat) {
  4204. for (var i = 0; i < entries.length; i ++) {
  4205. var e = entries[i];
  4206. if (abs === '/')
  4207. e = abs + e;
  4208. else
  4209. e = abs + '/' + e;
  4210. this.cache[e] = true;
  4211. }
  4212. }
  4213. this.cache[abs] = entries;
  4214. // mark and cache dir-ness
  4215. return entries
  4216. };
  4217. GlobSync.prototype._readdirError = function (f, er) {
  4218. // handle errors, and cache the information
  4219. switch (er.code) {
  4220. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  4221. case 'ENOTDIR': // totally normal. means it *does* exist.
  4222. var abs = this._makeAbs(f);
  4223. this.cache[abs] = 'FILE';
  4224. if (abs === this.cwdAbs) {
  4225. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  4226. error.path = this.cwd;
  4227. error.code = er.code;
  4228. throw error
  4229. }
  4230. break
  4231. case 'ENOENT': // not terribly unusual
  4232. case 'ELOOP':
  4233. case 'ENAMETOOLONG':
  4234. case 'UNKNOWN':
  4235. this.cache[this._makeAbs(f)] = false;
  4236. break
  4237. default: // some unusual error. Treat as failure.
  4238. this.cache[this._makeAbs(f)] = false;
  4239. if (this.strict)
  4240. throw er
  4241. if (!this.silent)
  4242. console.error('glob error', er);
  4243. break
  4244. }
  4245. };
  4246. GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  4247. var entries = this._readdir(abs, inGlobStar);
  4248. // no entries means not a dir, so it can never have matches
  4249. // foo.txt/** doesn't match foo.txt
  4250. if (!entries)
  4251. return
  4252. // test without the globstar, and with every child both below
  4253. // and replacing the globstar.
  4254. var remainWithoutGlobStar = remain.slice(1);
  4255. var gspref = prefix ? [ prefix ] : [];
  4256. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  4257. // the noGlobStar pattern exits the inGlobStar state
  4258. this._process(noGlobStar, index, false);
  4259. var len = entries.length;
  4260. var isSym = this.symlinks[abs];
  4261. // If it's a symlink, and we're in a globstar, then stop
  4262. if (isSym && inGlobStar)
  4263. return
  4264. for (var i = 0; i < len; i++) {
  4265. var e = entries[i];
  4266. if (e.charAt(0) === '.' && !this.dot)
  4267. continue
  4268. // these two cases enter the inGlobStar state
  4269. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  4270. this._process(instead, index, true);
  4271. var below = gspref.concat(entries[i], remain);
  4272. this._process(below, index, true);
  4273. }
  4274. };
  4275. GlobSync.prototype._processSimple = function (prefix, index) {
  4276. // XXX review this. Shouldn't it be doing the mounting etc
  4277. // before doing stat? kinda weird?
  4278. var exists = this._stat(prefix);
  4279. if (!this.matches[index])
  4280. this.matches[index] = Object.create(null);
  4281. // If it doesn't exist, then just mark the lack of results
  4282. if (!exists)
  4283. return
  4284. if (prefix && isAbsolute(prefix) && !this.nomount) {
  4285. var trail = /[\/\\]$/.test(prefix);
  4286. if (prefix.charAt(0) === '/') {
  4287. prefix = path.join(this.root, prefix);
  4288. } else {
  4289. prefix = path.resolve(this.root, prefix);
  4290. if (trail)
  4291. prefix += '/';
  4292. }
  4293. }
  4294. if (process.platform === 'win32')
  4295. prefix = prefix.replace(/\\/g, '/');
  4296. // Mark this as a match
  4297. this._emitMatch(index, prefix);
  4298. };
  4299. // Returns either 'DIR', 'FILE', or false
  4300. GlobSync.prototype._stat = function (f) {
  4301. var abs = this._makeAbs(f);
  4302. var needDir = f.slice(-1) === '/';
  4303. if (f.length > this.maxLength)
  4304. return false
  4305. if (!this.stat && ownProp(this.cache, abs)) {
  4306. var c = this.cache[abs];
  4307. if (Array.isArray(c))
  4308. c = 'DIR';
  4309. // It exists, but maybe not how we need it
  4310. if (!needDir || c === 'DIR')
  4311. return c
  4312. if (needDir && c === 'FILE')
  4313. return false
  4314. // otherwise we have to stat, because maybe c=true
  4315. // if we know it exists, but not what it is.
  4316. }
  4317. var stat = this.statCache[abs];
  4318. if (!stat) {
  4319. var lstat;
  4320. try {
  4321. lstat = this.fs.lstatSync(abs);
  4322. } catch (er) {
  4323. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  4324. this.statCache[abs] = false;
  4325. return false
  4326. }
  4327. }
  4328. if (lstat && lstat.isSymbolicLink()) {
  4329. try {
  4330. stat = this.fs.statSync(abs);
  4331. } catch (er) {
  4332. stat = lstat;
  4333. }
  4334. } else {
  4335. stat = lstat;
  4336. }
  4337. }
  4338. this.statCache[abs] = stat;
  4339. var c = true;
  4340. if (stat)
  4341. c = stat.isDirectory() ? 'DIR' : 'FILE';
  4342. this.cache[abs] = this.cache[abs] || c;
  4343. if (needDir && c === 'FILE')
  4344. return false
  4345. return c
  4346. };
  4347. GlobSync.prototype._mark = function (p) {
  4348. return common.mark(this, p)
  4349. };
  4350. GlobSync.prototype._makeAbs = function (f) {
  4351. return common.makeAbs(this, f)
  4352. };
  4353. return sync$9;
  4354. }
  4355. // Returns a wrapper function that returns a wrapped callback
  4356. // The wrapper function should do some stuff, and return a
  4357. // presumably different callback function.
  4358. // This makes sure that own properties are retained, so that
  4359. // decorations and such are not lost along the way.
  4360. var wrappy_1 = wrappy$2;
  4361. function wrappy$2 (fn, cb) {
  4362. if (fn && cb) return wrappy$2(fn)(cb)
  4363. if (typeof fn !== 'function')
  4364. throw new TypeError('need wrapper function')
  4365. Object.keys(fn).forEach(function (k) {
  4366. wrapper[k] = fn[k];
  4367. });
  4368. return wrapper
  4369. function wrapper() {
  4370. var args = new Array(arguments.length);
  4371. for (var i = 0; i < args.length; i++) {
  4372. args[i] = arguments[i];
  4373. }
  4374. var ret = fn.apply(this, args);
  4375. var cb = args[args.length-1];
  4376. if (typeof ret === 'function' && ret !== cb) {
  4377. Object.keys(cb).forEach(function (k) {
  4378. ret[k] = cb[k];
  4379. });
  4380. }
  4381. return ret
  4382. }
  4383. }
  4384. var once$2 = {exports: {}};
  4385. var wrappy$1 = wrappy_1;
  4386. once$2.exports = wrappy$1(once$1);
  4387. once$2.exports.strict = wrappy$1(onceStrict);
  4388. once$1.proto = once$1(function () {
  4389. Object.defineProperty(Function.prototype, 'once', {
  4390. value: function () {
  4391. return once$1(this)
  4392. },
  4393. configurable: true
  4394. });
  4395. Object.defineProperty(Function.prototype, 'onceStrict', {
  4396. value: function () {
  4397. return onceStrict(this)
  4398. },
  4399. configurable: true
  4400. });
  4401. });
  4402. function once$1 (fn) {
  4403. var f = function () {
  4404. if (f.called) return f.value
  4405. f.called = true;
  4406. return f.value = fn.apply(this, arguments)
  4407. };
  4408. f.called = false;
  4409. return f
  4410. }
  4411. function onceStrict (fn) {
  4412. var f = function () {
  4413. if (f.called)
  4414. throw new Error(f.onceError)
  4415. f.called = true;
  4416. return f.value = fn.apply(this, arguments)
  4417. };
  4418. var name = fn.name || 'Function wrapped with `once`';
  4419. f.onceError = name + " shouldn't be called more than once";
  4420. f.called = false;
  4421. return f
  4422. }
  4423. var onceExports = once$2.exports;
  4424. var wrappy = wrappy_1;
  4425. var reqs = Object.create(null);
  4426. var once = onceExports;
  4427. var inflight_1 = wrappy(inflight);
  4428. function inflight (key, cb) {
  4429. if (reqs[key]) {
  4430. reqs[key].push(cb);
  4431. return null
  4432. } else {
  4433. reqs[key] = [cb];
  4434. return makeres(key)
  4435. }
  4436. }
  4437. function makeres (key) {
  4438. return once(function RES () {
  4439. var cbs = reqs[key];
  4440. var len = cbs.length;
  4441. var args = slice$1(arguments);
  4442. // XXX It's somewhat ambiguous whether a new callback added in this
  4443. // pass should be queued for later execution if something in the
  4444. // list of callbacks throws, or if it should just be discarded.
  4445. // However, it's such an edge case that it hardly matters, and either
  4446. // choice is likely as surprising as the other.
  4447. // As it happens, we do go ahead and schedule it for later execution.
  4448. try {
  4449. for (var i = 0; i < len; i++) {
  4450. cbs[i].apply(null, args);
  4451. }
  4452. } finally {
  4453. if (cbs.length > len) {
  4454. // added more in the interim.
  4455. // de-zalgo, just in case, but don't call again.
  4456. cbs.splice(0, len);
  4457. process.nextTick(function () {
  4458. RES.apply(null, args);
  4459. });
  4460. } else {
  4461. delete reqs[key];
  4462. }
  4463. }
  4464. })
  4465. }
  4466. function slice$1 (args) {
  4467. var length = args.length;
  4468. var array = [];
  4469. for (var i = 0; i < length; i++) array[i] = args[i];
  4470. return array
  4471. }
  4472. var glob_1;
  4473. var hasRequiredGlob;
  4474. function requireGlob () {
  4475. if (hasRequiredGlob) return glob_1;
  4476. hasRequiredGlob = 1;
  4477. // Approach:
  4478. //
  4479. // 1. Get the minimatch set
  4480. // 2. For each pattern in the set, PROCESS(pattern, false)
  4481. // 3. Store matches per-set, then uniq them
  4482. //
  4483. // PROCESS(pattern, inGlobStar)
  4484. // Get the first [n] items from pattern that are all strings
  4485. // Join these together. This is PREFIX.
  4486. // If there is no more remaining, then stat(PREFIX) and
  4487. // add to matches if it succeeds. END.
  4488. //
  4489. // If inGlobStar and PREFIX is symlink and points to dir
  4490. // set ENTRIES = []
  4491. // else readdir(PREFIX) as ENTRIES
  4492. // If fail, END
  4493. //
  4494. // with ENTRIES
  4495. // If pattern[n] is GLOBSTAR
  4496. // // handle the case where the globstar match is empty
  4497. // // by pruning it out, and testing the resulting pattern
  4498. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  4499. // // handle other cases.
  4500. // for ENTRY in ENTRIES (not dotfiles)
  4501. // // attach globstar + tail onto the entry
  4502. // // Mark that this entry is a globstar match
  4503. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  4504. //
  4505. // else // not globstar
  4506. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  4507. // Test ENTRY against pattern[n]
  4508. // If fails, continue
  4509. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  4510. //
  4511. // Caveat:
  4512. // Cache all stats and readdirs results to minimize syscall. Since all
  4513. // we ever care about is existence and directory-ness, we can just keep
  4514. // `true` for files, and [children,...] for directories, or `false` for
  4515. // things that don't exist.
  4516. glob_1 = glob;
  4517. var rp = fs_realpath;
  4518. var minimatch = minimatch_1;
  4519. var inherits = inheritsExports;
  4520. var EE = require$$0$5.EventEmitter;
  4521. var path = require$$0$4;
  4522. var assert = require$$5;
  4523. var isAbsolute = require$$0$4.isAbsolute;
  4524. var globSync = requireSync();
  4525. var common = common$c;
  4526. var setopts = common.setopts;
  4527. var ownProp = common.ownProp;
  4528. var inflight = inflight_1;
  4529. var childrenIgnored = common.childrenIgnored;
  4530. var isIgnored = common.isIgnored;
  4531. var once = onceExports;
  4532. function glob (pattern, options, cb) {
  4533. if (typeof options === 'function') cb = options, options = {};
  4534. if (!options) options = {};
  4535. if (options.sync) {
  4536. if (cb)
  4537. throw new TypeError('callback provided to sync glob')
  4538. return globSync(pattern, options)
  4539. }
  4540. return new Glob(pattern, options, cb)
  4541. }
  4542. glob.sync = globSync;
  4543. var GlobSync = glob.GlobSync = globSync.GlobSync;
  4544. // old api surface
  4545. glob.glob = glob;
  4546. function extend (origin, add) {
  4547. if (add === null || typeof add !== 'object') {
  4548. return origin
  4549. }
  4550. var keys = Object.keys(add);
  4551. var i = keys.length;
  4552. while (i--) {
  4553. origin[keys[i]] = add[keys[i]];
  4554. }
  4555. return origin
  4556. }
  4557. glob.hasMagic = function (pattern, options_) {
  4558. var options = extend({}, options_);
  4559. options.noprocess = true;
  4560. var g = new Glob(pattern, options);
  4561. var set = g.minimatch.set;
  4562. if (!pattern)
  4563. return false
  4564. if (set.length > 1)
  4565. return true
  4566. for (var j = 0; j < set[0].length; j++) {
  4567. if (typeof set[0][j] !== 'string')
  4568. return true
  4569. }
  4570. return false
  4571. };
  4572. glob.Glob = Glob;
  4573. inherits(Glob, EE);
  4574. function Glob (pattern, options, cb) {
  4575. if (typeof options === 'function') {
  4576. cb = options;
  4577. options = null;
  4578. }
  4579. if (options && options.sync) {
  4580. if (cb)
  4581. throw new TypeError('callback provided to sync glob')
  4582. return new GlobSync(pattern, options)
  4583. }
  4584. if (!(this instanceof Glob))
  4585. return new Glob(pattern, options, cb)
  4586. setopts(this, pattern, options);
  4587. this._didRealPath = false;
  4588. // process each pattern in the minimatch set
  4589. var n = this.minimatch.set.length;
  4590. // The matches are stored as {<filename>: true,...} so that
  4591. // duplicates are automagically pruned.
  4592. // Later, we do an Object.keys() on these.
  4593. // Keep them as a list so we can fill in when nonull is set.
  4594. this.matches = new Array(n);
  4595. if (typeof cb === 'function') {
  4596. cb = once(cb);
  4597. this.on('error', cb);
  4598. this.on('end', function (matches) {
  4599. cb(null, matches);
  4600. });
  4601. }
  4602. var self = this;
  4603. this._processing = 0;
  4604. this._emitQueue = [];
  4605. this._processQueue = [];
  4606. this.paused = false;
  4607. if (this.noprocess)
  4608. return this
  4609. if (n === 0)
  4610. return done()
  4611. var sync = true;
  4612. for (var i = 0; i < n; i ++) {
  4613. this._process(this.minimatch.set[i], i, false, done);
  4614. }
  4615. sync = false;
  4616. function done () {
  4617. --self._processing;
  4618. if (self._processing <= 0) {
  4619. if (sync) {
  4620. process.nextTick(function () {
  4621. self._finish();
  4622. });
  4623. } else {
  4624. self._finish();
  4625. }
  4626. }
  4627. }
  4628. }
  4629. Glob.prototype._finish = function () {
  4630. assert(this instanceof Glob);
  4631. if (this.aborted)
  4632. return
  4633. if (this.realpath && !this._didRealpath)
  4634. return this._realpath()
  4635. common.finish(this);
  4636. this.emit('end', this.found);
  4637. };
  4638. Glob.prototype._realpath = function () {
  4639. if (this._didRealpath)
  4640. return
  4641. this._didRealpath = true;
  4642. var n = this.matches.length;
  4643. if (n === 0)
  4644. return this._finish()
  4645. var self = this;
  4646. for (var i = 0; i < this.matches.length; i++)
  4647. this._realpathSet(i, next);
  4648. function next () {
  4649. if (--n === 0)
  4650. self._finish();
  4651. }
  4652. };
  4653. Glob.prototype._realpathSet = function (index, cb) {
  4654. var matchset = this.matches[index];
  4655. if (!matchset)
  4656. return cb()
  4657. var found = Object.keys(matchset);
  4658. var self = this;
  4659. var n = found.length;
  4660. if (n === 0)
  4661. return cb()
  4662. var set = this.matches[index] = Object.create(null);
  4663. found.forEach(function (p, i) {
  4664. // If there's a problem with the stat, then it means that
  4665. // one or more of the links in the realpath couldn't be
  4666. // resolved. just return the abs value in that case.
  4667. p = self._makeAbs(p);
  4668. rp.realpath(p, self.realpathCache, function (er, real) {
  4669. if (!er)
  4670. set[real] = true;
  4671. else if (er.syscall === 'stat')
  4672. set[p] = true;
  4673. else
  4674. self.emit('error', er); // srsly wtf right here
  4675. if (--n === 0) {
  4676. self.matches[index] = set;
  4677. cb();
  4678. }
  4679. });
  4680. });
  4681. };
  4682. Glob.prototype._mark = function (p) {
  4683. return common.mark(this, p)
  4684. };
  4685. Glob.prototype._makeAbs = function (f) {
  4686. return common.makeAbs(this, f)
  4687. };
  4688. Glob.prototype.abort = function () {
  4689. this.aborted = true;
  4690. this.emit('abort');
  4691. };
  4692. Glob.prototype.pause = function () {
  4693. if (!this.paused) {
  4694. this.paused = true;
  4695. this.emit('pause');
  4696. }
  4697. };
  4698. Glob.prototype.resume = function () {
  4699. if (this.paused) {
  4700. this.emit('resume');
  4701. this.paused = false;
  4702. if (this._emitQueue.length) {
  4703. var eq = this._emitQueue.slice(0);
  4704. this._emitQueue.length = 0;
  4705. for (var i = 0; i < eq.length; i ++) {
  4706. var e = eq[i];
  4707. this._emitMatch(e[0], e[1]);
  4708. }
  4709. }
  4710. if (this._processQueue.length) {
  4711. var pq = this._processQueue.slice(0);
  4712. this._processQueue.length = 0;
  4713. for (var i = 0; i < pq.length; i ++) {
  4714. var p = pq[i];
  4715. this._processing--;
  4716. this._process(p[0], p[1], p[2], p[3]);
  4717. }
  4718. }
  4719. }
  4720. };
  4721. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  4722. assert(this instanceof Glob);
  4723. assert(typeof cb === 'function');
  4724. if (this.aborted)
  4725. return
  4726. this._processing++;
  4727. if (this.paused) {
  4728. this._processQueue.push([pattern, index, inGlobStar, cb]);
  4729. return
  4730. }
  4731. //console.error('PROCESS %d', this._processing, pattern)
  4732. // Get the first [n] parts of pattern that are all strings.
  4733. var n = 0;
  4734. while (typeof pattern[n] === 'string') {
  4735. n ++;
  4736. }
  4737. // now n is the index of the first one that is *not* a string.
  4738. // see if there's anything else
  4739. var prefix;
  4740. switch (n) {
  4741. // if not, then this is rather simple
  4742. case pattern.length:
  4743. this._processSimple(pattern.join('/'), index, cb);
  4744. return
  4745. case 0:
  4746. // pattern *starts* with some non-trivial item.
  4747. // going to readdir(cwd), but not include the prefix in matches.
  4748. prefix = null;
  4749. break
  4750. default:
  4751. // pattern has some string bits in the front.
  4752. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  4753. // or 'relative' like '../baz'
  4754. prefix = pattern.slice(0, n).join('/');
  4755. break
  4756. }
  4757. var remain = pattern.slice(n);
  4758. // get the list of entries.
  4759. var read;
  4760. if (prefix === null)
  4761. read = '.';
  4762. else if (isAbsolute(prefix) ||
  4763. isAbsolute(pattern.map(function (p) {
  4764. return typeof p === 'string' ? p : '[*]'
  4765. }).join('/'))) {
  4766. if (!prefix || !isAbsolute(prefix))
  4767. prefix = '/' + prefix;
  4768. read = prefix;
  4769. } else
  4770. read = prefix;
  4771. var abs = this._makeAbs(read);
  4772. //if ignored, skip _processing
  4773. if (childrenIgnored(this, read))
  4774. return cb()
  4775. var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  4776. if (isGlobStar)
  4777. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  4778. else
  4779. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  4780. };
  4781. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  4782. var self = this;
  4783. this._readdir(abs, inGlobStar, function (er, entries) {
  4784. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  4785. });
  4786. };
  4787. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  4788. // if the abs isn't a dir, then nothing can match!
  4789. if (!entries)
  4790. return cb()
  4791. // It will only match dot entries if it starts with a dot, or if
  4792. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  4793. var pn = remain[0];
  4794. var negate = !!this.minimatch.negate;
  4795. var rawGlob = pn._glob;
  4796. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  4797. var matchedEntries = [];
  4798. for (var i = 0; i < entries.length; i++) {
  4799. var e = entries[i];
  4800. if (e.charAt(0) !== '.' || dotOk) {
  4801. var m;
  4802. if (negate && !prefix) {
  4803. m = !e.match(pn);
  4804. } else {
  4805. m = e.match(pn);
  4806. }
  4807. if (m)
  4808. matchedEntries.push(e);
  4809. }
  4810. }
  4811. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  4812. var len = matchedEntries.length;
  4813. // If there are no matched entries, then nothing matches.
  4814. if (len === 0)
  4815. return cb()
  4816. // if this is the last remaining pattern bit, then no need for
  4817. // an additional stat *unless* the user has specified mark or
  4818. // stat explicitly. We know they exist, since readdir returned
  4819. // them.
  4820. if (remain.length === 1 && !this.mark && !this.stat) {
  4821. if (!this.matches[index])
  4822. this.matches[index] = Object.create(null);
  4823. for (var i = 0; i < len; i ++) {
  4824. var e = matchedEntries[i];
  4825. if (prefix) {
  4826. if (prefix !== '/')
  4827. e = prefix + '/' + e;
  4828. else
  4829. e = prefix + e;
  4830. }
  4831. if (e.charAt(0) === '/' && !this.nomount) {
  4832. e = path.join(this.root, e);
  4833. }
  4834. this._emitMatch(index, e);
  4835. }
  4836. // This was the last one, and no stats were needed
  4837. return cb()
  4838. }
  4839. // now test all matched entries as stand-ins for that part
  4840. // of the pattern.
  4841. remain.shift();
  4842. for (var i = 0; i < len; i ++) {
  4843. var e = matchedEntries[i];
  4844. if (prefix) {
  4845. if (prefix !== '/')
  4846. e = prefix + '/' + e;
  4847. else
  4848. e = prefix + e;
  4849. }
  4850. this._process([e].concat(remain), index, inGlobStar, cb);
  4851. }
  4852. cb();
  4853. };
  4854. Glob.prototype._emitMatch = function (index, e) {
  4855. if (this.aborted)
  4856. return
  4857. if (isIgnored(this, e))
  4858. return
  4859. if (this.paused) {
  4860. this._emitQueue.push([index, e]);
  4861. return
  4862. }
  4863. var abs = isAbsolute(e) ? e : this._makeAbs(e);
  4864. if (this.mark)
  4865. e = this._mark(e);
  4866. if (this.absolute)
  4867. e = abs;
  4868. if (this.matches[index][e])
  4869. return
  4870. if (this.nodir) {
  4871. var c = this.cache[abs];
  4872. if (c === 'DIR' || Array.isArray(c))
  4873. return
  4874. }
  4875. this.matches[index][e] = true;
  4876. var st = this.statCache[abs];
  4877. if (st)
  4878. this.emit('stat', e, st);
  4879. this.emit('match', e);
  4880. };
  4881. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  4882. if (this.aborted)
  4883. return
  4884. // follow all symlinked directories forever
  4885. // just proceed as if this is a non-globstar situation
  4886. if (this.follow)
  4887. return this._readdir(abs, false, cb)
  4888. var lstatkey = 'lstat\0' + abs;
  4889. var self = this;
  4890. var lstatcb = inflight(lstatkey, lstatcb_);
  4891. if (lstatcb)
  4892. self.fs.lstat(abs, lstatcb);
  4893. function lstatcb_ (er, lstat) {
  4894. if (er && er.code === 'ENOENT')
  4895. return cb()
  4896. var isSym = lstat && lstat.isSymbolicLink();
  4897. self.symlinks[abs] = isSym;
  4898. // If it's not a symlink or a dir, then it's definitely a regular file.
  4899. // don't bother doing a readdir in that case.
  4900. if (!isSym && lstat && !lstat.isDirectory()) {
  4901. self.cache[abs] = 'FILE';
  4902. cb();
  4903. } else
  4904. self._readdir(abs, false, cb);
  4905. }
  4906. };
  4907. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  4908. if (this.aborted)
  4909. return
  4910. cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
  4911. if (!cb)
  4912. return
  4913. //console.error('RD %j %j', +inGlobStar, abs)
  4914. if (inGlobStar && !ownProp(this.symlinks, abs))
  4915. return this._readdirInGlobStar(abs, cb)
  4916. if (ownProp(this.cache, abs)) {
  4917. var c = this.cache[abs];
  4918. if (!c || c === 'FILE')
  4919. return cb()
  4920. if (Array.isArray(c))
  4921. return cb(null, c)
  4922. }
  4923. var self = this;
  4924. self.fs.readdir(abs, readdirCb(this, abs, cb));
  4925. };
  4926. function readdirCb (self, abs, cb) {
  4927. return function (er, entries) {
  4928. if (er)
  4929. self._readdirError(abs, er, cb);
  4930. else
  4931. self._readdirEntries(abs, entries, cb);
  4932. }
  4933. }
  4934. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  4935. if (this.aborted)
  4936. return
  4937. // if we haven't asked to stat everything, then just
  4938. // assume that everything in there exists, so we can avoid
  4939. // having to stat it a second time.
  4940. if (!this.mark && !this.stat) {
  4941. for (var i = 0; i < entries.length; i ++) {
  4942. var e = entries[i];
  4943. if (abs === '/')
  4944. e = abs + e;
  4945. else
  4946. e = abs + '/' + e;
  4947. this.cache[e] = true;
  4948. }
  4949. }
  4950. this.cache[abs] = entries;
  4951. return cb(null, entries)
  4952. };
  4953. Glob.prototype._readdirError = function (f, er, cb) {
  4954. if (this.aborted)
  4955. return
  4956. // handle errors, and cache the information
  4957. switch (er.code) {
  4958. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  4959. case 'ENOTDIR': // totally normal. means it *does* exist.
  4960. var abs = this._makeAbs(f);
  4961. this.cache[abs] = 'FILE';
  4962. if (abs === this.cwdAbs) {
  4963. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  4964. error.path = this.cwd;
  4965. error.code = er.code;
  4966. this.emit('error', error);
  4967. this.abort();
  4968. }
  4969. break
  4970. case 'ENOENT': // not terribly unusual
  4971. case 'ELOOP':
  4972. case 'ENAMETOOLONG':
  4973. case 'UNKNOWN':
  4974. this.cache[this._makeAbs(f)] = false;
  4975. break
  4976. default: // some unusual error. Treat as failure.
  4977. this.cache[this._makeAbs(f)] = false;
  4978. if (this.strict) {
  4979. this.emit('error', er);
  4980. // If the error is handled, then we abort
  4981. // if not, we threw out of here
  4982. this.abort();
  4983. }
  4984. if (!this.silent)
  4985. console.error('glob error', er);
  4986. break
  4987. }
  4988. return cb()
  4989. };
  4990. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  4991. var self = this;
  4992. this._readdir(abs, inGlobStar, function (er, entries) {
  4993. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  4994. });
  4995. };
  4996. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  4997. //console.error('pgs2', prefix, remain[0], entries)
  4998. // no entries means not a dir, so it can never have matches
  4999. // foo.txt/** doesn't match foo.txt
  5000. if (!entries)
  5001. return cb()
  5002. // test without the globstar, and with every child both below
  5003. // and replacing the globstar.
  5004. var remainWithoutGlobStar = remain.slice(1);
  5005. var gspref = prefix ? [ prefix ] : [];
  5006. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  5007. // the noGlobStar pattern exits the inGlobStar state
  5008. this._process(noGlobStar, index, false, cb);
  5009. var isSym = this.symlinks[abs];
  5010. var len = entries.length;
  5011. // If it's a symlink, and we're in a globstar, then stop
  5012. if (isSym && inGlobStar)
  5013. return cb()
  5014. for (var i = 0; i < len; i++) {
  5015. var e = entries[i];
  5016. if (e.charAt(0) === '.' && !this.dot)
  5017. continue
  5018. // these two cases enter the inGlobStar state
  5019. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  5020. this._process(instead, index, true, cb);
  5021. var below = gspref.concat(entries[i], remain);
  5022. this._process(below, index, true, cb);
  5023. }
  5024. cb();
  5025. };
  5026. Glob.prototype._processSimple = function (prefix, index, cb) {
  5027. // XXX review this. Shouldn't it be doing the mounting etc
  5028. // before doing stat? kinda weird?
  5029. var self = this;
  5030. this._stat(prefix, function (er, exists) {
  5031. self._processSimple2(prefix, index, er, exists, cb);
  5032. });
  5033. };
  5034. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  5035. //console.error('ps2', prefix, exists)
  5036. if (!this.matches[index])
  5037. this.matches[index] = Object.create(null);
  5038. // If it doesn't exist, then just mark the lack of results
  5039. if (!exists)
  5040. return cb()
  5041. if (prefix && isAbsolute(prefix) && !this.nomount) {
  5042. var trail = /[\/\\]$/.test(prefix);
  5043. if (prefix.charAt(0) === '/') {
  5044. prefix = path.join(this.root, prefix);
  5045. } else {
  5046. prefix = path.resolve(this.root, prefix);
  5047. if (trail)
  5048. prefix += '/';
  5049. }
  5050. }
  5051. if (process.platform === 'win32')
  5052. prefix = prefix.replace(/\\/g, '/');
  5053. // Mark this as a match
  5054. this._emitMatch(index, prefix);
  5055. cb();
  5056. };
  5057. // Returns either 'DIR', 'FILE', or false
  5058. Glob.prototype._stat = function (f, cb) {
  5059. var abs = this._makeAbs(f);
  5060. var needDir = f.slice(-1) === '/';
  5061. if (f.length > this.maxLength)
  5062. return cb()
  5063. if (!this.stat && ownProp(this.cache, abs)) {
  5064. var c = this.cache[abs];
  5065. if (Array.isArray(c))
  5066. c = 'DIR';
  5067. // It exists, but maybe not how we need it
  5068. if (!needDir || c === 'DIR')
  5069. return cb(null, c)
  5070. if (needDir && c === 'FILE')
  5071. return cb()
  5072. // otherwise we have to stat, because maybe c=true
  5073. // if we know it exists, but not what it is.
  5074. }
  5075. var stat = this.statCache[abs];
  5076. if (stat !== undefined) {
  5077. if (stat === false)
  5078. return cb(null, stat)
  5079. else {
  5080. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  5081. if (needDir && type === 'FILE')
  5082. return cb()
  5083. else
  5084. return cb(null, type, stat)
  5085. }
  5086. }
  5087. var self = this;
  5088. var statcb = inflight('stat\0' + abs, lstatcb_);
  5089. if (statcb)
  5090. self.fs.lstat(abs, statcb);
  5091. function lstatcb_ (er, lstat) {
  5092. if (lstat && lstat.isSymbolicLink()) {
  5093. // If it's a symlink, then treat it as the target, unless
  5094. // the target does not exist, then treat it as a file.
  5095. return self.fs.stat(abs, function (er, stat) {
  5096. if (er)
  5097. self._stat2(f, abs, null, lstat, cb);
  5098. else
  5099. self._stat2(f, abs, er, stat, cb);
  5100. })
  5101. } else {
  5102. self._stat2(f, abs, er, lstat, cb);
  5103. }
  5104. }
  5105. };
  5106. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  5107. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  5108. this.statCache[abs] = false;
  5109. return cb()
  5110. }
  5111. var needDir = f.slice(-1) === '/';
  5112. this.statCache[abs] = stat;
  5113. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  5114. return cb(null, false, stat)
  5115. var c = true;
  5116. if (stat)
  5117. c = stat.isDirectory() ? 'DIR' : 'FILE';
  5118. this.cache[abs] = this.cache[abs] || c;
  5119. if (needDir && c === 'FILE')
  5120. return cb()
  5121. return cb(null, c, stat)
  5122. };
  5123. return glob_1;
  5124. }
  5125. var globExports = requireGlob();
  5126. var glob$1 = /*@__PURE__*/getDefaultExportFromCjs(globExports);
  5127. const comma$1 = ','.charCodeAt(0);
  5128. const semicolon = ';'.charCodeAt(0);
  5129. const chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5130. const intToChar$1 = new Uint8Array(64); // 64 possible chars.
  5131. const charToInt$1 = new Uint8Array(128); // z is 122 in ASCII
  5132. for (let i = 0; i < chars$2.length; i++) {
  5133. const c = chars$2.charCodeAt(i);
  5134. intToChar$1[i] = c;
  5135. charToInt$1[c] = i;
  5136. }
  5137. // Provide a fallback for older environments.
  5138. const td = typeof TextDecoder !== 'undefined'
  5139. ? /* #__PURE__ */ new TextDecoder()
  5140. : typeof Buffer !== 'undefined'
  5141. ? {
  5142. decode(buf) {
  5143. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  5144. return out.toString();
  5145. },
  5146. }
  5147. : {
  5148. decode(buf) {
  5149. let out = '';
  5150. for (let i = 0; i < buf.length; i++) {
  5151. out += String.fromCharCode(buf[i]);
  5152. }
  5153. return out;
  5154. },
  5155. };
  5156. function encode$1(decoded) {
  5157. const state = new Int32Array(5);
  5158. const bufLength = 1024 * 16;
  5159. const subLength = bufLength - 36;
  5160. const buf = new Uint8Array(bufLength);
  5161. const sub = buf.subarray(0, subLength);
  5162. let pos = 0;
  5163. let out = '';
  5164. for (let i = 0; i < decoded.length; i++) {
  5165. const line = decoded[i];
  5166. if (i > 0) {
  5167. if (pos === bufLength) {
  5168. out += td.decode(buf);
  5169. pos = 0;
  5170. }
  5171. buf[pos++] = semicolon;
  5172. }
  5173. if (line.length === 0)
  5174. continue;
  5175. state[0] = 0;
  5176. for (let j = 0; j < line.length; j++) {
  5177. const segment = line[j];
  5178. // We can push up to 5 ints, each int can take at most 7 chars, and we
  5179. // may push a comma.
  5180. if (pos > subLength) {
  5181. out += td.decode(sub);
  5182. buf.copyWithin(0, subLength, pos);
  5183. pos -= subLength;
  5184. }
  5185. if (j > 0)
  5186. buf[pos++] = comma$1;
  5187. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  5188. if (segment.length === 1)
  5189. continue;
  5190. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  5191. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  5192. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  5193. if (segment.length === 4)
  5194. continue;
  5195. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  5196. }
  5197. }
  5198. return out + td.decode(buf.subarray(0, pos));
  5199. }
  5200. function encodeInteger(buf, pos, state, segment, j) {
  5201. const next = segment[j];
  5202. let num = next - state[j];
  5203. state[j] = next;
  5204. num = num < 0 ? (-num << 1) | 1 : num << 1;
  5205. do {
  5206. let clamped = num & 0b011111;
  5207. num >>>= 5;
  5208. if (num > 0)
  5209. clamped |= 0b100000;
  5210. buf[pos++] = intToChar$1[clamped];
  5211. } while (num > 0);
  5212. return pos;
  5213. }
  5214. let BitSet$1 = class BitSet {
  5215. constructor(arg) {
  5216. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  5217. }
  5218. add(n) {
  5219. this.bits[n >> 5] |= 1 << (n & 31);
  5220. }
  5221. has(n) {
  5222. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  5223. }
  5224. };
  5225. let Chunk$1 = class Chunk {
  5226. constructor(start, end, content) {
  5227. this.start = start;
  5228. this.end = end;
  5229. this.original = content;
  5230. this.intro = '';
  5231. this.outro = '';
  5232. this.content = content;
  5233. this.storeName = false;
  5234. this.edited = false;
  5235. {
  5236. this.previous = null;
  5237. this.next = null;
  5238. }
  5239. }
  5240. appendLeft(content) {
  5241. this.outro += content;
  5242. }
  5243. appendRight(content) {
  5244. this.intro = this.intro + content;
  5245. }
  5246. clone() {
  5247. const chunk = new Chunk(this.start, this.end, this.original);
  5248. chunk.intro = this.intro;
  5249. chunk.outro = this.outro;
  5250. chunk.content = this.content;
  5251. chunk.storeName = this.storeName;
  5252. chunk.edited = this.edited;
  5253. return chunk;
  5254. }
  5255. contains(index) {
  5256. return this.start < index && index < this.end;
  5257. }
  5258. eachNext(fn) {
  5259. let chunk = this;
  5260. while (chunk) {
  5261. fn(chunk);
  5262. chunk = chunk.next;
  5263. }
  5264. }
  5265. eachPrevious(fn) {
  5266. let chunk = this;
  5267. while (chunk) {
  5268. fn(chunk);
  5269. chunk = chunk.previous;
  5270. }
  5271. }
  5272. edit(content, storeName, contentOnly) {
  5273. this.content = content;
  5274. if (!contentOnly) {
  5275. this.intro = '';
  5276. this.outro = '';
  5277. }
  5278. this.storeName = storeName;
  5279. this.edited = true;
  5280. return this;
  5281. }
  5282. prependLeft(content) {
  5283. this.outro = content + this.outro;
  5284. }
  5285. prependRight(content) {
  5286. this.intro = content + this.intro;
  5287. }
  5288. split(index) {
  5289. const sliceIndex = index - this.start;
  5290. const originalBefore = this.original.slice(0, sliceIndex);
  5291. const originalAfter = this.original.slice(sliceIndex);
  5292. this.original = originalBefore;
  5293. const newChunk = new Chunk(index, this.end, originalAfter);
  5294. newChunk.outro = this.outro;
  5295. this.outro = '';
  5296. this.end = index;
  5297. if (this.edited) {
  5298. // TODO is this block necessary?...
  5299. newChunk.edit('', false);
  5300. this.content = '';
  5301. } else {
  5302. this.content = originalBefore;
  5303. }
  5304. newChunk.next = this.next;
  5305. if (newChunk.next) newChunk.next.previous = newChunk;
  5306. newChunk.previous = this;
  5307. this.next = newChunk;
  5308. return newChunk;
  5309. }
  5310. toString() {
  5311. return this.intro + this.content + this.outro;
  5312. }
  5313. trimEnd(rx) {
  5314. this.outro = this.outro.replace(rx, '');
  5315. if (this.outro.length) return true;
  5316. const trimmed = this.content.replace(rx, '');
  5317. if (trimmed.length) {
  5318. if (trimmed !== this.content) {
  5319. this.split(this.start + trimmed.length).edit('', undefined, true);
  5320. }
  5321. return true;
  5322. } else {
  5323. this.edit('', undefined, true);
  5324. this.intro = this.intro.replace(rx, '');
  5325. if (this.intro.length) return true;
  5326. }
  5327. }
  5328. trimStart(rx) {
  5329. this.intro = this.intro.replace(rx, '');
  5330. if (this.intro.length) return true;
  5331. const trimmed = this.content.replace(rx, '');
  5332. if (trimmed.length) {
  5333. if (trimmed !== this.content) {
  5334. this.split(this.end - trimmed.length);
  5335. this.edit('', undefined, true);
  5336. }
  5337. return true;
  5338. } else {
  5339. this.edit('', undefined, true);
  5340. this.outro = this.outro.replace(rx, '');
  5341. if (this.outro.length) return true;
  5342. }
  5343. }
  5344. };
  5345. function getBtoa$1 () {
  5346. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  5347. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  5348. } else if (typeof Buffer === 'function') {
  5349. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  5350. } else {
  5351. return () => {
  5352. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  5353. };
  5354. }
  5355. }
  5356. const btoa$2 = /*#__PURE__*/ getBtoa$1();
  5357. let SourceMap$2 = class SourceMap {
  5358. constructor(properties) {
  5359. this.version = 3;
  5360. this.file = properties.file;
  5361. this.sources = properties.sources;
  5362. this.sourcesContent = properties.sourcesContent;
  5363. this.names = properties.names;
  5364. this.mappings = encode$1(properties.mappings);
  5365. }
  5366. toString() {
  5367. return JSON.stringify(this);
  5368. }
  5369. toUrl() {
  5370. return 'data:application/json;charset=utf-8;base64,' + btoa$2(this.toString());
  5371. }
  5372. };
  5373. function guessIndent$1(code) {
  5374. const lines = code.split('\n');
  5375. const tabbed = lines.filter((line) => /^\t+/.test(line));
  5376. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  5377. if (tabbed.length === 0 && spaced.length === 0) {
  5378. return null;
  5379. }
  5380. // More lines tabbed than spaced? Assume tabs, and
  5381. // default to tabs in the case of a tie (or nothing
  5382. // to go on)
  5383. if (tabbed.length >= spaced.length) {
  5384. return '\t';
  5385. }
  5386. // Otherwise, we need to guess the multiple
  5387. const min = spaced.reduce((previous, current) => {
  5388. const numSpaces = /^ +/.exec(current)[0].length;
  5389. return Math.min(numSpaces, previous);
  5390. }, Infinity);
  5391. return new Array(min + 1).join(' ');
  5392. }
  5393. function getRelativePath$1(from, to) {
  5394. const fromParts = from.split(/[/\\]/);
  5395. const toParts = to.split(/[/\\]/);
  5396. fromParts.pop(); // get dirname
  5397. while (fromParts[0] === toParts[0]) {
  5398. fromParts.shift();
  5399. toParts.shift();
  5400. }
  5401. if (fromParts.length) {
  5402. let i = fromParts.length;
  5403. while (i--) fromParts[i] = '..';
  5404. }
  5405. return fromParts.concat(toParts).join('/');
  5406. }
  5407. const toString$3 = Object.prototype.toString;
  5408. function isObject$3(thing) {
  5409. return toString$3.call(thing) === '[object Object]';
  5410. }
  5411. function getLocator$1(source) {
  5412. const originalLines = source.split('\n');
  5413. const lineOffsets = [];
  5414. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  5415. lineOffsets.push(pos);
  5416. pos += originalLines[i].length + 1;
  5417. }
  5418. return function locate(index) {
  5419. let i = 0;
  5420. let j = lineOffsets.length;
  5421. while (i < j) {
  5422. const m = (i + j) >> 1;
  5423. if (index < lineOffsets[m]) {
  5424. j = m;
  5425. } else {
  5426. i = m + 1;
  5427. }
  5428. }
  5429. const line = i - 1;
  5430. const column = index - lineOffsets[line];
  5431. return { line, column };
  5432. };
  5433. }
  5434. let Mappings$1 = class Mappings {
  5435. constructor(hires) {
  5436. this.hires = hires;
  5437. this.generatedCodeLine = 0;
  5438. this.generatedCodeColumn = 0;
  5439. this.raw = [];
  5440. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  5441. this.pending = null;
  5442. }
  5443. addEdit(sourceIndex, content, loc, nameIndex) {
  5444. if (content.length) {
  5445. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  5446. if (nameIndex >= 0) {
  5447. segment.push(nameIndex);
  5448. }
  5449. this.rawSegments.push(segment);
  5450. } else if (this.pending) {
  5451. this.rawSegments.push(this.pending);
  5452. }
  5453. this.advance(content);
  5454. this.pending = null;
  5455. }
  5456. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  5457. let originalCharIndex = chunk.start;
  5458. let first = true;
  5459. while (originalCharIndex < chunk.end) {
  5460. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  5461. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  5462. }
  5463. if (original[originalCharIndex] === '\n') {
  5464. loc.line += 1;
  5465. loc.column = 0;
  5466. this.generatedCodeLine += 1;
  5467. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  5468. this.generatedCodeColumn = 0;
  5469. first = true;
  5470. } else {
  5471. loc.column += 1;
  5472. this.generatedCodeColumn += 1;
  5473. first = false;
  5474. }
  5475. originalCharIndex += 1;
  5476. }
  5477. this.pending = null;
  5478. }
  5479. advance(str) {
  5480. if (!str) return;
  5481. const lines = str.split('\n');
  5482. if (lines.length > 1) {
  5483. for (let i = 0; i < lines.length - 1; i++) {
  5484. this.generatedCodeLine++;
  5485. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  5486. }
  5487. this.generatedCodeColumn = 0;
  5488. }
  5489. this.generatedCodeColumn += lines[lines.length - 1].length;
  5490. }
  5491. };
  5492. const n$2 = '\n';
  5493. const warned$1 = {
  5494. insertLeft: false,
  5495. insertRight: false,
  5496. storeName: false,
  5497. };
  5498. let MagicString$1 = class MagicString {
  5499. constructor(string, options = {}) {
  5500. const chunk = new Chunk$1(0, string.length, string);
  5501. Object.defineProperties(this, {
  5502. original: { writable: true, value: string },
  5503. outro: { writable: true, value: '' },
  5504. intro: { writable: true, value: '' },
  5505. firstChunk: { writable: true, value: chunk },
  5506. lastChunk: { writable: true, value: chunk },
  5507. lastSearchedChunk: { writable: true, value: chunk },
  5508. byStart: { writable: true, value: {} },
  5509. byEnd: { writable: true, value: {} },
  5510. filename: { writable: true, value: options.filename },
  5511. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  5512. sourcemapLocations: { writable: true, value: new BitSet$1() },
  5513. storedNames: { writable: true, value: {} },
  5514. indentStr: { writable: true, value: undefined },
  5515. });
  5516. this.byStart[0] = chunk;
  5517. this.byEnd[string.length] = chunk;
  5518. }
  5519. addSourcemapLocation(char) {
  5520. this.sourcemapLocations.add(char);
  5521. }
  5522. append(content) {
  5523. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  5524. this.outro += content;
  5525. return this;
  5526. }
  5527. appendLeft(index, content) {
  5528. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5529. this._split(index);
  5530. const chunk = this.byEnd[index];
  5531. if (chunk) {
  5532. chunk.appendLeft(content);
  5533. } else {
  5534. this.intro += content;
  5535. }
  5536. return this;
  5537. }
  5538. appendRight(index, content) {
  5539. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5540. this._split(index);
  5541. const chunk = this.byStart[index];
  5542. if (chunk) {
  5543. chunk.appendRight(content);
  5544. } else {
  5545. this.outro += content;
  5546. }
  5547. return this;
  5548. }
  5549. clone() {
  5550. const cloned = new MagicString(this.original, { filename: this.filename });
  5551. let originalChunk = this.firstChunk;
  5552. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  5553. while (originalChunk) {
  5554. cloned.byStart[clonedChunk.start] = clonedChunk;
  5555. cloned.byEnd[clonedChunk.end] = clonedChunk;
  5556. const nextOriginalChunk = originalChunk.next;
  5557. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  5558. if (nextClonedChunk) {
  5559. clonedChunk.next = nextClonedChunk;
  5560. nextClonedChunk.previous = clonedChunk;
  5561. clonedChunk = nextClonedChunk;
  5562. }
  5563. originalChunk = nextOriginalChunk;
  5564. }
  5565. cloned.lastChunk = clonedChunk;
  5566. if (this.indentExclusionRanges) {
  5567. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  5568. }
  5569. cloned.sourcemapLocations = new BitSet$1(this.sourcemapLocations);
  5570. cloned.intro = this.intro;
  5571. cloned.outro = this.outro;
  5572. return cloned;
  5573. }
  5574. generateDecodedMap(options) {
  5575. options = options || {};
  5576. const sourceIndex = 0;
  5577. const names = Object.keys(this.storedNames);
  5578. const mappings = new Mappings$1(options.hires);
  5579. const locate = getLocator$1(this.original);
  5580. if (this.intro) {
  5581. mappings.advance(this.intro);
  5582. }
  5583. this.firstChunk.eachNext((chunk) => {
  5584. const loc = locate(chunk.start);
  5585. if (chunk.intro.length) mappings.advance(chunk.intro);
  5586. if (chunk.edited) {
  5587. mappings.addEdit(
  5588. sourceIndex,
  5589. chunk.content,
  5590. loc,
  5591. chunk.storeName ? names.indexOf(chunk.original) : -1
  5592. );
  5593. } else {
  5594. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  5595. }
  5596. if (chunk.outro.length) mappings.advance(chunk.outro);
  5597. });
  5598. return {
  5599. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  5600. sources: [options.source ? getRelativePath$1(options.file || '', options.source) : null],
  5601. sourcesContent: options.includeContent ? [this.original] : [null],
  5602. names,
  5603. mappings: mappings.raw,
  5604. };
  5605. }
  5606. generateMap(options) {
  5607. return new SourceMap$2(this.generateDecodedMap(options));
  5608. }
  5609. _ensureindentStr() {
  5610. if (this.indentStr === undefined) {
  5611. this.indentStr = guessIndent$1(this.original);
  5612. }
  5613. }
  5614. _getRawIndentString() {
  5615. this._ensureindentStr();
  5616. return this.indentStr;
  5617. }
  5618. getIndentString() {
  5619. this._ensureindentStr();
  5620. return this.indentStr === null ? '\t' : this.indentStr;
  5621. }
  5622. indent(indentStr, options) {
  5623. const pattern = /^[^\r\n]/gm;
  5624. if (isObject$3(indentStr)) {
  5625. options = indentStr;
  5626. indentStr = undefined;
  5627. }
  5628. if (indentStr === undefined) {
  5629. this._ensureindentStr();
  5630. indentStr = this.indentStr || '\t';
  5631. }
  5632. if (indentStr === '') return this; // noop
  5633. options = options || {};
  5634. // Process exclusion ranges
  5635. const isExcluded = {};
  5636. if (options.exclude) {
  5637. const exclusions =
  5638. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  5639. exclusions.forEach((exclusion) => {
  5640. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  5641. isExcluded[i] = true;
  5642. }
  5643. });
  5644. }
  5645. let shouldIndentNextCharacter = options.indentStart !== false;
  5646. const replacer = (match) => {
  5647. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  5648. shouldIndentNextCharacter = true;
  5649. return match;
  5650. };
  5651. this.intro = this.intro.replace(pattern, replacer);
  5652. let charIndex = 0;
  5653. let chunk = this.firstChunk;
  5654. while (chunk) {
  5655. const end = chunk.end;
  5656. if (chunk.edited) {
  5657. if (!isExcluded[charIndex]) {
  5658. chunk.content = chunk.content.replace(pattern, replacer);
  5659. if (chunk.content.length) {
  5660. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  5661. }
  5662. }
  5663. } else {
  5664. charIndex = chunk.start;
  5665. while (charIndex < end) {
  5666. if (!isExcluded[charIndex]) {
  5667. const char = this.original[charIndex];
  5668. if (char === '\n') {
  5669. shouldIndentNextCharacter = true;
  5670. } else if (char !== '\r' && shouldIndentNextCharacter) {
  5671. shouldIndentNextCharacter = false;
  5672. if (charIndex === chunk.start) {
  5673. chunk.prependRight(indentStr);
  5674. } else {
  5675. this._splitChunk(chunk, charIndex);
  5676. chunk = chunk.next;
  5677. chunk.prependRight(indentStr);
  5678. }
  5679. }
  5680. }
  5681. charIndex += 1;
  5682. }
  5683. }
  5684. charIndex = chunk.end;
  5685. chunk = chunk.next;
  5686. }
  5687. this.outro = this.outro.replace(pattern, replacer);
  5688. return this;
  5689. }
  5690. insert() {
  5691. throw new Error(
  5692. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  5693. );
  5694. }
  5695. insertLeft(index, content) {
  5696. if (!warned$1.insertLeft) {
  5697. console.warn(
  5698. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  5699. ); // eslint-disable-line no-console
  5700. warned$1.insertLeft = true;
  5701. }
  5702. return this.appendLeft(index, content);
  5703. }
  5704. insertRight(index, content) {
  5705. if (!warned$1.insertRight) {
  5706. console.warn(
  5707. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  5708. ); // eslint-disable-line no-console
  5709. warned$1.insertRight = true;
  5710. }
  5711. return this.prependRight(index, content);
  5712. }
  5713. move(start, end, index) {
  5714. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  5715. this._split(start);
  5716. this._split(end);
  5717. this._split(index);
  5718. const first = this.byStart[start];
  5719. const last = this.byEnd[end];
  5720. const oldLeft = first.previous;
  5721. const oldRight = last.next;
  5722. const newRight = this.byStart[index];
  5723. if (!newRight && last === this.lastChunk) return this;
  5724. const newLeft = newRight ? newRight.previous : this.lastChunk;
  5725. if (oldLeft) oldLeft.next = oldRight;
  5726. if (oldRight) oldRight.previous = oldLeft;
  5727. if (newLeft) newLeft.next = first;
  5728. if (newRight) newRight.previous = last;
  5729. if (!first.previous) this.firstChunk = last.next;
  5730. if (!last.next) {
  5731. this.lastChunk = first.previous;
  5732. this.lastChunk.next = null;
  5733. }
  5734. first.previous = newLeft;
  5735. last.next = newRight || null;
  5736. if (!newLeft) this.firstChunk = first;
  5737. if (!newRight) this.lastChunk = last;
  5738. return this;
  5739. }
  5740. overwrite(start, end, content, options) {
  5741. options = options || {};
  5742. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  5743. }
  5744. update(start, end, content, options) {
  5745. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  5746. while (start < 0) start += this.original.length;
  5747. while (end < 0) end += this.original.length;
  5748. if (end > this.original.length) throw new Error('end is out of bounds');
  5749. if (start === end)
  5750. throw new Error(
  5751. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  5752. );
  5753. this._split(start);
  5754. this._split(end);
  5755. if (options === true) {
  5756. if (!warned$1.storeName) {
  5757. console.warn(
  5758. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  5759. ); // eslint-disable-line no-console
  5760. warned$1.storeName = true;
  5761. }
  5762. options = { storeName: true };
  5763. }
  5764. const storeName = options !== undefined ? options.storeName : false;
  5765. const overwrite = options !== undefined ? options.overwrite : false;
  5766. if (storeName) {
  5767. const original = this.original.slice(start, end);
  5768. Object.defineProperty(this.storedNames, original, {
  5769. writable: true,
  5770. value: true,
  5771. enumerable: true,
  5772. });
  5773. }
  5774. const first = this.byStart[start];
  5775. const last = this.byEnd[end];
  5776. if (first) {
  5777. let chunk = first;
  5778. while (chunk !== last) {
  5779. if (chunk.next !== this.byStart[chunk.end]) {
  5780. throw new Error('Cannot overwrite across a split point');
  5781. }
  5782. chunk = chunk.next;
  5783. chunk.edit('', false);
  5784. }
  5785. first.edit(content, storeName, !overwrite);
  5786. } else {
  5787. // must be inserting at the end
  5788. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  5789. // TODO last chunk in the array may not be the last chunk, if it's moved...
  5790. last.next = newChunk;
  5791. newChunk.previous = last;
  5792. }
  5793. return this;
  5794. }
  5795. prepend(content) {
  5796. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  5797. this.intro = content + this.intro;
  5798. return this;
  5799. }
  5800. prependLeft(index, content) {
  5801. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5802. this._split(index);
  5803. const chunk = this.byEnd[index];
  5804. if (chunk) {
  5805. chunk.prependLeft(content);
  5806. } else {
  5807. this.intro = content + this.intro;
  5808. }
  5809. return this;
  5810. }
  5811. prependRight(index, content) {
  5812. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  5813. this._split(index);
  5814. const chunk = this.byStart[index];
  5815. if (chunk) {
  5816. chunk.prependRight(content);
  5817. } else {
  5818. this.outro = content + this.outro;
  5819. }
  5820. return this;
  5821. }
  5822. remove(start, end) {
  5823. while (start < 0) start += this.original.length;
  5824. while (end < 0) end += this.original.length;
  5825. if (start === end) return this;
  5826. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  5827. if (start > end) throw new Error('end must be greater than start');
  5828. this._split(start);
  5829. this._split(end);
  5830. let chunk = this.byStart[start];
  5831. while (chunk) {
  5832. chunk.intro = '';
  5833. chunk.outro = '';
  5834. chunk.edit('');
  5835. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  5836. }
  5837. return this;
  5838. }
  5839. lastChar() {
  5840. if (this.outro.length) return this.outro[this.outro.length - 1];
  5841. let chunk = this.lastChunk;
  5842. do {
  5843. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  5844. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  5845. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  5846. } while ((chunk = chunk.previous));
  5847. if (this.intro.length) return this.intro[this.intro.length - 1];
  5848. return '';
  5849. }
  5850. lastLine() {
  5851. let lineIndex = this.outro.lastIndexOf(n$2);
  5852. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  5853. let lineStr = this.outro;
  5854. let chunk = this.lastChunk;
  5855. do {
  5856. if (chunk.outro.length > 0) {
  5857. lineIndex = chunk.outro.lastIndexOf(n$2);
  5858. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  5859. lineStr = chunk.outro + lineStr;
  5860. }
  5861. if (chunk.content.length > 0) {
  5862. lineIndex = chunk.content.lastIndexOf(n$2);
  5863. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  5864. lineStr = chunk.content + lineStr;
  5865. }
  5866. if (chunk.intro.length > 0) {
  5867. lineIndex = chunk.intro.lastIndexOf(n$2);
  5868. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  5869. lineStr = chunk.intro + lineStr;
  5870. }
  5871. } while ((chunk = chunk.previous));
  5872. lineIndex = this.intro.lastIndexOf(n$2);
  5873. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  5874. return this.intro + lineStr;
  5875. }
  5876. slice(start = 0, end = this.original.length) {
  5877. while (start < 0) start += this.original.length;
  5878. while (end < 0) end += this.original.length;
  5879. let result = '';
  5880. // find start chunk
  5881. let chunk = this.firstChunk;
  5882. while (chunk && (chunk.start > start || chunk.end <= start)) {
  5883. // found end chunk before start
  5884. if (chunk.start < end && chunk.end >= end) {
  5885. return result;
  5886. }
  5887. chunk = chunk.next;
  5888. }
  5889. if (chunk && chunk.edited && chunk.start !== start)
  5890. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  5891. const startChunk = chunk;
  5892. while (chunk) {
  5893. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  5894. result += chunk.intro;
  5895. }
  5896. const containsEnd = chunk.start < end && chunk.end >= end;
  5897. if (containsEnd && chunk.edited && chunk.end !== end)
  5898. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  5899. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  5900. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  5901. result += chunk.content.slice(sliceStart, sliceEnd);
  5902. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  5903. result += chunk.outro;
  5904. }
  5905. if (containsEnd) {
  5906. break;
  5907. }
  5908. chunk = chunk.next;
  5909. }
  5910. return result;
  5911. }
  5912. // TODO deprecate this? not really very useful
  5913. snip(start, end) {
  5914. const clone = this.clone();
  5915. clone.remove(0, start);
  5916. clone.remove(end, clone.original.length);
  5917. return clone;
  5918. }
  5919. _split(index) {
  5920. if (this.byStart[index] || this.byEnd[index]) return;
  5921. let chunk = this.lastSearchedChunk;
  5922. const searchForward = index > chunk.end;
  5923. while (chunk) {
  5924. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  5925. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  5926. }
  5927. }
  5928. _splitChunk(chunk, index) {
  5929. if (chunk.edited && chunk.content.length) {
  5930. // zero-length edited chunks are a special case (overlapping replacements)
  5931. const loc = getLocator$1(this.original)(index);
  5932. throw new Error(
  5933. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  5934. );
  5935. }
  5936. const newChunk = chunk.split(index);
  5937. this.byEnd[index] = chunk;
  5938. this.byStart[index] = newChunk;
  5939. this.byEnd[newChunk.end] = newChunk;
  5940. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  5941. this.lastSearchedChunk = chunk;
  5942. return true;
  5943. }
  5944. toString() {
  5945. let str = this.intro;
  5946. let chunk = this.firstChunk;
  5947. while (chunk) {
  5948. str += chunk.toString();
  5949. chunk = chunk.next;
  5950. }
  5951. return str + this.outro;
  5952. }
  5953. isEmpty() {
  5954. let chunk = this.firstChunk;
  5955. do {
  5956. if (
  5957. (chunk.intro.length && chunk.intro.trim()) ||
  5958. (chunk.content.length && chunk.content.trim()) ||
  5959. (chunk.outro.length && chunk.outro.trim())
  5960. )
  5961. return false;
  5962. } while ((chunk = chunk.next));
  5963. return true;
  5964. }
  5965. length() {
  5966. let chunk = this.firstChunk;
  5967. let length = 0;
  5968. do {
  5969. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  5970. } while ((chunk = chunk.next));
  5971. return length;
  5972. }
  5973. trimLines() {
  5974. return this.trim('[\\r\\n]');
  5975. }
  5976. trim(charType) {
  5977. return this.trimStart(charType).trimEnd(charType);
  5978. }
  5979. trimEndAborted(charType) {
  5980. const rx = new RegExp((charType || '\\s') + '+$');
  5981. this.outro = this.outro.replace(rx, '');
  5982. if (this.outro.length) return true;
  5983. let chunk = this.lastChunk;
  5984. do {
  5985. const end = chunk.end;
  5986. const aborted = chunk.trimEnd(rx);
  5987. // if chunk was trimmed, we have a new lastChunk
  5988. if (chunk.end !== end) {
  5989. if (this.lastChunk === chunk) {
  5990. this.lastChunk = chunk.next;
  5991. }
  5992. this.byEnd[chunk.end] = chunk;
  5993. this.byStart[chunk.next.start] = chunk.next;
  5994. this.byEnd[chunk.next.end] = chunk.next;
  5995. }
  5996. if (aborted) return true;
  5997. chunk = chunk.previous;
  5998. } while (chunk);
  5999. return false;
  6000. }
  6001. trimEnd(charType) {
  6002. this.trimEndAborted(charType);
  6003. return this;
  6004. }
  6005. trimStartAborted(charType) {
  6006. const rx = new RegExp('^' + (charType || '\\s') + '+');
  6007. this.intro = this.intro.replace(rx, '');
  6008. if (this.intro.length) return true;
  6009. let chunk = this.firstChunk;
  6010. do {
  6011. const end = chunk.end;
  6012. const aborted = chunk.trimStart(rx);
  6013. if (chunk.end !== end) {
  6014. // special case...
  6015. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  6016. this.byEnd[chunk.end] = chunk;
  6017. this.byStart[chunk.next.start] = chunk.next;
  6018. this.byEnd[chunk.next.end] = chunk.next;
  6019. }
  6020. if (aborted) return true;
  6021. chunk = chunk.next;
  6022. } while (chunk);
  6023. return false;
  6024. }
  6025. trimStart(charType) {
  6026. this.trimStartAborted(charType);
  6027. return this;
  6028. }
  6029. hasChanged() {
  6030. return this.original !== this.toString();
  6031. }
  6032. _replaceRegexp(searchValue, replacement) {
  6033. function getReplacement(match, str) {
  6034. if (typeof replacement === 'string') {
  6035. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  6036. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  6037. if (i === '$') return '$';
  6038. if (i === '&') return match[0];
  6039. const num = +i;
  6040. if (num < match.length) return match[+i];
  6041. return `$${i}`;
  6042. });
  6043. } else {
  6044. return replacement(...match, match.index, str, match.groups);
  6045. }
  6046. }
  6047. function matchAll(re, str) {
  6048. let match;
  6049. const matches = [];
  6050. while ((match = re.exec(str))) {
  6051. matches.push(match);
  6052. }
  6053. return matches;
  6054. }
  6055. if (searchValue.global) {
  6056. const matches = matchAll(searchValue, this.original);
  6057. matches.forEach((match) => {
  6058. if (match.index != null)
  6059. this.overwrite(
  6060. match.index,
  6061. match.index + match[0].length,
  6062. getReplacement(match, this.original)
  6063. );
  6064. });
  6065. } else {
  6066. const match = this.original.match(searchValue);
  6067. if (match && match.index != null)
  6068. this.overwrite(
  6069. match.index,
  6070. match.index + match[0].length,
  6071. getReplacement(match, this.original)
  6072. );
  6073. }
  6074. return this;
  6075. }
  6076. _replaceString(string, replacement) {
  6077. const { original } = this;
  6078. const index = original.indexOf(string);
  6079. if (index !== -1) {
  6080. this.overwrite(index, index + string.length, replacement);
  6081. }
  6082. return this;
  6083. }
  6084. replace(searchValue, replacement) {
  6085. if (typeof searchValue === 'string') {
  6086. return this._replaceString(searchValue, replacement);
  6087. }
  6088. return this._replaceRegexp(searchValue, replacement);
  6089. }
  6090. _replaceAllString(string, replacement) {
  6091. const { original } = this;
  6092. const stringLength = string.length;
  6093. for (
  6094. let index = original.indexOf(string);
  6095. index !== -1;
  6096. index = original.indexOf(string, index + stringLength)
  6097. ) {
  6098. this.overwrite(index, index + stringLength, replacement);
  6099. }
  6100. return this;
  6101. }
  6102. replaceAll(searchValue, replacement) {
  6103. if (typeof searchValue === 'string') {
  6104. return this._replaceAllString(searchValue, replacement);
  6105. }
  6106. if (!searchValue.global) {
  6107. throw new TypeError(
  6108. 'MagicString.prototype.replaceAll called with a non-global RegExp argument'
  6109. );
  6110. }
  6111. return this._replaceRegexp(searchValue, replacement);
  6112. }
  6113. };
  6114. function isReference(node, parent) {
  6115. if (node.type === 'MemberExpression') {
  6116. return !node.computed && isReference(node.object, node);
  6117. }
  6118. if (node.type === 'Identifier') {
  6119. if (!parent)
  6120. return true;
  6121. switch (parent.type) {
  6122. // disregard `bar` in `foo.bar`
  6123. case 'MemberExpression': return parent.computed || node === parent.object;
  6124. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  6125. case 'MethodDefinition': return parent.computed;
  6126. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  6127. case 'FieldDefinition': return parent.computed || node === parent.value;
  6128. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  6129. case 'Property': return parent.computed || node === parent.value;
  6130. // disregard the `bar` in `export { foo as bar }` or
  6131. // the foo in `import { foo as bar }`
  6132. case 'ExportSpecifier':
  6133. case 'ImportSpecifier': return node === parent.local;
  6134. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  6135. case 'LabeledStatement':
  6136. case 'BreakStatement':
  6137. case 'ContinueStatement': return false;
  6138. default: return true;
  6139. }
  6140. }
  6141. return false;
  6142. }
  6143. var version$3 = "25.0.3";
  6144. var peerDependencies = {
  6145. rollup: "^2.68.0||^3.0.0"
  6146. };
  6147. function tryParse(parse, code, id) {
  6148. try {
  6149. return parse(code, { allowReturnOutsideFunction: true });
  6150. } catch (err) {
  6151. err.message += ` in ${id}`;
  6152. throw err;
  6153. }
  6154. }
  6155. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  6156. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  6157. function hasCjsKeywords(code, ignoreGlobal) {
  6158. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  6159. return firstpass.test(code);
  6160. }
  6161. /* eslint-disable no-underscore-dangle */
  6162. function analyzeTopLevelStatements(parse, code, id) {
  6163. const ast = tryParse(parse, code, id);
  6164. let isEsModule = false;
  6165. let hasDefaultExport = false;
  6166. let hasNamedExports = false;
  6167. for (const node of ast.body) {
  6168. switch (node.type) {
  6169. case 'ExportDefaultDeclaration':
  6170. isEsModule = true;
  6171. hasDefaultExport = true;
  6172. break;
  6173. case 'ExportNamedDeclaration':
  6174. isEsModule = true;
  6175. if (node.declaration) {
  6176. hasNamedExports = true;
  6177. } else {
  6178. for (const specifier of node.specifiers) {
  6179. if (specifier.exported.name === 'default') {
  6180. hasDefaultExport = true;
  6181. } else {
  6182. hasNamedExports = true;
  6183. }
  6184. }
  6185. }
  6186. break;
  6187. case 'ExportAllDeclaration':
  6188. isEsModule = true;
  6189. if (node.exported && node.exported.name === 'default') {
  6190. hasDefaultExport = true;
  6191. } else {
  6192. hasNamedExports = true;
  6193. }
  6194. break;
  6195. case 'ImportDeclaration':
  6196. isEsModule = true;
  6197. break;
  6198. }
  6199. }
  6200. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  6201. }
  6202. /* eslint-disable import/prefer-default-export */
  6203. function deconflict(scopes, globals, identifier) {
  6204. let i = 1;
  6205. let deconflicted = makeLegalIdentifier(identifier);
  6206. const hasConflicts = () =>
  6207. scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  6208. while (hasConflicts()) {
  6209. deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
  6210. i += 1;
  6211. }
  6212. for (const scope of scopes) {
  6213. scope.declarations[deconflicted] = true;
  6214. }
  6215. return deconflicted;
  6216. }
  6217. function getName(id) {
  6218. const name = makeLegalIdentifier(basename$1(id, extname(id)));
  6219. if (name !== 'index') {
  6220. return name;
  6221. }
  6222. return makeLegalIdentifier(basename$1(dirname$1(id)));
  6223. }
  6224. function normalizePathSlashes(path) {
  6225. return path.replace(/\\/g, '/');
  6226. }
  6227. const getVirtualPathForDynamicRequirePath = (path, commonDir) =>
  6228. `/${normalizePathSlashes(relative$1(commonDir, path))}`;
  6229. function capitalize(name) {
  6230. return name[0].toUpperCase() + name.slice(1);
  6231. }
  6232. function getStrictRequiresFilter({ strictRequires }) {
  6233. switch (strictRequires) {
  6234. case true:
  6235. return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
  6236. // eslint-disable-next-line no-undefined
  6237. case undefined:
  6238. case 'auto':
  6239. case 'debug':
  6240. case null:
  6241. return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
  6242. case false:
  6243. return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
  6244. default:
  6245. if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) {
  6246. return {
  6247. strictRequiresFilter: createFilter$1(strictRequires),
  6248. detectCyclesAndConditional: false
  6249. };
  6250. }
  6251. throw new Error('Unexpected value for "strictRequires" option.');
  6252. }
  6253. }
  6254. function getPackageEntryPoint(dirPath) {
  6255. let entryPoint = 'index.js';
  6256. try {
  6257. if (existsSync(join$1(dirPath, 'package.json'))) {
  6258. entryPoint =
  6259. JSON.parse(readFileSync(join$1(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
  6260. entryPoint;
  6261. }
  6262. } catch (ignored) {
  6263. // ignored
  6264. }
  6265. return entryPoint;
  6266. }
  6267. function isDirectory(path) {
  6268. try {
  6269. if (statSync$1(path).isDirectory()) return true;
  6270. } catch (ignored) {
  6271. // Nothing to do here
  6272. }
  6273. return false;
  6274. }
  6275. function getDynamicRequireModules(patterns, dynamicRequireRoot) {
  6276. const dynamicRequireModules = new Map();
  6277. const dirNames = new Set();
  6278. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  6279. const isNegated = pattern.startsWith('!');
  6280. const modifyMap = (targetPath, resolvedPath) =>
  6281. isNegated
  6282. ? dynamicRequireModules.delete(targetPath)
  6283. : dynamicRequireModules.set(targetPath, resolvedPath);
  6284. for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) {
  6285. const resolvedPath = resolve$3(path);
  6286. const requirePath = normalizePathSlashes(resolvedPath);
  6287. if (isDirectory(resolvedPath)) {
  6288. dirNames.add(resolvedPath);
  6289. const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path)));
  6290. modifyMap(requirePath, modulePath);
  6291. modifyMap(normalizePathSlashes(modulePath), modulePath);
  6292. } else {
  6293. dirNames.add(dirname$1(resolvedPath));
  6294. modifyMap(requirePath, resolvedPath);
  6295. }
  6296. }
  6297. }
  6298. return {
  6299. commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
  6300. dynamicRequireModules
  6301. };
  6302. }
  6303. const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
  6304. const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire';
  6305. const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire';
  6306. function getDynamicModuleRegistry(
  6307. isDynamicRequireModulesEnabled,
  6308. dynamicRequireModules,
  6309. commonDir,
  6310. ignoreDynamicRequires
  6311. ) {
  6312. if (!isDynamicRequireModulesEnabled) {
  6313. return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
  6314. ${FAILED_REQUIRE_ERROR}
  6315. }`;
  6316. }
  6317. const dynamicModuleImports = [...dynamicRequireModules.values()]
  6318. .map(
  6319. (id, index) =>
  6320. `import ${
  6321. id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }`
  6322. } from ${JSON.stringify(id)};`
  6323. )
  6324. .join('\n');
  6325. const dynamicModuleProps = [...dynamicRequireModules.keys()]
  6326. .map(
  6327. (id, index) =>
  6328. `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${
  6329. id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}`
  6330. }`
  6331. )
  6332. .join(',\n');
  6333. return `${dynamicModuleImports}
  6334. var dynamicModules;
  6335. function getDynamicModules() {
  6336. return dynamicModules || (dynamicModules = {
  6337. ${dynamicModuleProps}
  6338. });
  6339. }
  6340. export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
  6341. function handleRequire(path) {
  6342. var resolvedPath = commonjsResolve(path, originalModuleDir);
  6343. if (resolvedPath !== null) {
  6344. return getDynamicModules()[resolvedPath]();
  6345. }
  6346. ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
  6347. }
  6348. handleRequire.resolve = function (path) {
  6349. var resolvedPath = commonjsResolve(path, originalModuleDir);
  6350. if (resolvedPath !== null) {
  6351. return resolvedPath;
  6352. }
  6353. return require.resolve(path);
  6354. }
  6355. return handleRequire;
  6356. }
  6357. function commonjsResolve (path, originalModuleDir) {
  6358. var shouldTryNodeModules = isPossibleNodeModulesPath(path);
  6359. path = normalize(path);
  6360. var relPath;
  6361. if (path[0] === '/') {
  6362. originalModuleDir = '';
  6363. }
  6364. var modules = getDynamicModules();
  6365. var checkedExtensions = ['', '.js', '.json'];
  6366. while (true) {
  6367. if (!shouldTryNodeModules) {
  6368. relPath = normalize(originalModuleDir + '/' + path);
  6369. } else {
  6370. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  6371. }
  6372. if (relPath.endsWith('/..')) {
  6373. break; // Travelled too far up, avoid infinite loop
  6374. }
  6375. for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
  6376. var resolvedPath = relPath + checkedExtensions[extensionIndex];
  6377. if (modules[resolvedPath]) {
  6378. return resolvedPath;
  6379. }
  6380. }
  6381. if (!shouldTryNodeModules) break;
  6382. var nextDir = normalize(originalModuleDir + '/..');
  6383. if (nextDir === originalModuleDir) break;
  6384. originalModuleDir = nextDir;
  6385. }
  6386. return null;
  6387. }
  6388. function isPossibleNodeModulesPath (modulePath) {
  6389. var c0 = modulePath[0];
  6390. if (c0 === '/' || c0 === '\\\\') return false;
  6391. var c1 = modulePath[1], c2 = modulePath[2];
  6392. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  6393. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  6394. if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
  6395. return true;
  6396. }
  6397. function normalize (path) {
  6398. path = path.replace(/\\\\/g, '/');
  6399. var parts = path.split('/');
  6400. var slashed = parts[0] === '';
  6401. for (var i = 1; i < parts.length; i++) {
  6402. if (parts[i] === '.' || parts[i] === '') {
  6403. parts.splice(i--, 1);
  6404. }
  6405. }
  6406. for (var i = 1; i < parts.length; i++) {
  6407. if (parts[i] !== '..') continue;
  6408. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  6409. parts.splice(--i, 2);
  6410. i--;
  6411. }
  6412. }
  6413. path = parts.join('/');
  6414. if (slashed && path[0] !== '/') path = '/' + path;
  6415. else if (path.length === 0) path = '.';
  6416. return path;
  6417. }`;
  6418. }
  6419. const isWrappedId = (id, suffix) => id.endsWith(suffix);
  6420. const wrapId$1 = (id, suffix) => `\0${id}${suffix}`;
  6421. const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
  6422. const PROXY_SUFFIX = '?commonjs-proxy';
  6423. const WRAPPED_SUFFIX = '?commonjs-wrapped';
  6424. const EXTERNAL_SUFFIX = '?commonjs-external';
  6425. const EXPORTS_SUFFIX = '?commonjs-exports';
  6426. const MODULE_SUFFIX = '?commonjs-module';
  6427. const ENTRY_SUFFIX = '?commonjs-entry';
  6428. const ES_IMPORT_SUFFIX = '?commonjs-es-import';
  6429. const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules';
  6430. const HELPERS_ID = '\0commonjsHelpers.js';
  6431. const IS_WRAPPED_COMMONJS = 'withRequireFunction';
  6432. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  6433. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  6434. // This could be improved by inspecting Rollup's "generatedCode" option
  6435. const HELPERS = `
  6436. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  6437. export function getDefaultExportFromCjs (x) {
  6438. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  6439. }
  6440. export function getDefaultExportFromNamespaceIfPresent (n) {
  6441. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  6442. }
  6443. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  6444. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  6445. }
  6446. export function getAugmentedNamespace(n) {
  6447. if (n.__esModule) return n;
  6448. var f = n.default;
  6449. if (typeof f == "function") {
  6450. var a = function a () {
  6451. if (this instanceof a) {
  6452. return Reflect.construct(f, arguments, this.constructor);
  6453. }
  6454. return f.apply(this, arguments);
  6455. };
  6456. a.prototype = f.prototype;
  6457. } else a = {};
  6458. Object.defineProperty(a, '__esModule', {value: true});
  6459. Object.keys(n).forEach(function (k) {
  6460. var d = Object.getOwnPropertyDescriptor(n, k);
  6461. Object.defineProperty(a, k, d.get ? d : {
  6462. enumerable: true,
  6463. get: function () {
  6464. return n[k];
  6465. }
  6466. });
  6467. });
  6468. return a;
  6469. }
  6470. `;
  6471. function getHelpersModule() {
  6472. return HELPERS;
  6473. }
  6474. function getUnknownRequireProxy(id, requireReturnsDefault) {
  6475. if (requireReturnsDefault === true || id.endsWith('.json')) {
  6476. return `export { default } from ${JSON.stringify(id)};`;
  6477. }
  6478. const name = getName(id);
  6479. const exported =
  6480. requireReturnsDefault === 'auto'
  6481. ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  6482. : requireReturnsDefault === 'preferred'
  6483. ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  6484. : !requireReturnsDefault
  6485. ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  6486. : `export default ${name};`;
  6487. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  6488. }
  6489. async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
  6490. const name = getName(id);
  6491. const {
  6492. meta: { commonjs: commonjsMeta }
  6493. } = await loadModule({ id });
  6494. if (!commonjsMeta) {
  6495. return getUnknownRequireProxy(id, requireReturnsDefault);
  6496. }
  6497. if (commonjsMeta.isCommonJS) {
  6498. return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  6499. }
  6500. if (!requireReturnsDefault) {
  6501. return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  6502. id
  6503. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  6504. }
  6505. if (
  6506. requireReturnsDefault !== true &&
  6507. (requireReturnsDefault === 'namespace' ||
  6508. !commonjsMeta.hasDefaultExport ||
  6509. (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports))
  6510. ) {
  6511. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  6512. }
  6513. return `export { default } from ${JSON.stringify(id)};`;
  6514. }
  6515. function getEntryProxy(id, defaultIsModuleExports, getModuleInfo) {
  6516. const {
  6517. meta: { commonjs: commonjsMeta },
  6518. hasDefaultExport
  6519. } = getModuleInfo(id);
  6520. if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
  6521. const stringifiedId = JSON.stringify(id);
  6522. let code = `export * from ${stringifiedId};`;
  6523. if (hasDefaultExport) {
  6524. code += `export { default } from ${stringifiedId};`;
  6525. }
  6526. return code;
  6527. }
  6528. return getEsImportProxy(id, defaultIsModuleExports);
  6529. }
  6530. function getEsImportProxy(id, defaultIsModuleExports) {
  6531. const name = getName(id);
  6532. const exportsName = `${name}Exports`;
  6533. const requireModule = `require${capitalize(name)}`;
  6534. let code =
  6535. `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` +
  6536. `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` +
  6537. `var ${exportsName} = ${requireModule}();\n` +
  6538. `export { ${exportsName} as __moduleExports };`;
  6539. if (defaultIsModuleExports === true) {
  6540. code += `\nexport { ${exportsName} as default };`;
  6541. } else {
  6542. code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
  6543. }
  6544. return {
  6545. code,
  6546. syntheticNamedExports: '__moduleExports'
  6547. };
  6548. }
  6549. /* eslint-disable no-param-reassign, no-undefined */
  6550. function getCandidatesForExtension(resolved, extension) {
  6551. return [resolved + extension, `${resolved}${sep$1}index${extension}`];
  6552. }
  6553. function getCandidates(resolved, extensions) {
  6554. return extensions.reduce(
  6555. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  6556. [resolved]
  6557. );
  6558. }
  6559. function resolveExtensions(importee, importer, extensions) {
  6560. // not our problem
  6561. if (importee[0] !== '.' || !importer) return undefined;
  6562. const resolved = resolve$3(dirname$1(importer), importee);
  6563. const candidates = getCandidates(resolved, extensions);
  6564. for (let i = 0; i < candidates.length; i += 1) {
  6565. try {
  6566. const stats = statSync$1(candidates[i]);
  6567. if (stats.isFile()) return { id: candidates[i] };
  6568. } catch (err) {
  6569. /* noop */
  6570. }
  6571. }
  6572. return undefined;
  6573. }
  6574. function getResolveId(extensions, isPossibleCjsId) {
  6575. const currentlyResolving = new Map();
  6576. return {
  6577. /**
  6578. * This is a Maps of importers to Sets of require sources being resolved at
  6579. * the moment by resolveRequireSourcesAndUpdateMeta
  6580. */
  6581. currentlyResolving,
  6582. async resolveId(importee, importer, resolveOptions) {
  6583. const customOptions = resolveOptions.custom;
  6584. // All logic below is specific to ES imports.
  6585. // Also, if we do not skip this logic for requires that are resolved while
  6586. // transforming a commonjs file, it can easily lead to deadlocks.
  6587. if (
  6588. customOptions &&
  6589. customOptions['node-resolve'] &&
  6590. customOptions['node-resolve'].isRequire
  6591. ) {
  6592. return null;
  6593. }
  6594. const currentlyResolvingForParent = currentlyResolving.get(importer);
  6595. if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
  6596. this.warn({
  6597. code: 'THIS_RESOLVE_WITHOUT_OPTIONS',
  6598. message:
  6599. 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
  6600. url: 'https://rollupjs.org/guide/en/#resolveid'
  6601. });
  6602. return null;
  6603. }
  6604. if (isWrappedId(importee, WRAPPED_SUFFIX)) {
  6605. return unwrapId$1(importee, WRAPPED_SUFFIX);
  6606. }
  6607. if (
  6608. importee.endsWith(ENTRY_SUFFIX) ||
  6609. isWrappedId(importee, MODULE_SUFFIX) ||
  6610. isWrappedId(importee, EXPORTS_SUFFIX) ||
  6611. isWrappedId(importee, PROXY_SUFFIX) ||
  6612. isWrappedId(importee, ES_IMPORT_SUFFIX) ||
  6613. isWrappedId(importee, EXTERNAL_SUFFIX) ||
  6614. importee.startsWith(HELPERS_ID) ||
  6615. importee === DYNAMIC_MODULES_ID
  6616. ) {
  6617. return importee;
  6618. }
  6619. if (importer) {
  6620. if (
  6621. importer === DYNAMIC_MODULES_ID ||
  6622. // Proxies are only importing resolved ids, no need to resolve again
  6623. isWrappedId(importer, PROXY_SUFFIX) ||
  6624. isWrappedId(importer, ES_IMPORT_SUFFIX) ||
  6625. importer.endsWith(ENTRY_SUFFIX)
  6626. ) {
  6627. return importee;
  6628. }
  6629. if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
  6630. // We need to return null for unresolved imports so that the proper warning is shown
  6631. if (
  6632. !(await this.resolve(
  6633. importee,
  6634. importer,
  6635. Object.assign({ skipSelf: true }, resolveOptions)
  6636. ))
  6637. ) {
  6638. return null;
  6639. }
  6640. // For other external imports, we need to make sure they are handled as external
  6641. return { id: importee, external: true };
  6642. }
  6643. }
  6644. if (importee.startsWith('\0')) {
  6645. return null;
  6646. }
  6647. // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and
  6648. // if that is the case, we need to add a proxy.
  6649. const resolved =
  6650. (await this.resolve(
  6651. importee,
  6652. importer,
  6653. Object.assign({ skipSelf: true }, resolveOptions)
  6654. )) || resolveExtensions(importee, importer, extensions);
  6655. // Make sure that even if other plugins resolve again, we ignore our own proxies
  6656. if (
  6657. !resolved ||
  6658. resolved.external ||
  6659. resolved.id.endsWith(ENTRY_SUFFIX) ||
  6660. isWrappedId(resolved.id, ES_IMPORT_SUFFIX) ||
  6661. !isPossibleCjsId(resolved.id)
  6662. ) {
  6663. return resolved;
  6664. }
  6665. const moduleInfo = await this.load(resolved);
  6666. const {
  6667. meta: { commonjs: commonjsMeta }
  6668. } = moduleInfo;
  6669. if (commonjsMeta) {
  6670. const { isCommonJS } = commonjsMeta;
  6671. if (isCommonJS) {
  6672. if (resolveOptions.isEntry) {
  6673. moduleInfo.moduleSideEffects = true;
  6674. // We must not precede entry proxies with a `\0` as that will mess up relative external resolution
  6675. return resolved.id + ENTRY_SUFFIX;
  6676. }
  6677. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  6678. return { id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
  6679. }
  6680. }
  6681. }
  6682. return resolved;
  6683. }
  6684. };
  6685. }
  6686. function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) {
  6687. const knownCjsModuleTypes = Object.create(null);
  6688. const requiredIds = Object.create(null);
  6689. const unconditionallyRequiredIds = Object.create(null);
  6690. const dependencies = Object.create(null);
  6691. const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set());
  6692. const isCyclic = (id) => {
  6693. const dependenciesToCheck = new Set(getDependencies(id));
  6694. for (const dependency of dependenciesToCheck) {
  6695. if (dependency === id) {
  6696. return true;
  6697. }
  6698. for (const childDependency of getDependencies(dependency)) {
  6699. dependenciesToCheck.add(childDependency);
  6700. }
  6701. }
  6702. return false;
  6703. };
  6704. // Once a module is listed here, its type (wrapped or not) is fixed and may
  6705. // not change for the rest of the current build, to not break already
  6706. // transformed modules.
  6707. const fullyAnalyzedModules = Object.create(null);
  6708. const getTypeForFullyAnalyzedModule = (id) => {
  6709. const knownType = knownCjsModuleTypes[id];
  6710. if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
  6711. return knownType;
  6712. }
  6713. if (isCyclic(id)) {
  6714. return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS);
  6715. }
  6716. return knownType;
  6717. };
  6718. const setInitialParentType = (id, initialCommonJSType) => {
  6719. // Fully analyzed modules may never change type
  6720. if (fullyAnalyzedModules[id]) {
  6721. return;
  6722. }
  6723. knownCjsModuleTypes[id] = initialCommonJSType;
  6724. if (
  6725. detectCyclesAndConditional &&
  6726. knownCjsModuleTypes[id] === true &&
  6727. requiredIds[id] &&
  6728. !unconditionallyRequiredIds[id]
  6729. ) {
  6730. knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
  6731. }
  6732. };
  6733. const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
  6734. const childId = resolved.id;
  6735. requiredIds[childId] = true;
  6736. if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
  6737. unconditionallyRequiredIds[childId] = true;
  6738. }
  6739. getDependencies(parentId).add(childId);
  6740. if (!isCyclic(childId)) {
  6741. // This makes sure the current transform handler waits for all direct
  6742. // dependencies to be loaded and transformed and therefore for all
  6743. // transitive CommonJS dependencies to be loaded as well so that all
  6744. // cycles have been found and knownCjsModuleTypes is reliable.
  6745. await loadModule(resolved);
  6746. }
  6747. };
  6748. const getTypeForImportedModule = async (resolved, loadModule) => {
  6749. if (resolved.id in knownCjsModuleTypes) {
  6750. // This handles cyclic ES dependencies
  6751. return knownCjsModuleTypes[resolved.id];
  6752. }
  6753. const {
  6754. meta: { commonjs }
  6755. } = await loadModule(resolved);
  6756. return (commonjs && commonjs.isCommonJS) || false;
  6757. };
  6758. return {
  6759. getWrappedIds: () =>
  6760. Object.keys(knownCjsModuleTypes).filter(
  6761. (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
  6762. ),
  6763. isRequiredId: (id) => requiredIds[id],
  6764. async shouldTransformCachedModule({
  6765. id: parentId,
  6766. resolvedSources,
  6767. meta: { commonjs: parentMeta }
  6768. }) {
  6769. // We explicitly track ES modules to handle circular imports
  6770. if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
  6771. if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
  6772. const parentRequires = parentMeta && parentMeta.requires;
  6773. if (parentRequires) {
  6774. setInitialParentType(parentId, parentMeta.initialCommonJSType);
  6775. await Promise.all(
  6776. parentRequires.map(({ resolved, isConditional }) =>
  6777. analyzeRequiredModule(parentId, resolved, isConditional, this.load)
  6778. )
  6779. );
  6780. if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
  6781. return true;
  6782. }
  6783. for (const {
  6784. resolved: { id }
  6785. } of parentRequires) {
  6786. if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
  6787. return true;
  6788. }
  6789. }
  6790. // Now that we decided to go with the cached copy, neither the parent
  6791. // module nor any of its children may change types anymore
  6792. fullyAnalyzedModules[parentId] = true;
  6793. for (const {
  6794. resolved: { id }
  6795. } of parentRequires) {
  6796. fullyAnalyzedModules[id] = true;
  6797. }
  6798. }
  6799. const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
  6800. return (
  6801. await Promise.all(
  6802. Object.keys(resolvedSources)
  6803. .map((source) => resolvedSources[source])
  6804. .filter(({ id, external }) => !(external || parentRequireSet.has(id)))
  6805. .map(async (resolved) => {
  6806. if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
  6807. return (
  6808. (await getTypeForImportedModule(
  6809. (
  6810. await this.load({ id: resolved.id })
  6811. ).meta.commonjs.resolved,
  6812. this.load
  6813. )) !== IS_WRAPPED_COMMONJS
  6814. );
  6815. }
  6816. return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS;
  6817. })
  6818. )
  6819. ).some((shouldTransform) => shouldTransform);
  6820. },
  6821. /* eslint-disable no-param-reassign */
  6822. resolveRequireSourcesAndUpdateMeta:
  6823. (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
  6824. parentMeta.initialCommonJSType = isParentCommonJS;
  6825. parentMeta.requires = [];
  6826. parentMeta.isRequiredCommonJS = Object.create(null);
  6827. setInitialParentType(parentId, isParentCommonJS);
  6828. const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set();
  6829. currentlyResolving.set(parentId, currentlyResolvingForParent);
  6830. const requireTargets = await Promise.all(
  6831. sources.map(async ({ source, isConditional }) => {
  6832. // Never analyze or proxy internal modules
  6833. if (source.startsWith('\0')) {
  6834. return { id: source, allowProxy: false };
  6835. }
  6836. currentlyResolvingForParent.add(source);
  6837. const resolved =
  6838. (await rollupContext.resolve(source, parentId, {
  6839. custom: { 'node-resolve': { isRequire: true } }
  6840. })) || resolveExtensions(source, parentId, extensions);
  6841. currentlyResolvingForParent.delete(source);
  6842. if (!resolved) {
  6843. return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false };
  6844. }
  6845. const childId = resolved.id;
  6846. if (resolved.external) {
  6847. return { id: wrapId$1(childId, EXTERNAL_SUFFIX), allowProxy: false };
  6848. }
  6849. parentMeta.requires.push({ resolved, isConditional });
  6850. await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
  6851. return { id: childId, allowProxy: true };
  6852. })
  6853. );
  6854. parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
  6855. fullyAnalyzedModules[parentId] = true;
  6856. return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
  6857. // eslint-disable-next-line no-multi-assign
  6858. const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] =
  6859. getTypeForFullyAnalyzedModule(dependencyId));
  6860. fullyAnalyzedModules[dependencyId] = true;
  6861. return {
  6862. source: sources[index].source,
  6863. id: allowProxy
  6864. ? isCommonJS === IS_WRAPPED_COMMONJS
  6865. ? wrapId$1(dependencyId, WRAPPED_SUFFIX)
  6866. : wrapId$1(dependencyId, PROXY_SUFFIX)
  6867. : dependencyId,
  6868. isCommonJS
  6869. };
  6870. });
  6871. },
  6872. isCurrentlyResolving(source, parentId) {
  6873. const currentlyResolvingForParent = currentlyResolving.get(parentId);
  6874. return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
  6875. }
  6876. };
  6877. }
  6878. function validateVersion(actualVersion, peerDependencyVersion, name) {
  6879. const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
  6880. let minMajor = Infinity;
  6881. let minMinor = Infinity;
  6882. let minPatch = Infinity;
  6883. let foundVersion;
  6884. // eslint-disable-next-line no-cond-assign
  6885. while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
  6886. const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
  6887. if (foundMajor < minMajor) {
  6888. minMajor = foundMajor;
  6889. minMinor = foundMinor;
  6890. minPatch = foundPatch;
  6891. }
  6892. }
  6893. if (!actualVersion) {
  6894. throw new Error(
  6895. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.`
  6896. );
  6897. }
  6898. const [major, minor, patch] = actualVersion.split('.').map(Number);
  6899. if (
  6900. major < minMajor ||
  6901. (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
  6902. ) {
  6903. throw new Error(
  6904. `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.`
  6905. );
  6906. }
  6907. }
  6908. const operators = {
  6909. '==': (x) => equals(x.left, x.right, false),
  6910. '!=': (x) => not(operators['=='](x)),
  6911. '===': (x) => equals(x.left, x.right, true),
  6912. '!==': (x) => not(operators['==='](x)),
  6913. '!': (x) => isFalsy(x.argument),
  6914. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  6915. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  6916. };
  6917. function not(value) {
  6918. return value === null ? value : !value;
  6919. }
  6920. function equals(a, b, strict) {
  6921. if (a.type !== b.type) return null;
  6922. // eslint-disable-next-line eqeqeq
  6923. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  6924. return null;
  6925. }
  6926. function isTruthy(node) {
  6927. if (!node) return false;
  6928. if (node.type === 'Literal') return !!node.value;
  6929. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  6930. if (node.operator in operators) return operators[node.operator](node);
  6931. return null;
  6932. }
  6933. function isFalsy(node) {
  6934. return not(isTruthy(node));
  6935. }
  6936. function getKeypath(node) {
  6937. const parts = [];
  6938. while (node.type === 'MemberExpression') {
  6939. if (node.computed) return null;
  6940. parts.unshift(node.property.name);
  6941. // eslint-disable-next-line no-param-reassign
  6942. node = node.object;
  6943. }
  6944. if (node.type !== 'Identifier') return null;
  6945. const { name } = node;
  6946. parts.unshift(name);
  6947. return { name, keypath: parts.join('.') };
  6948. }
  6949. const KEY_COMPILED_ESM = '__esModule';
  6950. function getDefineCompiledEsmType(node) {
  6951. const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports');
  6952. const definedProperty =
  6953. definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports');
  6954. if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
  6955. return isTruthy(definedProperty.value)
  6956. ? definedPropertyWithExports
  6957. ? 'exports'
  6958. : 'module'
  6959. : false;
  6960. }
  6961. return false;
  6962. }
  6963. function getDefinePropertyCallName(node, targetName) {
  6964. const {
  6965. callee: { object, property }
  6966. } = node;
  6967. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  6968. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  6969. if (node.arguments.length !== 3) return;
  6970. const targetNames = targetName.split('.');
  6971. const [target, key, value] = node.arguments;
  6972. if (targetNames.length === 1) {
  6973. if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
  6974. return;
  6975. }
  6976. }
  6977. if (targetNames.length === 2) {
  6978. if (
  6979. target.type !== 'MemberExpression' ||
  6980. target.object.name !== targetNames[0] ||
  6981. target.property.name !== targetNames[1]
  6982. ) {
  6983. return;
  6984. }
  6985. }
  6986. if (value.type !== 'ObjectExpression' || !value.properties) return;
  6987. const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
  6988. if (!valueProperty || !valueProperty.value) return;
  6989. // eslint-disable-next-line consistent-return
  6990. return { key: key.value, value: valueProperty.value };
  6991. }
  6992. function isShorthandProperty(parent) {
  6993. return parent && parent.type === 'Property' && parent.shorthand;
  6994. }
  6995. function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
  6996. const args = [];
  6997. const passedArgs = [];
  6998. if (uses.module) {
  6999. args.push('module');
  7000. passedArgs.push(moduleName);
  7001. }
  7002. if (uses.exports) {
  7003. args.push('exports');
  7004. passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
  7005. }
  7006. magicString
  7007. .trim()
  7008. .indent('\t', { exclude: indentExclusionRanges })
  7009. .prepend(`(function (${args.join(', ')}) {\n`)
  7010. // For some reason, this line is only indented correctly when using a
  7011. // require-wrapper if we have this leading space
  7012. .append(` \n} (${passedArgs.join(', ')}));`);
  7013. }
  7014. function rewriteExportsAndGetExportsBlock(
  7015. magicString,
  7016. moduleName,
  7017. exportsName,
  7018. exportedExportsName,
  7019. wrapped,
  7020. moduleExportsAssignments,
  7021. firstTopLevelModuleExportsAssignment,
  7022. exportsAssignmentsByName,
  7023. topLevelAssignments,
  7024. defineCompiledEsmExpressions,
  7025. deconflictedExportNames,
  7026. code,
  7027. HELPERS_NAME,
  7028. exportMode,
  7029. defaultIsModuleExports,
  7030. usesRequireWrapper,
  7031. requireName
  7032. ) {
  7033. const exports = [];
  7034. const exportDeclarations = [];
  7035. if (usesRequireWrapper) {
  7036. getExportsWhenUsingRequireWrapper(
  7037. magicString,
  7038. wrapped,
  7039. exportMode,
  7040. exports,
  7041. moduleExportsAssignments,
  7042. exportsAssignmentsByName,
  7043. moduleName,
  7044. exportsName,
  7045. requireName,
  7046. defineCompiledEsmExpressions
  7047. );
  7048. } else if (exportMode === 'replace') {
  7049. getExportsForReplacedModuleExports(
  7050. magicString,
  7051. exports,
  7052. exportDeclarations,
  7053. moduleExportsAssignments,
  7054. firstTopLevelModuleExportsAssignment,
  7055. exportsName,
  7056. defaultIsModuleExports,
  7057. HELPERS_NAME
  7058. );
  7059. } else {
  7060. if (exportMode === 'module') {
  7061. exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
  7062. exports.push(`${exportedExportsName} as __moduleExports`);
  7063. } else {
  7064. exports.push(`${exportsName} as __moduleExports`);
  7065. }
  7066. if (wrapped) {
  7067. exportDeclarations.push(
  7068. getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
  7069. );
  7070. } else {
  7071. getExports(
  7072. magicString,
  7073. exports,
  7074. exportDeclarations,
  7075. moduleExportsAssignments,
  7076. exportsAssignmentsByName,
  7077. deconflictedExportNames,
  7078. topLevelAssignments,
  7079. moduleName,
  7080. exportsName,
  7081. exportedExportsName,
  7082. defineCompiledEsmExpressions,
  7083. HELPERS_NAME,
  7084. defaultIsModuleExports,
  7085. exportMode
  7086. );
  7087. }
  7088. }
  7089. if (exports.length) {
  7090. exportDeclarations.push(`export { ${exports.join(', ')} }`);
  7091. }
  7092. return `\n\n${exportDeclarations.join(';\n')};`;
  7093. }
  7094. function getExportsWhenUsingRequireWrapper(
  7095. magicString,
  7096. wrapped,
  7097. exportMode,
  7098. exports,
  7099. moduleExportsAssignments,
  7100. exportsAssignmentsByName,
  7101. moduleName,
  7102. exportsName,
  7103. requireName,
  7104. defineCompiledEsmExpressions
  7105. ) {
  7106. exports.push(`${requireName} as __require`);
  7107. if (wrapped) return;
  7108. if (exportMode === 'replace') {
  7109. rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
  7110. } else {
  7111. rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
  7112. // Collect and rewrite named exports
  7113. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  7114. for (const { node, type } of nodes) {
  7115. magicString.overwrite(
  7116. node.start,
  7117. node.left.end,
  7118. `${
  7119. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  7120. }.${exportName}`
  7121. );
  7122. }
  7123. }
  7124. replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  7125. defineCompiledEsmExpressions,
  7126. magicString,
  7127. exportMode,
  7128. moduleName,
  7129. exportsName
  7130. );
  7131. }
  7132. }
  7133. function getExportsForReplacedModuleExports(
  7134. magicString,
  7135. exports,
  7136. exportDeclarations,
  7137. moduleExportsAssignments,
  7138. firstTopLevelModuleExportsAssignment,
  7139. exportsName,
  7140. defaultIsModuleExports,
  7141. HELPERS_NAME
  7142. ) {
  7143. for (const { left } of moduleExportsAssignments) {
  7144. magicString.overwrite(left.start, left.end, exportsName);
  7145. }
  7146. magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
  7147. exports.push(`${exportsName} as __moduleExports`);
  7148. exportDeclarations.push(
  7149. getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)
  7150. );
  7151. }
  7152. function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
  7153. return `export default ${
  7154. defaultIsModuleExports === true
  7155. ? exportedExportsName
  7156. : defaultIsModuleExports === false
  7157. ? `${exportedExportsName}.default`
  7158. : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`
  7159. }`;
  7160. }
  7161. function getExports(
  7162. magicString,
  7163. exports,
  7164. exportDeclarations,
  7165. moduleExportsAssignments,
  7166. exportsAssignmentsByName,
  7167. deconflictedExportNames,
  7168. topLevelAssignments,
  7169. moduleName,
  7170. exportsName,
  7171. exportedExportsName,
  7172. defineCompiledEsmExpressions,
  7173. HELPERS_NAME,
  7174. defaultIsModuleExports,
  7175. exportMode
  7176. ) {
  7177. let deconflictedDefaultExportName;
  7178. // Collect and rewrite module.exports assignments
  7179. for (const { left } of moduleExportsAssignments) {
  7180. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  7181. }
  7182. // Collect and rewrite named exports
  7183. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  7184. const deconflicted = deconflictedExportNames[exportName];
  7185. let needsDeclaration = true;
  7186. for (const { node, type } of nodes) {
  7187. let replacement = `${deconflicted} = ${
  7188. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  7189. }.${exportName}`;
  7190. if (needsDeclaration && topLevelAssignments.has(node)) {
  7191. replacement = `var ${replacement}`;
  7192. needsDeclaration = false;
  7193. }
  7194. magicString.overwrite(node.start, node.left.end, replacement);
  7195. }
  7196. if (needsDeclaration) {
  7197. magicString.prepend(`var ${deconflicted};\n`);
  7198. }
  7199. if (exportName === 'default') {
  7200. deconflictedDefaultExportName = deconflicted;
  7201. } else {
  7202. exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
  7203. }
  7204. }
  7205. const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  7206. defineCompiledEsmExpressions,
  7207. magicString,
  7208. exportMode,
  7209. moduleName,
  7210. exportsName
  7211. );
  7212. if (
  7213. defaultIsModuleExports === false ||
  7214. (defaultIsModuleExports === 'auto' &&
  7215. isRestorableCompiledEsm &&
  7216. moduleExportsAssignments.length === 0)
  7217. ) {
  7218. // If there is no deconflictedDefaultExportName, then we use the namespace as
  7219. // fallback because there can be no "default" property on the namespace
  7220. exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
  7221. } else if (
  7222. defaultIsModuleExports === true ||
  7223. (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0)
  7224. ) {
  7225. exports.push(`${exportedExportsName} as default`);
  7226. } else {
  7227. exportDeclarations.push(
  7228. getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
  7229. );
  7230. }
  7231. }
  7232. function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
  7233. for (const { left } of moduleExportsAssignments) {
  7234. magicString.overwrite(left.start, left.end, exportsName);
  7235. }
  7236. }
  7237. function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
  7238. defineCompiledEsmExpressions,
  7239. magicString,
  7240. exportMode,
  7241. moduleName,
  7242. exportsName
  7243. ) {
  7244. let isRestorableCompiledEsm = false;
  7245. for (const { node, type } of defineCompiledEsmExpressions) {
  7246. isRestorableCompiledEsm = true;
  7247. const moduleExportsExpression =
  7248. node.type === 'CallExpression' ? node.arguments[0] : node.left.object;
  7249. magicString.overwrite(
  7250. moduleExportsExpression.start,
  7251. moduleExportsExpression.end,
  7252. exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName
  7253. );
  7254. }
  7255. return isRestorableCompiledEsm;
  7256. }
  7257. function isRequireExpression(node, scope) {
  7258. if (!node) return false;
  7259. if (node.type !== 'CallExpression') return false;
  7260. // Weird case of `require()` or `module.require()` without arguments
  7261. if (node.arguments.length === 0) return false;
  7262. return isRequire(node.callee, scope);
  7263. }
  7264. function isRequire(node, scope) {
  7265. return (
  7266. (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
  7267. (node.type === 'MemberExpression' && isModuleRequire(node, scope))
  7268. );
  7269. }
  7270. function isModuleRequire({ object, property }, scope) {
  7271. return (
  7272. object.type === 'Identifier' &&
  7273. object.name === 'module' &&
  7274. property.type === 'Identifier' &&
  7275. property.name === 'require' &&
  7276. !scope.contains('module')
  7277. );
  7278. }
  7279. function hasDynamicArguments(node) {
  7280. return (
  7281. node.arguments.length > 1 ||
  7282. (node.arguments[0].type !== 'Literal' &&
  7283. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  7284. );
  7285. }
  7286. const reservedMethod = { resolve: true, cache: true, main: true };
  7287. function isNodeRequirePropertyAccess(parent) {
  7288. return parent && parent.property && reservedMethod[parent.property.name];
  7289. }
  7290. function getRequireStringArg(node) {
  7291. return node.arguments[0].type === 'Literal'
  7292. ? node.arguments[0].value
  7293. : node.arguments[0].quasis[0].value.cooked;
  7294. }
  7295. function getRequireHandlers() {
  7296. const requireExpressions = [];
  7297. function addRequireExpression(
  7298. sourceId,
  7299. node,
  7300. scope,
  7301. usesReturnValue,
  7302. isInsideTryBlock,
  7303. isInsideConditional,
  7304. toBeRemoved
  7305. ) {
  7306. requireExpressions.push({
  7307. sourceId,
  7308. node,
  7309. scope,
  7310. usesReturnValue,
  7311. isInsideTryBlock,
  7312. isInsideConditional,
  7313. toBeRemoved
  7314. });
  7315. }
  7316. async function rewriteRequireExpressionsAndGetImportBlock(
  7317. magicString,
  7318. topLevelDeclarations,
  7319. reassignedNames,
  7320. helpersName,
  7321. dynamicRequireName,
  7322. moduleName,
  7323. exportsName,
  7324. id,
  7325. exportMode,
  7326. resolveRequireSourcesAndUpdateMeta,
  7327. needsRequireWrapper,
  7328. isEsModule,
  7329. isDynamicRequireModulesEnabled,
  7330. getIgnoreTryCatchRequireStatementMode,
  7331. commonjsMeta
  7332. ) {
  7333. const imports = [];
  7334. imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
  7335. if (dynamicRequireName) {
  7336. imports.push(
  7337. `import { ${
  7338. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  7339. } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`
  7340. );
  7341. }
  7342. if (exportMode === 'module') {
  7343. imports.push(
  7344. `import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`,
  7345. `var ${exportsName} = ${moduleName}.exports`
  7346. );
  7347. } else if (exportMode === 'exports') {
  7348. imports.push(
  7349. `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}`
  7350. );
  7351. }
  7352. const requiresBySource = collectSources(requireExpressions);
  7353. const requireTargets = await resolveRequireSourcesAndUpdateMeta(
  7354. id,
  7355. needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
  7356. commonjsMeta,
  7357. Object.keys(requiresBySource).map((source) => {
  7358. return {
  7359. source,
  7360. isConditional: requiresBySource[source].every((require) => require.isInsideConditional)
  7361. };
  7362. })
  7363. );
  7364. processRequireExpressions(
  7365. imports,
  7366. requireTargets,
  7367. requiresBySource,
  7368. getIgnoreTryCatchRequireStatementMode,
  7369. magicString
  7370. );
  7371. return imports.length ? `${imports.join(';\n')};\n\n` : '';
  7372. }
  7373. return {
  7374. addRequireExpression,
  7375. rewriteRequireExpressionsAndGetImportBlock
  7376. };
  7377. }
  7378. function collectSources(requireExpressions) {
  7379. const requiresBySource = Object.create(null);
  7380. for (const requireExpression of requireExpressions) {
  7381. const { sourceId } = requireExpression;
  7382. if (!requiresBySource[sourceId]) {
  7383. requiresBySource[sourceId] = [];
  7384. }
  7385. const requires = requiresBySource[sourceId];
  7386. requires.push(requireExpression);
  7387. }
  7388. return requiresBySource;
  7389. }
  7390. function processRequireExpressions(
  7391. imports,
  7392. requireTargets,
  7393. requiresBySource,
  7394. getIgnoreTryCatchRequireStatementMode,
  7395. magicString
  7396. ) {
  7397. const generateRequireName = getGenerateRequireName();
  7398. for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
  7399. const requires = requiresBySource[source];
  7400. const name = generateRequireName(requires);
  7401. let usesRequired = false;
  7402. let needsImport = false;
  7403. for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
  7404. const { canConvertRequire, shouldRemoveRequire } =
  7405. isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX)
  7406. ? getIgnoreTryCatchRequireStatementMode(source)
  7407. : { canConvertRequire: true, shouldRemoveRequire: false };
  7408. if (shouldRemoveRequire) {
  7409. if (usesReturnValue) {
  7410. magicString.overwrite(node.start, node.end, 'undefined');
  7411. } else {
  7412. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  7413. }
  7414. } else if (canConvertRequire) {
  7415. needsImport = true;
  7416. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  7417. magicString.overwrite(node.start, node.end, `${name}()`);
  7418. } else if (usesReturnValue) {
  7419. usesRequired = true;
  7420. magicString.overwrite(node.start, node.end, name);
  7421. } else {
  7422. magicString.remove(toBeRemoved.start, toBeRemoved.end);
  7423. }
  7424. }
  7425. }
  7426. if (needsImport) {
  7427. if (isCommonJS === IS_WRAPPED_COMMONJS) {
  7428. imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`);
  7429. } else {
  7430. imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`);
  7431. }
  7432. }
  7433. }
  7434. }
  7435. function getGenerateRequireName() {
  7436. let uid = 0;
  7437. return (requires) => {
  7438. let name;
  7439. const hasNameConflict = ({ scope }) => scope.contains(name);
  7440. do {
  7441. name = `require$$${uid}`;
  7442. uid += 1;
  7443. } while (requires.some(hasNameConflict));
  7444. return name;
  7445. };
  7446. }
  7447. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  7448. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  7449. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  7450. // There are three different types of CommonJS modules, described by their
  7451. // "exportMode":
  7452. // - exports: Only assignments to (module.)exports properties
  7453. // - replace: A single assignment to module.exports itself
  7454. // - module: Anything else
  7455. // Special cases:
  7456. // - usesRequireWrapper
  7457. // - isWrapped
  7458. async function transformCommonjs(
  7459. parse,
  7460. code,
  7461. id,
  7462. isEsModule,
  7463. ignoreGlobal,
  7464. ignoreRequire,
  7465. ignoreDynamicRequires,
  7466. getIgnoreTryCatchRequireStatementMode,
  7467. sourceMap,
  7468. isDynamicRequireModulesEnabled,
  7469. dynamicRequireModules,
  7470. commonDir,
  7471. astCache,
  7472. defaultIsModuleExports,
  7473. needsRequireWrapper,
  7474. resolveRequireSourcesAndUpdateMeta,
  7475. isRequired,
  7476. checkDynamicRequire,
  7477. commonjsMeta
  7478. ) {
  7479. const ast = astCache || tryParse(parse, code, id);
  7480. const magicString = new MagicString$1(code);
  7481. const uses = {
  7482. module: false,
  7483. exports: false,
  7484. global: false,
  7485. require: false
  7486. };
  7487. const virtualDynamicRequirePath =
  7488. isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir);
  7489. let scope = attachScopes(ast, 'scope');
  7490. let lexicalDepth = 0;
  7491. let programDepth = 0;
  7492. let classBodyDepth = 0;
  7493. let currentTryBlockEnd = null;
  7494. let shouldWrap = false;
  7495. const globals = new Set();
  7496. // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require
  7497. // or contains nested requires, those should be handled as function calls unless there is an
  7498. // unconditional require elsewhere.
  7499. let currentConditionalNodeEnd = null;
  7500. const conditionalNodes = new Set();
  7501. const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
  7502. // See which names are assigned to. This is necessary to prevent
  7503. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  7504. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  7505. const reassignedNames = new Set();
  7506. const topLevelDeclarations = [];
  7507. const skippedNodes = new Set();
  7508. const moduleAccessScopes = new Set([scope]);
  7509. const exportsAccessScopes = new Set([scope]);
  7510. const moduleExportsAssignments = [];
  7511. let firstTopLevelModuleExportsAssignment = null;
  7512. const exportsAssignmentsByName = new Map();
  7513. const topLevelAssignments = new Set();
  7514. const topLevelDefineCompiledEsmExpressions = [];
  7515. const replacedGlobal = [];
  7516. const replacedDynamicRequires = [];
  7517. const importedVariables = new Set();
  7518. const indentExclusionRanges = [];
  7519. walk$4(ast, {
  7520. enter(node, parent) {
  7521. if (skippedNodes.has(node)) {
  7522. this.skip();
  7523. return;
  7524. }
  7525. if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
  7526. currentTryBlockEnd = null;
  7527. }
  7528. if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) {
  7529. currentConditionalNodeEnd = null;
  7530. }
  7531. if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) {
  7532. currentConditionalNodeEnd = node.end;
  7533. }
  7534. programDepth += 1;
  7535. if (node.scope) ({ scope } = node);
  7536. if (functionType.test(node.type)) lexicalDepth += 1;
  7537. if (sourceMap) {
  7538. magicString.addSourcemapLocation(node.start);
  7539. magicString.addSourcemapLocation(node.end);
  7540. }
  7541. // eslint-disable-next-line default-case
  7542. switch (node.type) {
  7543. case 'AssignmentExpression':
  7544. if (node.left.type === 'MemberExpression') {
  7545. const flattened = getKeypath(node.left);
  7546. if (!flattened || scope.contains(flattened.name)) return;
  7547. const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
  7548. if (!exportsPatternMatch || flattened.keypath === 'exports') return;
  7549. const [, exportName] = exportsPatternMatch;
  7550. uses[flattened.name] = true;
  7551. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  7552. if (flattened.keypath === 'module.exports') {
  7553. moduleExportsAssignments.push(node);
  7554. if (programDepth > 3) {
  7555. moduleAccessScopes.add(scope);
  7556. } else if (!firstTopLevelModuleExportsAssignment) {
  7557. firstTopLevelModuleExportsAssignment = node;
  7558. }
  7559. } else if (exportName === KEY_COMPILED_ESM) {
  7560. if (programDepth > 3) {
  7561. shouldWrap = true;
  7562. } else {
  7563. // The "type" is either "module" or "exports" to discern
  7564. // assignments to module.exports vs exports if needed
  7565. topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name });
  7566. }
  7567. } else {
  7568. const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
  7569. nodes: [],
  7570. scopes: new Set()
  7571. };
  7572. exportsAssignments.nodes.push({ node, type: flattened.name });
  7573. exportsAssignments.scopes.add(scope);
  7574. exportsAccessScopes.add(scope);
  7575. exportsAssignmentsByName.set(exportName, exportsAssignments);
  7576. if (programDepth <= 3) {
  7577. topLevelAssignments.add(node);
  7578. }
  7579. }
  7580. skippedNodes.add(node.left);
  7581. } else {
  7582. for (const name of extractAssignedNames(node.left)) {
  7583. reassignedNames.add(name);
  7584. }
  7585. }
  7586. return;
  7587. case 'CallExpression': {
  7588. const defineCompiledEsmType = getDefineCompiledEsmType(node);
  7589. if (defineCompiledEsmType) {
  7590. if (programDepth === 3 && parent.type === 'ExpressionStatement') {
  7591. // skip special handling for [module.]exports until we know we render this
  7592. skippedNodes.add(node.arguments[0]);
  7593. topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType });
  7594. } else {
  7595. shouldWrap = true;
  7596. }
  7597. return;
  7598. }
  7599. // Transform require.resolve
  7600. if (
  7601. isDynamicRequireModulesEnabled &&
  7602. node.callee.object &&
  7603. isRequire(node.callee.object, scope) &&
  7604. node.callee.property.name === 'resolve'
  7605. ) {
  7606. checkDynamicRequire(node.start);
  7607. uses.require = true;
  7608. const requireNode = node.callee.object;
  7609. replacedDynamicRequires.push(requireNode);
  7610. skippedNodes.add(node.callee);
  7611. return;
  7612. }
  7613. if (!isRequireExpression(node, scope)) {
  7614. const keypath = getKeypath(node.callee);
  7615. if (keypath && importedVariables.has(keypath.name)) {
  7616. // Heuristic to deoptimize requires after a required function has been called
  7617. currentConditionalNodeEnd = Infinity;
  7618. }
  7619. return;
  7620. }
  7621. skippedNodes.add(node.callee);
  7622. uses.require = true;
  7623. if (hasDynamicArguments(node)) {
  7624. if (isDynamicRequireModulesEnabled) {
  7625. checkDynamicRequire(node.start);
  7626. }
  7627. if (!ignoreDynamicRequires) {
  7628. replacedDynamicRequires.push(node.callee);
  7629. }
  7630. return;
  7631. }
  7632. const requireStringArg = getRequireStringArg(node);
  7633. if (!ignoreRequire(requireStringArg)) {
  7634. const usesReturnValue = parent.type !== 'ExpressionStatement';
  7635. const toBeRemoved =
  7636. parent.type === 'ExpressionStatement' &&
  7637. (!currentConditionalNodeEnd ||
  7638. // We should completely remove requires directly in a try-catch
  7639. // so that Rollup can remove up the try-catch
  7640. (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd))
  7641. ? parent
  7642. : node;
  7643. addRequireExpression(
  7644. requireStringArg,
  7645. node,
  7646. scope,
  7647. usesReturnValue,
  7648. currentTryBlockEnd !== null,
  7649. currentConditionalNodeEnd !== null,
  7650. toBeRemoved
  7651. );
  7652. if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
  7653. for (const name of extractAssignedNames(parent.id)) {
  7654. importedVariables.add(name);
  7655. }
  7656. }
  7657. }
  7658. return;
  7659. }
  7660. case 'ClassBody':
  7661. classBodyDepth += 1;
  7662. return;
  7663. case 'ConditionalExpression':
  7664. case 'IfStatement':
  7665. // skip dead branches
  7666. if (isFalsy(node.test)) {
  7667. skippedNodes.add(node.consequent);
  7668. } else if (isTruthy(node.test)) {
  7669. if (node.alternate) {
  7670. skippedNodes.add(node.alternate);
  7671. }
  7672. } else {
  7673. conditionalNodes.add(node.consequent);
  7674. if (node.alternate) {
  7675. conditionalNodes.add(node.alternate);
  7676. }
  7677. }
  7678. return;
  7679. case 'ArrowFunctionExpression':
  7680. case 'FunctionDeclaration':
  7681. case 'FunctionExpression':
  7682. // requires in functions should be conditional unless it is an IIFE
  7683. if (
  7684. currentConditionalNodeEnd === null &&
  7685. !(parent.type === 'CallExpression' && parent.callee === node)
  7686. ) {
  7687. currentConditionalNodeEnd = node.end;
  7688. }
  7689. return;
  7690. case 'Identifier': {
  7691. const { name } = node;
  7692. if (!isReference(node, parent) || scope.contains(name)) return;
  7693. switch (name) {
  7694. case 'require':
  7695. uses.require = true;
  7696. if (isNodeRequirePropertyAccess(parent)) {
  7697. return;
  7698. }
  7699. if (!ignoreDynamicRequires) {
  7700. if (isShorthandProperty(parent)) {
  7701. magicString.prependRight(node.start, 'require: ');
  7702. }
  7703. replacedDynamicRequires.push(node);
  7704. }
  7705. return;
  7706. case 'module':
  7707. case 'exports':
  7708. shouldWrap = true;
  7709. uses[name] = true;
  7710. return;
  7711. case 'global':
  7712. uses.global = true;
  7713. if (!ignoreGlobal) {
  7714. replacedGlobal.push(node);
  7715. }
  7716. return;
  7717. case 'define':
  7718. magicString.overwrite(node.start, node.end, 'undefined', {
  7719. storeName: true
  7720. });
  7721. return;
  7722. default:
  7723. globals.add(name);
  7724. return;
  7725. }
  7726. }
  7727. case 'LogicalExpression':
  7728. // skip dead branches
  7729. if (node.operator === '&&') {
  7730. if (isFalsy(node.left)) {
  7731. skippedNodes.add(node.right);
  7732. } else if (!isTruthy(node.left)) {
  7733. conditionalNodes.add(node.right);
  7734. }
  7735. } else if (node.operator === '||') {
  7736. if (isTruthy(node.left)) {
  7737. skippedNodes.add(node.right);
  7738. } else if (!isFalsy(node.left)) {
  7739. conditionalNodes.add(node.right);
  7740. }
  7741. }
  7742. return;
  7743. case 'MemberExpression':
  7744. if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
  7745. uses.require = true;
  7746. replacedDynamicRequires.push(node);
  7747. skippedNodes.add(node.object);
  7748. skippedNodes.add(node.property);
  7749. }
  7750. return;
  7751. case 'ReturnStatement':
  7752. // if top-level return, we need to wrap it
  7753. if (lexicalDepth === 0) {
  7754. shouldWrap = true;
  7755. }
  7756. return;
  7757. case 'ThisExpression':
  7758. // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
  7759. if (lexicalDepth === 0 && !classBodyDepth) {
  7760. uses.global = true;
  7761. if (!ignoreGlobal) {
  7762. replacedGlobal.push(node);
  7763. }
  7764. }
  7765. return;
  7766. case 'TryStatement':
  7767. if (currentTryBlockEnd === null) {
  7768. currentTryBlockEnd = node.block.end;
  7769. }
  7770. if (currentConditionalNodeEnd === null) {
  7771. currentConditionalNodeEnd = node.end;
  7772. }
  7773. return;
  7774. case 'UnaryExpression':
  7775. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  7776. if (node.operator === 'typeof') {
  7777. const flattened = getKeypath(node.argument);
  7778. if (!flattened) return;
  7779. if (scope.contains(flattened.name)) return;
  7780. if (
  7781. !isEsModule &&
  7782. (flattened.keypath === 'module.exports' ||
  7783. flattened.keypath === 'module' ||
  7784. flattened.keypath === 'exports')
  7785. ) {
  7786. magicString.overwrite(node.start, node.end, `'object'`, {
  7787. storeName: false
  7788. });
  7789. }
  7790. }
  7791. return;
  7792. case 'VariableDeclaration':
  7793. if (!scope.parent) {
  7794. topLevelDeclarations.push(node);
  7795. }
  7796. return;
  7797. case 'TemplateElement':
  7798. if (node.value.raw.includes('\n')) {
  7799. indentExclusionRanges.push([node.start, node.end]);
  7800. }
  7801. }
  7802. },
  7803. leave(node) {
  7804. programDepth -= 1;
  7805. if (node.scope) scope = scope.parent;
  7806. if (functionType.test(node.type)) lexicalDepth -= 1;
  7807. if (node.type === 'ClassBody') classBodyDepth -= 1;
  7808. }
  7809. });
  7810. const nameBase = getName(id);
  7811. const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  7812. const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  7813. const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
  7814. const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
  7815. const helpersName = deconflict([scope], globals, 'commonjsHelpers');
  7816. const dynamicRequireName =
  7817. replacedDynamicRequires.length > 0 &&
  7818. deconflict(
  7819. [scope],
  7820. globals,
  7821. isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  7822. );
  7823. const deconflictedExportNames = Object.create(null);
  7824. for (const [exportName, { scopes }] of exportsAssignmentsByName) {
  7825. deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  7826. }
  7827. for (const node of replacedGlobal) {
  7828. magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, {
  7829. storeName: true
  7830. });
  7831. }
  7832. for (const node of replacedDynamicRequires) {
  7833. magicString.overwrite(
  7834. node.start,
  7835. node.end,
  7836. isDynamicRequireModulesEnabled
  7837. ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})`
  7838. : dynamicRequireName,
  7839. {
  7840. contentOnly: true,
  7841. storeName: true
  7842. }
  7843. );
  7844. }
  7845. // We cannot wrap ES/mixed modules
  7846. shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
  7847. if (
  7848. !(
  7849. shouldWrap ||
  7850. isRequired ||
  7851. needsRequireWrapper ||
  7852. uses.module ||
  7853. uses.exports ||
  7854. uses.require ||
  7855. topLevelDefineCompiledEsmExpressions.length > 0
  7856. ) &&
  7857. (ignoreGlobal || !uses.global)
  7858. ) {
  7859. return { meta: { commonjs: { isCommonJS: false } } };
  7860. }
  7861. let leadingComment = '';
  7862. if (code.startsWith('/*')) {
  7863. const commentEnd = code.indexOf('*/', 2) + 2;
  7864. leadingComment = `${code.slice(0, commentEnd)}\n`;
  7865. magicString.remove(0, commentEnd).trim();
  7866. }
  7867. const exportMode = isEsModule
  7868. ? 'none'
  7869. : shouldWrap
  7870. ? uses.module
  7871. ? 'module'
  7872. : 'exports'
  7873. : firstTopLevelModuleExportsAssignment
  7874. ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
  7875. ? 'replace'
  7876. : 'module'
  7877. : moduleExportsAssignments.length === 0
  7878. ? 'exports'
  7879. : 'module';
  7880. const exportedExportsName =
  7881. exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
  7882. const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
  7883. magicString,
  7884. topLevelDeclarations,
  7885. reassignedNames,
  7886. helpersName,
  7887. dynamicRequireName,
  7888. moduleName,
  7889. exportsName,
  7890. id,
  7891. exportMode,
  7892. resolveRequireSourcesAndUpdateMeta,
  7893. needsRequireWrapper,
  7894. isEsModule,
  7895. isDynamicRequireModulesEnabled,
  7896. getIgnoreTryCatchRequireStatementMode,
  7897. commonjsMeta
  7898. );
  7899. const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
  7900. const exportBlock = isEsModule
  7901. ? ''
  7902. : rewriteExportsAndGetExportsBlock(
  7903. magicString,
  7904. moduleName,
  7905. exportsName,
  7906. exportedExportsName,
  7907. shouldWrap,
  7908. moduleExportsAssignments,
  7909. firstTopLevelModuleExportsAssignment,
  7910. exportsAssignmentsByName,
  7911. topLevelAssignments,
  7912. topLevelDefineCompiledEsmExpressions,
  7913. deconflictedExportNames,
  7914. code,
  7915. helpersName,
  7916. exportMode,
  7917. defaultIsModuleExports,
  7918. usesRequireWrapper,
  7919. requireName
  7920. );
  7921. if (shouldWrap) {
  7922. wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
  7923. }
  7924. if (usesRequireWrapper) {
  7925. magicString.trim().indent('\t', {
  7926. exclude: indentExclusionRanges
  7927. });
  7928. const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName;
  7929. magicString.prepend(
  7930. `var ${isRequiredName};
  7931. function ${requireName} () {
  7932. \tif (${isRequiredName}) return ${exported};
  7933. \t${isRequiredName} = 1;
  7934. `
  7935. ).append(`
  7936. \treturn ${exported};
  7937. }`);
  7938. if (exportMode === 'replace') {
  7939. magicString.prepend(`var ${exportsName};\n`);
  7940. }
  7941. }
  7942. magicString
  7943. .trim()
  7944. .prepend(leadingComment + importBlock)
  7945. .append(exportBlock);
  7946. return {
  7947. code: magicString.toString(),
  7948. map: sourceMap ? magicString.generateMap() : null,
  7949. syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports',
  7950. meta: { commonjs: commonjsMeta }
  7951. };
  7952. }
  7953. const PLUGIN_NAME = 'commonjs';
  7954. function commonjs(options = {}) {
  7955. const {
  7956. ignoreGlobal,
  7957. ignoreDynamicRequires,
  7958. requireReturnsDefault: requireReturnsDefaultOption,
  7959. defaultIsModuleExports: defaultIsModuleExportsOption,
  7960. esmExternals
  7961. } = options;
  7962. const extensions = options.extensions || ['.js'];
  7963. const filter = createFilter$1(options.include, options.exclude);
  7964. const isPossibleCjsId = (id) => {
  7965. const extName = extname(id);
  7966. return extName === '.cjs' || (extensions.includes(extName) && filter(id));
  7967. };
  7968. const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options);
  7969. const getRequireReturnsDefault =
  7970. typeof requireReturnsDefaultOption === 'function'
  7971. ? requireReturnsDefaultOption
  7972. : () => requireReturnsDefaultOption;
  7973. let esmExternalIds;
  7974. const isEsmExternal =
  7975. typeof esmExternals === 'function'
  7976. ? esmExternals
  7977. : Array.isArray(esmExternals)
  7978. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  7979. : () => esmExternals;
  7980. const getDefaultIsModuleExports =
  7981. typeof defaultIsModuleExportsOption === 'function'
  7982. ? defaultIsModuleExportsOption
  7983. : () =>
  7984. typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
  7985. const dynamicRequireRoot =
  7986. typeof options.dynamicRequireRoot === 'string'
  7987. ? resolve$3(options.dynamicRequireRoot)
  7988. : process.cwd();
  7989. const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
  7990. options.dynamicRequireTargets,
  7991. dynamicRequireRoot
  7992. );
  7993. const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
  7994. const ignoreRequire =
  7995. typeof options.ignore === 'function'
  7996. ? options.ignore
  7997. : Array.isArray(options.ignore)
  7998. ? (id) => options.ignore.includes(id)
  7999. : () => false;
  8000. const getIgnoreTryCatchRequireStatementMode = (id) => {
  8001. const mode =
  8002. typeof options.ignoreTryCatch === 'function'
  8003. ? options.ignoreTryCatch(id)
  8004. : Array.isArray(options.ignoreTryCatch)
  8005. ? options.ignoreTryCatch.includes(id)
  8006. : typeof options.ignoreTryCatch !== 'undefined'
  8007. ? options.ignoreTryCatch
  8008. : true;
  8009. return {
  8010. canConvertRequire: mode !== 'remove' && mode !== true,
  8011. shouldRemoveRequire: mode === 'remove'
  8012. };
  8013. };
  8014. const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId);
  8015. const sourceMap = options.sourceMap !== false;
  8016. // Initialized in buildStart
  8017. let requireResolver;
  8018. function transformAndCheckExports(code, id) {
  8019. const normalizedId = normalizePathSlashes(id);
  8020. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
  8021. this.parse,
  8022. code,
  8023. id
  8024. );
  8025. const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
  8026. if (hasDefaultExport) {
  8027. commonjsMeta.hasDefaultExport = true;
  8028. }
  8029. if (hasNamedExports) {
  8030. commonjsMeta.hasNamedExports = true;
  8031. }
  8032. if (
  8033. !dynamicRequireModules.has(normalizedId) &&
  8034. (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) ||
  8035. (isEsModule && !options.transformMixedEsModules))
  8036. ) {
  8037. commonjsMeta.isCommonJS = false;
  8038. return { meta: { commonjs: commonjsMeta } };
  8039. }
  8040. const needsRequireWrapper =
  8041. !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
  8042. const checkDynamicRequire = (position) => {
  8043. const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
  8044. if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) {
  8045. this.error(
  8046. {
  8047. code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT',
  8048. normalizedId,
  8049. normalizedDynamicRequireRoot,
  8050. message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1(
  8051. normalizedId
  8052. )}" or one of its parent directories.`
  8053. },
  8054. position
  8055. );
  8056. }
  8057. };
  8058. return transformCommonjs(
  8059. this.parse,
  8060. code,
  8061. id,
  8062. isEsModule,
  8063. ignoreGlobal || isEsModule,
  8064. ignoreRequire,
  8065. ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
  8066. getIgnoreTryCatchRequireStatementMode,
  8067. sourceMap,
  8068. isDynamicRequireModulesEnabled,
  8069. dynamicRequireModules,
  8070. commonDir,
  8071. ast,
  8072. getDefaultIsModuleExports(id),
  8073. needsRequireWrapper,
  8074. requireResolver.resolveRequireSourcesAndUpdateMeta(this),
  8075. requireResolver.isRequiredId(id),
  8076. checkDynamicRequire,
  8077. commonjsMeta
  8078. );
  8079. }
  8080. return {
  8081. name: PLUGIN_NAME,
  8082. version: version$3,
  8083. options(rawOptions) {
  8084. // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver
  8085. // do not prevent our plugin from resolving entry points ot proxies.
  8086. const plugins = Array.isArray(rawOptions.plugins)
  8087. ? [...rawOptions.plugins]
  8088. : rawOptions.plugins
  8089. ? [rawOptions.plugins]
  8090. : [];
  8091. plugins.unshift({
  8092. name: 'commonjs--resolver',
  8093. resolveId
  8094. });
  8095. return { ...rawOptions, plugins };
  8096. },
  8097. buildStart({ plugins }) {
  8098. validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup');
  8099. const nodeResolve = plugins.find(({ name }) => name === 'node-resolve');
  8100. if (nodeResolve) {
  8101. validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve');
  8102. }
  8103. if (options.namedExports != null) {
  8104. this.warn(
  8105. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  8106. );
  8107. }
  8108. requireResolver = getRequireResolver(
  8109. extensions,
  8110. detectCyclesAndConditional,
  8111. currentlyResolving
  8112. );
  8113. },
  8114. buildEnd() {
  8115. if (options.strictRequires === 'debug') {
  8116. const wrappedIds = requireResolver.getWrappedIds();
  8117. if (wrappedIds.length) {
  8118. this.warn({
  8119. code: 'WRAPPED_IDS',
  8120. ids: wrappedIds,
  8121. message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds
  8122. .map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`)
  8123. .join(',\n')}\n]`
  8124. });
  8125. } else {
  8126. this.warn({
  8127. code: 'WRAPPED_IDS',
  8128. ids: wrappedIds,
  8129. message: 'The commonjs plugin did not wrap any files.'
  8130. });
  8131. }
  8132. }
  8133. },
  8134. load(id) {
  8135. if (id === HELPERS_ID) {
  8136. return getHelpersModule();
  8137. }
  8138. if (isWrappedId(id, MODULE_SUFFIX)) {
  8139. const name = getName(unwrapId$1(id, MODULE_SUFFIX));
  8140. return {
  8141. code: `var ${name} = {exports: {}}; export {${name} as __module}`,
  8142. meta: { commonjs: { isCommonJS: false } }
  8143. };
  8144. }
  8145. if (isWrappedId(id, EXPORTS_SUFFIX)) {
  8146. const name = getName(unwrapId$1(id, EXPORTS_SUFFIX));
  8147. return {
  8148. code: `var ${name} = {}; export {${name} as __exports}`,
  8149. meta: { commonjs: { isCommonJS: false } }
  8150. };
  8151. }
  8152. if (isWrappedId(id, EXTERNAL_SUFFIX)) {
  8153. const actualId = unwrapId$1(id, EXTERNAL_SUFFIX);
  8154. return getUnknownRequireProxy(
  8155. actualId,
  8156. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  8157. );
  8158. }
  8159. // entry suffix is just appended to not mess up relative external resolution
  8160. if (id.endsWith(ENTRY_SUFFIX)) {
  8161. const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
  8162. return getEntryProxy(acutalId, getDefaultIsModuleExports(acutalId), this.getModuleInfo);
  8163. }
  8164. if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
  8165. const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX);
  8166. return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
  8167. }
  8168. if (id === DYNAMIC_MODULES_ID) {
  8169. return getDynamicModuleRegistry(
  8170. isDynamicRequireModulesEnabled,
  8171. dynamicRequireModules,
  8172. commonDir,
  8173. ignoreDynamicRequires
  8174. );
  8175. }
  8176. if (isWrappedId(id, PROXY_SUFFIX)) {
  8177. const actualId = unwrapId$1(id, PROXY_SUFFIX);
  8178. return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
  8179. }
  8180. return null;
  8181. },
  8182. shouldTransformCachedModule(...args) {
  8183. return requireResolver.shouldTransformCachedModule.call(this, ...args);
  8184. },
  8185. transform(code, id) {
  8186. if (!isPossibleCjsId(id)) return null;
  8187. try {
  8188. return transformAndCheckExports.call(this, code, id);
  8189. } catch (err) {
  8190. return this.error(err, err.loc);
  8191. }
  8192. }
  8193. };
  8194. }
  8195. const comma = ','.charCodeAt(0);
  8196. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  8197. const intToChar = new Uint8Array(64); // 64 possible chars.
  8198. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  8199. for (let i = 0; i < chars$1.length; i++) {
  8200. const c = chars$1.charCodeAt(i);
  8201. intToChar[i] = c;
  8202. charToInt[c] = i;
  8203. }
  8204. function decode(mappings) {
  8205. const state = new Int32Array(5);
  8206. const decoded = [];
  8207. let index = 0;
  8208. do {
  8209. const semi = indexOf(mappings, index);
  8210. const line = [];
  8211. let sorted = true;
  8212. let lastCol = 0;
  8213. state[0] = 0;
  8214. for (let i = index; i < semi; i++) {
  8215. let seg;
  8216. i = decodeInteger(mappings, i, state, 0); // genColumn
  8217. const col = state[0];
  8218. if (col < lastCol)
  8219. sorted = false;
  8220. lastCol = col;
  8221. if (hasMoreVlq(mappings, i, semi)) {
  8222. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  8223. i = decodeInteger(mappings, i, state, 2); // sourceLine
  8224. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  8225. if (hasMoreVlq(mappings, i, semi)) {
  8226. i = decodeInteger(mappings, i, state, 4); // namesIndex
  8227. seg = [col, state[1], state[2], state[3], state[4]];
  8228. }
  8229. else {
  8230. seg = [col, state[1], state[2], state[3]];
  8231. }
  8232. }
  8233. else {
  8234. seg = [col];
  8235. }
  8236. line.push(seg);
  8237. }
  8238. if (!sorted)
  8239. sort(line);
  8240. decoded.push(line);
  8241. index = semi + 1;
  8242. } while (index <= mappings.length);
  8243. return decoded;
  8244. }
  8245. function indexOf(mappings, index) {
  8246. const idx = mappings.indexOf(';', index);
  8247. return idx === -1 ? mappings.length : idx;
  8248. }
  8249. function decodeInteger(mappings, pos, state, j) {
  8250. let value = 0;
  8251. let shift = 0;
  8252. let integer = 0;
  8253. do {
  8254. const c = mappings.charCodeAt(pos++);
  8255. integer = charToInt[c];
  8256. value |= (integer & 31) << shift;
  8257. shift += 5;
  8258. } while (integer & 32);
  8259. const shouldNegate = value & 1;
  8260. value >>>= 1;
  8261. if (shouldNegate) {
  8262. value = -0x80000000 | -value;
  8263. }
  8264. state[j] += value;
  8265. return pos;
  8266. }
  8267. function hasMoreVlq(mappings, i, length) {
  8268. if (i >= length)
  8269. return false;
  8270. return mappings.charCodeAt(i) !== comma;
  8271. }
  8272. function sort(line) {
  8273. line.sort(sortComparator$1);
  8274. }
  8275. function sortComparator$1(a, b) {
  8276. return a[0] - b[0];
  8277. }
  8278. // Matches the scheme of a URL, eg "http://"
  8279. const schemeRegex = /^[\w+.-]+:\/\//;
  8280. /**
  8281. * Matches the parts of a URL:
  8282. * 1. Scheme, including ":", guaranteed.
  8283. * 2. User/password, including "@", optional.
  8284. * 3. Host, guaranteed.
  8285. * 4. Port, including ":", optional.
  8286. * 5. Path, including "/", optional.
  8287. * 6. Query, including "?", optional.
  8288. * 7. Hash, including "#", optional.
  8289. */
  8290. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  8291. /**
  8292. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  8293. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  8294. *
  8295. * 1. Host, optional.
  8296. * 2. Path, which may include "/", guaranteed.
  8297. * 3. Query, including "?", optional.
  8298. * 4. Hash, including "#", optional.
  8299. */
  8300. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  8301. var UrlType;
  8302. (function (UrlType) {
  8303. UrlType[UrlType["Empty"] = 1] = "Empty";
  8304. UrlType[UrlType["Hash"] = 2] = "Hash";
  8305. UrlType[UrlType["Query"] = 3] = "Query";
  8306. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  8307. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  8308. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  8309. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  8310. })(UrlType || (UrlType = {}));
  8311. function isAbsoluteUrl(input) {
  8312. return schemeRegex.test(input);
  8313. }
  8314. function isSchemeRelativeUrl(input) {
  8315. return input.startsWith('//');
  8316. }
  8317. function isAbsolutePath(input) {
  8318. return input.startsWith('/');
  8319. }
  8320. function isFileUrl(input) {
  8321. return input.startsWith('file:');
  8322. }
  8323. function isRelative(input) {
  8324. return /^[.?#]/.test(input);
  8325. }
  8326. function parseAbsoluteUrl(input) {
  8327. const match = urlRegex.exec(input);
  8328. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  8329. }
  8330. function parseFileUrl(input) {
  8331. const match = fileRegex.exec(input);
  8332. const path = match[2];
  8333. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  8334. }
  8335. function makeUrl(scheme, user, host, port, path, query, hash) {
  8336. return {
  8337. scheme,
  8338. user,
  8339. host,
  8340. port,
  8341. path,
  8342. query,
  8343. hash,
  8344. type: UrlType.Absolute,
  8345. };
  8346. }
  8347. function parseUrl$2(input) {
  8348. if (isSchemeRelativeUrl(input)) {
  8349. const url = parseAbsoluteUrl('http:' + input);
  8350. url.scheme = '';
  8351. url.type = UrlType.SchemeRelative;
  8352. return url;
  8353. }
  8354. if (isAbsolutePath(input)) {
  8355. const url = parseAbsoluteUrl('http://foo.com' + input);
  8356. url.scheme = '';
  8357. url.host = '';
  8358. url.type = UrlType.AbsolutePath;
  8359. return url;
  8360. }
  8361. if (isFileUrl(input))
  8362. return parseFileUrl(input);
  8363. if (isAbsoluteUrl(input))
  8364. return parseAbsoluteUrl(input);
  8365. const url = parseAbsoluteUrl('http://foo.com/' + input);
  8366. url.scheme = '';
  8367. url.host = '';
  8368. url.type = input
  8369. ? input.startsWith('?')
  8370. ? UrlType.Query
  8371. : input.startsWith('#')
  8372. ? UrlType.Hash
  8373. : UrlType.RelativePath
  8374. : UrlType.Empty;
  8375. return url;
  8376. }
  8377. function stripPathFilename(path) {
  8378. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  8379. // paths. It's not a file, so we can't strip it.
  8380. if (path.endsWith('/..'))
  8381. return path;
  8382. const index = path.lastIndexOf('/');
  8383. return path.slice(0, index + 1);
  8384. }
  8385. function mergePaths(url, base) {
  8386. normalizePath$4(base, base.type);
  8387. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  8388. // path).
  8389. if (url.path === '/') {
  8390. url.path = base.path;
  8391. }
  8392. else {
  8393. // Resolution happens relative to the base path's directory, not the file.
  8394. url.path = stripPathFilename(base.path) + url.path;
  8395. }
  8396. }
  8397. /**
  8398. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  8399. * "foo/.". We need to normalize to a standard representation.
  8400. */
  8401. function normalizePath$4(url, type) {
  8402. const rel = type <= UrlType.RelativePath;
  8403. const pieces = url.path.split('/');
  8404. // We need to preserve the first piece always, so that we output a leading slash. The item at
  8405. // pieces[0] is an empty string.
  8406. let pointer = 1;
  8407. // Positive is the number of real directories we've output, used for popping a parent directory.
  8408. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  8409. let positive = 0;
  8410. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  8411. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  8412. // real directory, we won't need to append, unless the other conditions happen again.
  8413. let addTrailingSlash = false;
  8414. for (let i = 1; i < pieces.length; i++) {
  8415. const piece = pieces[i];
  8416. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  8417. if (!piece) {
  8418. addTrailingSlash = true;
  8419. continue;
  8420. }
  8421. // If we encounter a real directory, then we don't need to append anymore.
  8422. addTrailingSlash = false;
  8423. // A current directory, which we can always drop.
  8424. if (piece === '.')
  8425. continue;
  8426. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  8427. // have an excess of parents, and we'll need to keep the "..".
  8428. if (piece === '..') {
  8429. if (positive) {
  8430. addTrailingSlash = true;
  8431. positive--;
  8432. pointer--;
  8433. }
  8434. else if (rel) {
  8435. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  8436. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  8437. pieces[pointer++] = piece;
  8438. }
  8439. continue;
  8440. }
  8441. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  8442. // any popped or dropped directories.
  8443. pieces[pointer++] = piece;
  8444. positive++;
  8445. }
  8446. let path = '';
  8447. for (let i = 1; i < pointer; i++) {
  8448. path += '/' + pieces[i];
  8449. }
  8450. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  8451. path += '/';
  8452. }
  8453. url.path = path;
  8454. }
  8455. /**
  8456. * Attempts to resolve `input` URL/path relative to `base`.
  8457. */
  8458. function resolve$2(input, base) {
  8459. if (!input && !base)
  8460. return '';
  8461. const url = parseUrl$2(input);
  8462. let inputType = url.type;
  8463. if (base && inputType !== UrlType.Absolute) {
  8464. const baseUrl = parseUrl$2(base);
  8465. const baseType = baseUrl.type;
  8466. switch (inputType) {
  8467. case UrlType.Empty:
  8468. url.hash = baseUrl.hash;
  8469. // fall through
  8470. case UrlType.Hash:
  8471. url.query = baseUrl.query;
  8472. // fall through
  8473. case UrlType.Query:
  8474. case UrlType.RelativePath:
  8475. mergePaths(url, baseUrl);
  8476. // fall through
  8477. case UrlType.AbsolutePath:
  8478. // The host, user, and port are joined, you can't copy one without the others.
  8479. url.user = baseUrl.user;
  8480. url.host = baseUrl.host;
  8481. url.port = baseUrl.port;
  8482. // fall through
  8483. case UrlType.SchemeRelative:
  8484. // The input doesn't have a schema at least, so we need to copy at least that over.
  8485. url.scheme = baseUrl.scheme;
  8486. }
  8487. if (baseType > inputType)
  8488. inputType = baseType;
  8489. }
  8490. normalizePath$4(url, inputType);
  8491. const queryHash = url.query + url.hash;
  8492. switch (inputType) {
  8493. // This is impossible, because of the empty checks at the start of the function.
  8494. // case UrlType.Empty:
  8495. case UrlType.Hash:
  8496. case UrlType.Query:
  8497. return queryHash;
  8498. case UrlType.RelativePath: {
  8499. // The first char is always a "/", and we need it to be relative.
  8500. const path = url.path.slice(1);
  8501. if (!path)
  8502. return queryHash || '.';
  8503. if (isRelative(base || input) && !isRelative(path)) {
  8504. // If base started with a leading ".", or there is no base and input started with a ".",
  8505. // then we need to ensure that the relative path starts with a ".". We don't know if
  8506. // relative starts with a "..", though, so check before prepending.
  8507. return './' + path + queryHash;
  8508. }
  8509. return path + queryHash;
  8510. }
  8511. case UrlType.AbsolutePath:
  8512. return url.path + queryHash;
  8513. default:
  8514. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  8515. }
  8516. }
  8517. function resolve$1(input, base) {
  8518. // The base is always treated as a directory, if it's not empty.
  8519. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  8520. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  8521. if (base && !base.endsWith('/'))
  8522. base += '/';
  8523. return resolve$2(input, base);
  8524. }
  8525. /**
  8526. * Removes everything after the last "/", but leaves the slash.
  8527. */
  8528. function stripFilename(path) {
  8529. if (!path)
  8530. return '';
  8531. const index = path.lastIndexOf('/');
  8532. return path.slice(0, index + 1);
  8533. }
  8534. const COLUMN$1 = 0;
  8535. const SOURCES_INDEX$1 = 1;
  8536. const SOURCE_LINE$1 = 2;
  8537. const SOURCE_COLUMN$1 = 3;
  8538. const NAMES_INDEX$1 = 4;
  8539. function maybeSort(mappings, owned) {
  8540. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  8541. if (unsortedIndex === mappings.length)
  8542. return mappings;
  8543. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  8544. // not, we do not want to modify the consumer's input array.
  8545. if (!owned)
  8546. mappings = mappings.slice();
  8547. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  8548. mappings[i] = sortSegments(mappings[i], owned);
  8549. }
  8550. return mappings;
  8551. }
  8552. function nextUnsortedSegmentLine(mappings, start) {
  8553. for (let i = start; i < mappings.length; i++) {
  8554. if (!isSorted(mappings[i]))
  8555. return i;
  8556. }
  8557. return mappings.length;
  8558. }
  8559. function isSorted(line) {
  8560. for (let j = 1; j < line.length; j++) {
  8561. if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
  8562. return false;
  8563. }
  8564. }
  8565. return true;
  8566. }
  8567. function sortSegments(line, owned) {
  8568. if (!owned)
  8569. line = line.slice();
  8570. return line.sort(sortComparator);
  8571. }
  8572. function sortComparator(a, b) {
  8573. return a[COLUMN$1] - b[COLUMN$1];
  8574. }
  8575. let found = false;
  8576. /**
  8577. * A binary search implementation that returns the index if a match is found.
  8578. * If no match is found, then the left-index (the index associated with the item that comes just
  8579. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  8580. * the next index:
  8581. *
  8582. * ```js
  8583. * const array = [1, 3];
  8584. * const needle = 2;
  8585. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  8586. *
  8587. * assert.equal(index, 0);
  8588. * array.splice(index + 1, 0, needle);
  8589. * assert.deepEqual(array, [1, 2, 3]);
  8590. * ```
  8591. */
  8592. function binarySearch(haystack, needle, low, high) {
  8593. while (low <= high) {
  8594. const mid = low + ((high - low) >> 1);
  8595. const cmp = haystack[mid][COLUMN$1] - needle;
  8596. if (cmp === 0) {
  8597. found = true;
  8598. return mid;
  8599. }
  8600. if (cmp < 0) {
  8601. low = mid + 1;
  8602. }
  8603. else {
  8604. high = mid - 1;
  8605. }
  8606. }
  8607. found = false;
  8608. return low - 1;
  8609. }
  8610. function upperBound(haystack, needle, index) {
  8611. for (let i = index + 1; i < haystack.length; index = i++) {
  8612. if (haystack[i][COLUMN$1] !== needle)
  8613. break;
  8614. }
  8615. return index;
  8616. }
  8617. function lowerBound(haystack, needle, index) {
  8618. for (let i = index - 1; i >= 0; index = i--) {
  8619. if (haystack[i][COLUMN$1] !== needle)
  8620. break;
  8621. }
  8622. return index;
  8623. }
  8624. function memoizedState() {
  8625. return {
  8626. lastKey: -1,
  8627. lastNeedle: -1,
  8628. lastIndex: -1,
  8629. };
  8630. }
  8631. /**
  8632. * This overly complicated beast is just to record the last tested line/column and the resulting
  8633. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  8634. */
  8635. function memoizedBinarySearch(haystack, needle, state, key) {
  8636. const { lastKey, lastNeedle, lastIndex } = state;
  8637. let low = 0;
  8638. let high = haystack.length - 1;
  8639. if (key === lastKey) {
  8640. if (needle === lastNeedle) {
  8641. found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
  8642. return lastIndex;
  8643. }
  8644. if (needle >= lastNeedle) {
  8645. // lastIndex may be -1 if the previous needle was not found.
  8646. low = lastIndex === -1 ? 0 : lastIndex;
  8647. }
  8648. else {
  8649. high = lastIndex;
  8650. }
  8651. }
  8652. state.lastKey = key;
  8653. state.lastNeedle = needle;
  8654. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  8655. }
  8656. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  8657. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  8658. const LEAST_UPPER_BOUND = -1;
  8659. const GREATEST_LOWER_BOUND = 1;
  8660. /**
  8661. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  8662. */
  8663. let decodedMappings;
  8664. /**
  8665. * A low-level API to find the segment associated with a generated line/column (think, from a
  8666. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  8667. */
  8668. let traceSegment;
  8669. /**
  8670. * A higher-level API to find the source/line/column associated with a generated line/column
  8671. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  8672. * `source-map` library.
  8673. */
  8674. let originalPositionFor$1;
  8675. class TraceMap {
  8676. constructor(map, mapUrl) {
  8677. const isString = typeof map === 'string';
  8678. if (!isString && map._decodedMemo)
  8679. return map;
  8680. const parsed = (isString ? JSON.parse(map) : map);
  8681. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  8682. this.version = version;
  8683. this.file = file;
  8684. this.names = names;
  8685. this.sourceRoot = sourceRoot;
  8686. this.sources = sources;
  8687. this.sourcesContent = sourcesContent;
  8688. const from = resolve$1(sourceRoot || '', stripFilename(mapUrl));
  8689. this.resolvedSources = sources.map((s) => resolve$1(s || '', from));
  8690. const { mappings } = parsed;
  8691. if (typeof mappings === 'string') {
  8692. this._encoded = mappings;
  8693. this._decoded = undefined;
  8694. }
  8695. else {
  8696. this._encoded = undefined;
  8697. this._decoded = maybeSort(mappings, isString);
  8698. }
  8699. this._decodedMemo = memoizedState();
  8700. this._bySources = undefined;
  8701. this._bySourceMemos = undefined;
  8702. }
  8703. }
  8704. (() => {
  8705. decodedMappings = (map) => {
  8706. return (map._decoded || (map._decoded = decode(map._encoded)));
  8707. };
  8708. traceSegment = (map, line, column) => {
  8709. const decoded = decodedMappings(map);
  8710. // It's common for parent source maps to have pointers to lines that have no
  8711. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  8712. if (line >= decoded.length)
  8713. return null;
  8714. const segments = decoded[line];
  8715. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  8716. return index === -1 ? null : segments[index];
  8717. };
  8718. originalPositionFor$1 = (map, { line, column, bias }) => {
  8719. line--;
  8720. if (line < 0)
  8721. throw new Error(LINE_GTR_ZERO);
  8722. if (column < 0)
  8723. throw new Error(COL_GTR_EQ_ZERO);
  8724. const decoded = decodedMappings(map);
  8725. // It's common for parent source maps to have pointers to lines that have no
  8726. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  8727. if (line >= decoded.length)
  8728. return OMapping(null, null, null, null);
  8729. const segments = decoded[line];
  8730. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  8731. if (index === -1)
  8732. return OMapping(null, null, null, null);
  8733. const segment = segments[index];
  8734. if (segment.length === 1)
  8735. return OMapping(null, null, null, null);
  8736. const { names, resolvedSources } = map;
  8737. return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
  8738. };
  8739. })();
  8740. function OMapping(source, line, column, name) {
  8741. return { source, line, column, name };
  8742. }
  8743. function traceSegmentInternal(segments, memo, line, column, bias) {
  8744. let index = memoizedBinarySearch(segments, column, memo, line);
  8745. if (found) {
  8746. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  8747. }
  8748. else if (bias === LEAST_UPPER_BOUND)
  8749. index++;
  8750. if (index === -1 || index === segments.length)
  8751. return -1;
  8752. return index;
  8753. }
  8754. /**
  8755. * Gets the index associated with `key` in the backing array, if it is already present.
  8756. */
  8757. let get;
  8758. /**
  8759. * Puts `key` into the backing array, if it is not already present. Returns
  8760. * the index of the `key` in the backing array.
  8761. */
  8762. let put;
  8763. /**
  8764. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  8765. * index of the `key` in the backing array.
  8766. *
  8767. * This is designed to allow synchronizing a second array with the contents of the backing array,
  8768. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  8769. * and there are never duplicates.
  8770. */
  8771. class SetArray {
  8772. constructor() {
  8773. this._indexes = { __proto__: null };
  8774. this.array = [];
  8775. }
  8776. }
  8777. (() => {
  8778. get = (strarr, key) => strarr._indexes[key];
  8779. put = (strarr, key) => {
  8780. // The key may or may not be present. If it is present, it's a number.
  8781. const index = get(strarr, key);
  8782. if (index !== undefined)
  8783. return index;
  8784. const { array, _indexes: indexes } = strarr;
  8785. return (indexes[key] = array.push(key) - 1);
  8786. };
  8787. })();
  8788. const COLUMN = 0;
  8789. const SOURCES_INDEX = 1;
  8790. const SOURCE_LINE = 2;
  8791. const SOURCE_COLUMN = 3;
  8792. const NAMES_INDEX = 4;
  8793. const NO_NAME = -1;
  8794. /**
  8795. * Same as `addSegment`, but will only add the segment if it generates useful information in the
  8796. * resulting map. This only works correctly if segments are added **in order**, meaning you should
  8797. * not add a segment with a lower generated line/column than one that came before.
  8798. */
  8799. let maybeAddSegment;
  8800. /**
  8801. * Adds/removes the content of the source file to the source map.
  8802. */
  8803. let setSourceContent;
  8804. /**
  8805. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  8806. * a sourcemap, or to JSON.stringify.
  8807. */
  8808. let toDecodedMap;
  8809. /**
  8810. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  8811. * a sourcemap, or to JSON.stringify.
  8812. */
  8813. let toEncodedMap;
  8814. // This split declaration is only so that terser can elminiate the static initialization block.
  8815. let addSegmentInternal;
  8816. /**
  8817. * Provides the state to generate a sourcemap.
  8818. */
  8819. class GenMapping {
  8820. constructor({ file, sourceRoot } = {}) {
  8821. this._names = new SetArray();
  8822. this._sources = new SetArray();
  8823. this._sourcesContent = [];
  8824. this._mappings = [];
  8825. this.file = file;
  8826. this.sourceRoot = sourceRoot;
  8827. }
  8828. }
  8829. (() => {
  8830. maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  8831. return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
  8832. };
  8833. setSourceContent = (map, source, content) => {
  8834. const { _sources: sources, _sourcesContent: sourcesContent } = map;
  8835. sourcesContent[put(sources, source)] = content;
  8836. };
  8837. toDecodedMap = (map) => {
  8838. const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  8839. removeEmptyFinalLines(mappings);
  8840. return {
  8841. version: 3,
  8842. file: file || undefined,
  8843. names: names.array,
  8844. sourceRoot: sourceRoot || undefined,
  8845. sources: sources.array,
  8846. sourcesContent,
  8847. mappings,
  8848. };
  8849. };
  8850. toEncodedMap = (map) => {
  8851. const decoded = toDecodedMap(map);
  8852. return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) });
  8853. };
  8854. // Internal helpers
  8855. addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
  8856. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  8857. const line = getLine(mappings, genLine);
  8858. const index = getColumnIndex(line, genColumn);
  8859. if (!source) {
  8860. if (skipable && skipSourceless(line, index))
  8861. return;
  8862. return insert(line, index, [genColumn]);
  8863. }
  8864. const sourcesIndex = put(sources, source);
  8865. const namesIndex = name ? put(names, name) : NO_NAME;
  8866. if (sourcesIndex === sourcesContent.length)
  8867. sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null;
  8868. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  8869. return;
  8870. }
  8871. return insert(line, index, name
  8872. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
  8873. : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  8874. };
  8875. })();
  8876. function getLine(mappings, index) {
  8877. for (let i = mappings.length; i <= index; i++) {
  8878. mappings[i] = [];
  8879. }
  8880. return mappings[index];
  8881. }
  8882. function getColumnIndex(line, genColumn) {
  8883. let index = line.length;
  8884. for (let i = index - 1; i >= 0; index = i--) {
  8885. const current = line[i];
  8886. if (genColumn >= current[COLUMN])
  8887. break;
  8888. }
  8889. return index;
  8890. }
  8891. function insert(array, index, value) {
  8892. for (let i = array.length; i > index; i--) {
  8893. array[i] = array[i - 1];
  8894. }
  8895. array[index] = value;
  8896. }
  8897. function removeEmptyFinalLines(mappings) {
  8898. const { length } = mappings;
  8899. let len = length;
  8900. for (let i = len - 1; i >= 0; len = i, i--) {
  8901. if (mappings[i].length > 0)
  8902. break;
  8903. }
  8904. if (len < length)
  8905. mappings.length = len;
  8906. }
  8907. function skipSourceless(line, index) {
  8908. // The start of a line is already sourceless, so adding a sourceless segment to the beginning
  8909. // doesn't generate any useful information.
  8910. if (index === 0)
  8911. return true;
  8912. const prev = line[index - 1];
  8913. // If the previous segment is also sourceless, then adding another sourceless segment doesn't
  8914. // genrate any new information. Else, this segment will end the source/named segment and point to
  8915. // a sourceless position, which is useful.
  8916. return prev.length === 1;
  8917. }
  8918. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  8919. // A source/named segment at the start of a line gives position at that genColumn
  8920. if (index === 0)
  8921. return false;
  8922. const prev = line[index - 1];
  8923. // If the previous segment is sourceless, then we're transitioning to a source.
  8924. if (prev.length === 1)
  8925. return false;
  8926. // If the previous segment maps to the exact same source position, then this segment doesn't
  8927. // provide any new position information.
  8928. return (sourcesIndex === prev[SOURCES_INDEX] &&
  8929. sourceLine === prev[SOURCE_LINE] &&
  8930. sourceColumn === prev[SOURCE_COLUMN] &&
  8931. namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
  8932. }
  8933. const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);
  8934. const EMPTY_SOURCES = [];
  8935. function SegmentObject(source, line, column, name, content) {
  8936. return { source, line, column, name, content };
  8937. }
  8938. function Source(map, sources, source, content) {
  8939. return {
  8940. map,
  8941. sources,
  8942. source,
  8943. content,
  8944. };
  8945. }
  8946. /**
  8947. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  8948. * (which may themselves be SourceMapTrees).
  8949. */
  8950. function MapSource(map, sources) {
  8951. return Source(map, sources, '', null);
  8952. }
  8953. /**
  8954. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  8955. * segment tracing ends at the `OriginalSource`.
  8956. */
  8957. function OriginalSource(source, content) {
  8958. return Source(null, EMPTY_SOURCES, source, content);
  8959. }
  8960. /**
  8961. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  8962. * resolving each mapping in terms of the original source files.
  8963. */
  8964. function traceMappings(tree) {
  8965. // TODO: Eventually support sourceRoot, which has to be removed because the sources are already
  8966. // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
  8967. const gen = new GenMapping({ file: tree.map.file });
  8968. const { sources: rootSources, map } = tree;
  8969. const rootNames = map.names;
  8970. const rootMappings = decodedMappings(map);
  8971. for (let i = 0; i < rootMappings.length; i++) {
  8972. const segments = rootMappings[i];
  8973. for (let j = 0; j < segments.length; j++) {
  8974. const segment = segments[j];
  8975. const genCol = segment[0];
  8976. let traced = SOURCELESS_MAPPING;
  8977. // 1-length segments only move the current generated column, there's no source information
  8978. // to gather from it.
  8979. if (segment.length !== 1) {
  8980. const source = rootSources[segment[1]];
  8981. traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  8982. // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
  8983. // respective segment into an original source.
  8984. if (traced == null)
  8985. continue;
  8986. }
  8987. const { column, line, name, content, source } = traced;
  8988. maybeAddSegment(gen, i, genCol, source, line, column, name);
  8989. if (source && content != null)
  8990. setSourceContent(gen, source, content);
  8991. }
  8992. }
  8993. return gen;
  8994. }
  8995. /**
  8996. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  8997. * child SourceMapTrees, until we find the original source map.
  8998. */
  8999. function originalPositionFor(source, line, column, name) {
  9000. if (!source.map) {
  9001. return SegmentObject(source.source, line, column, name, source.content);
  9002. }
  9003. const segment = traceSegment(source.map, line, column);
  9004. // If we couldn't find a segment, then this doesn't exist in the sourcemap.
  9005. if (segment == null)
  9006. return null;
  9007. // 1-length segments only move the current generated column, there's no source information
  9008. // to gather from it.
  9009. if (segment.length === 1)
  9010. return SOURCELESS_MAPPING;
  9011. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  9012. }
  9013. function asArray(value) {
  9014. if (Array.isArray(value))
  9015. return value;
  9016. return [value];
  9017. }
  9018. /**
  9019. * Recursively builds a tree structure out of sourcemap files, with each node
  9020. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  9021. * `OriginalSource`s and `SourceMapTree`s.
  9022. *
  9023. * Every sourcemap is composed of a collection of source files and mappings
  9024. * into locations of those source files. When we generate a `SourceMapTree` for
  9025. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  9026. * does not have an associated sourcemap, it is considered an original,
  9027. * unmodified source file.
  9028. */
  9029. function buildSourceMapTree(input, loader) {
  9030. const maps = asArray(input).map((m) => new TraceMap(m, ''));
  9031. const map = maps.pop();
  9032. for (let i = 0; i < maps.length; i++) {
  9033. if (maps[i].sources.length > 1) {
  9034. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  9035. 'Did you specify these with the most recent transformation maps first?');
  9036. }
  9037. }
  9038. let tree = build$2(map, loader, '', 0);
  9039. for (let i = maps.length - 1; i >= 0; i--) {
  9040. tree = MapSource(maps[i], [tree]);
  9041. }
  9042. return tree;
  9043. }
  9044. function build$2(map, loader, importer, importerDepth) {
  9045. const { resolvedSources, sourcesContent } = map;
  9046. const depth = importerDepth + 1;
  9047. const children = resolvedSources.map((sourceFile, i) => {
  9048. // The loading context gives the loader more information about why this file is being loaded
  9049. // (eg, from which importer). It also allows the loader to override the location of the loaded
  9050. // sourcemap/original source, or to override the content in the sourcesContent field if it's
  9051. // an unmodified source file.
  9052. const ctx = {
  9053. importer,
  9054. depth,
  9055. source: sourceFile || '',
  9056. content: undefined,
  9057. };
  9058. // Use the provided loader callback to retrieve the file's sourcemap.
  9059. // TODO: We should eventually support async loading of sourcemap files.
  9060. const sourceMap = loader(ctx.source, ctx);
  9061. const { source, content } = ctx;
  9062. // If there is a sourcemap, then we need to recurse into it to load its source files.
  9063. if (sourceMap)
  9064. return build$2(new TraceMap(sourceMap, source), loader, source, depth);
  9065. // Else, it's an an unmodified source file.
  9066. // The contents of this unmodified source file can be overridden via the loader context,
  9067. // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
  9068. // the importing sourcemap's `sourcesContent` field.
  9069. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
  9070. return OriginalSource(source, sourceContent);
  9071. });
  9072. return MapSource(map, children);
  9073. }
  9074. /**
  9075. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  9076. * provided to it.
  9077. */
  9078. let SourceMap$1 = class SourceMap {
  9079. constructor(map, options) {
  9080. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  9081. this.version = out.version; // SourceMap spec says this should be first.
  9082. this.file = out.file;
  9083. this.mappings = out.mappings;
  9084. this.names = out.names;
  9085. this.sourceRoot = out.sourceRoot;
  9086. this.sources = out.sources;
  9087. if (!options.excludeContent) {
  9088. this.sourcesContent = out.sourcesContent;
  9089. }
  9090. }
  9091. toString() {
  9092. return JSON.stringify(this);
  9093. }
  9094. };
  9095. /**
  9096. * Traces through all the mappings in the root sourcemap, through the sources
  9097. * (and their sourcemaps), all the way back to the original source location.
  9098. *
  9099. * `loader` will be called every time we encounter a source file. If it returns
  9100. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  9101. * it returns a falsey value, that source file is treated as an original,
  9102. * unmodified source file.
  9103. *
  9104. * Pass `excludeContent` to exclude any self-containing source file content
  9105. * from the output sourcemap.
  9106. *
  9107. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  9108. * VLQ encoded) mappings.
  9109. */
  9110. function remapping(input, loader, options) {
  9111. const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
  9112. const tree = buildSourceMapTree(input, loader);
  9113. return new SourceMap$1(traceMappings(tree), opts);
  9114. }
  9115. var src$2 = {exports: {}};
  9116. var browser$3 = {exports: {}};
  9117. /**
  9118. * Helpers.
  9119. */
  9120. var ms$1;
  9121. var hasRequiredMs$1;
  9122. function requireMs$1 () {
  9123. if (hasRequiredMs$1) return ms$1;
  9124. hasRequiredMs$1 = 1;
  9125. var s = 1000;
  9126. var m = s * 60;
  9127. var h = m * 60;
  9128. var d = h * 24;
  9129. var w = d * 7;
  9130. var y = d * 365.25;
  9131. /**
  9132. * Parse or format the given `val`.
  9133. *
  9134. * Options:
  9135. *
  9136. * - `long` verbose formatting [false]
  9137. *
  9138. * @param {String|Number} val
  9139. * @param {Object} [options]
  9140. * @throws {Error} throw an error if val is not a non-empty string or a number
  9141. * @return {String|Number}
  9142. * @api public
  9143. */
  9144. ms$1 = function(val, options) {
  9145. options = options || {};
  9146. var type = typeof val;
  9147. if (type === 'string' && val.length > 0) {
  9148. return parse(val);
  9149. } else if (type === 'number' && isFinite(val)) {
  9150. return options.long ? fmtLong(val) : fmtShort(val);
  9151. }
  9152. throw new Error(
  9153. 'val is not a non-empty string or a valid number. val=' +
  9154. JSON.stringify(val)
  9155. );
  9156. };
  9157. /**
  9158. * Parse the given `str` and return milliseconds.
  9159. *
  9160. * @param {String} str
  9161. * @return {Number}
  9162. * @api private
  9163. */
  9164. function parse(str) {
  9165. str = String(str);
  9166. if (str.length > 100) {
  9167. return;
  9168. }
  9169. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  9170. str
  9171. );
  9172. if (!match) {
  9173. return;
  9174. }
  9175. var n = parseFloat(match[1]);
  9176. var type = (match[2] || 'ms').toLowerCase();
  9177. switch (type) {
  9178. case 'years':
  9179. case 'year':
  9180. case 'yrs':
  9181. case 'yr':
  9182. case 'y':
  9183. return n * y;
  9184. case 'weeks':
  9185. case 'week':
  9186. case 'w':
  9187. return n * w;
  9188. case 'days':
  9189. case 'day':
  9190. case 'd':
  9191. return n * d;
  9192. case 'hours':
  9193. case 'hour':
  9194. case 'hrs':
  9195. case 'hr':
  9196. case 'h':
  9197. return n * h;
  9198. case 'minutes':
  9199. case 'minute':
  9200. case 'mins':
  9201. case 'min':
  9202. case 'm':
  9203. return n * m;
  9204. case 'seconds':
  9205. case 'second':
  9206. case 'secs':
  9207. case 'sec':
  9208. case 's':
  9209. return n * s;
  9210. case 'milliseconds':
  9211. case 'millisecond':
  9212. case 'msecs':
  9213. case 'msec':
  9214. case 'ms':
  9215. return n;
  9216. default:
  9217. return undefined;
  9218. }
  9219. }
  9220. /**
  9221. * Short format for `ms`.
  9222. *
  9223. * @param {Number} ms
  9224. * @return {String}
  9225. * @api private
  9226. */
  9227. function fmtShort(ms) {
  9228. var msAbs = Math.abs(ms);
  9229. if (msAbs >= d) {
  9230. return Math.round(ms / d) + 'd';
  9231. }
  9232. if (msAbs >= h) {
  9233. return Math.round(ms / h) + 'h';
  9234. }
  9235. if (msAbs >= m) {
  9236. return Math.round(ms / m) + 'm';
  9237. }
  9238. if (msAbs >= s) {
  9239. return Math.round(ms / s) + 's';
  9240. }
  9241. return ms + 'ms';
  9242. }
  9243. /**
  9244. * Long format for `ms`.
  9245. *
  9246. * @param {Number} ms
  9247. * @return {String}
  9248. * @api private
  9249. */
  9250. function fmtLong(ms) {
  9251. var msAbs = Math.abs(ms);
  9252. if (msAbs >= d) {
  9253. return plural(ms, msAbs, d, 'day');
  9254. }
  9255. if (msAbs >= h) {
  9256. return plural(ms, msAbs, h, 'hour');
  9257. }
  9258. if (msAbs >= m) {
  9259. return plural(ms, msAbs, m, 'minute');
  9260. }
  9261. if (msAbs >= s) {
  9262. return plural(ms, msAbs, s, 'second');
  9263. }
  9264. return ms + ' ms';
  9265. }
  9266. /**
  9267. * Pluralization helper.
  9268. */
  9269. function plural(ms, msAbs, n, name) {
  9270. var isPlural = msAbs >= n * 1.5;
  9271. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  9272. }
  9273. return ms$1;
  9274. }
  9275. var common$b;
  9276. var hasRequiredCommon;
  9277. function requireCommon () {
  9278. if (hasRequiredCommon) return common$b;
  9279. hasRequiredCommon = 1;
  9280. /**
  9281. * This is the common logic for both the Node.js and web browser
  9282. * implementations of `debug()`.
  9283. */
  9284. function setup(env) {
  9285. createDebug.debug = createDebug;
  9286. createDebug.default = createDebug;
  9287. createDebug.coerce = coerce;
  9288. createDebug.disable = disable;
  9289. createDebug.enable = enable;
  9290. createDebug.enabled = enabled;
  9291. createDebug.humanize = requireMs$1();
  9292. createDebug.destroy = destroy;
  9293. Object.keys(env).forEach(key => {
  9294. createDebug[key] = env[key];
  9295. });
  9296. /**
  9297. * The currently active debug mode names, and names to skip.
  9298. */
  9299. createDebug.names = [];
  9300. createDebug.skips = [];
  9301. /**
  9302. * Map of special "%n" handling functions, for the debug "format" argument.
  9303. *
  9304. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  9305. */
  9306. createDebug.formatters = {};
  9307. /**
  9308. * Selects a color for a debug namespace
  9309. * @param {String} namespace The namespace string for the debug instance to be colored
  9310. * @return {Number|String} An ANSI color code for the given namespace
  9311. * @api private
  9312. */
  9313. function selectColor(namespace) {
  9314. let hash = 0;
  9315. for (let i = 0; i < namespace.length; i++) {
  9316. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  9317. hash |= 0; // Convert to 32bit integer
  9318. }
  9319. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  9320. }
  9321. createDebug.selectColor = selectColor;
  9322. /**
  9323. * Create a debugger with the given `namespace`.
  9324. *
  9325. * @param {String} namespace
  9326. * @return {Function}
  9327. * @api public
  9328. */
  9329. function createDebug(namespace) {
  9330. let prevTime;
  9331. let enableOverride = null;
  9332. let namespacesCache;
  9333. let enabledCache;
  9334. function debug(...args) {
  9335. // Disabled?
  9336. if (!debug.enabled) {
  9337. return;
  9338. }
  9339. const self = debug;
  9340. // Set `diff` timestamp
  9341. const curr = Number(new Date());
  9342. const ms = curr - (prevTime || curr);
  9343. self.diff = ms;
  9344. self.prev = prevTime;
  9345. self.curr = curr;
  9346. prevTime = curr;
  9347. args[0] = createDebug.coerce(args[0]);
  9348. if (typeof args[0] !== 'string') {
  9349. // Anything else let's inspect with %O
  9350. args.unshift('%O');
  9351. }
  9352. // Apply any `formatters` transformations
  9353. let index = 0;
  9354. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  9355. // If we encounter an escaped % then don't increase the array index
  9356. if (match === '%%') {
  9357. return '%';
  9358. }
  9359. index++;
  9360. const formatter = createDebug.formatters[format];
  9361. if (typeof formatter === 'function') {
  9362. const val = args[index];
  9363. match = formatter.call(self, val);
  9364. // Now we need to remove `args[index]` since it's inlined in the `format`
  9365. args.splice(index, 1);
  9366. index--;
  9367. }
  9368. return match;
  9369. });
  9370. // Apply env-specific formatting (colors, etc.)
  9371. createDebug.formatArgs.call(self, args);
  9372. const logFn = self.log || createDebug.log;
  9373. logFn.apply(self, args);
  9374. }
  9375. debug.namespace = namespace;
  9376. debug.useColors = createDebug.useColors();
  9377. debug.color = createDebug.selectColor(namespace);
  9378. debug.extend = extend;
  9379. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  9380. Object.defineProperty(debug, 'enabled', {
  9381. enumerable: true,
  9382. configurable: false,
  9383. get: () => {
  9384. if (enableOverride !== null) {
  9385. return enableOverride;
  9386. }
  9387. if (namespacesCache !== createDebug.namespaces) {
  9388. namespacesCache = createDebug.namespaces;
  9389. enabledCache = createDebug.enabled(namespace);
  9390. }
  9391. return enabledCache;
  9392. },
  9393. set: v => {
  9394. enableOverride = v;
  9395. }
  9396. });
  9397. // Env-specific initialization logic for debug instances
  9398. if (typeof createDebug.init === 'function') {
  9399. createDebug.init(debug);
  9400. }
  9401. return debug;
  9402. }
  9403. function extend(namespace, delimiter) {
  9404. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  9405. newDebug.log = this.log;
  9406. return newDebug;
  9407. }
  9408. /**
  9409. * Enables a debug mode by namespaces. This can include modes
  9410. * separated by a colon and wildcards.
  9411. *
  9412. * @param {String} namespaces
  9413. * @api public
  9414. */
  9415. function enable(namespaces) {
  9416. createDebug.save(namespaces);
  9417. createDebug.namespaces = namespaces;
  9418. createDebug.names = [];
  9419. createDebug.skips = [];
  9420. let i;
  9421. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  9422. const len = split.length;
  9423. for (i = 0; i < len; i++) {
  9424. if (!split[i]) {
  9425. // ignore empty strings
  9426. continue;
  9427. }
  9428. namespaces = split[i].replace(/\*/g, '.*?');
  9429. if (namespaces[0] === '-') {
  9430. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  9431. } else {
  9432. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  9433. }
  9434. }
  9435. }
  9436. /**
  9437. * Disable debug output.
  9438. *
  9439. * @return {String} namespaces
  9440. * @api public
  9441. */
  9442. function disable() {
  9443. const namespaces = [
  9444. ...createDebug.names.map(toNamespace),
  9445. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  9446. ].join(',');
  9447. createDebug.enable('');
  9448. return namespaces;
  9449. }
  9450. /**
  9451. * Returns true if the given mode name is enabled, false otherwise.
  9452. *
  9453. * @param {String} name
  9454. * @return {Boolean}
  9455. * @api public
  9456. */
  9457. function enabled(name) {
  9458. if (name[name.length - 1] === '*') {
  9459. return true;
  9460. }
  9461. let i;
  9462. let len;
  9463. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  9464. if (createDebug.skips[i].test(name)) {
  9465. return false;
  9466. }
  9467. }
  9468. for (i = 0, len = createDebug.names.length; i < len; i++) {
  9469. if (createDebug.names[i].test(name)) {
  9470. return true;
  9471. }
  9472. }
  9473. return false;
  9474. }
  9475. /**
  9476. * Convert regexp to namespace
  9477. *
  9478. * @param {RegExp} regxep
  9479. * @return {String} namespace
  9480. * @api private
  9481. */
  9482. function toNamespace(regexp) {
  9483. return regexp.toString()
  9484. .substring(2, regexp.toString().length - 2)
  9485. .replace(/\.\*\?$/, '*');
  9486. }
  9487. /**
  9488. * Coerce `val`.
  9489. *
  9490. * @param {Mixed} val
  9491. * @return {Mixed}
  9492. * @api private
  9493. */
  9494. function coerce(val) {
  9495. if (val instanceof Error) {
  9496. return val.stack || val.message;
  9497. }
  9498. return val;
  9499. }
  9500. /**
  9501. * XXX DO NOT USE. This is a temporary stub function.
  9502. * XXX It WILL be removed in the next major release.
  9503. */
  9504. function destroy() {
  9505. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  9506. }
  9507. createDebug.enable(createDebug.load());
  9508. return createDebug;
  9509. }
  9510. common$b = setup;
  9511. return common$b;
  9512. }
  9513. /* eslint-env browser */
  9514. var hasRequiredBrowser$1;
  9515. function requireBrowser$1 () {
  9516. if (hasRequiredBrowser$1) return browser$3.exports;
  9517. hasRequiredBrowser$1 = 1;
  9518. (function (module, exports) {
  9519. /**
  9520. * This is the web browser implementation of `debug()`.
  9521. */
  9522. exports.formatArgs = formatArgs;
  9523. exports.save = save;
  9524. exports.load = load;
  9525. exports.useColors = useColors;
  9526. exports.storage = localstorage();
  9527. exports.destroy = (() => {
  9528. let warned = false;
  9529. return () => {
  9530. if (!warned) {
  9531. warned = true;
  9532. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  9533. }
  9534. };
  9535. })();
  9536. /**
  9537. * Colors.
  9538. */
  9539. exports.colors = [
  9540. '#0000CC',
  9541. '#0000FF',
  9542. '#0033CC',
  9543. '#0033FF',
  9544. '#0066CC',
  9545. '#0066FF',
  9546. '#0099CC',
  9547. '#0099FF',
  9548. '#00CC00',
  9549. '#00CC33',
  9550. '#00CC66',
  9551. '#00CC99',
  9552. '#00CCCC',
  9553. '#00CCFF',
  9554. '#3300CC',
  9555. '#3300FF',
  9556. '#3333CC',
  9557. '#3333FF',
  9558. '#3366CC',
  9559. '#3366FF',
  9560. '#3399CC',
  9561. '#3399FF',
  9562. '#33CC00',
  9563. '#33CC33',
  9564. '#33CC66',
  9565. '#33CC99',
  9566. '#33CCCC',
  9567. '#33CCFF',
  9568. '#6600CC',
  9569. '#6600FF',
  9570. '#6633CC',
  9571. '#6633FF',
  9572. '#66CC00',
  9573. '#66CC33',
  9574. '#9900CC',
  9575. '#9900FF',
  9576. '#9933CC',
  9577. '#9933FF',
  9578. '#99CC00',
  9579. '#99CC33',
  9580. '#CC0000',
  9581. '#CC0033',
  9582. '#CC0066',
  9583. '#CC0099',
  9584. '#CC00CC',
  9585. '#CC00FF',
  9586. '#CC3300',
  9587. '#CC3333',
  9588. '#CC3366',
  9589. '#CC3399',
  9590. '#CC33CC',
  9591. '#CC33FF',
  9592. '#CC6600',
  9593. '#CC6633',
  9594. '#CC9900',
  9595. '#CC9933',
  9596. '#CCCC00',
  9597. '#CCCC33',
  9598. '#FF0000',
  9599. '#FF0033',
  9600. '#FF0066',
  9601. '#FF0099',
  9602. '#FF00CC',
  9603. '#FF00FF',
  9604. '#FF3300',
  9605. '#FF3333',
  9606. '#FF3366',
  9607. '#FF3399',
  9608. '#FF33CC',
  9609. '#FF33FF',
  9610. '#FF6600',
  9611. '#FF6633',
  9612. '#FF9900',
  9613. '#FF9933',
  9614. '#FFCC00',
  9615. '#FFCC33'
  9616. ];
  9617. /**
  9618. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  9619. * and the Firebug extension (any Firefox version) are known
  9620. * to support "%c" CSS customizations.
  9621. *
  9622. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  9623. */
  9624. // eslint-disable-next-line complexity
  9625. function useColors() {
  9626. // NB: In an Electron preload script, document will be defined but not fully
  9627. // initialized. Since we know we're in Chrome, we'll just detect this case
  9628. // explicitly
  9629. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  9630. return true;
  9631. }
  9632. // Internet Explorer and Edge do not support colors.
  9633. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  9634. return false;
  9635. }
  9636. // Is webkit? http://stackoverflow.com/a/16459606/376773
  9637. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  9638. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  9639. // Is firebug? http://stackoverflow.com/a/398120/376773
  9640. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  9641. // Is firefox >= v31?
  9642. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  9643. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  9644. // Double check webkit in userAgent just in case we are in a worker
  9645. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  9646. }
  9647. /**
  9648. * Colorize log arguments if enabled.
  9649. *
  9650. * @api public
  9651. */
  9652. function formatArgs(args) {
  9653. args[0] = (this.useColors ? '%c' : '') +
  9654. this.namespace +
  9655. (this.useColors ? ' %c' : ' ') +
  9656. args[0] +
  9657. (this.useColors ? '%c ' : ' ') +
  9658. '+' + module.exports.humanize(this.diff);
  9659. if (!this.useColors) {
  9660. return;
  9661. }
  9662. const c = 'color: ' + this.color;
  9663. args.splice(1, 0, c, 'color: inherit');
  9664. // The final "%c" is somewhat tricky, because there could be other
  9665. // arguments passed either before or after the %c, so we need to
  9666. // figure out the correct index to insert the CSS into
  9667. let index = 0;
  9668. let lastC = 0;
  9669. args[0].replace(/%[a-zA-Z%]/g, match => {
  9670. if (match === '%%') {
  9671. return;
  9672. }
  9673. index++;
  9674. if (match === '%c') {
  9675. // We only are interested in the *last* %c
  9676. // (the user may have provided their own)
  9677. lastC = index;
  9678. }
  9679. });
  9680. args.splice(lastC, 0, c);
  9681. }
  9682. /**
  9683. * Invokes `console.debug()` when available.
  9684. * No-op when `console.debug` is not a "function".
  9685. * If `console.debug` is not available, falls back
  9686. * to `console.log`.
  9687. *
  9688. * @api public
  9689. */
  9690. exports.log = console.debug || console.log || (() => {});
  9691. /**
  9692. * Save `namespaces`.
  9693. *
  9694. * @param {String} namespaces
  9695. * @api private
  9696. */
  9697. function save(namespaces) {
  9698. try {
  9699. if (namespaces) {
  9700. exports.storage.setItem('debug', namespaces);
  9701. } else {
  9702. exports.storage.removeItem('debug');
  9703. }
  9704. } catch (error) {
  9705. // Swallow
  9706. // XXX (@Qix-) should we be logging these?
  9707. }
  9708. }
  9709. /**
  9710. * Load `namespaces`.
  9711. *
  9712. * @return {String} returns the previously persisted debug modes
  9713. * @api private
  9714. */
  9715. function load() {
  9716. let r;
  9717. try {
  9718. r = exports.storage.getItem('debug');
  9719. } catch (error) {
  9720. // Swallow
  9721. // XXX (@Qix-) should we be logging these?
  9722. }
  9723. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  9724. if (!r && typeof process !== 'undefined' && 'env' in process) {
  9725. r = process.env.DEBUG;
  9726. }
  9727. return r;
  9728. }
  9729. /**
  9730. * Localstorage attempts to return the localstorage.
  9731. *
  9732. * This is necessary because safari throws
  9733. * when a user disables cookies/localstorage
  9734. * and you attempt to access it.
  9735. *
  9736. * @return {LocalStorage}
  9737. * @api private
  9738. */
  9739. function localstorage() {
  9740. try {
  9741. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  9742. // The Browser also has localStorage in the global context.
  9743. return localStorage;
  9744. } catch (error) {
  9745. // Swallow
  9746. // XXX (@Qix-) should we be logging these?
  9747. }
  9748. }
  9749. module.exports = requireCommon()(exports);
  9750. const {formatters} = module.exports;
  9751. /**
  9752. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  9753. */
  9754. formatters.j = function (v) {
  9755. try {
  9756. return JSON.stringify(v);
  9757. } catch (error) {
  9758. return '[UnexpectedJSONParseError]: ' + error.message;
  9759. }
  9760. };
  9761. } (browser$3, browser$3.exports));
  9762. return browser$3.exports;
  9763. }
  9764. var node$1 = {exports: {}};
  9765. /**
  9766. * Module dependencies.
  9767. */
  9768. var hasRequiredNode$1;
  9769. function requireNode$1 () {
  9770. if (hasRequiredNode$1) return node$1.exports;
  9771. hasRequiredNode$1 = 1;
  9772. (function (module, exports) {
  9773. const tty = require$$0$3;
  9774. const util = require$$0$6;
  9775. /**
  9776. * This is the Node.js implementation of `debug()`.
  9777. */
  9778. exports.init = init;
  9779. exports.log = log;
  9780. exports.formatArgs = formatArgs;
  9781. exports.save = save;
  9782. exports.load = load;
  9783. exports.useColors = useColors;
  9784. exports.destroy = util.deprecate(
  9785. () => {},
  9786. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  9787. );
  9788. /**
  9789. * Colors.
  9790. */
  9791. exports.colors = [6, 2, 3, 4, 5, 1];
  9792. try {
  9793. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  9794. // eslint-disable-next-line import/no-extraneous-dependencies
  9795. const supportsColor = require('supports-color');
  9796. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  9797. exports.colors = [
  9798. 20,
  9799. 21,
  9800. 26,
  9801. 27,
  9802. 32,
  9803. 33,
  9804. 38,
  9805. 39,
  9806. 40,
  9807. 41,
  9808. 42,
  9809. 43,
  9810. 44,
  9811. 45,
  9812. 56,
  9813. 57,
  9814. 62,
  9815. 63,
  9816. 68,
  9817. 69,
  9818. 74,
  9819. 75,
  9820. 76,
  9821. 77,
  9822. 78,
  9823. 79,
  9824. 80,
  9825. 81,
  9826. 92,
  9827. 93,
  9828. 98,
  9829. 99,
  9830. 112,
  9831. 113,
  9832. 128,
  9833. 129,
  9834. 134,
  9835. 135,
  9836. 148,
  9837. 149,
  9838. 160,
  9839. 161,
  9840. 162,
  9841. 163,
  9842. 164,
  9843. 165,
  9844. 166,
  9845. 167,
  9846. 168,
  9847. 169,
  9848. 170,
  9849. 171,
  9850. 172,
  9851. 173,
  9852. 178,
  9853. 179,
  9854. 184,
  9855. 185,
  9856. 196,
  9857. 197,
  9858. 198,
  9859. 199,
  9860. 200,
  9861. 201,
  9862. 202,
  9863. 203,
  9864. 204,
  9865. 205,
  9866. 206,
  9867. 207,
  9868. 208,
  9869. 209,
  9870. 214,
  9871. 215,
  9872. 220,
  9873. 221
  9874. ];
  9875. }
  9876. } catch (error) {
  9877. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  9878. }
  9879. /**
  9880. * Build up the default `inspectOpts` object from the environment variables.
  9881. *
  9882. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  9883. */
  9884. exports.inspectOpts = Object.keys(process.env).filter(key => {
  9885. return /^debug_/i.test(key);
  9886. }).reduce((obj, key) => {
  9887. // Camel-case
  9888. const prop = key
  9889. .substring(6)
  9890. .toLowerCase()
  9891. .replace(/_([a-z])/g, (_, k) => {
  9892. return k.toUpperCase();
  9893. });
  9894. // Coerce string value into JS value
  9895. let val = process.env[key];
  9896. if (/^(yes|on|true|enabled)$/i.test(val)) {
  9897. val = true;
  9898. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  9899. val = false;
  9900. } else if (val === 'null') {
  9901. val = null;
  9902. } else {
  9903. val = Number(val);
  9904. }
  9905. obj[prop] = val;
  9906. return obj;
  9907. }, {});
  9908. /**
  9909. * Is stdout a TTY? Colored output is enabled when `true`.
  9910. */
  9911. function useColors() {
  9912. return 'colors' in exports.inspectOpts ?
  9913. Boolean(exports.inspectOpts.colors) :
  9914. tty.isatty(process.stderr.fd);
  9915. }
  9916. /**
  9917. * Adds ANSI color escape codes if enabled.
  9918. *
  9919. * @api public
  9920. */
  9921. function formatArgs(args) {
  9922. const {namespace: name, useColors} = this;
  9923. if (useColors) {
  9924. const c = this.color;
  9925. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  9926. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  9927. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  9928. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  9929. } else {
  9930. args[0] = getDate() + name + ' ' + args[0];
  9931. }
  9932. }
  9933. function getDate() {
  9934. if (exports.inspectOpts.hideDate) {
  9935. return '';
  9936. }
  9937. return new Date().toISOString() + ' ';
  9938. }
  9939. /**
  9940. * Invokes `util.format()` with the specified arguments and writes to stderr.
  9941. */
  9942. function log(...args) {
  9943. return process.stderr.write(util.format(...args) + '\n');
  9944. }
  9945. /**
  9946. * Save `namespaces`.
  9947. *
  9948. * @param {String} namespaces
  9949. * @api private
  9950. */
  9951. function save(namespaces) {
  9952. if (namespaces) {
  9953. process.env.DEBUG = namespaces;
  9954. } else {
  9955. // If you set a process.env field to null or undefined, it gets cast to the
  9956. // string 'null' or 'undefined'. Just delete instead.
  9957. delete process.env.DEBUG;
  9958. }
  9959. }
  9960. /**
  9961. * Load `namespaces`.
  9962. *
  9963. * @return {String} returns the previously persisted debug modes
  9964. * @api private
  9965. */
  9966. function load() {
  9967. return process.env.DEBUG;
  9968. }
  9969. /**
  9970. * Init logic for `debug` instances.
  9971. *
  9972. * Create a new `inspectOpts` object in case `useColors` is set
  9973. * differently for a particular `debug` instance.
  9974. */
  9975. function init(debug) {
  9976. debug.inspectOpts = {};
  9977. const keys = Object.keys(exports.inspectOpts);
  9978. for (let i = 0; i < keys.length; i++) {
  9979. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  9980. }
  9981. }
  9982. module.exports = requireCommon()(exports);
  9983. const {formatters} = module.exports;
  9984. /**
  9985. * Map %o to `util.inspect()`, all on a single line.
  9986. */
  9987. formatters.o = function (v) {
  9988. this.inspectOpts.colors = this.useColors;
  9989. return util.inspect(v, this.inspectOpts)
  9990. .split('\n')
  9991. .map(str => str.trim())
  9992. .join(' ');
  9993. };
  9994. /**
  9995. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  9996. */
  9997. formatters.O = function (v) {
  9998. this.inspectOpts.colors = this.useColors;
  9999. return util.inspect(v, this.inspectOpts);
  10000. };
  10001. } (node$1, node$1.exports));
  10002. return node$1.exports;
  10003. }
  10004. /**
  10005. * Detect Electron renderer / nwjs process, which is node, but we should
  10006. * treat as a browser.
  10007. */
  10008. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  10009. src$2.exports = requireBrowser$1();
  10010. } else {
  10011. src$2.exports = requireNode$1();
  10012. }
  10013. var srcExports$1 = src$2.exports;
  10014. var debug$g = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1);
  10015. let pnp;
  10016. if (process.versions.pnp) {
  10017. try {
  10018. pnp = createRequire$1(import.meta.url)('pnpapi');
  10019. }
  10020. catch { }
  10021. }
  10022. function invalidatePackageData(packageCache, pkgPath) {
  10023. const pkgDir = path$o.dirname(pkgPath);
  10024. packageCache.forEach((pkg, cacheKey) => {
  10025. if (pkg.dir === pkgDir) {
  10026. packageCache.delete(cacheKey);
  10027. }
  10028. });
  10029. }
  10030. function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
  10031. if (pnp) {
  10032. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  10033. if (packageCache?.has(cacheKey))
  10034. return packageCache.get(cacheKey);
  10035. try {
  10036. const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
  10037. considerBuiltins: false,
  10038. });
  10039. if (!pkg)
  10040. return null;
  10041. const pkgData = loadPackageData(path$o.join(pkg, 'package.json'));
  10042. packageCache?.set(cacheKey, pkgData);
  10043. return pkgData;
  10044. }
  10045. catch {
  10046. return null;
  10047. }
  10048. }
  10049. const originalBasedir = basedir;
  10050. while (basedir) {
  10051. if (packageCache) {
  10052. const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks);
  10053. if (cached)
  10054. return cached;
  10055. }
  10056. const pkg = path$o.join(basedir, 'node_modules', pkgName, 'package.json');
  10057. try {
  10058. if (fs$l.existsSync(pkg)) {
  10059. const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
  10060. const pkgData = loadPackageData(pkgPath);
  10061. if (packageCache) {
  10062. setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
  10063. }
  10064. return pkgData;
  10065. }
  10066. }
  10067. catch { }
  10068. const nextBasedir = path$o.dirname(basedir);
  10069. if (nextBasedir === basedir)
  10070. break;
  10071. basedir = nextBasedir;
  10072. }
  10073. return null;
  10074. }
  10075. function findNearestPackageData(basedir, packageCache) {
  10076. const originalBasedir = basedir;
  10077. while (basedir) {
  10078. if (packageCache) {
  10079. const cached = getFnpdCache(packageCache, basedir, originalBasedir);
  10080. if (cached)
  10081. return cached;
  10082. }
  10083. const pkgPath = path$o.join(basedir, 'package.json');
  10084. try {
  10085. if (fs$l.statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) {
  10086. const pkgData = loadPackageData(pkgPath);
  10087. if (packageCache) {
  10088. setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
  10089. }
  10090. return pkgData;
  10091. }
  10092. }
  10093. catch { }
  10094. const nextBasedir = path$o.dirname(basedir);
  10095. if (nextBasedir === basedir)
  10096. break;
  10097. basedir = nextBasedir;
  10098. }
  10099. return null;
  10100. }
  10101. // Finds the nearest package.json with a `name` field
  10102. function findNearestMainPackageData(basedir, packageCache) {
  10103. const nearestPackage = findNearestPackageData(basedir, packageCache);
  10104. return (nearestPackage &&
  10105. (nearestPackage.data.name
  10106. ? nearestPackage
  10107. : findNearestMainPackageData(path$o.dirname(nearestPackage.dir), packageCache)));
  10108. }
  10109. function loadPackageData(pkgPath) {
  10110. const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8'));
  10111. const pkgDir = path$o.dirname(pkgPath);
  10112. const { sideEffects } = data;
  10113. let hasSideEffects;
  10114. if (typeof sideEffects === 'boolean') {
  10115. hasSideEffects = () => sideEffects;
  10116. }
  10117. else if (Array.isArray(sideEffects)) {
  10118. const finalPackageSideEffects = sideEffects.map((sideEffect) => {
  10119. /*
  10120. * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css.
  10121. * https://webpack.js.org/guides/tree-shaking/
  10122. * https://github.com/vitejs/vite/pull/11807
  10123. */
  10124. if (sideEffect.includes('/')) {
  10125. return sideEffect;
  10126. }
  10127. return `**/${sideEffect}`;
  10128. });
  10129. hasSideEffects = createFilter(finalPackageSideEffects, null, {
  10130. resolve: pkgDir,
  10131. });
  10132. }
  10133. else {
  10134. hasSideEffects = () => true;
  10135. }
  10136. const pkg = {
  10137. dir: pkgDir,
  10138. data,
  10139. hasSideEffects,
  10140. webResolvedImports: {},
  10141. nodeResolvedImports: {},
  10142. setResolvedCache(key, entry, targetWeb) {
  10143. if (targetWeb) {
  10144. pkg.webResolvedImports[key] = entry;
  10145. }
  10146. else {
  10147. pkg.nodeResolvedImports[key] = entry;
  10148. }
  10149. },
  10150. getResolvedCache(key, targetWeb) {
  10151. if (targetWeb) {
  10152. return pkg.webResolvedImports[key];
  10153. }
  10154. else {
  10155. return pkg.nodeResolvedImports[key];
  10156. }
  10157. },
  10158. };
  10159. return pkg;
  10160. }
  10161. function watchPackageDataPlugin(packageCache) {
  10162. // a list of files to watch before the plugin is ready
  10163. const watchQueue = new Set();
  10164. const watchedDirs = new Set();
  10165. const watchFileStub = (id) => {
  10166. watchQueue.add(id);
  10167. };
  10168. let watchFile = watchFileStub;
  10169. const setPackageData = packageCache.set.bind(packageCache);
  10170. packageCache.set = (id, pkg) => {
  10171. if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) {
  10172. watchedDirs.add(pkg.dir);
  10173. watchFile(path$o.join(pkg.dir, 'package.json'));
  10174. }
  10175. return setPackageData(id, pkg);
  10176. };
  10177. return {
  10178. name: 'vite:watch-package-data',
  10179. buildStart() {
  10180. watchFile = this.addWatchFile.bind(this);
  10181. watchQueue.forEach(watchFile);
  10182. watchQueue.clear();
  10183. },
  10184. buildEnd() {
  10185. watchFile = watchFileStub;
  10186. },
  10187. watchChange(id) {
  10188. if (id.endsWith('/package.json')) {
  10189. invalidatePackageData(packageCache, path$o.normalize(id));
  10190. }
  10191. },
  10192. handleHotUpdate({ file }) {
  10193. if (file.endsWith('/package.json')) {
  10194. invalidatePackageData(packageCache, path$o.normalize(file));
  10195. }
  10196. },
  10197. };
  10198. }
  10199. /**
  10200. * Get cached `resolvePackageData` value based on `basedir`. When one is found,
  10201. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  10202. * we cache the value for those in-between directories as well.
  10203. *
  10204. * This makes it so the fs is only read once for a shared `basedir`.
  10205. */
  10206. function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
  10207. const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  10208. const pkgData = packageCache.get(cacheKey);
  10209. if (pkgData) {
  10210. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10211. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  10212. });
  10213. return pkgData;
  10214. }
  10215. }
  10216. function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
  10217. packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
  10218. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10219. packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  10220. });
  10221. }
  10222. // package cache key for `resolvePackageData`
  10223. function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
  10224. return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
  10225. }
  10226. /**
  10227. * Get cached `findNearestPackageData` value based on `basedir`. When one is found,
  10228. * and we've already traversed some directories between `basedir` and `originalBasedir`,
  10229. * we cache the value for those in-between directories as well.
  10230. *
  10231. * This makes it so the fs is only read once for a shared `basedir`.
  10232. */
  10233. function getFnpdCache(packageCache, basedir, originalBasedir) {
  10234. const cacheKey = getFnpdCacheKey(basedir);
  10235. const pkgData = packageCache.get(cacheKey);
  10236. if (pkgData) {
  10237. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10238. packageCache.set(getFnpdCacheKey(dir), pkgData);
  10239. });
  10240. return pkgData;
  10241. }
  10242. }
  10243. function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
  10244. packageCache.set(getFnpdCacheKey(basedir), pkgData);
  10245. traverseBetweenDirs(originalBasedir, basedir, (dir) => {
  10246. packageCache.set(getFnpdCacheKey(dir), pkgData);
  10247. });
  10248. }
  10249. // package cache key for `findNearestPackageData`
  10250. function getFnpdCacheKey(basedir) {
  10251. return `fnpd_${basedir}`;
  10252. }
  10253. /**
  10254. * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
  10255. * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
  10256. * @param shorterDir Shorter dir path, e.g. `/User/foo`
  10257. */
  10258. function traverseBetweenDirs(longerDir, shorterDir, cb) {
  10259. while (longerDir !== shorterDir) {
  10260. cb(longerDir);
  10261. longerDir = path$o.dirname(longerDir);
  10262. }
  10263. }
  10264. const createFilter = createFilter$1;
  10265. const windowsSlashRE = /\\/g;
  10266. function slash$1(p) {
  10267. return p.replace(windowsSlashRE, '/');
  10268. }
  10269. /**
  10270. * Prepend `/@id/` and replace null byte so the id is URL-safe.
  10271. * This is prepended to resolved ids that are not valid browser
  10272. * import specifiers by the importAnalysis plugin.
  10273. */
  10274. function wrapId(id) {
  10275. return id.startsWith(VALID_ID_PREFIX)
  10276. ? id
  10277. : VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER);
  10278. }
  10279. /**
  10280. * Undo {@link wrapId}'s `/@id/` and null byte replacements.
  10281. */
  10282. function unwrapId(id) {
  10283. return id.startsWith(VALID_ID_PREFIX)
  10284. ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0')
  10285. : id;
  10286. }
  10287. const replaceSlashOrColonRE = /[/:]/g;
  10288. const replaceDotRE = /\./g;
  10289. const replaceNestedIdRE = /(\s*>\s*)/g;
  10290. const replaceHashRE = /#/g;
  10291. const flattenId = (id) => id
  10292. .replace(replaceSlashOrColonRE, '_')
  10293. .replace(replaceDotRE, '__')
  10294. .replace(replaceNestedIdRE, '___')
  10295. .replace(replaceHashRE, '____');
  10296. const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > ');
  10297. // Supported by Node, Deno, Bun
  10298. const NODE_BUILTIN_NAMESPACE = 'node:';
  10299. // Supported by Deno
  10300. const NPM_BUILTIN_NAMESPACE = 'npm:';
  10301. // Supported by Bun
  10302. const BUN_BUILTIN_NAMESPACE = 'bun:';
  10303. //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
  10304. const builtins = new Set([
  10305. ...builtinModules,
  10306. 'assert/strict',
  10307. 'diagnostics_channel',
  10308. 'dns/promises',
  10309. 'fs/promises',
  10310. 'path/posix',
  10311. 'path/win32',
  10312. 'readline/promises',
  10313. 'stream/consumers',
  10314. 'stream/promises',
  10315. 'stream/web',
  10316. 'timers/promises',
  10317. 'util/types',
  10318. 'wasi',
  10319. ]);
  10320. // Some runtimes like Bun injects namespaced modules here, which is not a node builtin
  10321. const nodeBuiltins = [...builtins].filter((id) => !id.includes(':'));
  10322. // TODO: Use `isBuiltin` from `node:module`, but Deno doesn't support it
  10323. function isBuiltin(id) {
  10324. if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE))
  10325. return true;
  10326. if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE))
  10327. return true;
  10328. return isNodeBuiltin(id);
  10329. }
  10330. function isNodeBuiltin(id) {
  10331. if (id.startsWith(NODE_BUILTIN_NAMESPACE))
  10332. return true;
  10333. return nodeBuiltins.includes(id);
  10334. }
  10335. function isInNodeModules(id) {
  10336. return id.includes('node_modules');
  10337. }
  10338. function moduleListContains(moduleList, id) {
  10339. return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
  10340. }
  10341. function isOptimizable(id, optimizeDeps) {
  10342. const { extensions } = optimizeDeps;
  10343. return (OPTIMIZABLE_ENTRY_RE.test(id) ||
  10344. (extensions?.some((ext) => id.endsWith(ext)) ?? false));
  10345. }
  10346. const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
  10347. const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
  10348. // TODO: use import()
  10349. const _require$3 = createRequire$1(import.meta.url);
  10350. // set in bin/vite.js
  10351. const filter = process.env.VITE_DEBUG_FILTER;
  10352. const DEBUG = process.env.DEBUG;
  10353. function createDebugger(namespace, options = {}) {
  10354. const log = debug$g(namespace);
  10355. const { onlyWhenFocused } = options;
  10356. let enabled = log.enabled;
  10357. if (enabled && onlyWhenFocused) {
  10358. const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace;
  10359. enabled = !!DEBUG?.includes(ns);
  10360. }
  10361. if (enabled) {
  10362. return (...args) => {
  10363. if (!filter || args.some((a) => a?.includes?.(filter))) {
  10364. log(...args);
  10365. }
  10366. };
  10367. }
  10368. }
  10369. function testCaseInsensitiveFS() {
  10370. if (!CLIENT_ENTRY.endsWith('client.mjs')) {
  10371. throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
  10372. }
  10373. if (!fs$l.existsSync(CLIENT_ENTRY)) {
  10374. throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
  10375. CLIENT_ENTRY);
  10376. }
  10377. return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
  10378. }
  10379. function isUrl(path) {
  10380. try {
  10381. new URL$3(path);
  10382. return true;
  10383. }
  10384. catch {
  10385. return false;
  10386. }
  10387. }
  10388. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  10389. const isWindows$4 = os$4.platform() === 'win32';
  10390. const VOLUME_RE = /^[A-Z]:/i;
  10391. function normalizePath$3(id) {
  10392. return path$o.posix.normalize(isWindows$4 ? slash$1(id) : id);
  10393. }
  10394. function fsPathFromId(id) {
  10395. const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
  10396. return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`;
  10397. }
  10398. function fsPathFromUrl(url) {
  10399. return fsPathFromId(cleanUrl(url));
  10400. }
  10401. function withTrailingSlash(path) {
  10402. if (path[path.length - 1] !== '/') {
  10403. return `${path}/`;
  10404. }
  10405. return path;
  10406. }
  10407. /**
  10408. * Check if dir is a parent of file
  10409. *
  10410. * Warning: parameters are not validated, only works with normalized absolute paths
  10411. *
  10412. * @param dir - normalized absolute path
  10413. * @param file - normalized absolute path
  10414. * @returns true if dir is a parent of file
  10415. */
  10416. function isParentDirectory(dir, file) {
  10417. dir = withTrailingSlash(dir);
  10418. return (file.startsWith(dir) ||
  10419. (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
  10420. }
  10421. /**
  10422. * Check if 2 file name are identical
  10423. *
  10424. * Warning: parameters are not validated, only works with normalized absolute paths
  10425. *
  10426. * @param file1 - normalized absolute path
  10427. * @param file2 - normalized absolute path
  10428. * @returns true if both files url are identical
  10429. */
  10430. function isSameFileUri(file1, file2) {
  10431. return (file1 === file2 ||
  10432. (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase()));
  10433. }
  10434. const queryRE = /\?.*$/s;
  10435. const postfixRE = /[?#].*$/s;
  10436. function cleanUrl(url) {
  10437. return url.replace(postfixRE, '');
  10438. }
  10439. const externalRE = /^(https?:)?\/\//;
  10440. const isExternalUrl = (url) => externalRE.test(url);
  10441. const dataUrlRE = /^\s*data:/i;
  10442. const isDataUrl = (url) => dataUrlRE.test(url);
  10443. const virtualModuleRE = /^virtual-module:.*/;
  10444. const virtualModulePrefix = 'virtual-module:';
  10445. const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
  10446. const isJSRequest = (url) => {
  10447. url = cleanUrl(url);
  10448. if (knownJsSrcRE.test(url)) {
  10449. return true;
  10450. }
  10451. if (!path$o.extname(url) && url[url.length - 1] !== '/') {
  10452. return true;
  10453. }
  10454. return false;
  10455. };
  10456. const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/;
  10457. const isTsRequest = (url) => knownTsRE.test(url);
  10458. const importQueryRE = /(\?|&)import=?(?:&|$)/;
  10459. const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
  10460. const internalPrefixes = [
  10461. FS_PREFIX,
  10462. VALID_ID_PREFIX,
  10463. CLIENT_PUBLIC_PATH,
  10464. ENV_PUBLIC_PATH,
  10465. ];
  10466. const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`);
  10467. const trailingSeparatorRE = /[?&]$/;
  10468. const isImportRequest = (url) => importQueryRE.test(url);
  10469. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  10470. function removeImportQuery(url) {
  10471. return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '');
  10472. }
  10473. function removeDirectQuery(url) {
  10474. return url.replace(directRequestRE$1, '$1').replace(trailingSeparatorRE, '');
  10475. }
  10476. const replacePercentageRE = /%/g;
  10477. function injectQuery(url, queryToInject) {
  10478. // encode percents for consistent behavior with pathToFileURL
  10479. // see #2614 for details
  10480. const resolvedUrl = new URL$3(url.replace(replacePercentageRE, '%25'), 'relative:///');
  10481. const { search, hash } = resolvedUrl;
  10482. let pathname = cleanUrl(url);
  10483. pathname = isWindows$4 ? slash$1(pathname) : pathname;
  10484. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash ?? ''}`;
  10485. }
  10486. const timestampRE = /\bt=\d{13}&?\b/;
  10487. function removeTimestampQuery(url) {
  10488. return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
  10489. }
  10490. async function asyncReplace(input, re, replacer) {
  10491. let match;
  10492. let remaining = input;
  10493. let rewritten = '';
  10494. while ((match = re.exec(remaining))) {
  10495. rewritten += remaining.slice(0, match.index);
  10496. rewritten += await replacer(match);
  10497. remaining = remaining.slice(match.index + match[0].length);
  10498. }
  10499. rewritten += remaining;
  10500. return rewritten;
  10501. }
  10502. function timeFrom(start, subtract = 0) {
  10503. const time = performance.now() - start - subtract;
  10504. const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' ');
  10505. if (time < 10) {
  10506. return colors$1.green(timeString);
  10507. }
  10508. else if (time < 50) {
  10509. return colors$1.yellow(timeString);
  10510. }
  10511. else {
  10512. return colors$1.red(timeString);
  10513. }
  10514. }
  10515. /**
  10516. * pretty url for logging.
  10517. */
  10518. function prettifyUrl(url, root) {
  10519. url = removeTimestampQuery(url);
  10520. const isAbsoluteFile = url.startsWith(root);
  10521. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  10522. const file = path$o.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
  10523. return colors$1.dim(file);
  10524. }
  10525. else {
  10526. return colors$1.dim(url);
  10527. }
  10528. }
  10529. function isObject$2(value) {
  10530. return Object.prototype.toString.call(value) === '[object Object]';
  10531. }
  10532. function isDefined(value) {
  10533. return value != null;
  10534. }
  10535. function tryStatSync(file) {
  10536. try {
  10537. return fs$l.statSync(file, { throwIfNoEntry: false });
  10538. }
  10539. catch {
  10540. // Ignore errors
  10541. }
  10542. }
  10543. function lookupFile(dir, fileNames) {
  10544. while (dir) {
  10545. for (const fileName of fileNames) {
  10546. const fullPath = path$o.join(dir, fileName);
  10547. if (tryStatSync(fullPath)?.isFile())
  10548. return fullPath;
  10549. }
  10550. const parentDir = path$o.dirname(dir);
  10551. if (parentDir === dir)
  10552. return;
  10553. dir = parentDir;
  10554. }
  10555. }
  10556. const splitRE = /\r?\n/;
  10557. const range = 2;
  10558. function pad$1(source, n = 2) {
  10559. const lines = source.split(splitRE);
  10560. return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
  10561. }
  10562. function posToNumber(source, pos) {
  10563. if (typeof pos === 'number')
  10564. return pos;
  10565. const lines = source.split(splitRE);
  10566. const { line, column } = pos;
  10567. let start = 0;
  10568. for (let i = 0; i < line - 1 && i < lines.length; i++) {
  10569. start += lines[i].length + 1;
  10570. }
  10571. return start + column;
  10572. }
  10573. function numberToPos(source, offset) {
  10574. if (typeof offset !== 'number')
  10575. return offset;
  10576. if (offset > source.length) {
  10577. throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
  10578. }
  10579. const lines = source.split(splitRE);
  10580. let counted = 0;
  10581. let line = 0;
  10582. let column = 0;
  10583. for (; line < lines.length; line++) {
  10584. const lineLength = lines[line].length + 1;
  10585. if (counted + lineLength >= offset) {
  10586. column = offset - counted + 1;
  10587. break;
  10588. }
  10589. counted += lineLength;
  10590. }
  10591. return { line: line + 1, column };
  10592. }
  10593. function generateCodeFrame(source, start = 0, end) {
  10594. start = posToNumber(source, start);
  10595. end = end || start;
  10596. const lines = source.split(splitRE);
  10597. let count = 0;
  10598. const res = [];
  10599. for (let i = 0; i < lines.length; i++) {
  10600. count += lines[i].length + 1;
  10601. if (count >= start) {
  10602. for (let j = i - range; j <= i + range || end > count; j++) {
  10603. if (j < 0 || j >= lines.length)
  10604. continue;
  10605. const line = j + 1;
  10606. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  10607. const lineLength = lines[j].length;
  10608. if (j === i) {
  10609. // push underline
  10610. const pad = Math.max(start - (count - lineLength) + 1, 0);
  10611. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  10612. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  10613. }
  10614. else if (j > i) {
  10615. if (end > count) {
  10616. const length = Math.max(Math.min(end - count, lineLength), 1);
  10617. res.push(` | ` + '^'.repeat(length));
  10618. }
  10619. count += lineLength + 1;
  10620. }
  10621. }
  10622. break;
  10623. }
  10624. }
  10625. return res.join('\n');
  10626. }
  10627. function isFileReadable(filename) {
  10628. try {
  10629. // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
  10630. if (!fs$l.statSync(filename, { throwIfNoEntry: false })) {
  10631. return false;
  10632. }
  10633. // Check if current process has read permission to the file
  10634. fs$l.accessSync(filename, fs$l.constants.R_OK);
  10635. return true;
  10636. }
  10637. catch {
  10638. return false;
  10639. }
  10640. }
  10641. const splitFirstDirRE = /(.+?)[\\/](.+)/;
  10642. /**
  10643. * Delete every file and subdirectory. **The given directory must exist.**
  10644. * Pass an optional `skip` array to preserve files under the root directory.
  10645. */
  10646. function emptyDir(dir, skip) {
  10647. const skipInDir = [];
  10648. let nested = null;
  10649. if (skip?.length) {
  10650. for (const file of skip) {
  10651. if (path$o.dirname(file) !== '.') {
  10652. const matched = file.match(splitFirstDirRE);
  10653. if (matched) {
  10654. nested ?? (nested = new Map());
  10655. const [, nestedDir, skipPath] = matched;
  10656. let nestedSkip = nested.get(nestedDir);
  10657. if (!nestedSkip) {
  10658. nestedSkip = [];
  10659. nested.set(nestedDir, nestedSkip);
  10660. }
  10661. if (!nestedSkip.includes(skipPath)) {
  10662. nestedSkip.push(skipPath);
  10663. }
  10664. }
  10665. }
  10666. else {
  10667. skipInDir.push(file);
  10668. }
  10669. }
  10670. }
  10671. for (const file of fs$l.readdirSync(dir)) {
  10672. if (skipInDir.includes(file)) {
  10673. continue;
  10674. }
  10675. if (nested?.has(file)) {
  10676. emptyDir(path$o.resolve(dir, file), nested.get(file));
  10677. }
  10678. else {
  10679. fs$l.rmSync(path$o.resolve(dir, file), { recursive: true, force: true });
  10680. }
  10681. }
  10682. }
  10683. function copyDir(srcDir, destDir) {
  10684. fs$l.mkdirSync(destDir, { recursive: true });
  10685. for (const file of fs$l.readdirSync(srcDir)) {
  10686. const srcFile = path$o.resolve(srcDir, file);
  10687. if (srcFile === destDir) {
  10688. continue;
  10689. }
  10690. const destFile = path$o.resolve(destDir, file);
  10691. const stat = fs$l.statSync(srcFile);
  10692. if (stat.isDirectory()) {
  10693. copyDir(srcFile, destFile);
  10694. }
  10695. else {
  10696. fs$l.copyFileSync(srcFile, destFile);
  10697. }
  10698. }
  10699. }
  10700. // `fs.realpathSync.native` resolves differently in Windows network drive,
  10701. // causing file read errors. skip for now.
  10702. // https://github.com/nodejs/node/issues/37737
  10703. let safeRealpathSync = isWindows$4
  10704. ? windowsSafeRealPathSync
  10705. : fs$l.realpathSync.native;
  10706. // Based on https://github.com/larrybahr/windows-network-drive
  10707. // MIT License, Copyright (c) 2017 Larry Bahr
  10708. const windowsNetworkMap = new Map();
  10709. function windowsMappedRealpathSync(path) {
  10710. const realPath = fs$l.realpathSync.native(path);
  10711. if (realPath.startsWith('\\\\')) {
  10712. for (const [network, volume] of windowsNetworkMap) {
  10713. if (realPath.startsWith(network))
  10714. return realPath.replace(network, volume);
  10715. }
  10716. }
  10717. return realPath;
  10718. }
  10719. const parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/;
  10720. let firstSafeRealPathSyncRun = false;
  10721. function windowsSafeRealPathSync(path) {
  10722. if (!firstSafeRealPathSyncRun) {
  10723. optimizeSafeRealPathSync();
  10724. firstSafeRealPathSyncRun = true;
  10725. }
  10726. return fs$l.realpathSync(path);
  10727. }
  10728. function optimizeSafeRealPathSync() {
  10729. // Skip if using Node <16.18 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931
  10730. const nodeVersion = process.versions.node.split('.').map(Number);
  10731. if (nodeVersion[0] < 16 || (nodeVersion[0] === 16 && nodeVersion[1] < 18)) {
  10732. safeRealpathSync = fs$l.realpathSync;
  10733. return;
  10734. }
  10735. // Check the availability `fs.realpathSync.native`
  10736. // in Windows virtual and RAM disks that bypass the Volume Mount Manager, in programs such as imDisk
  10737. // get the error EISDIR: illegal operation on a directory
  10738. try {
  10739. fs$l.realpathSync.native(path$o.resolve('./'));
  10740. }
  10741. catch (error) {
  10742. if (error.message.includes('EISDIR: illegal operation on a directory')) {
  10743. safeRealpathSync = fs$l.realpathSync;
  10744. return;
  10745. }
  10746. }
  10747. exec('net use', (error, stdout) => {
  10748. if (error)
  10749. return;
  10750. const lines = stdout.split('\n');
  10751. // OK Y: \\NETWORKA\Foo Microsoft Windows Network
  10752. // OK Z: \\NETWORKA\Bar Microsoft Windows Network
  10753. for (const line of lines) {
  10754. const m = line.match(parseNetUseRE);
  10755. if (m)
  10756. windowsNetworkMap.set(m[3], m[2]);
  10757. }
  10758. if (windowsNetworkMap.size === 0) {
  10759. safeRealpathSync = fs$l.realpathSync.native;
  10760. }
  10761. else {
  10762. safeRealpathSync = windowsMappedRealpathSync;
  10763. }
  10764. });
  10765. }
  10766. function ensureWatchedFile(watcher, file, root) {
  10767. if (file &&
  10768. // only need to watch if out of root
  10769. !file.startsWith(withTrailingSlash(root)) &&
  10770. // some rollup plugins use null bytes for private resolved Ids
  10771. !file.includes('\0') &&
  10772. fs$l.existsSync(file)) {
  10773. // resolve file to normalized system path
  10774. watcher.add(path$o.resolve(file));
  10775. }
  10776. }
  10777. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  10778. const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
  10779. function reduceSrcset(ret) {
  10780. return ret.reduce((prev, { url, descriptor }, index) => {
  10781. descriptor ?? (descriptor = '');
  10782. return (prev +=
  10783. url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
  10784. }, '');
  10785. }
  10786. function splitSrcSetDescriptor(srcs) {
  10787. return splitSrcSet(srcs)
  10788. .map((s) => {
  10789. const src = s.replace(escapedSpaceCharacters, ' ').trim();
  10790. const [url] = imageSetUrlRE.exec(src) || [''];
  10791. return {
  10792. url,
  10793. descriptor: src?.slice(url.length).trim(),
  10794. };
  10795. })
  10796. .filter(({ url }) => !!url);
  10797. }
  10798. function processSrcSet(srcs, replacer) {
  10799. return Promise.all(splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({
  10800. url: await replacer({ url, descriptor }),
  10801. descriptor,
  10802. }))).then((ret) => reduceSrcset(ret));
  10803. }
  10804. function processSrcSetSync(srcs, replacer) {
  10805. return reduceSrcset(splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({
  10806. url: replacer({ url, descriptor }),
  10807. descriptor,
  10808. })));
  10809. }
  10810. const cleanSrcSetRE = /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g;
  10811. function splitSrcSet(srcs) {
  10812. const parts = [];
  10813. // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..."
  10814. const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer);
  10815. let startIndex = 0;
  10816. let splitIndex;
  10817. do {
  10818. splitIndex = cleanedSrcs.indexOf(',', startIndex);
  10819. parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined));
  10820. startIndex = splitIndex + 1;
  10821. } while (splitIndex !== -1);
  10822. return parts;
  10823. }
  10824. const windowsDriveRE = /^[A-Z]:/;
  10825. const replaceWindowsDriveRE = /^([A-Z]):\//;
  10826. const linuxAbsolutePathRE = /^\/[^/]/;
  10827. function escapeToLinuxLikePath(path) {
  10828. if (windowsDriveRE.test(path)) {
  10829. return path.replace(replaceWindowsDriveRE, '/windows/$1/');
  10830. }
  10831. if (linuxAbsolutePathRE.test(path)) {
  10832. return `/linux${path}`;
  10833. }
  10834. return path;
  10835. }
  10836. const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
  10837. function unescapeToLinuxLikePath(path) {
  10838. if (path.startsWith('/linux/')) {
  10839. return path.slice('/linux'.length);
  10840. }
  10841. if (path.startsWith('/windows/')) {
  10842. return path.replace(revertWindowsDriveRE, '$1:/');
  10843. }
  10844. return path;
  10845. }
  10846. // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
  10847. const nullSourceMap = {
  10848. names: [],
  10849. sources: [],
  10850. mappings: '',
  10851. version: 3,
  10852. };
  10853. function combineSourcemaps(filename, sourcemapList) {
  10854. if (sourcemapList.length === 0 ||
  10855. sourcemapList.every((m) => m.sources.length === 0)) {
  10856. return { ...nullSourceMap };
  10857. }
  10858. // hack for parse broken with normalized absolute paths on windows (C:/path/to/something).
  10859. // escape them to linux like paths
  10860. // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442)
  10861. sourcemapList = sourcemapList.map((sourcemap) => {
  10862. const newSourcemaps = { ...sourcemap };
  10863. newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
  10864. if (sourcemap.sourceRoot) {
  10865. newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
  10866. }
  10867. return newSourcemaps;
  10868. });
  10869. const escapedFilename = escapeToLinuxLikePath(filename);
  10870. // We don't declare type here so we can convert/fake/map as RawSourceMap
  10871. let map; //: SourceMap
  10872. let mapIndex = 1;
  10873. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined;
  10874. if (useArrayInterface) {
  10875. map = remapping(sourcemapList, () => null);
  10876. }
  10877. else {
  10878. map = remapping(sourcemapList[0], function loader(sourcefile) {
  10879. if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
  10880. return sourcemapList[mapIndex++];
  10881. }
  10882. else {
  10883. return null;
  10884. }
  10885. });
  10886. }
  10887. if (!map.file) {
  10888. delete map.file;
  10889. }
  10890. // unescape the previous hack
  10891. map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
  10892. map.file = filename;
  10893. return map;
  10894. }
  10895. function unique(arr) {
  10896. return Array.from(new Set(arr));
  10897. }
  10898. /**
  10899. * Returns resolved localhost address when `dns.lookup` result differs from DNS
  10900. *
  10901. * `dns.lookup` result is same when defaultResultOrder is `verbatim`.
  10902. * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
  10903. * For example, when IPv6 is not supported on that machine/network.
  10904. */
  10905. async function getLocalhostAddressIfDiffersFromDNS() {
  10906. const [nodeResult, dnsResult] = await Promise.all([
  10907. promises.lookup('localhost'),
  10908. promises.lookup('localhost', { verbatim: true }),
  10909. ]);
  10910. const isSame = nodeResult.family === dnsResult.family &&
  10911. nodeResult.address === dnsResult.address;
  10912. return isSame ? undefined : nodeResult.address;
  10913. }
  10914. function diffDnsOrderChange(oldUrls, newUrls) {
  10915. return !(oldUrls === newUrls ||
  10916. (oldUrls &&
  10917. newUrls &&
  10918. arrayEqual(oldUrls.local, newUrls.local) &&
  10919. arrayEqual(oldUrls.network, newUrls.network)));
  10920. }
  10921. async function resolveHostname(optionsHost) {
  10922. let host;
  10923. if (optionsHost === undefined || optionsHost === false) {
  10924. // Use a secure default
  10925. host = 'localhost';
  10926. }
  10927. else if (optionsHost === true) {
  10928. // If passed --host in the CLI without arguments
  10929. host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
  10930. }
  10931. else {
  10932. host = optionsHost;
  10933. }
  10934. // Set host name to localhost when possible
  10935. let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host;
  10936. if (host === 'localhost') {
  10937. // See #8647 for more details.
  10938. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
  10939. if (localhostAddr) {
  10940. name = localhostAddr;
  10941. }
  10942. }
  10943. return { host, name };
  10944. }
  10945. async function resolveServerUrls(server, options, config) {
  10946. const address = server.address();
  10947. const isAddressInfo = (x) => x?.address;
  10948. if (!isAddressInfo(address)) {
  10949. return { local: [], network: [] };
  10950. }
  10951. const local = [];
  10952. const network = [];
  10953. const hostname = await resolveHostname(options.host);
  10954. const protocol = options.https ? 'https' : 'http';
  10955. const port = address.port;
  10956. const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase;
  10957. if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) {
  10958. let hostnameName = hostname.name;
  10959. // ipv6 host
  10960. if (hostnameName.includes(':')) {
  10961. hostnameName = `[${hostnameName}]`;
  10962. }
  10963. const address = `${protocol}://${hostnameName}:${port}${base}`;
  10964. if (loopbackHosts.has(hostname.host)) {
  10965. local.push(address);
  10966. }
  10967. else {
  10968. network.push(address);
  10969. }
  10970. }
  10971. else {
  10972. Object.values(os$4.networkInterfaces())
  10973. .flatMap((nInterface) => nInterface ?? [])
  10974. .filter((detail) => detail &&
  10975. detail.address &&
  10976. (detail.family === 'IPv4' ||
  10977. // @ts-expect-error Node 18.0 - 18.3 returns number
  10978. detail.family === 4))
  10979. .forEach((detail) => {
  10980. let host = detail.address.replace('127.0.0.1', hostname.name);
  10981. // ipv6 host
  10982. if (host.includes(':')) {
  10983. host = `[${host}]`;
  10984. }
  10985. const url = `${protocol}://${host}:${port}${base}`;
  10986. if (detail.address.includes('127.0.0.1')) {
  10987. local.push(url);
  10988. }
  10989. else {
  10990. network.push(url);
  10991. }
  10992. });
  10993. }
  10994. return { local, network };
  10995. }
  10996. function arraify(target) {
  10997. return Array.isArray(target) ? target : [target];
  10998. }
  10999. // Taken from https://stackoverflow.com/a/36328890
  11000. const multilineCommentsRE$1 = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
  11001. const singlelineCommentsRE$1 = /\/\/.*/g;
  11002. const requestQuerySplitRE = /\?(?!.*[/|}])/;
  11003. // @ts-expect-error jest only exists when running Jest
  11004. const usingDynamicImport = typeof jest === 'undefined';
  11005. /**
  11006. * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
  11007. *
  11008. * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
  11009. * if we're in a Jest environment.
  11010. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
  11011. *
  11012. * @param file File path to import.
  11013. */
  11014. const dynamicImport = usingDynamicImport
  11015. ? new Function('file', 'return import(file)')
  11016. : _require$3;
  11017. function parseRequest(id) {
  11018. const [_, search] = id.split(requestQuerySplitRE, 2);
  11019. if (!search) {
  11020. return null;
  11021. }
  11022. return Object.fromEntries(new URLSearchParams(search));
  11023. }
  11024. const blankReplacer = (match) => ' '.repeat(match.length);
  11025. function getHash(text) {
  11026. return createHash$2('sha256').update(text).digest('hex').substring(0, 8);
  11027. }
  11028. const _dirname = path$o.dirname(fileURLToPath(import.meta.url));
  11029. const requireResolveFromRootWithFallback = (root, id) => {
  11030. // check existence first, so if the package is not found,
  11031. // it won't be cached by nodejs, since there isn't a way to invalidate them:
  11032. // https://github.com/nodejs/node/issues/44663
  11033. const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname);
  11034. if (!found) {
  11035. const error = new Error(`${JSON.stringify(id)} not found.`);
  11036. error.code = 'MODULE_NOT_FOUND';
  11037. throw error;
  11038. }
  11039. // actually resolve
  11040. // Search in the root directory first, and fallback to the default require paths.
  11041. return _require$3.resolve(id, { paths: [root, _dirname] });
  11042. };
  11043. function emptyCssComments(raw) {
  11044. return raw.replace(multilineCommentsRE$1, (s) => ' '.repeat(s.length));
  11045. }
  11046. function removeComments(raw) {
  11047. return raw.replace(multilineCommentsRE$1, '').replace(singlelineCommentsRE$1, '');
  11048. }
  11049. function mergeConfigRecursively(defaults, overrides, rootPath) {
  11050. const merged = { ...defaults };
  11051. for (const key in overrides) {
  11052. const value = overrides[key];
  11053. if (value == null) {
  11054. continue;
  11055. }
  11056. const existing = merged[key];
  11057. if (existing == null) {
  11058. merged[key] = value;
  11059. continue;
  11060. }
  11061. // fields that require special handling
  11062. if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
  11063. merged[key] = mergeAlias(existing, value);
  11064. continue;
  11065. }
  11066. else if (key === 'assetsInclude' && rootPath === '') {
  11067. merged[key] = [].concat(existing, value);
  11068. continue;
  11069. }
  11070. else if (key === 'noExternal' &&
  11071. rootPath === 'ssr' &&
  11072. (existing === true || value === true)) {
  11073. merged[key] = true;
  11074. continue;
  11075. }
  11076. if (Array.isArray(existing) || Array.isArray(value)) {
  11077. merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])];
  11078. continue;
  11079. }
  11080. if (isObject$2(existing) && isObject$2(value)) {
  11081. merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
  11082. continue;
  11083. }
  11084. merged[key] = value;
  11085. }
  11086. return merged;
  11087. }
  11088. function mergeConfig(defaults, overrides, isRoot = true) {
  11089. if (typeof defaults === 'function' || typeof overrides === 'function') {
  11090. throw new Error(`Cannot merge config in form of callback`);
  11091. }
  11092. return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.');
  11093. }
  11094. function mergeAlias(a, b) {
  11095. if (!a)
  11096. return b;
  11097. if (!b)
  11098. return a;
  11099. if (isObject$2(a) && isObject$2(b)) {
  11100. return { ...a, ...b };
  11101. }
  11102. // the order is flipped because the alias is resolved from top-down,
  11103. // where the later should have higher priority
  11104. return [...normalizeAlias(b), ...normalizeAlias(a)];
  11105. }
  11106. function normalizeAlias(o = []) {
  11107. return Array.isArray(o)
  11108. ? o.map(normalizeSingleAlias)
  11109. : Object.keys(o).map((find) => normalizeSingleAlias({
  11110. find,
  11111. replacement: o[find],
  11112. }));
  11113. }
  11114. // https://github.com/vitejs/vite/issues/1363
  11115. // work around https://github.com/rollup/plugins/issues/759
  11116. function normalizeSingleAlias({ find, replacement, customResolver, }) {
  11117. if (typeof find === 'string' &&
  11118. find[find.length - 1] === '/' &&
  11119. replacement[replacement.length - 1] === '/') {
  11120. find = find.slice(0, find.length - 1);
  11121. replacement = replacement.slice(0, replacement.length - 1);
  11122. }
  11123. const alias = {
  11124. find,
  11125. replacement,
  11126. };
  11127. if (customResolver) {
  11128. alias.customResolver = customResolver;
  11129. }
  11130. return alias;
  11131. }
  11132. /**
  11133. * Transforms transpiled code result where line numbers aren't altered,
  11134. * so we can skip sourcemap generation during dev
  11135. */
  11136. function transformStableResult(s, id, config) {
  11137. return {
  11138. code: s.toString(),
  11139. map: config.command === 'build' && config.build.sourcemap
  11140. ? s.generateMap({ hires: 'boundary', source: id })
  11141. : null,
  11142. };
  11143. }
  11144. async function asyncFlatten(arr) {
  11145. do {
  11146. arr = (await Promise.all(arr)).flat(Infinity);
  11147. } while (arr.some((v) => v?.then));
  11148. return arr;
  11149. }
  11150. // strip UTF-8 BOM
  11151. function stripBomTag(content) {
  11152. if (content.charCodeAt(0) === 0xfeff) {
  11153. return content.slice(1);
  11154. }
  11155. return content;
  11156. }
  11157. const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
  11158. /**
  11159. * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something)
  11160. * this function returns false for them but true for absolute paths (e.g. C:/something)
  11161. */
  11162. const isNonDriveRelativeAbsolutePath = (p) => {
  11163. if (!isWindows$4)
  11164. return p[0] === '/';
  11165. return windowsDrivePathPrefixRE.test(p);
  11166. };
  11167. /**
  11168. * Determine if a file is being requested with the correct case, to ensure
  11169. * consistent behaviour between dev and prod and across operating systems.
  11170. */
  11171. function shouldServeFile(filePath, root) {
  11172. // can skip case check on Linux
  11173. if (!isCaseInsensitiveFS)
  11174. return true;
  11175. return hasCorrectCase(filePath, root);
  11176. }
  11177. /**
  11178. * Note that we can't use realpath here, because we don't want to follow
  11179. * symlinks.
  11180. */
  11181. function hasCorrectCase(file, assets) {
  11182. if (file === assets)
  11183. return true;
  11184. const parent = path$o.dirname(file);
  11185. if (fs$l.readdirSync(parent).includes(path$o.basename(file))) {
  11186. return hasCorrectCase(parent, assets);
  11187. }
  11188. return false;
  11189. }
  11190. function joinUrlSegments(a, b) {
  11191. if (!a || !b) {
  11192. return a || b || '';
  11193. }
  11194. if (a[a.length - 1] === '/') {
  11195. a = a.substring(0, a.length - 1);
  11196. }
  11197. if (b[0] !== '/') {
  11198. b = '/' + b;
  11199. }
  11200. return a + b;
  11201. }
  11202. function removeLeadingSlash(str) {
  11203. return str[0] === '/' ? str.slice(1) : str;
  11204. }
  11205. function stripBase(path, base) {
  11206. if (path === base) {
  11207. return '/';
  11208. }
  11209. const devBase = withTrailingSlash(base);
  11210. return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
  11211. }
  11212. function arrayEqual(a, b) {
  11213. if (a === b)
  11214. return true;
  11215. if (a.length !== b.length)
  11216. return false;
  11217. for (let i = 0; i < a.length; i++) {
  11218. if (a[i] !== b[i])
  11219. return false;
  11220. }
  11221. return true;
  11222. }
  11223. function evalValue(rawValue) {
  11224. const fn = new Function(`
  11225. var console, exports, global, module, process, require
  11226. return (\n${rawValue}\n)
  11227. `);
  11228. return fn();
  11229. }
  11230. function getNpmPackageName(importPath) {
  11231. const parts = importPath.split('/');
  11232. if (parts[0][0] === '@') {
  11233. if (!parts[1])
  11234. return null;
  11235. return `${parts[0]}/${parts[1]}`;
  11236. }
  11237. else {
  11238. return parts[0];
  11239. }
  11240. }
  11241. const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
  11242. function escapeRegex(str) {
  11243. return str.replace(escapeRegexRE, '\\$&');
  11244. }
  11245. function getPackageManagerCommand(type = 'install') {
  11246. const packageManager = process.env.npm_config_user_agent?.split(' ')[0].split('/')[0] || 'npm';
  11247. switch (type) {
  11248. case 'install':
  11249. return packageManager === 'npm' ? 'npm install' : `${packageManager} add`;
  11250. case 'uninstall':
  11251. return packageManager === 'npm'
  11252. ? 'npm uninstall'
  11253. : `${packageManager} remove`;
  11254. case 'update':
  11255. return packageManager === 'yarn'
  11256. ? 'yarn upgrade'
  11257. : `${packageManager} update`;
  11258. default:
  11259. throw new TypeError(`Unknown command type: ${type}`);
  11260. }
  11261. }
  11262. /* eslint no-console: 0 */
  11263. const LogLevels = {
  11264. silent: 0,
  11265. error: 1,
  11266. warn: 2,
  11267. info: 3,
  11268. };
  11269. let lastType;
  11270. let lastMsg;
  11271. let sameCount = 0;
  11272. function clearScreen() {
  11273. const repeatCount = process.stdout.rows - 2;
  11274. const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
  11275. console.log(blank);
  11276. readline.cursorTo(process.stdout, 0, 0);
  11277. readline.clearScreenDown(process.stdout);
  11278. }
  11279. function createLogger(level = 'info', options = {}) {
  11280. if (options.customLogger) {
  11281. return options.customLogger;
  11282. }
  11283. const timeFormatter = new Intl.DateTimeFormat(undefined, {
  11284. hour: 'numeric',
  11285. minute: 'numeric',
  11286. second: 'numeric',
  11287. });
  11288. const loggedErrors = new WeakSet();
  11289. const { prefix = '[vite]', allowClearScreen = true } = options;
  11290. const thresh = LogLevels[level];
  11291. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  11292. const clear = canClearScreen ? clearScreen : () => { };
  11293. function output(type, msg, options = {}) {
  11294. if (thresh >= LogLevels[type]) {
  11295. const method = type === 'info' ? 'log' : type;
  11296. const format = () => {
  11297. if (options.timestamp) {
  11298. const tag = type === 'info'
  11299. ? colors$1.cyan(colors$1.bold(prefix))
  11300. : type === 'warn'
  11301. ? colors$1.yellow(colors$1.bold(prefix))
  11302. : colors$1.red(colors$1.bold(prefix));
  11303. return `${colors$1.dim(timeFormatter.format(new Date()))} ${tag} ${msg}`;
  11304. }
  11305. else {
  11306. return msg;
  11307. }
  11308. };
  11309. if (options.error) {
  11310. loggedErrors.add(options.error);
  11311. }
  11312. if (canClearScreen) {
  11313. if (type === lastType && msg === lastMsg) {
  11314. sameCount++;
  11315. clear();
  11316. console[method](format(), colors$1.yellow(`(x${sameCount + 1})`));
  11317. }
  11318. else {
  11319. sameCount = 0;
  11320. lastMsg = msg;
  11321. lastType = type;
  11322. if (options.clear) {
  11323. clear();
  11324. }
  11325. console[method](format());
  11326. }
  11327. }
  11328. else {
  11329. console[method](format());
  11330. }
  11331. }
  11332. }
  11333. const warnedMessages = new Set();
  11334. const logger = {
  11335. hasWarned: false,
  11336. info(msg, opts) {
  11337. output('info', msg, opts);
  11338. },
  11339. warn(msg, opts) {
  11340. logger.hasWarned = true;
  11341. output('warn', msg, opts);
  11342. },
  11343. warnOnce(msg, opts) {
  11344. if (warnedMessages.has(msg))
  11345. return;
  11346. logger.hasWarned = true;
  11347. output('warn', msg, opts);
  11348. warnedMessages.add(msg);
  11349. },
  11350. error(msg, opts) {
  11351. logger.hasWarned = true;
  11352. output('error', msg, opts);
  11353. },
  11354. clearScreen(type) {
  11355. if (thresh >= LogLevels[type]) {
  11356. clear();
  11357. }
  11358. },
  11359. hasErrorLogged(error) {
  11360. return loggedErrors.has(error);
  11361. },
  11362. };
  11363. return logger;
  11364. }
  11365. function printServerUrls(urls, optionsHost, info) {
  11366. const colorUrl = (url) => colors$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`));
  11367. for (const url of urls.local) {
  11368. info(` ${colors$1.green('➜')} ${colors$1.bold('Local')}: ${colorUrl(url)}`);
  11369. }
  11370. for (const url of urls.network) {
  11371. info(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: ${colorUrl(url)}`);
  11372. }
  11373. if (urls.network.length === 0 && optionsHost === undefined) {
  11374. info(colors$1.dim(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: use `) +
  11375. colors$1.bold('--host') +
  11376. colors$1.dim(' to expose'));
  11377. }
  11378. }
  11379. const groups = [
  11380. { name: 'Assets', color: colors$1.green },
  11381. { name: 'CSS', color: colors$1.magenta },
  11382. { name: 'JS', color: colors$1.cyan },
  11383. ];
  11384. const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/;
  11385. function buildReporterPlugin(config) {
  11386. const compress = promisify$4(gzip);
  11387. const chunkLimit = config.build.chunkSizeWarningLimit;
  11388. const numberFormatter = new Intl.NumberFormat('en', {
  11389. maximumFractionDigits: 2,
  11390. minimumFractionDigits: 2,
  11391. });
  11392. const displaySize = (bytes) => {
  11393. return `${numberFormatter.format(bytes / 1000)} kB`;
  11394. };
  11395. const tty = process.stdout.isTTY && !process.env.CI;
  11396. const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info;
  11397. let hasTransformed = false;
  11398. let hasRenderedChunk = false;
  11399. let hasCompressChunk = false;
  11400. let transformedCount = 0;
  11401. let chunkCount = 0;
  11402. let compressedCount = 0;
  11403. let startTime = Date.now();
  11404. async function getCompressedSize(code) {
  11405. if (config.build.ssr || !config.build.reportCompressedSize) {
  11406. return null;
  11407. }
  11408. if (shouldLogInfo && !hasCompressChunk) {
  11409. if (!tty) {
  11410. config.logger.info('computing gzip size...');
  11411. }
  11412. else {
  11413. writeLine('computing gzip size (0)...');
  11414. }
  11415. hasCompressChunk = true;
  11416. }
  11417. const compressed = await compress(typeof code === 'string' ? code : Buffer.from(code));
  11418. compressedCount++;
  11419. if (shouldLogInfo && tty) {
  11420. writeLine(`computing gzip size (${compressedCount})...`);
  11421. }
  11422. return compressed.length;
  11423. }
  11424. const logTransform = throttle((id) => {
  11425. writeLine(`transforming (${transformedCount}) ${colors$1.dim(path$o.relative(config.root, id))}`);
  11426. });
  11427. return {
  11428. name: 'vite:reporter',
  11429. transform(_, id) {
  11430. transformedCount++;
  11431. if (shouldLogInfo) {
  11432. if (!tty) {
  11433. if (!hasTransformed) {
  11434. config.logger.info(`transforming...`);
  11435. }
  11436. }
  11437. else {
  11438. if (id.includes(`?`))
  11439. return;
  11440. logTransform(id);
  11441. }
  11442. hasTransformed = true;
  11443. }
  11444. return null;
  11445. },
  11446. options() {
  11447. startTime = Date.now();
  11448. },
  11449. buildStart() {
  11450. transformedCount = 0;
  11451. },
  11452. buildEnd() {
  11453. if (shouldLogInfo) {
  11454. if (tty) {
  11455. clearLine();
  11456. }
  11457. config.logger.info(`${colors$1.green(`✓`)} ${transformedCount} modules transformed.`);
  11458. }
  11459. },
  11460. renderStart() {
  11461. chunkCount = 0;
  11462. compressedCount = 0;
  11463. },
  11464. renderChunk(code, chunk, options) {
  11465. if (!options.inlineDynamicImports) {
  11466. for (const id of chunk.moduleIds) {
  11467. const module = this.getModuleInfo(id);
  11468. if (!module)
  11469. continue;
  11470. // When a dynamic importer shares a chunk with the imported module,
  11471. // warn that the dynamic imported module will not be moved to another chunk (#12850).
  11472. if (module.importers.length && module.dynamicImporters.length) {
  11473. // Filter out the intersection of dynamic importers and sibling modules in
  11474. // the same chunk. The intersecting dynamic importers' dynamic import is not
  11475. // expected to work. Note we're only detecting the direct ineffective
  11476. // dynamic import here.
  11477. const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules(id) && chunk.moduleIds.includes(id));
  11478. if (detectedIneffectiveDynamicImport) {
  11479. this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`);
  11480. }
  11481. }
  11482. }
  11483. }
  11484. chunkCount++;
  11485. if (shouldLogInfo) {
  11486. if (!tty) {
  11487. if (!hasRenderedChunk) {
  11488. config.logger.info('rendering chunks...');
  11489. }
  11490. }
  11491. else {
  11492. writeLine(`rendering chunks (${chunkCount})...`);
  11493. }
  11494. hasRenderedChunk = true;
  11495. }
  11496. return null;
  11497. },
  11498. generateBundle() {
  11499. if (shouldLogInfo && tty)
  11500. clearLine();
  11501. },
  11502. async writeBundle({ dir: outDir }, output) {
  11503. let hasLargeChunks = false;
  11504. if (shouldLogInfo) {
  11505. const entries = (await Promise.all(Object.values(output).map(async (chunk) => {
  11506. if (chunk.type === 'chunk') {
  11507. return {
  11508. name: chunk.fileName,
  11509. group: 'JS',
  11510. size: chunk.code.length,
  11511. compressedSize: await getCompressedSize(chunk.code),
  11512. mapSize: chunk.map ? chunk.map.toString().length : null,
  11513. };
  11514. }
  11515. else {
  11516. if (chunk.fileName.endsWith('.map'))
  11517. return null;
  11518. const isCSS = chunk.fileName.endsWith('.css');
  11519. const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
  11520. return {
  11521. name: chunk.fileName,
  11522. group: isCSS ? 'CSS' : 'Assets',
  11523. size: chunk.source.length,
  11524. mapSize: null,
  11525. compressedSize: isCompressible
  11526. ? await getCompressedSize(chunk.source)
  11527. : null,
  11528. };
  11529. }
  11530. }))).filter(isDefined);
  11531. if (tty)
  11532. clearLine();
  11533. let longest = 0;
  11534. let biggestSize = 0;
  11535. let biggestMap = 0;
  11536. let biggestCompressSize = 0;
  11537. for (const entry of entries) {
  11538. if (entry.name.length > longest)
  11539. longest = entry.name.length;
  11540. if (entry.size > biggestSize)
  11541. biggestSize = entry.size;
  11542. if (entry.mapSize && entry.mapSize > biggestMap) {
  11543. biggestMap = entry.mapSize;
  11544. }
  11545. if (entry.compressedSize &&
  11546. entry.compressedSize > biggestCompressSize) {
  11547. biggestCompressSize = entry.compressedSize;
  11548. }
  11549. }
  11550. const sizePad = displaySize(biggestSize).length;
  11551. const mapPad = displaySize(biggestMap).length;
  11552. const compressPad = displaySize(biggestCompressSize).length;
  11553. const relativeOutDir = normalizePath$3(path$o.relative(config.root, path$o.resolve(config.root, outDir ?? config.build.outDir)));
  11554. const assetsDir = path$o.join(config.build.assetsDir, '/');
  11555. for (const group of groups) {
  11556. const filtered = entries.filter((e) => e.group === group.name);
  11557. if (!filtered.length)
  11558. continue;
  11559. for (const entry of filtered.sort((a, z) => a.size - z.size)) {
  11560. const isLarge = group.name === 'JS' && entry.size / 1000 > chunkLimit;
  11561. if (isLarge)
  11562. hasLargeChunks = true;
  11563. const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
  11564. let log = colors$1.dim(withTrailingSlash(relativeOutDir));
  11565. log +=
  11566. !config.build.lib &&
  11567. entry.name.startsWith(withTrailingSlash(assetsDir))
  11568. ? colors$1.dim(assetsDir) +
  11569. group.color(entry.name
  11570. .slice(assetsDir.length)
  11571. .padEnd(longest + 2 - assetsDir.length))
  11572. : group.color(entry.name.padEnd(longest + 2));
  11573. log += colors$1.bold(sizeColor(displaySize(entry.size).padStart(sizePad)));
  11574. if (entry.compressedSize) {
  11575. log += colors$1.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`);
  11576. }
  11577. if (entry.mapSize) {
  11578. log += colors$1.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`);
  11579. }
  11580. config.logger.info(log);
  11581. }
  11582. }
  11583. }
  11584. else {
  11585. hasLargeChunks = Object.values(output).some((chunk) => {
  11586. return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit;
  11587. });
  11588. }
  11589. if (hasLargeChunks &&
  11590. config.build.minify &&
  11591. !config.build.lib &&
  11592. !config.build.ssr) {
  11593. config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` +
  11594. `- Using dynamic import() to code-split the application\n` +
  11595. `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` +
  11596. `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
  11597. }
  11598. },
  11599. closeBundle() {
  11600. if (shouldLogInfo && !config.build.watch) {
  11601. config.logger.info(`${colors$1.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`);
  11602. }
  11603. },
  11604. };
  11605. }
  11606. function writeLine(output) {
  11607. clearLine();
  11608. if (output.length < process.stdout.columns) {
  11609. process.stdout.write(output);
  11610. }
  11611. else {
  11612. process.stdout.write(output.substring(0, process.stdout.columns - 1));
  11613. }
  11614. }
  11615. function clearLine() {
  11616. process.stdout.clearLine(0);
  11617. process.stdout.cursorTo(0);
  11618. }
  11619. function throttle(fn) {
  11620. let timerHandle = null;
  11621. return (...args) => {
  11622. if (timerHandle)
  11623. return;
  11624. fn(...args);
  11625. timerHandle = setTimeout(() => {
  11626. timerHandle = null;
  11627. }, 100);
  11628. };
  11629. }
  11630. function displayTime(time) {
  11631. // display: {X}ms
  11632. if (time < 1000) {
  11633. return `${time}ms`;
  11634. }
  11635. time = time / 1000;
  11636. // display: {X}s
  11637. if (time < 60) {
  11638. return `${time.toFixed(2)}s`;
  11639. }
  11640. const mins = parseInt((time / 60).toString());
  11641. const seconds = time % 60;
  11642. // display: {X}m {Y}s
  11643. return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`;
  11644. }
  11645. // src/find.ts
  11646. async function find(filename, options) {
  11647. let dir = require$$0$4.dirname(require$$0$4.resolve(filename));
  11648. const root = (options == null ? void 0 : options.root) ? require$$0$4.resolve(options.root) : null;
  11649. while (dir) {
  11650. const tsconfig = await tsconfigInDir(dir, options);
  11651. if (tsconfig) {
  11652. return tsconfig;
  11653. } else {
  11654. if (root === dir) {
  11655. break;
  11656. }
  11657. const parent = require$$0$4.dirname(dir);
  11658. if (parent === dir) {
  11659. break;
  11660. } else {
  11661. dir = parent;
  11662. }
  11663. }
  11664. }
  11665. throw new Error(`no tsconfig file found for ${filename}`);
  11666. }
  11667. async function tsconfigInDir(dir, options) {
  11668. const tsconfig = require$$0$4.join(dir, "tsconfig.json");
  11669. if (options == null ? void 0 : options.tsConfigPaths) {
  11670. return options.tsConfigPaths.has(tsconfig) ? tsconfig : void 0;
  11671. }
  11672. try {
  11673. const stat = await promises$1.stat(tsconfig);
  11674. if (stat.isFile() || stat.isFIFO()) {
  11675. return tsconfig;
  11676. }
  11677. } catch (e) {
  11678. if (e.code !== "ENOENT") {
  11679. throw e;
  11680. }
  11681. }
  11682. }
  11683. var sep = require$$0$4.sep;
  11684. async function findAll(dir, options) {
  11685. const state = {
  11686. files: [],
  11687. calls: 0,
  11688. skip: options == null ? void 0 : options.skip,
  11689. err: false
  11690. };
  11691. return new Promise((resolve, reject) => {
  11692. walk$3(require$$0$4.resolve(dir), state, (err, files) => err ? reject(err) : resolve(files));
  11693. });
  11694. }
  11695. function walk$3(dir, state, done) {
  11696. if (state.err) {
  11697. return;
  11698. }
  11699. state.calls++;
  11700. readdir$4(dir, { withFileTypes: true }, (err, entries = []) => {
  11701. var _a;
  11702. if (state.err) {
  11703. return;
  11704. }
  11705. if (err && !(err.code === "ENOENT" || err.code === "EACCES" || err.code === "EPERM")) {
  11706. state.err = true;
  11707. done(err);
  11708. } else {
  11709. for (const ent of entries) {
  11710. if (ent.isDirectory() && !((_a = state.skip) == null ? void 0 : _a.call(state, ent.name))) {
  11711. walk$3(`${dir}${sep}${ent.name}`, state, done);
  11712. } else if (ent.isFile() && ent.name === "tsconfig.json") {
  11713. state.files.push(`${dir}${sep}tsconfig.json`);
  11714. }
  11715. }
  11716. if (--state.calls === 0) {
  11717. if (!state.err) {
  11718. done(null, state.files);
  11719. }
  11720. }
  11721. }
  11722. });
  11723. }
  11724. // src/to-json.ts
  11725. function toJson(tsconfigJson) {
  11726. const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
  11727. if (stripped.trim() === "") {
  11728. return "{}";
  11729. } else {
  11730. return stripped;
  11731. }
  11732. }
  11733. function stripDanglingComma(pseudoJson) {
  11734. let insideString = false;
  11735. let offset = 0;
  11736. let result = "";
  11737. let danglingCommaPos = null;
  11738. for (let i = 0; i < pseudoJson.length; i++) {
  11739. const currentCharacter = pseudoJson[i];
  11740. if (currentCharacter === '"') {
  11741. const escaped = isEscaped(pseudoJson, i);
  11742. if (!escaped) {
  11743. insideString = !insideString;
  11744. }
  11745. }
  11746. if (insideString) {
  11747. danglingCommaPos = null;
  11748. continue;
  11749. }
  11750. if (currentCharacter === ",") {
  11751. danglingCommaPos = i;
  11752. continue;
  11753. }
  11754. if (danglingCommaPos) {
  11755. if (currentCharacter === "}" || currentCharacter === "]") {
  11756. result += pseudoJson.slice(offset, danglingCommaPos) + " ";
  11757. offset = danglingCommaPos + 1;
  11758. danglingCommaPos = null;
  11759. } else if (!currentCharacter.match(/\s/)) {
  11760. danglingCommaPos = null;
  11761. }
  11762. }
  11763. }
  11764. return result + pseudoJson.substring(offset);
  11765. }
  11766. function isEscaped(jsonString, quotePosition) {
  11767. let index = quotePosition - 1;
  11768. let backslashCount = 0;
  11769. while (jsonString[index] === "\\") {
  11770. index -= 1;
  11771. backslashCount += 1;
  11772. }
  11773. return Boolean(backslashCount % 2);
  11774. }
  11775. function strip(string, start, end) {
  11776. return string.slice(start, end).replace(/\S/g, " ");
  11777. }
  11778. var singleComment = Symbol("singleComment");
  11779. var multiComment = Symbol("multiComment");
  11780. function stripJsonComments(jsonString) {
  11781. let isInsideString = false;
  11782. let isInsideComment = false;
  11783. let offset = 0;
  11784. let result = "";
  11785. for (let index = 0; index < jsonString.length; index++) {
  11786. const currentCharacter = jsonString[index];
  11787. const nextCharacter = jsonString[index + 1];
  11788. if (!isInsideComment && currentCharacter === '"') {
  11789. const escaped = isEscaped(jsonString, index);
  11790. if (!escaped) {
  11791. isInsideString = !isInsideString;
  11792. }
  11793. }
  11794. if (isInsideString) {
  11795. continue;
  11796. }
  11797. if (!isInsideComment && currentCharacter + nextCharacter === "//") {
  11798. result += jsonString.slice(offset, index);
  11799. offset = index;
  11800. isInsideComment = singleComment;
  11801. index++;
  11802. } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
  11803. index++;
  11804. isInsideComment = false;
  11805. result += strip(jsonString, offset, index);
  11806. offset = index;
  11807. } else if (isInsideComment === singleComment && currentCharacter === "\n") {
  11808. isInsideComment = false;
  11809. result += strip(jsonString, offset, index);
  11810. offset = index;
  11811. } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
  11812. result += jsonString.slice(offset, index);
  11813. offset = index;
  11814. isInsideComment = multiComment;
  11815. index++;
  11816. } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
  11817. index++;
  11818. isInsideComment = false;
  11819. result += strip(jsonString, offset, index + 1);
  11820. offset = index + 1;
  11821. }
  11822. }
  11823. return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
  11824. }
  11825. function stripBom(string) {
  11826. if (string.charCodeAt(0) === 65279) {
  11827. return string.slice(1);
  11828. }
  11829. return string;
  11830. }
  11831. var POSIX_SEP_RE = new RegExp("\\" + require$$0$4.posix.sep, "g");
  11832. var NATIVE_SEP_RE = new RegExp("\\" + require$$0$4.sep, "g");
  11833. var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
  11834. var GLOB_ALL_PATTERN = `**/*`;
  11835. var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
  11836. var DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join(
  11837. "|"
  11838. )})`;
  11839. new Function("path", "return import(path).then(m => m.default)");
  11840. async function resolveTSConfig(filename) {
  11841. if (require$$0$4.extname(filename) !== ".json") {
  11842. return;
  11843. }
  11844. const tsconfig = require$$0$4.resolve(filename);
  11845. try {
  11846. const stat = await promises$1.stat(tsconfig);
  11847. if (stat.isFile() || stat.isFIFO()) {
  11848. return tsconfig;
  11849. }
  11850. } catch (e) {
  11851. if (e.code !== "ENOENT") {
  11852. throw e;
  11853. }
  11854. }
  11855. throw new Error(`no tsconfig file found for ${filename}`);
  11856. }
  11857. function posix2native(filename) {
  11858. return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.posix.sep) ? filename.replace(POSIX_SEP_RE, require$$0$4.sep) : filename;
  11859. }
  11860. function native2posix(filename) {
  11861. return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.sep) ? filename.replace(NATIVE_SEP_RE, require$$0$4.posix.sep) : filename;
  11862. }
  11863. function resolve2posix(dir, filename) {
  11864. if (require$$0$4.sep === require$$0$4.posix.sep) {
  11865. return dir ? require$$0$4.resolve(dir, filename) : require$$0$4.resolve(filename);
  11866. }
  11867. return native2posix(
  11868. dir ? require$$0$4.resolve(posix2native(dir), posix2native(filename)) : require$$0$4.resolve(posix2native(filename))
  11869. );
  11870. }
  11871. function resolveReferencedTSConfigFiles(result) {
  11872. const dir = require$$0$4.dirname(result.tsconfigFile);
  11873. return result.tsconfig.references.map((ref) => {
  11874. const refPath = ref.path.endsWith(".json") ? ref.path : require$$0$4.join(ref.path, "tsconfig.json");
  11875. return resolve2posix(dir, refPath);
  11876. });
  11877. }
  11878. function resolveSolutionTSConfig(filename, result) {
  11879. if (result.referenced && DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) {
  11880. const solutionTSConfig = result.referenced.find(
  11881. (referenced) => isIncluded(filename, referenced)
  11882. );
  11883. if (solutionTSConfig) {
  11884. return {
  11885. ...solutionTSConfig,
  11886. solution: result
  11887. };
  11888. }
  11889. }
  11890. return result;
  11891. }
  11892. function isIncluded(filename, result) {
  11893. const dir = native2posix(require$$0$4.dirname(result.tsconfigFile));
  11894. const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
  11895. const absoluteFilename = resolve2posix(null, filename);
  11896. if (files.includes(filename)) {
  11897. return true;
  11898. }
  11899. const isIncluded2 = isGlobMatch(
  11900. absoluteFilename,
  11901. dir,
  11902. result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN])
  11903. );
  11904. if (isIncluded2) {
  11905. const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []);
  11906. return !isExcluded;
  11907. }
  11908. return false;
  11909. }
  11910. function isGlobMatch(filename, dir, patterns) {
  11911. return patterns.some((pattern) => {
  11912. let lastWildcardIndex = pattern.length;
  11913. let hasWildcard = false;
  11914. for (let i = pattern.length - 1; i > -1; i--) {
  11915. if (pattern[i] === "*" || pattern[i] === "?") {
  11916. lastWildcardIndex = i;
  11917. hasWildcard = true;
  11918. break;
  11919. }
  11920. }
  11921. if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) {
  11922. return false;
  11923. }
  11924. if (pattern.endsWith("*") && !DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext))) {
  11925. return false;
  11926. }
  11927. if (pattern === GLOB_ALL_PATTERN) {
  11928. return filename.startsWith(`${dir}/`);
  11929. }
  11930. const resolvedPattern = resolve2posix(dir, pattern);
  11931. let firstWildcardIndex = -1;
  11932. for (let i = 0; i < resolvedPattern.length; i++) {
  11933. if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
  11934. firstWildcardIndex = i;
  11935. hasWildcard = true;
  11936. break;
  11937. }
  11938. }
  11939. if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) {
  11940. return false;
  11941. }
  11942. if (!hasWildcard) {
  11943. return filename === resolvedPattern;
  11944. }
  11945. if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
  11946. return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
  11947. }
  11948. const regex = pattern2regex(resolvedPattern);
  11949. PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
  11950. return regex.test(filename);
  11951. });
  11952. }
  11953. function pattern2regex(resolvedPattern) {
  11954. let regexStr = "^";
  11955. for (let i = 0; i < resolvedPattern.length; i++) {
  11956. const char = resolvedPattern[i];
  11957. if (char === "?") {
  11958. regexStr += "[^\\/]";
  11959. continue;
  11960. }
  11961. if (char === "*") {
  11962. if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
  11963. i += 2;
  11964. regexStr += "(?:[^\\/]*\\/)*";
  11965. continue;
  11966. }
  11967. regexStr += "[^\\/]*";
  11968. continue;
  11969. }
  11970. if ("/.+^${}()|[]\\".includes(char)) {
  11971. regexStr += `\\`;
  11972. }
  11973. regexStr += char;
  11974. }
  11975. if (resolvedPattern.endsWith("*")) {
  11976. regexStr += DEFAULT_EXTENSIONS_RE_GROUP;
  11977. }
  11978. regexStr += "$";
  11979. return new RegExp(regexStr);
  11980. }
  11981. // src/parse.ts
  11982. async function parse$f(filename, options) {
  11983. const cache = options == null ? void 0 : options.cache;
  11984. if (cache == null ? void 0 : cache.has(filename)) {
  11985. return cache.get(filename);
  11986. }
  11987. let tsconfigFile;
  11988. if (options == null ? void 0 : options.resolveWithEmptyIfConfigNotFound) {
  11989. try {
  11990. tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
  11991. } catch (e) {
  11992. const notFoundResult = {
  11993. tsconfigFile: "no_tsconfig_file_found",
  11994. tsconfig: {}
  11995. };
  11996. cache == null ? void 0 : cache.set(filename, notFoundResult);
  11997. return notFoundResult;
  11998. }
  11999. } else {
  12000. tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
  12001. }
  12002. let result;
  12003. if (cache == null ? void 0 : cache.has(tsconfigFile)) {
  12004. result = cache.get(tsconfigFile);
  12005. } else {
  12006. result = await parseFile$1(tsconfigFile, cache);
  12007. await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]);
  12008. cache == null ? void 0 : cache.set(tsconfigFile, result);
  12009. }
  12010. result = resolveSolutionTSConfig(filename, result);
  12011. cache == null ? void 0 : cache.set(filename, result);
  12012. return result;
  12013. }
  12014. async function parseFile$1(tsconfigFile, cache) {
  12015. if (cache == null ? void 0 : cache.has(tsconfigFile)) {
  12016. return cache.get(tsconfigFile);
  12017. }
  12018. try {
  12019. const tsconfigJson = await promises$1.readFile(tsconfigFile, "utf-8");
  12020. const json = toJson(tsconfigJson);
  12021. const result = {
  12022. tsconfigFile,
  12023. tsconfig: normalizeTSConfig(JSON.parse(json), require$$0$4.dirname(tsconfigFile))
  12024. };
  12025. cache == null ? void 0 : cache.set(tsconfigFile, result);
  12026. return result;
  12027. } catch (e) {
  12028. throw new TSConfckParseError(
  12029. `parsing ${tsconfigFile} failed: ${e}`,
  12030. "PARSE_FILE",
  12031. tsconfigFile,
  12032. e
  12033. );
  12034. }
  12035. }
  12036. function normalizeTSConfig(tsconfig, dir) {
  12037. var _a;
  12038. if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.baseUrl) && !require$$0$4.isAbsolute(tsconfig.compilerOptions.baseUrl)) {
  12039. tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl);
  12040. }
  12041. return tsconfig;
  12042. }
  12043. async function parseReferences(result, cache) {
  12044. if (!result.tsconfig.references) {
  12045. return;
  12046. }
  12047. const referencedFiles = resolveReferencedTSConfigFiles(result);
  12048. const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache)));
  12049. await Promise.all(referenced.map((ref) => parseExtends(ref, cache)));
  12050. result.referenced = referenced;
  12051. }
  12052. async function parseExtends(result, cache) {
  12053. if (!result.tsconfig.extends) {
  12054. return;
  12055. }
  12056. const extended = [
  12057. { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
  12058. ];
  12059. let pos = 0;
  12060. const extendsPath = [];
  12061. let currentBranchDepth = 0;
  12062. while (pos < extended.length) {
  12063. const extending = extended[pos];
  12064. extendsPath.push(extending.tsconfigFile);
  12065. if (extending.tsconfig.extends) {
  12066. currentBranchDepth += 1;
  12067. let resolvedExtends;
  12068. if (!Array.isArray(extending.tsconfig.extends)) {
  12069. resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
  12070. } else {
  12071. resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
  12072. }
  12073. const circularExtends = resolvedExtends.find(
  12074. (tsconfigFile) => extendsPath.includes(tsconfigFile)
  12075. );
  12076. if (circularExtends) {
  12077. const circle = extendsPath.concat([circularExtends]).join(" -> ");
  12078. throw new TSConfckParseError(
  12079. `Circular dependency in "extends": ${circle}`,
  12080. "EXTENDS_CIRCULAR",
  12081. result.tsconfigFile
  12082. );
  12083. }
  12084. extended.splice(
  12085. pos + 1,
  12086. 0,
  12087. ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))
  12088. );
  12089. } else {
  12090. extendsPath.splice(-currentBranchDepth);
  12091. currentBranchDepth = 0;
  12092. }
  12093. pos = pos + 1;
  12094. }
  12095. result.extended = extended;
  12096. for (const ext of result.extended.slice(1)) {
  12097. extendTSConfig(result, ext);
  12098. }
  12099. }
  12100. function resolveExtends(extended, from) {
  12101. let error;
  12102. try {
  12103. return createRequire$2(from).resolve(extended);
  12104. } catch (e) {
  12105. error = e;
  12106. }
  12107. if (!require$$0$4.isAbsolute(extended) && !extended.startsWith("./") && !extended.startsWith("../")) {
  12108. try {
  12109. const fallbackExtended = require$$0$4.join(extended, "tsconfig.json");
  12110. return createRequire$2(from).resolve(fallbackExtended);
  12111. } catch (e) {
  12112. error = e;
  12113. }
  12114. }
  12115. throw new TSConfckParseError(
  12116. `failed to resolve "extends":"${extended}" in ${from}`,
  12117. "EXTENDS_RESOLVE",
  12118. from,
  12119. error
  12120. );
  12121. }
  12122. var EXTENDABLE_KEYS = [
  12123. "compilerOptions",
  12124. "files",
  12125. "include",
  12126. "exclude",
  12127. "watchOptions",
  12128. "compileOnSave",
  12129. "typeAcquisition",
  12130. "buildOptions"
  12131. ];
  12132. function extendTSConfig(extending, extended) {
  12133. const extendingConfig = extending.tsconfig;
  12134. const extendedConfig = extended.tsconfig;
  12135. const relativePath = native2posix(
  12136. require$$0$4.relative(require$$0$4.dirname(extending.tsconfigFile), require$$0$4.dirname(extended.tsconfigFile))
  12137. );
  12138. for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) {
  12139. if (key === "compilerOptions") {
  12140. if (!extendingConfig.compilerOptions) {
  12141. extendingConfig.compilerOptions = {};
  12142. }
  12143. for (const option of Object.keys(extendedConfig.compilerOptions)) {
  12144. if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
  12145. continue;
  12146. }
  12147. extendingConfig.compilerOptions[option] = rebaseRelative(
  12148. option,
  12149. extendedConfig.compilerOptions[option],
  12150. relativePath
  12151. );
  12152. }
  12153. } else if (extendingConfig[key] === void 0) {
  12154. if (key === "watchOptions") {
  12155. extendingConfig.watchOptions = {};
  12156. for (const option of Object.keys(extendedConfig.watchOptions)) {
  12157. extendingConfig.watchOptions[option] = rebaseRelative(
  12158. option,
  12159. extendedConfig.watchOptions[option],
  12160. relativePath
  12161. );
  12162. }
  12163. } else {
  12164. extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
  12165. }
  12166. }
  12167. }
  12168. }
  12169. var REBASE_KEYS = [
  12170. // root
  12171. "files",
  12172. "include",
  12173. "exclude",
  12174. // compilerOptions
  12175. "baseUrl",
  12176. "rootDir",
  12177. "rootDirs",
  12178. "typeRoots",
  12179. "outDir",
  12180. "outFile",
  12181. "declarationDir",
  12182. // watchOptions
  12183. "excludeDirectories",
  12184. "excludeFiles"
  12185. ];
  12186. function rebaseRelative(key, value, prependPath) {
  12187. if (!REBASE_KEYS.includes(key)) {
  12188. return value;
  12189. }
  12190. if (Array.isArray(value)) {
  12191. return value.map((x) => rebasePath(x, prependPath));
  12192. } else {
  12193. return rebasePath(value, prependPath);
  12194. }
  12195. }
  12196. function rebasePath(value, prependPath) {
  12197. if (require$$0$4.isAbsolute(value)) {
  12198. return value;
  12199. } else {
  12200. return require$$0$4.posix.normalize(require$$0$4.posix.join(prependPath, value));
  12201. }
  12202. }
  12203. var TSConfckParseError = class _TSConfckParseError extends Error {
  12204. constructor(message, code, tsconfigFile, cause) {
  12205. super(message);
  12206. Object.setPrototypeOf(this, _TSConfckParseError.prototype);
  12207. this.name = _TSConfckParseError.name;
  12208. this.code = code;
  12209. this.cause = cause;
  12210. this.tsconfigFile = tsconfigFile;
  12211. }
  12212. };
  12213. // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
  12214. const ROOT_FILES = [
  12215. // '.git',
  12216. // https://pnpm.io/workspaces/
  12217. 'pnpm-workspace.yaml',
  12218. // https://rushjs.io/pages/advanced/config_files/
  12219. // 'rush.json',
  12220. // https://nx.dev/latest/react/getting-started/nx-setup
  12221. // 'workspace.json',
  12222. // 'nx.json',
  12223. // https://github.com/lerna/lerna#lernajson
  12224. 'lerna.json',
  12225. ];
  12226. // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
  12227. // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
  12228. function hasWorkspacePackageJSON(root) {
  12229. const path = join$2(root, 'package.json');
  12230. if (!isFileReadable(path)) {
  12231. return false;
  12232. }
  12233. try {
  12234. const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
  12235. return !!content.workspaces;
  12236. }
  12237. catch {
  12238. return false;
  12239. }
  12240. }
  12241. function hasRootFile(root) {
  12242. return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
  12243. }
  12244. function hasPackageJSON(root) {
  12245. const path = join$2(root, 'package.json');
  12246. return fs$l.existsSync(path);
  12247. }
  12248. /**
  12249. * Search up for the nearest `package.json`
  12250. */
  12251. function searchForPackageRoot(current, root = current) {
  12252. if (hasPackageJSON(current))
  12253. return current;
  12254. const dir = dirname$2(current);
  12255. // reach the fs root
  12256. if (!dir || dir === current)
  12257. return root;
  12258. return searchForPackageRoot(dir, root);
  12259. }
  12260. /**
  12261. * Search up for the nearest workspace root
  12262. */
  12263. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  12264. if (hasRootFile(current))
  12265. return current;
  12266. if (hasWorkspacePackageJSON(current))
  12267. return current;
  12268. const dir = dirname$2(current);
  12269. // reach the fs root
  12270. if (!dir || dir === current)
  12271. return root;
  12272. return searchForWorkspaceRoot(dir, root);
  12273. }
  12274. const debug$f = createDebugger('vite:esbuild');
  12275. const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{\s*"use strict";)/s;
  12276. const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{\s*"use strict";)/s;
  12277. const validExtensionRE = /\.\w+$/;
  12278. const jsxExtensionsRE = /\.(?:j|t)sx\b/;
  12279. let server;
  12280. async function transformWithEsbuild(code, filename, options, inMap) {
  12281. let loader = options?.loader;
  12282. if (!loader) {
  12283. // if the id ends with a valid ext, use it (e.g. vue blocks)
  12284. // otherwise, cleanup the query before checking the ext
  12285. const ext = path$o
  12286. .extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename))
  12287. .slice(1);
  12288. if (ext === 'cjs' || ext === 'mjs') {
  12289. loader = 'js';
  12290. }
  12291. else if (ext === 'cts' || ext === 'mts') {
  12292. loader = 'ts';
  12293. }
  12294. else {
  12295. loader = ext;
  12296. }
  12297. }
  12298. let tsconfigRaw = options?.tsconfigRaw;
  12299. const fallbackSupported = {};
  12300. // if options provide tsconfigRaw in string, it takes highest precedence
  12301. if (typeof tsconfigRaw !== 'string') {
  12302. // these fields would affect the compilation result
  12303. // https://esbuild.github.io/content-types/#tsconfig-json
  12304. const meaningfulFields = [
  12305. 'alwaysStrict',
  12306. 'experimentalDecorators',
  12307. 'importsNotUsedAsValues',
  12308. 'jsx',
  12309. 'jsxFactory',
  12310. 'jsxFragmentFactory',
  12311. 'jsxImportSource',
  12312. 'preserveValueImports',
  12313. 'target',
  12314. 'useDefineForClassFields',
  12315. 'verbatimModuleSyntax',
  12316. ];
  12317. const compilerOptionsForFile = {};
  12318. if (loader === 'ts' || loader === 'tsx') {
  12319. const loadedTsconfig = await loadTsconfigJsonForFile(filename);
  12320. const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
  12321. for (const field of meaningfulFields) {
  12322. if (field in loadedCompilerOptions) {
  12323. // @ts-expect-error TypeScript can't tell they are of the same type
  12324. compilerOptionsForFile[field] = loadedCompilerOptions[field];
  12325. }
  12326. }
  12327. }
  12328. const compilerOptions = {
  12329. ...compilerOptionsForFile,
  12330. ...tsconfigRaw?.compilerOptions,
  12331. };
  12332. // esbuild uses `useDefineForClassFields: true` when `tsconfig.compilerOptions.target` isn't declared
  12333. // but we want `useDefineForClassFields: false` when `tsconfig.compilerOptions.target` isn't declared
  12334. // to align with the TypeScript's behavior
  12335. if (compilerOptions.useDefineForClassFields === undefined &&
  12336. compilerOptions.target === undefined) {
  12337. compilerOptions.useDefineForClassFields = false;
  12338. }
  12339. // esbuild v0.18 only transforms decorators when `experimentalDecorators` is set to `true`.
  12340. // To preserve compat with the esbuild breaking change, we set `experimentalDecorators` to
  12341. // `true` by default if it's unset.
  12342. // TODO: Remove this in Vite 5
  12343. if (compilerOptions.experimentalDecorators === undefined) {
  12344. compilerOptions.experimentalDecorators = true;
  12345. }
  12346. // Compat with esbuild 0.17 where static properties are transpiled to
  12347. // static blocks when `useDefineForClassFields` is false. Its support
  12348. // is not great yet, so temporarily disable it for now.
  12349. // TODO: Remove this in Vite 5, don't pass hardcoded `esnext` target
  12350. // to `transformWithEsbuild` in the esbuild plugin.
  12351. if (compilerOptions.useDefineForClassFields !== true) {
  12352. fallbackSupported['class-static-blocks'] = false;
  12353. }
  12354. // esbuild uses tsconfig fields when both the normal options and tsconfig was set
  12355. // but we want to prioritize the normal options
  12356. if (options) {
  12357. options.jsx && (compilerOptions.jsx = undefined);
  12358. options.jsxFactory && (compilerOptions.jsxFactory = undefined);
  12359. options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined);
  12360. options.jsxImportSource && (compilerOptions.jsxImportSource = undefined);
  12361. }
  12362. tsconfigRaw = {
  12363. ...tsconfigRaw,
  12364. compilerOptions,
  12365. };
  12366. }
  12367. const resolvedOptions = {
  12368. sourcemap: true,
  12369. // ensure source file name contains full query
  12370. sourcefile: filename,
  12371. ...options,
  12372. loader,
  12373. tsconfigRaw,
  12374. supported: {
  12375. ...fallbackSupported,
  12376. ...options?.supported,
  12377. },
  12378. };
  12379. // Some projects in the ecosystem are calling this function with an ESBuildOptions
  12380. // object and esbuild throws an error for extra fields
  12381. // @ts-expect-error include exists in ESBuildOptions
  12382. delete resolvedOptions.include;
  12383. // @ts-expect-error exclude exists in ESBuildOptions
  12384. delete resolvedOptions.exclude;
  12385. // @ts-expect-error jsxInject exists in ESBuildOptions
  12386. delete resolvedOptions.jsxInject;
  12387. try {
  12388. const result = await transform$1(code, resolvedOptions);
  12389. let map;
  12390. if (inMap && resolvedOptions.sourcemap) {
  12391. const nextMap = JSON.parse(result.map);
  12392. nextMap.sourcesContent = [];
  12393. map = combineSourcemaps(filename, [
  12394. nextMap,
  12395. inMap,
  12396. ]);
  12397. }
  12398. else {
  12399. map =
  12400. resolvedOptions.sourcemap && resolvedOptions.sourcemap !== 'inline'
  12401. ? JSON.parse(result.map)
  12402. : { mappings: '' };
  12403. }
  12404. return {
  12405. ...result,
  12406. map,
  12407. };
  12408. }
  12409. catch (e) {
  12410. debug$f?.(`esbuild error with options used: `, resolvedOptions);
  12411. // patch error information
  12412. if (e.errors) {
  12413. e.frame = '';
  12414. e.errors.forEach((m) => {
  12415. if (m.text === 'Experimental decorators are not currently enabled') {
  12416. m.text +=
  12417. '. Vite 4.4+ now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.';
  12418. }
  12419. e.frame += `\n` + prettifyMessage(m, code);
  12420. });
  12421. e.loc = e.errors[0].location;
  12422. }
  12423. throw e;
  12424. }
  12425. }
  12426. function esbuildPlugin(config) {
  12427. const options = config.esbuild;
  12428. const { jsxInject, include, exclude, ...esbuildTransformOptions } = options;
  12429. const filter = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  12430. // Remove optimization options for dev as we only need to transpile them,
  12431. // and for build as the final optimization is in `buildEsbuildPlugin`
  12432. const transformOptions = {
  12433. target: 'esnext',
  12434. charset: 'utf8',
  12435. ...esbuildTransformOptions,
  12436. minify: false,
  12437. minifyIdentifiers: false,
  12438. minifySyntax: false,
  12439. minifyWhitespace: false,
  12440. treeShaking: false,
  12441. // keepNames is not needed when minify is disabled.
  12442. // Also transforming multiple times with keepNames enabled breaks
  12443. // tree-shaking. (#9164)
  12444. keepNames: false,
  12445. };
  12446. initTSConfck(config.root);
  12447. return {
  12448. name: 'vite:esbuild',
  12449. configureServer(_server) {
  12450. server = _server;
  12451. server.watcher
  12452. .on('add', reloadOnTsconfigChange)
  12453. .on('change', reloadOnTsconfigChange)
  12454. .on('unlink', reloadOnTsconfigChange);
  12455. },
  12456. buildEnd() {
  12457. // recycle serve to avoid preventing Node self-exit (#6815)
  12458. server = null;
  12459. },
  12460. async transform(code, id) {
  12461. if (filter(id) || filter(cleanUrl(id))) {
  12462. const result = await transformWithEsbuild(code, id, transformOptions);
  12463. if (result.warnings.length) {
  12464. result.warnings.forEach((m) => {
  12465. this.warn(prettifyMessage(m, code));
  12466. });
  12467. }
  12468. if (jsxInject && jsxExtensionsRE.test(id)) {
  12469. result.code = jsxInject + ';' + result.code;
  12470. }
  12471. return {
  12472. code: result.code,
  12473. map: result.map,
  12474. };
  12475. }
  12476. },
  12477. };
  12478. }
  12479. const rollupToEsbuildFormatMap = {
  12480. es: 'esm',
  12481. cjs: 'cjs',
  12482. // passing `var Lib = (() => {})()` to esbuild with format = "iife"
  12483. // will turn it to `(() => { var Lib = (() => {})() })()`,
  12484. // so we remove the format config to tell esbuild not doing this
  12485. //
  12486. // although esbuild doesn't change format, there is still possibility
  12487. // that `{ treeShaking: true }` removes a top-level no-side-effect variable
  12488. // like: `var Lib = 1`, which becomes `` after esbuild transforming,
  12489. // but thankfully rollup does not do this optimization now
  12490. iife: undefined,
  12491. };
  12492. const buildEsbuildPlugin = (config) => {
  12493. initTSConfck(config.root);
  12494. return {
  12495. name: 'vite:esbuild-transpile',
  12496. async renderChunk(code, chunk, opts) {
  12497. // @ts-expect-error injected by @vitejs/plugin-legacy
  12498. if (opts.__vite_skip_esbuild__) {
  12499. return null;
  12500. }
  12501. const options = resolveEsbuildTranspileOptions(config, opts.format);
  12502. if (!options) {
  12503. return null;
  12504. }
  12505. const res = await transformWithEsbuild(code, chunk.fileName, options);
  12506. if (config.build.lib) {
  12507. // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
  12508. // names are minified potentially causing collision with other globals.
  12509. // We use a regex to inject the helpers inside the wrappers.
  12510. // We don't need to create a MagicString here because both the helpers and
  12511. // the headers don't modify the sourcemap
  12512. const injectHelpers = opts.format === 'umd'
  12513. ? INJECT_HELPERS_UMD_RE
  12514. : opts.format === 'iife'
  12515. ? INJECT_HELPERS_IIFE_RE
  12516. : undefined;
  12517. if (injectHelpers) {
  12518. res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers);
  12519. }
  12520. }
  12521. return res;
  12522. },
  12523. };
  12524. };
  12525. function resolveEsbuildTranspileOptions(config, format) {
  12526. const target = config.build.target;
  12527. const minify = config.build.minify === 'esbuild';
  12528. if ((!target || target === 'esnext') && !minify) {
  12529. return null;
  12530. }
  12531. // Do not minify whitespace for ES lib output since that would remove
  12532. // pure annotations and break tree-shaking
  12533. // https://github.com/vuejs/core/issues/2860#issuecomment-926882793
  12534. const isEsLibBuild = config.build.lib && format === 'es';
  12535. const esbuildOptions = config.esbuild || {};
  12536. const options = {
  12537. charset: 'utf8',
  12538. ...esbuildOptions,
  12539. target: target || undefined,
  12540. format: rollupToEsbuildFormatMap[format],
  12541. // the final build should always support dynamic import and import.meta.
  12542. // if they need to be polyfilled, plugin-legacy should be used.
  12543. // plugin-legacy detects these two features when checking for modern code.
  12544. supported: {
  12545. 'dynamic-import': true,
  12546. 'import-meta': true,
  12547. ...esbuildOptions.supported,
  12548. },
  12549. };
  12550. // If no minify, disable all minify options
  12551. if (!minify) {
  12552. return {
  12553. ...options,
  12554. minify: false,
  12555. minifyIdentifiers: false,
  12556. minifySyntax: false,
  12557. minifyWhitespace: false,
  12558. treeShaking: false,
  12559. };
  12560. }
  12561. // If user enable fine-grain minify options, minify with their options instead
  12562. if (options.minifyIdentifiers != null ||
  12563. options.minifySyntax != null ||
  12564. options.minifyWhitespace != null) {
  12565. if (isEsLibBuild) {
  12566. // Disable minify whitespace as it breaks tree-shaking
  12567. return {
  12568. ...options,
  12569. minify: false,
  12570. minifyIdentifiers: options.minifyIdentifiers ?? true,
  12571. minifySyntax: options.minifySyntax ?? true,
  12572. minifyWhitespace: false,
  12573. treeShaking: true,
  12574. };
  12575. }
  12576. else {
  12577. return {
  12578. ...options,
  12579. minify: false,
  12580. minifyIdentifiers: options.minifyIdentifiers ?? true,
  12581. minifySyntax: options.minifySyntax ?? true,
  12582. minifyWhitespace: options.minifyWhitespace ?? true,
  12583. treeShaking: true,
  12584. };
  12585. }
  12586. }
  12587. // Else apply default minify options
  12588. if (isEsLibBuild) {
  12589. // Minify all except whitespace as it breaks tree-shaking
  12590. return {
  12591. ...options,
  12592. minify: false,
  12593. minifyIdentifiers: true,
  12594. minifySyntax: true,
  12595. minifyWhitespace: false,
  12596. treeShaking: true,
  12597. };
  12598. }
  12599. else {
  12600. return {
  12601. ...options,
  12602. minify: true,
  12603. treeShaking: true,
  12604. };
  12605. }
  12606. }
  12607. function prettifyMessage(m, code) {
  12608. let res = colors$1.yellow(m.text);
  12609. if (m.location) {
  12610. const lines = code.split(/\r?\n/g);
  12611. const line = Number(m.location.line);
  12612. const column = Number(m.location.column);
  12613. const offset = lines
  12614. .slice(0, line - 1)
  12615. .map((l) => l.length)
  12616. .reduce((total, l) => total + l + 1, 0) + column;
  12617. res += `\n` + generateCodeFrame(code, offset, offset + 1);
  12618. }
  12619. return res + `\n`;
  12620. }
  12621. let tsconfckRoot;
  12622. let tsconfckParseOptions = { resolveWithEmptyIfConfigNotFound: true };
  12623. function initTSConfck(root, force = false) {
  12624. // bail if already cached
  12625. if (!force && root === tsconfckRoot)
  12626. return;
  12627. const workspaceRoot = searchForWorkspaceRoot(root);
  12628. tsconfckRoot = root;
  12629. tsconfckParseOptions = initTSConfckParseOptions(workspaceRoot);
  12630. // cached as the options value itself when promise is resolved
  12631. tsconfckParseOptions.then((options) => {
  12632. if (root === tsconfckRoot) {
  12633. tsconfckParseOptions = options;
  12634. }
  12635. });
  12636. }
  12637. async function initTSConfckParseOptions(workspaceRoot) {
  12638. const start = debug$f ? performance.now() : 0;
  12639. const options = {
  12640. cache: new Map(),
  12641. root: workspaceRoot,
  12642. tsConfigPaths: new Set(await findAll(workspaceRoot, {
  12643. skip: (dir) => dir === 'node_modules' || dir === '.git',
  12644. })),
  12645. resolveWithEmptyIfConfigNotFound: true,
  12646. };
  12647. debug$f?.(timeFrom(start), 'tsconfck init', colors$1.dim(workspaceRoot));
  12648. return options;
  12649. }
  12650. async function loadTsconfigJsonForFile(filename) {
  12651. try {
  12652. const result = await parse$f(filename, await tsconfckParseOptions);
  12653. // tsconfig could be out of root, make sure it is watched on dev
  12654. if (server && result.tsconfigFile !== 'no_tsconfig_file_found') {
  12655. ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
  12656. }
  12657. return result.tsconfig;
  12658. }
  12659. catch (e) {
  12660. if (e instanceof TSConfckParseError) {
  12661. // tsconfig could be out of root, make sure it is watched on dev
  12662. if (server && e.tsconfigFile) {
  12663. ensureWatchedFile(server.watcher, e.tsconfigFile, server.config.root);
  12664. }
  12665. }
  12666. throw e;
  12667. }
  12668. }
  12669. async function reloadOnTsconfigChange(changedFile) {
  12670. // server could be closed externally after a file change is detected
  12671. if (!server)
  12672. return;
  12673. // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one
  12674. // any json file in the tsconfig cache could have been used to compile ts
  12675. if (path$o.basename(changedFile) === 'tsconfig.json' ||
  12676. (changedFile.endsWith('.json') &&
  12677. (await tsconfckParseOptions)?.cache?.has(changedFile))) {
  12678. server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
  12679. // clear module graph to remove code compiled with outdated config
  12680. server.moduleGraph.invalidateAll();
  12681. // reset tsconfck so that recompile works with up2date configs
  12682. initTSConfck(server.config.root, true);
  12683. // server may not be available if vite config is updated at the same time
  12684. if (server) {
  12685. // force full reload
  12686. server.ws.send({
  12687. type: 'full-reload',
  12688. path: '*',
  12689. });
  12690. }
  12691. }
  12692. }
  12693. var dist$1 = {};
  12694. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  12695. return (mod && mod.__esModule) ? mod : { "default": mod };
  12696. };
  12697. Object.defineProperty(dist$1, "__esModule", { value: true });
  12698. var Worker_1 = dist$1.Worker = void 0;
  12699. const os_1 = __importDefault(require$$2);
  12700. const worker_threads_1 = require$$1;
  12701. class Worker {
  12702. constructor(fn, options = {}) {
  12703. this.code = genWorkerCode(fn);
  12704. this.max = options.max || Math.max(1, os_1.default.cpus().length - 1);
  12705. this.pool = [];
  12706. this.idlePool = [];
  12707. this.queue = [];
  12708. }
  12709. async run(...args) {
  12710. const worker = await this._getAvailableWorker();
  12711. return new Promise((resolve, reject) => {
  12712. worker.currentResolve = resolve;
  12713. worker.currentReject = reject;
  12714. worker.postMessage(args);
  12715. });
  12716. }
  12717. stop() {
  12718. this.pool.forEach((w) => w.unref());
  12719. this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.')));
  12720. this.pool = [];
  12721. this.idlePool = [];
  12722. this.queue = [];
  12723. }
  12724. async _getAvailableWorker() {
  12725. // has idle one?
  12726. if (this.idlePool.length) {
  12727. return this.idlePool.shift();
  12728. }
  12729. // can spawn more?
  12730. if (this.pool.length < this.max) {
  12731. const worker = new worker_threads_1.Worker(this.code, { eval: true });
  12732. worker.on('message', (res) => {
  12733. worker.currentResolve && worker.currentResolve(res);
  12734. worker.currentResolve = null;
  12735. this._assignDoneWorker(worker);
  12736. });
  12737. worker.on('error', (err) => {
  12738. worker.currentReject && worker.currentReject(err);
  12739. worker.currentReject = null;
  12740. });
  12741. worker.on('exit', (code) => {
  12742. const i = this.pool.indexOf(worker);
  12743. if (i > -1)
  12744. this.pool.splice(i, 1);
  12745. if (code !== 0 && worker.currentReject) {
  12746. worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`));
  12747. worker.currentReject = null;
  12748. }
  12749. });
  12750. this.pool.push(worker);
  12751. return worker;
  12752. }
  12753. // no one is available, we have to wait
  12754. let resolve;
  12755. let reject;
  12756. const onWorkerAvailablePromise = new Promise((r, rj) => {
  12757. resolve = r;
  12758. reject = rj;
  12759. });
  12760. this.queue.push([resolve, reject]);
  12761. return onWorkerAvailablePromise;
  12762. }
  12763. _assignDoneWorker(worker) {
  12764. // someone's waiting already?
  12765. if (this.queue.length) {
  12766. const [resolve] = this.queue.shift();
  12767. resolve(worker);
  12768. return;
  12769. }
  12770. // take a rest.
  12771. this.idlePool.push(worker);
  12772. }
  12773. }
  12774. Worker_1 = dist$1.Worker = Worker;
  12775. function genWorkerCode(fn) {
  12776. return `
  12777. const doWork = ${fn.toString()}
  12778. const { parentPort } = require('worker_threads')
  12779. parentPort.on('message', async (args) => {
  12780. const res = await doWork(...args)
  12781. parentPort.postMessage(res)
  12782. })
  12783. `;
  12784. }
  12785. let terserPath;
  12786. const loadTerserPath = (root) => {
  12787. if (terserPath)
  12788. return terserPath;
  12789. try {
  12790. terserPath = requireResolveFromRootWithFallback(root, 'terser');
  12791. }
  12792. catch (e) {
  12793. if (e.code === 'MODULE_NOT_FOUND') {
  12794. throw new Error('terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.');
  12795. }
  12796. else {
  12797. const message = new Error(`terser failed to load:\n${e.message}`);
  12798. message.stack = e.stack + '\n' + message.stack;
  12799. throw message;
  12800. }
  12801. }
  12802. return terserPath;
  12803. };
  12804. function terserPlugin(config) {
  12805. const makeWorker = () => new Worker_1(async (terserPath, code, options) => {
  12806. // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205
  12807. // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs
  12808. const terser = require(terserPath);
  12809. return terser.minify(code, options);
  12810. });
  12811. let worker;
  12812. return {
  12813. name: 'vite:terser',
  12814. async renderChunk(code, _chunk, outputOptions) {
  12815. // This plugin is included for any non-false value of config.build.minify,
  12816. // so that normal chunks can use the preferred minifier, and legacy chunks
  12817. // can use terser.
  12818. if (config.build.minify !== 'terser' &&
  12819. // @ts-expect-error injected by @vitejs/plugin-legacy
  12820. !outputOptions.__vite_force_terser__) {
  12821. return null;
  12822. }
  12823. // Do not minify ES lib output since that would remove pure annotations
  12824. // and break tree-shaking.
  12825. if (config.build.lib && outputOptions.format === 'es') {
  12826. return null;
  12827. }
  12828. // Lazy load worker.
  12829. worker || (worker = makeWorker());
  12830. const terserPath = loadTerserPath(config.root);
  12831. const res = await worker.run(terserPath, code, {
  12832. safari10: true,
  12833. ...config.build.terserOptions,
  12834. sourceMap: !!outputOptions.sourcemap,
  12835. module: outputOptions.format.startsWith('es'),
  12836. toplevel: outputOptions.format === 'cjs',
  12837. });
  12838. return {
  12839. code: res.code,
  12840. map: res.map,
  12841. };
  12842. },
  12843. closeBundle() {
  12844. worker?.stop();
  12845. },
  12846. };
  12847. }
  12848. var json = JSON;
  12849. var isArray$1 = Array.isArray || function (x) {
  12850. return {}.toString.call(x) === '[object Array]';
  12851. };
  12852. var objectKeys = Object.keys || function (obj) {
  12853. var has = Object.prototype.hasOwnProperty || function () { return true; };
  12854. var keys = [];
  12855. for (var key in obj) {
  12856. if (has.call(obj, key)) { keys.push(key); }
  12857. }
  12858. return keys;
  12859. };
  12860. var jsonStableStringify = function (obj, opts) {
  12861. if (!opts) { opts = {}; }
  12862. if (typeof opts === 'function') { opts = { cmp: opts }; }
  12863. var space = opts.space || '';
  12864. if (typeof space === 'number') { space = Array(space + 1).join(' '); }
  12865. var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
  12866. var replacer = opts.replacer || function (key, value) { return value; };
  12867. var cmp = opts.cmp && (function (f) {
  12868. return function (node) {
  12869. return function (a, b) {
  12870. var aobj = { key: a, value: node[a] };
  12871. var bobj = { key: b, value: node[b] };
  12872. return f(aobj, bobj);
  12873. };
  12874. };
  12875. }(opts.cmp));
  12876. var seen = [];
  12877. return (function stringify(parent, key, node, level) {
  12878. var indent = space ? '\n' + new Array(level + 1).join(space) : '';
  12879. var colonSeparator = space ? ': ' : ':';
  12880. if (node && node.toJSON && typeof node.toJSON === 'function') {
  12881. node = node.toJSON();
  12882. }
  12883. node = replacer.call(parent, key, node);
  12884. if (node === undefined) {
  12885. return;
  12886. }
  12887. if (typeof node !== 'object' || node === null) {
  12888. return json.stringify(node);
  12889. }
  12890. if (isArray$1(node)) {
  12891. var out = [];
  12892. for (var i = 0; i < node.length; i++) {
  12893. var item = stringify(node, i, node[i], level + 1) || json.stringify(null);
  12894. out.push(indent + space + item);
  12895. }
  12896. return '[' + out.join(',') + indent + ']';
  12897. }
  12898. if (seen.indexOf(node) !== -1) {
  12899. if (cycles) { return json.stringify('__cycle__'); }
  12900. throw new TypeError('Converting circular structure to JSON');
  12901. } else { seen.push(node); }
  12902. var keys = objectKeys(node).sort(cmp && cmp(node));
  12903. var out = [];
  12904. for (var i = 0; i < keys.length; i++) {
  12905. var key = keys[i];
  12906. var value = stringify(node, key, node[key], level + 1);
  12907. if (!value) { continue; }
  12908. var keyValue = json.stringify(key)
  12909. + colonSeparator
  12910. + value;
  12911. out.push(indent + space + keyValue);
  12912. }
  12913. seen.splice(seen.indexOf(node), 1);
  12914. return '{' + out.join(',') + indent + '}';
  12915. }({ '': obj }, '', obj, 0));
  12916. };
  12917. var jsonStableStringify$1 = /*@__PURE__*/getDefaultExportFromCjs(jsonStableStringify);
  12918. const mimes$1 = {
  12919. "ez": "application/andrew-inset",
  12920. "aw": "application/applixware",
  12921. "atom": "application/atom+xml",
  12922. "atomcat": "application/atomcat+xml",
  12923. "atomdeleted": "application/atomdeleted+xml",
  12924. "atomsvc": "application/atomsvc+xml",
  12925. "dwd": "application/atsc-dwd+xml",
  12926. "held": "application/atsc-held+xml",
  12927. "rsat": "application/atsc-rsat+xml",
  12928. "bdoc": "application/bdoc",
  12929. "xcs": "application/calendar+xml",
  12930. "ccxml": "application/ccxml+xml",
  12931. "cdfx": "application/cdfx+xml",
  12932. "cdmia": "application/cdmi-capability",
  12933. "cdmic": "application/cdmi-container",
  12934. "cdmid": "application/cdmi-domain",
  12935. "cdmio": "application/cdmi-object",
  12936. "cdmiq": "application/cdmi-queue",
  12937. "cu": "application/cu-seeme",
  12938. "mpd": "application/dash+xml",
  12939. "davmount": "application/davmount+xml",
  12940. "dbk": "application/docbook+xml",
  12941. "dssc": "application/dssc+der",
  12942. "xdssc": "application/dssc+xml",
  12943. "es": "application/ecmascript",
  12944. "ecma": "application/ecmascript",
  12945. "emma": "application/emma+xml",
  12946. "emotionml": "application/emotionml+xml",
  12947. "epub": "application/epub+zip",
  12948. "exi": "application/exi",
  12949. "fdt": "application/fdt+xml",
  12950. "pfr": "application/font-tdpfr",
  12951. "geojson": "application/geo+json",
  12952. "gml": "application/gml+xml",
  12953. "gpx": "application/gpx+xml",
  12954. "gxf": "application/gxf",
  12955. "gz": "application/gzip",
  12956. "hjson": "application/hjson",
  12957. "stk": "application/hyperstudio",
  12958. "ink": "application/inkml+xml",
  12959. "inkml": "application/inkml+xml",
  12960. "ipfix": "application/ipfix",
  12961. "its": "application/its+xml",
  12962. "jar": "application/java-archive",
  12963. "war": "application/java-archive",
  12964. "ear": "application/java-archive",
  12965. "ser": "application/java-serialized-object",
  12966. "class": "application/java-vm",
  12967. "js": "application/javascript",
  12968. "mjs": "application/javascript",
  12969. "json": "application/json",
  12970. "map": "application/json",
  12971. "json5": "application/json5",
  12972. "jsonml": "application/jsonml+json",
  12973. "jsonld": "application/ld+json",
  12974. "lgr": "application/lgr+xml",
  12975. "lostxml": "application/lost+xml",
  12976. "hqx": "application/mac-binhex40",
  12977. "cpt": "application/mac-compactpro",
  12978. "mads": "application/mads+xml",
  12979. "webmanifest": "application/manifest+json",
  12980. "mrc": "application/marc",
  12981. "mrcx": "application/marcxml+xml",
  12982. "ma": "application/mathematica",
  12983. "nb": "application/mathematica",
  12984. "mb": "application/mathematica",
  12985. "mathml": "application/mathml+xml",
  12986. "mbox": "application/mbox",
  12987. "mscml": "application/mediaservercontrol+xml",
  12988. "metalink": "application/metalink+xml",
  12989. "meta4": "application/metalink4+xml",
  12990. "mets": "application/mets+xml",
  12991. "maei": "application/mmt-aei+xml",
  12992. "musd": "application/mmt-usd+xml",
  12993. "mods": "application/mods+xml",
  12994. "m21": "application/mp21",
  12995. "mp21": "application/mp21",
  12996. "mp4s": "application/mp4",
  12997. "m4p": "application/mp4",
  12998. "doc": "application/msword",
  12999. "dot": "application/msword",
  13000. "mxf": "application/mxf",
  13001. "nq": "application/n-quads",
  13002. "nt": "application/n-triples",
  13003. "cjs": "application/node",
  13004. "bin": "application/octet-stream",
  13005. "dms": "application/octet-stream",
  13006. "lrf": "application/octet-stream",
  13007. "mar": "application/octet-stream",
  13008. "so": "application/octet-stream",
  13009. "dist": "application/octet-stream",
  13010. "distz": "application/octet-stream",
  13011. "pkg": "application/octet-stream",
  13012. "bpk": "application/octet-stream",
  13013. "dump": "application/octet-stream",
  13014. "elc": "application/octet-stream",
  13015. "deploy": "application/octet-stream",
  13016. "exe": "application/octet-stream",
  13017. "dll": "application/octet-stream",
  13018. "deb": "application/octet-stream",
  13019. "dmg": "application/octet-stream",
  13020. "iso": "application/octet-stream",
  13021. "img": "application/octet-stream",
  13022. "msi": "application/octet-stream",
  13023. "msp": "application/octet-stream",
  13024. "msm": "application/octet-stream",
  13025. "buffer": "application/octet-stream",
  13026. "oda": "application/oda",
  13027. "opf": "application/oebps-package+xml",
  13028. "ogx": "application/ogg",
  13029. "omdoc": "application/omdoc+xml",
  13030. "onetoc": "application/onenote",
  13031. "onetoc2": "application/onenote",
  13032. "onetmp": "application/onenote",
  13033. "onepkg": "application/onenote",
  13034. "oxps": "application/oxps",
  13035. "relo": "application/p2p-overlay+xml",
  13036. "xer": "application/patch-ops-error+xml",
  13037. "pdf": "application/pdf",
  13038. "pgp": "application/pgp-encrypted",
  13039. "asc": "application/pgp-signature",
  13040. "sig": "application/pgp-signature",
  13041. "prf": "application/pics-rules",
  13042. "p10": "application/pkcs10",
  13043. "p7m": "application/pkcs7-mime",
  13044. "p7c": "application/pkcs7-mime",
  13045. "p7s": "application/pkcs7-signature",
  13046. "p8": "application/pkcs8",
  13047. "ac": "application/pkix-attr-cert",
  13048. "cer": "application/pkix-cert",
  13049. "crl": "application/pkix-crl",
  13050. "pkipath": "application/pkix-pkipath",
  13051. "pki": "application/pkixcmp",
  13052. "pls": "application/pls+xml",
  13053. "ai": "application/postscript",
  13054. "eps": "application/postscript",
  13055. "ps": "application/postscript",
  13056. "provx": "application/provenance+xml",
  13057. "cww": "application/prs.cww",
  13058. "pskcxml": "application/pskc+xml",
  13059. "raml": "application/raml+yaml",
  13060. "rdf": "application/rdf+xml",
  13061. "owl": "application/rdf+xml",
  13062. "rif": "application/reginfo+xml",
  13063. "rnc": "application/relax-ng-compact-syntax",
  13064. "rl": "application/resource-lists+xml",
  13065. "rld": "application/resource-lists-diff+xml",
  13066. "rs": "application/rls-services+xml",
  13067. "rapd": "application/route-apd+xml",
  13068. "sls": "application/route-s-tsid+xml",
  13069. "rusd": "application/route-usd+xml",
  13070. "gbr": "application/rpki-ghostbusters",
  13071. "mft": "application/rpki-manifest",
  13072. "roa": "application/rpki-roa",
  13073. "rsd": "application/rsd+xml",
  13074. "rss": "application/rss+xml",
  13075. "rtf": "application/rtf",
  13076. "sbml": "application/sbml+xml",
  13077. "scq": "application/scvp-cv-request",
  13078. "scs": "application/scvp-cv-response",
  13079. "spq": "application/scvp-vp-request",
  13080. "spp": "application/scvp-vp-response",
  13081. "sdp": "application/sdp",
  13082. "senmlx": "application/senml+xml",
  13083. "sensmlx": "application/sensml+xml",
  13084. "setpay": "application/set-payment-initiation",
  13085. "setreg": "application/set-registration-initiation",
  13086. "shf": "application/shf+xml",
  13087. "siv": "application/sieve",
  13088. "sieve": "application/sieve",
  13089. "smi": "application/smil+xml",
  13090. "smil": "application/smil+xml",
  13091. "rq": "application/sparql-query",
  13092. "srx": "application/sparql-results+xml",
  13093. "gram": "application/srgs",
  13094. "grxml": "application/srgs+xml",
  13095. "sru": "application/sru+xml",
  13096. "ssdl": "application/ssdl+xml",
  13097. "ssml": "application/ssml+xml",
  13098. "swidtag": "application/swid+xml",
  13099. "tei": "application/tei+xml",
  13100. "teicorpus": "application/tei+xml",
  13101. "tfi": "application/thraud+xml",
  13102. "tsd": "application/timestamped-data",
  13103. "toml": "application/toml",
  13104. "trig": "application/trig",
  13105. "ttml": "application/ttml+xml",
  13106. "ubj": "application/ubjson",
  13107. "rsheet": "application/urc-ressheet+xml",
  13108. "td": "application/urc-targetdesc+xml",
  13109. "vxml": "application/voicexml+xml",
  13110. "wasm": "application/wasm",
  13111. "wgt": "application/widget",
  13112. "hlp": "application/winhlp",
  13113. "wsdl": "application/wsdl+xml",
  13114. "wspolicy": "application/wspolicy+xml",
  13115. "xaml": "application/xaml+xml",
  13116. "xav": "application/xcap-att+xml",
  13117. "xca": "application/xcap-caps+xml",
  13118. "xdf": "application/xcap-diff+xml",
  13119. "xel": "application/xcap-el+xml",
  13120. "xns": "application/xcap-ns+xml",
  13121. "xenc": "application/xenc+xml",
  13122. "xhtml": "application/xhtml+xml",
  13123. "xht": "application/xhtml+xml",
  13124. "xlf": "application/xliff+xml",
  13125. "xml": "application/xml",
  13126. "xsl": "application/xml",
  13127. "xsd": "application/xml",
  13128. "rng": "application/xml",
  13129. "dtd": "application/xml-dtd",
  13130. "xop": "application/xop+xml",
  13131. "xpl": "application/xproc+xml",
  13132. "xslt": "application/xml",
  13133. "xspf": "application/xspf+xml",
  13134. "mxml": "application/xv+xml",
  13135. "xhvml": "application/xv+xml",
  13136. "xvml": "application/xv+xml",
  13137. "xvm": "application/xv+xml",
  13138. "yang": "application/yang",
  13139. "yin": "application/yin+xml",
  13140. "zip": "application/zip",
  13141. "3gpp": "video/3gpp",
  13142. "adp": "audio/adpcm",
  13143. "amr": "audio/amr",
  13144. "au": "audio/basic",
  13145. "snd": "audio/basic",
  13146. "mid": "audio/midi",
  13147. "midi": "audio/midi",
  13148. "kar": "audio/midi",
  13149. "rmi": "audio/midi",
  13150. "mxmf": "audio/mobile-xmf",
  13151. "mp3": "audio/mpeg",
  13152. "m4a": "audio/mp4",
  13153. "mp4a": "audio/mp4",
  13154. "mpga": "audio/mpeg",
  13155. "mp2": "audio/mpeg",
  13156. "mp2a": "audio/mpeg",
  13157. "m2a": "audio/mpeg",
  13158. "m3a": "audio/mpeg",
  13159. "oga": "audio/ogg",
  13160. "ogg": "audio/ogg",
  13161. "spx": "audio/ogg",
  13162. "opus": "audio/ogg",
  13163. "s3m": "audio/s3m",
  13164. "sil": "audio/silk",
  13165. "wav": "audio/wav",
  13166. "weba": "audio/webm",
  13167. "xm": "audio/xm",
  13168. "ttc": "font/collection",
  13169. "otf": "font/otf",
  13170. "ttf": "font/ttf",
  13171. "woff": "font/woff",
  13172. "woff2": "font/woff2",
  13173. "exr": "image/aces",
  13174. "apng": "image/apng",
  13175. "avif": "image/avif",
  13176. "bmp": "image/bmp",
  13177. "cgm": "image/cgm",
  13178. "drle": "image/dicom-rle",
  13179. "emf": "image/emf",
  13180. "fits": "image/fits",
  13181. "g3": "image/g3fax",
  13182. "gif": "image/gif",
  13183. "heic": "image/heic",
  13184. "heics": "image/heic-sequence",
  13185. "heif": "image/heif",
  13186. "heifs": "image/heif-sequence",
  13187. "hej2": "image/hej2k",
  13188. "hsj2": "image/hsj2",
  13189. "ief": "image/ief",
  13190. "jls": "image/jls",
  13191. "jp2": "image/jp2",
  13192. "jpg2": "image/jp2",
  13193. "jpeg": "image/jpeg",
  13194. "jpg": "image/jpeg",
  13195. "jpe": "image/jpeg",
  13196. "jph": "image/jph",
  13197. "jhc": "image/jphc",
  13198. "jpm": "image/jpm",
  13199. "jpx": "image/jpx",
  13200. "jpf": "image/jpx",
  13201. "jxr": "image/jxr",
  13202. "jxra": "image/jxra",
  13203. "jxrs": "image/jxrs",
  13204. "jxs": "image/jxs",
  13205. "jxsc": "image/jxsc",
  13206. "jxsi": "image/jxsi",
  13207. "jxss": "image/jxss",
  13208. "ktx": "image/ktx",
  13209. "ktx2": "image/ktx2",
  13210. "png": "image/png",
  13211. "btif": "image/prs.btif",
  13212. "pti": "image/prs.pti",
  13213. "sgi": "image/sgi",
  13214. "svg": "image/svg+xml",
  13215. "svgz": "image/svg+xml",
  13216. "t38": "image/t38",
  13217. "tif": "image/tiff",
  13218. "tiff": "image/tiff",
  13219. "tfx": "image/tiff-fx",
  13220. "webp": "image/webp",
  13221. "wmf": "image/wmf",
  13222. "disposition-notification": "message/disposition-notification",
  13223. "u8msg": "message/global",
  13224. "u8dsn": "message/global-delivery-status",
  13225. "u8mdn": "message/global-disposition-notification",
  13226. "u8hdr": "message/global-headers",
  13227. "eml": "message/rfc822",
  13228. "mime": "message/rfc822",
  13229. "3mf": "model/3mf",
  13230. "gltf": "model/gltf+json",
  13231. "glb": "model/gltf-binary",
  13232. "igs": "model/iges",
  13233. "iges": "model/iges",
  13234. "msh": "model/mesh",
  13235. "mesh": "model/mesh",
  13236. "silo": "model/mesh",
  13237. "mtl": "model/mtl",
  13238. "obj": "model/obj",
  13239. "stpz": "model/step+zip",
  13240. "stpxz": "model/step-xml+zip",
  13241. "stl": "model/stl",
  13242. "wrl": "model/vrml",
  13243. "vrml": "model/vrml",
  13244. "x3db": "model/x3d+fastinfoset",
  13245. "x3dbz": "model/x3d+binary",
  13246. "x3dv": "model/x3d-vrml",
  13247. "x3dvz": "model/x3d+vrml",
  13248. "x3d": "model/x3d+xml",
  13249. "x3dz": "model/x3d+xml",
  13250. "appcache": "text/cache-manifest",
  13251. "manifest": "text/cache-manifest",
  13252. "ics": "text/calendar",
  13253. "ifb": "text/calendar",
  13254. "coffee": "text/coffeescript",
  13255. "litcoffee": "text/coffeescript",
  13256. "css": "text/css",
  13257. "csv": "text/csv",
  13258. "html": "text/html",
  13259. "htm": "text/html",
  13260. "shtml": "text/html",
  13261. "jade": "text/jade",
  13262. "jsx": "text/jsx",
  13263. "less": "text/less",
  13264. "markdown": "text/markdown",
  13265. "md": "text/markdown",
  13266. "mml": "text/mathml",
  13267. "mdx": "text/mdx",
  13268. "n3": "text/n3",
  13269. "txt": "text/plain",
  13270. "text": "text/plain",
  13271. "conf": "text/plain",
  13272. "def": "text/plain",
  13273. "list": "text/plain",
  13274. "log": "text/plain",
  13275. "in": "text/plain",
  13276. "ini": "text/plain",
  13277. "dsc": "text/prs.lines.tag",
  13278. "rtx": "text/richtext",
  13279. "sgml": "text/sgml",
  13280. "sgm": "text/sgml",
  13281. "shex": "text/shex",
  13282. "slim": "text/slim",
  13283. "slm": "text/slim",
  13284. "spdx": "text/spdx",
  13285. "stylus": "text/stylus",
  13286. "styl": "text/stylus",
  13287. "tsv": "text/tab-separated-values",
  13288. "t": "text/troff",
  13289. "tr": "text/troff",
  13290. "roff": "text/troff",
  13291. "man": "text/troff",
  13292. "me": "text/troff",
  13293. "ms": "text/troff",
  13294. "ttl": "text/turtle",
  13295. "uri": "text/uri-list",
  13296. "uris": "text/uri-list",
  13297. "urls": "text/uri-list",
  13298. "vcard": "text/vcard",
  13299. "vtt": "text/vtt",
  13300. "yaml": "text/yaml",
  13301. "yml": "text/yaml",
  13302. "3gp": "video/3gpp",
  13303. "3g2": "video/3gpp2",
  13304. "h261": "video/h261",
  13305. "h263": "video/h263",
  13306. "h264": "video/h264",
  13307. "m4s": "video/iso.segment",
  13308. "jpgv": "video/jpeg",
  13309. "jpgm": "image/jpm",
  13310. "mj2": "video/mj2",
  13311. "mjp2": "video/mj2",
  13312. "ts": "video/mp2t",
  13313. "mp4": "video/mp4",
  13314. "mp4v": "video/mp4",
  13315. "mpg4": "video/mp4",
  13316. "mpeg": "video/mpeg",
  13317. "mpg": "video/mpeg",
  13318. "mpe": "video/mpeg",
  13319. "m1v": "video/mpeg",
  13320. "m2v": "video/mpeg",
  13321. "ogv": "video/ogg",
  13322. "qt": "video/quicktime",
  13323. "mov": "video/quicktime",
  13324. "webm": "video/webm"
  13325. };
  13326. function lookup(extn) {
  13327. let tmp = ('' + extn).trim().toLowerCase();
  13328. let idx = tmp.lastIndexOf('.');
  13329. return mimes$1[!~idx ? tmp : tmp.substring(++idx)];
  13330. }
  13331. class BitSet {
  13332. constructor(arg) {
  13333. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  13334. }
  13335. add(n) {
  13336. this.bits[n >> 5] |= 1 << (n & 31);
  13337. }
  13338. has(n) {
  13339. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  13340. }
  13341. }
  13342. class Chunk {
  13343. constructor(start, end, content) {
  13344. this.start = start;
  13345. this.end = end;
  13346. this.original = content;
  13347. this.intro = '';
  13348. this.outro = '';
  13349. this.content = content;
  13350. this.storeName = false;
  13351. this.edited = false;
  13352. {
  13353. this.previous = null;
  13354. this.next = null;
  13355. }
  13356. }
  13357. appendLeft(content) {
  13358. this.outro += content;
  13359. }
  13360. appendRight(content) {
  13361. this.intro = this.intro + content;
  13362. }
  13363. clone() {
  13364. const chunk = new Chunk(this.start, this.end, this.original);
  13365. chunk.intro = this.intro;
  13366. chunk.outro = this.outro;
  13367. chunk.content = this.content;
  13368. chunk.storeName = this.storeName;
  13369. chunk.edited = this.edited;
  13370. return chunk;
  13371. }
  13372. contains(index) {
  13373. return this.start < index && index < this.end;
  13374. }
  13375. eachNext(fn) {
  13376. let chunk = this;
  13377. while (chunk) {
  13378. fn(chunk);
  13379. chunk = chunk.next;
  13380. }
  13381. }
  13382. eachPrevious(fn) {
  13383. let chunk = this;
  13384. while (chunk) {
  13385. fn(chunk);
  13386. chunk = chunk.previous;
  13387. }
  13388. }
  13389. edit(content, storeName, contentOnly) {
  13390. this.content = content;
  13391. if (!contentOnly) {
  13392. this.intro = '';
  13393. this.outro = '';
  13394. }
  13395. this.storeName = storeName;
  13396. this.edited = true;
  13397. return this;
  13398. }
  13399. prependLeft(content) {
  13400. this.outro = content + this.outro;
  13401. }
  13402. prependRight(content) {
  13403. this.intro = content + this.intro;
  13404. }
  13405. split(index) {
  13406. const sliceIndex = index - this.start;
  13407. const originalBefore = this.original.slice(0, sliceIndex);
  13408. const originalAfter = this.original.slice(sliceIndex);
  13409. this.original = originalBefore;
  13410. const newChunk = new Chunk(index, this.end, originalAfter);
  13411. newChunk.outro = this.outro;
  13412. this.outro = '';
  13413. this.end = index;
  13414. if (this.edited) {
  13415. // TODO is this block necessary?...
  13416. newChunk.edit('', false);
  13417. this.content = '';
  13418. } else {
  13419. this.content = originalBefore;
  13420. }
  13421. newChunk.next = this.next;
  13422. if (newChunk.next) newChunk.next.previous = newChunk;
  13423. newChunk.previous = this;
  13424. this.next = newChunk;
  13425. return newChunk;
  13426. }
  13427. toString() {
  13428. return this.intro + this.content + this.outro;
  13429. }
  13430. trimEnd(rx) {
  13431. this.outro = this.outro.replace(rx, '');
  13432. if (this.outro.length) return true;
  13433. const trimmed = this.content.replace(rx, '');
  13434. if (trimmed.length) {
  13435. if (trimmed !== this.content) {
  13436. this.split(this.start + trimmed.length).edit('', undefined, true);
  13437. }
  13438. return true;
  13439. } else {
  13440. this.edit('', undefined, true);
  13441. this.intro = this.intro.replace(rx, '');
  13442. if (this.intro.length) return true;
  13443. }
  13444. }
  13445. trimStart(rx) {
  13446. this.intro = this.intro.replace(rx, '');
  13447. if (this.intro.length) return true;
  13448. const trimmed = this.content.replace(rx, '');
  13449. if (trimmed.length) {
  13450. if (trimmed !== this.content) {
  13451. this.split(this.end - trimmed.length);
  13452. this.edit('', undefined, true);
  13453. }
  13454. return true;
  13455. } else {
  13456. this.edit('', undefined, true);
  13457. this.outro = this.outro.replace(rx, '');
  13458. if (this.outro.length) return true;
  13459. }
  13460. }
  13461. }
  13462. function getBtoa() {
  13463. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  13464. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  13465. } else if (typeof Buffer === 'function') {
  13466. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  13467. } else {
  13468. return () => {
  13469. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  13470. };
  13471. }
  13472. }
  13473. const btoa$1 = /*#__PURE__*/ getBtoa();
  13474. class SourceMap {
  13475. constructor(properties) {
  13476. this.version = 3;
  13477. this.file = properties.file;
  13478. this.sources = properties.sources;
  13479. this.sourcesContent = properties.sourcesContent;
  13480. this.names = properties.names;
  13481. this.mappings = encode$1(properties.mappings);
  13482. if (typeof properties.x_google_ignoreList !== 'undefined') {
  13483. this.x_google_ignoreList = properties.x_google_ignoreList;
  13484. }
  13485. }
  13486. toString() {
  13487. return JSON.stringify(this);
  13488. }
  13489. toUrl() {
  13490. return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
  13491. }
  13492. }
  13493. function guessIndent(code) {
  13494. const lines = code.split('\n');
  13495. const tabbed = lines.filter((line) => /^\t+/.test(line));
  13496. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  13497. if (tabbed.length === 0 && spaced.length === 0) {
  13498. return null;
  13499. }
  13500. // More lines tabbed than spaced? Assume tabs, and
  13501. // default to tabs in the case of a tie (or nothing
  13502. // to go on)
  13503. if (tabbed.length >= spaced.length) {
  13504. return '\t';
  13505. }
  13506. // Otherwise, we need to guess the multiple
  13507. const min = spaced.reduce((previous, current) => {
  13508. const numSpaces = /^ +/.exec(current)[0].length;
  13509. return Math.min(numSpaces, previous);
  13510. }, Infinity);
  13511. return new Array(min + 1).join(' ');
  13512. }
  13513. function getRelativePath(from, to) {
  13514. const fromParts = from.split(/[/\\]/);
  13515. const toParts = to.split(/[/\\]/);
  13516. fromParts.pop(); // get dirname
  13517. while (fromParts[0] === toParts[0]) {
  13518. fromParts.shift();
  13519. toParts.shift();
  13520. }
  13521. if (fromParts.length) {
  13522. let i = fromParts.length;
  13523. while (i--) fromParts[i] = '..';
  13524. }
  13525. return fromParts.concat(toParts).join('/');
  13526. }
  13527. const toString$2 = Object.prototype.toString;
  13528. function isObject$1(thing) {
  13529. return toString$2.call(thing) === '[object Object]';
  13530. }
  13531. function getLocator(source) {
  13532. const originalLines = source.split('\n');
  13533. const lineOffsets = [];
  13534. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  13535. lineOffsets.push(pos);
  13536. pos += originalLines[i].length + 1;
  13537. }
  13538. return function locate(index) {
  13539. let i = 0;
  13540. let j = lineOffsets.length;
  13541. while (i < j) {
  13542. const m = (i + j) >> 1;
  13543. if (index < lineOffsets[m]) {
  13544. j = m;
  13545. } else {
  13546. i = m + 1;
  13547. }
  13548. }
  13549. const line = i - 1;
  13550. const column = index - lineOffsets[line];
  13551. return { line, column };
  13552. };
  13553. }
  13554. const wordRegex = /\w/;
  13555. class Mappings {
  13556. constructor(hires) {
  13557. this.hires = hires;
  13558. this.generatedCodeLine = 0;
  13559. this.generatedCodeColumn = 0;
  13560. this.raw = [];
  13561. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  13562. this.pending = null;
  13563. }
  13564. addEdit(sourceIndex, content, loc, nameIndex) {
  13565. if (content.length) {
  13566. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  13567. if (nameIndex >= 0) {
  13568. segment.push(nameIndex);
  13569. }
  13570. this.rawSegments.push(segment);
  13571. } else if (this.pending) {
  13572. this.rawSegments.push(this.pending);
  13573. }
  13574. this.advance(content);
  13575. this.pending = null;
  13576. }
  13577. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  13578. let originalCharIndex = chunk.start;
  13579. let first = true;
  13580. // when iterating each char, check if it's in a word boundary
  13581. let charInHiresBoundary = false;
  13582. while (originalCharIndex < chunk.end) {
  13583. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  13584. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  13585. if (this.hires === 'boundary') {
  13586. // in hires "boundary", group segments per word boundary than per char
  13587. if (wordRegex.test(original[originalCharIndex])) {
  13588. // for first char in the boundary found, start the boundary by pushing a segment
  13589. if (!charInHiresBoundary) {
  13590. this.rawSegments.push(segment);
  13591. charInHiresBoundary = true;
  13592. }
  13593. } else {
  13594. // for non-word char, end the boundary by pushing a segment
  13595. this.rawSegments.push(segment);
  13596. charInHiresBoundary = false;
  13597. }
  13598. } else {
  13599. this.rawSegments.push(segment);
  13600. }
  13601. }
  13602. if (original[originalCharIndex] === '\n') {
  13603. loc.line += 1;
  13604. loc.column = 0;
  13605. this.generatedCodeLine += 1;
  13606. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  13607. this.generatedCodeColumn = 0;
  13608. first = true;
  13609. } else {
  13610. loc.column += 1;
  13611. this.generatedCodeColumn += 1;
  13612. first = false;
  13613. }
  13614. originalCharIndex += 1;
  13615. }
  13616. this.pending = null;
  13617. }
  13618. advance(str) {
  13619. if (!str) return;
  13620. const lines = str.split('\n');
  13621. if (lines.length > 1) {
  13622. for (let i = 0; i < lines.length - 1; i++) {
  13623. this.generatedCodeLine++;
  13624. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  13625. }
  13626. this.generatedCodeColumn = 0;
  13627. }
  13628. this.generatedCodeColumn += lines[lines.length - 1].length;
  13629. }
  13630. }
  13631. const n$1 = '\n';
  13632. const warned = {
  13633. insertLeft: false,
  13634. insertRight: false,
  13635. storeName: false,
  13636. };
  13637. class MagicString {
  13638. constructor(string, options = {}) {
  13639. const chunk = new Chunk(0, string.length, string);
  13640. Object.defineProperties(this, {
  13641. original: { writable: true, value: string },
  13642. outro: { writable: true, value: '' },
  13643. intro: { writable: true, value: '' },
  13644. firstChunk: { writable: true, value: chunk },
  13645. lastChunk: { writable: true, value: chunk },
  13646. lastSearchedChunk: { writable: true, value: chunk },
  13647. byStart: { writable: true, value: {} },
  13648. byEnd: { writable: true, value: {} },
  13649. filename: { writable: true, value: options.filename },
  13650. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  13651. sourcemapLocations: { writable: true, value: new BitSet() },
  13652. storedNames: { writable: true, value: {} },
  13653. indentStr: { writable: true, value: undefined },
  13654. ignoreList: { writable: true, value: options.ignoreList },
  13655. });
  13656. this.byStart[0] = chunk;
  13657. this.byEnd[string.length] = chunk;
  13658. }
  13659. addSourcemapLocation(char) {
  13660. this.sourcemapLocations.add(char);
  13661. }
  13662. append(content) {
  13663. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  13664. this.outro += content;
  13665. return this;
  13666. }
  13667. appendLeft(index, content) {
  13668. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13669. this._split(index);
  13670. const chunk = this.byEnd[index];
  13671. if (chunk) {
  13672. chunk.appendLeft(content);
  13673. } else {
  13674. this.intro += content;
  13675. }
  13676. return this;
  13677. }
  13678. appendRight(index, content) {
  13679. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13680. this._split(index);
  13681. const chunk = this.byStart[index];
  13682. if (chunk) {
  13683. chunk.appendRight(content);
  13684. } else {
  13685. this.outro += content;
  13686. }
  13687. return this;
  13688. }
  13689. clone() {
  13690. const cloned = new MagicString(this.original, { filename: this.filename });
  13691. let originalChunk = this.firstChunk;
  13692. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  13693. while (originalChunk) {
  13694. cloned.byStart[clonedChunk.start] = clonedChunk;
  13695. cloned.byEnd[clonedChunk.end] = clonedChunk;
  13696. const nextOriginalChunk = originalChunk.next;
  13697. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  13698. if (nextClonedChunk) {
  13699. clonedChunk.next = nextClonedChunk;
  13700. nextClonedChunk.previous = clonedChunk;
  13701. clonedChunk = nextClonedChunk;
  13702. }
  13703. originalChunk = nextOriginalChunk;
  13704. }
  13705. cloned.lastChunk = clonedChunk;
  13706. if (this.indentExclusionRanges) {
  13707. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  13708. }
  13709. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  13710. cloned.intro = this.intro;
  13711. cloned.outro = this.outro;
  13712. return cloned;
  13713. }
  13714. generateDecodedMap(options) {
  13715. options = options || {};
  13716. const sourceIndex = 0;
  13717. const names = Object.keys(this.storedNames);
  13718. const mappings = new Mappings(options.hires);
  13719. const locate = getLocator(this.original);
  13720. if (this.intro) {
  13721. mappings.advance(this.intro);
  13722. }
  13723. this.firstChunk.eachNext((chunk) => {
  13724. const loc = locate(chunk.start);
  13725. if (chunk.intro.length) mappings.advance(chunk.intro);
  13726. if (chunk.edited) {
  13727. mappings.addEdit(
  13728. sourceIndex,
  13729. chunk.content,
  13730. loc,
  13731. chunk.storeName ? names.indexOf(chunk.original) : -1,
  13732. );
  13733. } else {
  13734. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  13735. }
  13736. if (chunk.outro.length) mappings.advance(chunk.outro);
  13737. });
  13738. return {
  13739. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  13740. sources: [
  13741. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  13742. ],
  13743. sourcesContent: options.includeContent ? [this.original] : undefined,
  13744. names,
  13745. mappings: mappings.raw,
  13746. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  13747. };
  13748. }
  13749. generateMap(options) {
  13750. return new SourceMap(this.generateDecodedMap(options));
  13751. }
  13752. _ensureindentStr() {
  13753. if (this.indentStr === undefined) {
  13754. this.indentStr = guessIndent(this.original);
  13755. }
  13756. }
  13757. _getRawIndentString() {
  13758. this._ensureindentStr();
  13759. return this.indentStr;
  13760. }
  13761. getIndentString() {
  13762. this._ensureindentStr();
  13763. return this.indentStr === null ? '\t' : this.indentStr;
  13764. }
  13765. indent(indentStr, options) {
  13766. const pattern = /^[^\r\n]/gm;
  13767. if (isObject$1(indentStr)) {
  13768. options = indentStr;
  13769. indentStr = undefined;
  13770. }
  13771. if (indentStr === undefined) {
  13772. this._ensureindentStr();
  13773. indentStr = this.indentStr || '\t';
  13774. }
  13775. if (indentStr === '') return this; // noop
  13776. options = options || {};
  13777. // Process exclusion ranges
  13778. const isExcluded = {};
  13779. if (options.exclude) {
  13780. const exclusions =
  13781. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  13782. exclusions.forEach((exclusion) => {
  13783. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  13784. isExcluded[i] = true;
  13785. }
  13786. });
  13787. }
  13788. let shouldIndentNextCharacter = options.indentStart !== false;
  13789. const replacer = (match) => {
  13790. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  13791. shouldIndentNextCharacter = true;
  13792. return match;
  13793. };
  13794. this.intro = this.intro.replace(pattern, replacer);
  13795. let charIndex = 0;
  13796. let chunk = this.firstChunk;
  13797. while (chunk) {
  13798. const end = chunk.end;
  13799. if (chunk.edited) {
  13800. if (!isExcluded[charIndex]) {
  13801. chunk.content = chunk.content.replace(pattern, replacer);
  13802. if (chunk.content.length) {
  13803. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  13804. }
  13805. }
  13806. } else {
  13807. charIndex = chunk.start;
  13808. while (charIndex < end) {
  13809. if (!isExcluded[charIndex]) {
  13810. const char = this.original[charIndex];
  13811. if (char === '\n') {
  13812. shouldIndentNextCharacter = true;
  13813. } else if (char !== '\r' && shouldIndentNextCharacter) {
  13814. shouldIndentNextCharacter = false;
  13815. if (charIndex === chunk.start) {
  13816. chunk.prependRight(indentStr);
  13817. } else {
  13818. this._splitChunk(chunk, charIndex);
  13819. chunk = chunk.next;
  13820. chunk.prependRight(indentStr);
  13821. }
  13822. }
  13823. }
  13824. charIndex += 1;
  13825. }
  13826. }
  13827. charIndex = chunk.end;
  13828. chunk = chunk.next;
  13829. }
  13830. this.outro = this.outro.replace(pattern, replacer);
  13831. return this;
  13832. }
  13833. insert() {
  13834. throw new Error(
  13835. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  13836. );
  13837. }
  13838. insertLeft(index, content) {
  13839. if (!warned.insertLeft) {
  13840. console.warn(
  13841. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  13842. ); // eslint-disable-line no-console
  13843. warned.insertLeft = true;
  13844. }
  13845. return this.appendLeft(index, content);
  13846. }
  13847. insertRight(index, content) {
  13848. if (!warned.insertRight) {
  13849. console.warn(
  13850. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  13851. ); // eslint-disable-line no-console
  13852. warned.insertRight = true;
  13853. }
  13854. return this.prependRight(index, content);
  13855. }
  13856. move(start, end, index) {
  13857. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  13858. this._split(start);
  13859. this._split(end);
  13860. this._split(index);
  13861. const first = this.byStart[start];
  13862. const last = this.byEnd[end];
  13863. const oldLeft = first.previous;
  13864. const oldRight = last.next;
  13865. const newRight = this.byStart[index];
  13866. if (!newRight && last === this.lastChunk) return this;
  13867. const newLeft = newRight ? newRight.previous : this.lastChunk;
  13868. if (oldLeft) oldLeft.next = oldRight;
  13869. if (oldRight) oldRight.previous = oldLeft;
  13870. if (newLeft) newLeft.next = first;
  13871. if (newRight) newRight.previous = last;
  13872. if (!first.previous) this.firstChunk = last.next;
  13873. if (!last.next) {
  13874. this.lastChunk = first.previous;
  13875. this.lastChunk.next = null;
  13876. }
  13877. first.previous = newLeft;
  13878. last.next = newRight || null;
  13879. if (!newLeft) this.firstChunk = first;
  13880. if (!newRight) this.lastChunk = last;
  13881. return this;
  13882. }
  13883. overwrite(start, end, content, options) {
  13884. options = options || {};
  13885. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  13886. }
  13887. update(start, end, content, options) {
  13888. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  13889. while (start < 0) start += this.original.length;
  13890. while (end < 0) end += this.original.length;
  13891. if (end > this.original.length) throw new Error('end is out of bounds');
  13892. if (start === end)
  13893. throw new Error(
  13894. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  13895. );
  13896. this._split(start);
  13897. this._split(end);
  13898. if (options === true) {
  13899. if (!warned.storeName) {
  13900. console.warn(
  13901. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  13902. ); // eslint-disable-line no-console
  13903. warned.storeName = true;
  13904. }
  13905. options = { storeName: true };
  13906. }
  13907. const storeName = options !== undefined ? options.storeName : false;
  13908. const overwrite = options !== undefined ? options.overwrite : false;
  13909. if (storeName) {
  13910. const original = this.original.slice(start, end);
  13911. Object.defineProperty(this.storedNames, original, {
  13912. writable: true,
  13913. value: true,
  13914. enumerable: true,
  13915. });
  13916. }
  13917. const first = this.byStart[start];
  13918. const last = this.byEnd[end];
  13919. if (first) {
  13920. let chunk = first;
  13921. while (chunk !== last) {
  13922. if (chunk.next !== this.byStart[chunk.end]) {
  13923. throw new Error('Cannot overwrite across a split point');
  13924. }
  13925. chunk = chunk.next;
  13926. chunk.edit('', false);
  13927. }
  13928. first.edit(content, storeName, !overwrite);
  13929. } else {
  13930. // must be inserting at the end
  13931. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  13932. // TODO last chunk in the array may not be the last chunk, if it's moved...
  13933. last.next = newChunk;
  13934. newChunk.previous = last;
  13935. }
  13936. return this;
  13937. }
  13938. prepend(content) {
  13939. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  13940. this.intro = content + this.intro;
  13941. return this;
  13942. }
  13943. prependLeft(index, content) {
  13944. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13945. this._split(index);
  13946. const chunk = this.byEnd[index];
  13947. if (chunk) {
  13948. chunk.prependLeft(content);
  13949. } else {
  13950. this.intro = content + this.intro;
  13951. }
  13952. return this;
  13953. }
  13954. prependRight(index, content) {
  13955. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  13956. this._split(index);
  13957. const chunk = this.byStart[index];
  13958. if (chunk) {
  13959. chunk.prependRight(content);
  13960. } else {
  13961. this.outro = content + this.outro;
  13962. }
  13963. return this;
  13964. }
  13965. remove(start, end) {
  13966. while (start < 0) start += this.original.length;
  13967. while (end < 0) end += this.original.length;
  13968. if (start === end) return this;
  13969. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  13970. if (start > end) throw new Error('end must be greater than start');
  13971. this._split(start);
  13972. this._split(end);
  13973. let chunk = this.byStart[start];
  13974. while (chunk) {
  13975. chunk.intro = '';
  13976. chunk.outro = '';
  13977. chunk.edit('');
  13978. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  13979. }
  13980. return this;
  13981. }
  13982. lastChar() {
  13983. if (this.outro.length) return this.outro[this.outro.length - 1];
  13984. let chunk = this.lastChunk;
  13985. do {
  13986. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  13987. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  13988. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  13989. } while ((chunk = chunk.previous));
  13990. if (this.intro.length) return this.intro[this.intro.length - 1];
  13991. return '';
  13992. }
  13993. lastLine() {
  13994. let lineIndex = this.outro.lastIndexOf(n$1);
  13995. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  13996. let lineStr = this.outro;
  13997. let chunk = this.lastChunk;
  13998. do {
  13999. if (chunk.outro.length > 0) {
  14000. lineIndex = chunk.outro.lastIndexOf(n$1);
  14001. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  14002. lineStr = chunk.outro + lineStr;
  14003. }
  14004. if (chunk.content.length > 0) {
  14005. lineIndex = chunk.content.lastIndexOf(n$1);
  14006. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  14007. lineStr = chunk.content + lineStr;
  14008. }
  14009. if (chunk.intro.length > 0) {
  14010. lineIndex = chunk.intro.lastIndexOf(n$1);
  14011. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  14012. lineStr = chunk.intro + lineStr;
  14013. }
  14014. } while ((chunk = chunk.previous));
  14015. lineIndex = this.intro.lastIndexOf(n$1);
  14016. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  14017. return this.intro + lineStr;
  14018. }
  14019. slice(start = 0, end = this.original.length) {
  14020. while (start < 0) start += this.original.length;
  14021. while (end < 0) end += this.original.length;
  14022. let result = '';
  14023. // find start chunk
  14024. let chunk = this.firstChunk;
  14025. while (chunk && (chunk.start > start || chunk.end <= start)) {
  14026. // found end chunk before start
  14027. if (chunk.start < end && chunk.end >= end) {
  14028. return result;
  14029. }
  14030. chunk = chunk.next;
  14031. }
  14032. if (chunk && chunk.edited && chunk.start !== start)
  14033. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  14034. const startChunk = chunk;
  14035. while (chunk) {
  14036. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  14037. result += chunk.intro;
  14038. }
  14039. const containsEnd = chunk.start < end && chunk.end >= end;
  14040. if (containsEnd && chunk.edited && chunk.end !== end)
  14041. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  14042. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  14043. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  14044. result += chunk.content.slice(sliceStart, sliceEnd);
  14045. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  14046. result += chunk.outro;
  14047. }
  14048. if (containsEnd) {
  14049. break;
  14050. }
  14051. chunk = chunk.next;
  14052. }
  14053. return result;
  14054. }
  14055. // TODO deprecate this? not really very useful
  14056. snip(start, end) {
  14057. const clone = this.clone();
  14058. clone.remove(0, start);
  14059. clone.remove(end, clone.original.length);
  14060. return clone;
  14061. }
  14062. _split(index) {
  14063. if (this.byStart[index] || this.byEnd[index]) return;
  14064. let chunk = this.lastSearchedChunk;
  14065. const searchForward = index > chunk.end;
  14066. while (chunk) {
  14067. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  14068. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  14069. }
  14070. }
  14071. _splitChunk(chunk, index) {
  14072. if (chunk.edited && chunk.content.length) {
  14073. // zero-length edited chunks are a special case (overlapping replacements)
  14074. const loc = getLocator(this.original)(index);
  14075. throw new Error(
  14076. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  14077. );
  14078. }
  14079. const newChunk = chunk.split(index);
  14080. this.byEnd[index] = chunk;
  14081. this.byStart[index] = newChunk;
  14082. this.byEnd[newChunk.end] = newChunk;
  14083. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  14084. this.lastSearchedChunk = chunk;
  14085. return true;
  14086. }
  14087. toString() {
  14088. let str = this.intro;
  14089. let chunk = this.firstChunk;
  14090. while (chunk) {
  14091. str += chunk.toString();
  14092. chunk = chunk.next;
  14093. }
  14094. return str + this.outro;
  14095. }
  14096. isEmpty() {
  14097. let chunk = this.firstChunk;
  14098. do {
  14099. if (
  14100. (chunk.intro.length && chunk.intro.trim()) ||
  14101. (chunk.content.length && chunk.content.trim()) ||
  14102. (chunk.outro.length && chunk.outro.trim())
  14103. )
  14104. return false;
  14105. } while ((chunk = chunk.next));
  14106. return true;
  14107. }
  14108. length() {
  14109. let chunk = this.firstChunk;
  14110. let length = 0;
  14111. do {
  14112. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  14113. } while ((chunk = chunk.next));
  14114. return length;
  14115. }
  14116. trimLines() {
  14117. return this.trim('[\\r\\n]');
  14118. }
  14119. trim(charType) {
  14120. return this.trimStart(charType).trimEnd(charType);
  14121. }
  14122. trimEndAborted(charType) {
  14123. const rx = new RegExp((charType || '\\s') + '+$');
  14124. this.outro = this.outro.replace(rx, '');
  14125. if (this.outro.length) return true;
  14126. let chunk = this.lastChunk;
  14127. do {
  14128. const end = chunk.end;
  14129. const aborted = chunk.trimEnd(rx);
  14130. // if chunk was trimmed, we have a new lastChunk
  14131. if (chunk.end !== end) {
  14132. if (this.lastChunk === chunk) {
  14133. this.lastChunk = chunk.next;
  14134. }
  14135. this.byEnd[chunk.end] = chunk;
  14136. this.byStart[chunk.next.start] = chunk.next;
  14137. this.byEnd[chunk.next.end] = chunk.next;
  14138. }
  14139. if (aborted) return true;
  14140. chunk = chunk.previous;
  14141. } while (chunk);
  14142. return false;
  14143. }
  14144. trimEnd(charType) {
  14145. this.trimEndAborted(charType);
  14146. return this;
  14147. }
  14148. trimStartAborted(charType) {
  14149. const rx = new RegExp('^' + (charType || '\\s') + '+');
  14150. this.intro = this.intro.replace(rx, '');
  14151. if (this.intro.length) return true;
  14152. let chunk = this.firstChunk;
  14153. do {
  14154. const end = chunk.end;
  14155. const aborted = chunk.trimStart(rx);
  14156. if (chunk.end !== end) {
  14157. // special case...
  14158. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  14159. this.byEnd[chunk.end] = chunk;
  14160. this.byStart[chunk.next.start] = chunk.next;
  14161. this.byEnd[chunk.next.end] = chunk.next;
  14162. }
  14163. if (aborted) return true;
  14164. chunk = chunk.next;
  14165. } while (chunk);
  14166. return false;
  14167. }
  14168. trimStart(charType) {
  14169. this.trimStartAborted(charType);
  14170. return this;
  14171. }
  14172. hasChanged() {
  14173. return this.original !== this.toString();
  14174. }
  14175. _replaceRegexp(searchValue, replacement) {
  14176. function getReplacement(match, str) {
  14177. if (typeof replacement === 'string') {
  14178. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  14179. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  14180. if (i === '$') return '$';
  14181. if (i === '&') return match[0];
  14182. const num = +i;
  14183. if (num < match.length) return match[+i];
  14184. return `$${i}`;
  14185. });
  14186. } else {
  14187. return replacement(...match, match.index, str, match.groups);
  14188. }
  14189. }
  14190. function matchAll(re, str) {
  14191. let match;
  14192. const matches = [];
  14193. while ((match = re.exec(str))) {
  14194. matches.push(match);
  14195. }
  14196. return matches;
  14197. }
  14198. if (searchValue.global) {
  14199. const matches = matchAll(searchValue, this.original);
  14200. matches.forEach((match) => {
  14201. if (match.index != null)
  14202. this.overwrite(
  14203. match.index,
  14204. match.index + match[0].length,
  14205. getReplacement(match, this.original),
  14206. );
  14207. });
  14208. } else {
  14209. const match = this.original.match(searchValue);
  14210. if (match && match.index != null)
  14211. this.overwrite(
  14212. match.index,
  14213. match.index + match[0].length,
  14214. getReplacement(match, this.original),
  14215. );
  14216. }
  14217. return this;
  14218. }
  14219. _replaceString(string, replacement) {
  14220. const { original } = this;
  14221. const index = original.indexOf(string);
  14222. if (index !== -1) {
  14223. this.overwrite(index, index + string.length, replacement);
  14224. }
  14225. return this;
  14226. }
  14227. replace(searchValue, replacement) {
  14228. if (typeof searchValue === 'string') {
  14229. return this._replaceString(searchValue, replacement);
  14230. }
  14231. return this._replaceRegexp(searchValue, replacement);
  14232. }
  14233. _replaceAllString(string, replacement) {
  14234. const { original } = this;
  14235. const stringLength = string.length;
  14236. for (
  14237. let index = original.indexOf(string);
  14238. index !== -1;
  14239. index = original.indexOf(string, index + stringLength)
  14240. ) {
  14241. this.overwrite(index, index + stringLength, replacement);
  14242. }
  14243. return this;
  14244. }
  14245. replaceAll(searchValue, replacement) {
  14246. if (typeof searchValue === 'string') {
  14247. return this._replaceAllString(searchValue, replacement);
  14248. }
  14249. if (!searchValue.global) {
  14250. throw new TypeError(
  14251. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  14252. );
  14253. }
  14254. return this._replaceRegexp(searchValue, replacement);
  14255. }
  14256. }
  14257. const assetUrlRE = /__VITE_ASSET__([a-z\d]+)__(?:\$_(.*?)__)?/g;
  14258. const rawRE$1 = /(?:\?|&)raw(?:&|$)/;
  14259. const urlRE$1 = /(\?|&)url(?:&|$)/;
  14260. const jsSourceMapRE = /\.[cm]?js\.map$/;
  14261. const unnededFinalQueryCharRE = /[?&]$/;
  14262. const assetCache = new WeakMap();
  14263. const generatedAssets = new WeakMap();
  14264. // add own dictionary entry by directly assigning mrmime
  14265. function registerCustomMime() {
  14266. // https://github.com/lukeed/mrmime/issues/3
  14267. mimes$1['ico'] = 'image/x-icon';
  14268. // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#flac
  14269. mimes$1['flac'] = 'audio/flac';
  14270. // mrmime and mime-db is not released yet: https://github.com/jshttp/mime-db/commit/c9242a9b7d4bb25d7a0c9244adec74aeef08d8a1
  14271. mimes$1['aac'] = 'audio/aac';
  14272. // https://wiki.xiph.org/MIME_Types_and_File_Extensions#.opus_-_audio/ogg
  14273. mimes$1['opus'] = 'audio/ogg';
  14274. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  14275. mimes$1['eot'] = 'application/vnd.ms-fontobject';
  14276. }
  14277. function renderAssetUrlInJS(ctx, config, chunk, opts, code) {
  14278. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker);
  14279. let match;
  14280. let s;
  14281. // Urls added with JS using e.g.
  14282. // imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes
  14283. // Urls added in CSS that is imported in JS end up like
  14284. // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";
  14285. // In both cases, the wrapping should already be fine
  14286. assetUrlRE.lastIndex = 0;
  14287. while ((match = assetUrlRE.exec(code))) {
  14288. s || (s = new MagicString(code));
  14289. const [full, referenceId, postfix = ''] = match;
  14290. const file = ctx.getFileName(referenceId);
  14291. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  14292. const filename = file + postfix;
  14293. const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
  14294. const replacementString = typeof replacement === 'string'
  14295. ? JSON.stringify(replacement).slice(1, -1)
  14296. : `"+${replacement.runtime}+"`;
  14297. s.update(match.index, match.index + full.length, replacementString);
  14298. }
  14299. // Replace __VITE_PUBLIC_ASSET__5aa0ddc0__ with absolute paths
  14300. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  14301. publicAssetUrlRE.lastIndex = 0;
  14302. while ((match = publicAssetUrlRE.exec(code))) {
  14303. s || (s = new MagicString(code));
  14304. const [full, hash] = match;
  14305. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  14306. const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime);
  14307. const replacementString = typeof replacement === 'string'
  14308. ? JSON.stringify(replacement).slice(1, -1)
  14309. : `"+${replacement.runtime}+"`;
  14310. s.update(match.index, match.index + full.length, replacementString);
  14311. }
  14312. return s;
  14313. }
  14314. /**
  14315. * Also supports loading plain strings with import text from './foo.txt?raw'
  14316. */
  14317. function assetPlugin(config) {
  14318. registerCustomMime();
  14319. return {
  14320. name: 'vite:asset',
  14321. buildStart() {
  14322. assetCache.set(config, new Map());
  14323. generatedAssets.set(config, new Map());
  14324. },
  14325. resolveId(id) {
  14326. if (!config.assetsInclude(cleanUrl(id)) && !urlRE$1.test(id)) {
  14327. return;
  14328. }
  14329. // imports to absolute urls pointing to files in /public
  14330. // will fail to resolve in the main resolver. handle them here.
  14331. const publicFile = checkPublicFile(id, config);
  14332. if (publicFile) {
  14333. return id;
  14334. }
  14335. },
  14336. async load(id) {
  14337. if (id[0] === '\0') {
  14338. // Rollup convention, this id should be handled by the
  14339. // plugin that marked it with \0
  14340. return;
  14341. }
  14342. // raw requests, read from disk
  14343. if (rawRE$1.test(id)) {
  14344. const file = checkPublicFile(id, config) || cleanUrl(id);
  14345. // raw query, read file and return as string
  14346. return `export default ${JSON.stringify(await fsp.readFile(file, 'utf-8'))}`;
  14347. }
  14348. if (!config.assetsInclude(cleanUrl(id)) && !urlRE$1.test(id)) {
  14349. return;
  14350. }
  14351. id = id.replace(urlRE$1, '$1').replace(unnededFinalQueryCharRE, '');
  14352. const url = await fileToUrl(id, config, this);
  14353. return `export default ${JSON.stringify(url)}`;
  14354. },
  14355. renderChunk(code, chunk, opts) {
  14356. const s = renderAssetUrlInJS(this, config, chunk, opts, code);
  14357. if (s) {
  14358. return {
  14359. code: s.toString(),
  14360. map: config.build.sourcemap
  14361. ? s.generateMap({ hires: 'boundary' })
  14362. : null,
  14363. };
  14364. }
  14365. else {
  14366. return null;
  14367. }
  14368. },
  14369. generateBundle(_, bundle) {
  14370. // do not emit assets for SSR build
  14371. if (config.command === 'build' &&
  14372. config.build.ssr &&
  14373. !config.build.ssrEmitAssets) {
  14374. for (const file in bundle) {
  14375. if (bundle[file].type === 'asset' &&
  14376. !file.endsWith('ssr-manifest.json') &&
  14377. !jsSourceMapRE.test(file)) {
  14378. delete bundle[file];
  14379. }
  14380. }
  14381. }
  14382. },
  14383. };
  14384. }
  14385. function checkPublicFile(url, { publicDir }) {
  14386. // note if the file is in /public, the resolver would have returned it
  14387. // as-is so it's not going to be a fully resolved path.
  14388. if (!publicDir || url[0] !== '/') {
  14389. return;
  14390. }
  14391. const publicFile = path$o.join(publicDir, cleanUrl(url));
  14392. if (!normalizePath$3(publicFile).startsWith(withTrailingSlash(normalizePath$3(publicDir)))) {
  14393. // can happen if URL starts with '../'
  14394. return;
  14395. }
  14396. if (fs$l.existsSync(publicFile)) {
  14397. return publicFile;
  14398. }
  14399. else {
  14400. return;
  14401. }
  14402. }
  14403. async function fileToUrl(id, config, ctx) {
  14404. if (config.command === 'serve') {
  14405. return fileToDevUrl(id, config);
  14406. }
  14407. else {
  14408. return fileToBuiltUrl(id, config, ctx);
  14409. }
  14410. }
  14411. function fileToDevUrl(id, config) {
  14412. let rtn;
  14413. if (checkPublicFile(id, config)) {
  14414. // in public dir, keep the url as-is
  14415. rtn = id;
  14416. }
  14417. else if (id.startsWith(withTrailingSlash(config.root))) {
  14418. // in project root, infer short public path
  14419. rtn = '/' + path$o.posix.relative(config.root, id);
  14420. }
  14421. else {
  14422. // outside of project root, use absolute fs path
  14423. // (this is special handled by the serve static middleware
  14424. rtn = path$o.posix.join(FS_PREFIX, id);
  14425. }
  14426. const base = joinUrlSegments(config.server?.origin ?? '', config.base);
  14427. return joinUrlSegments(base, removeLeadingSlash(rtn));
  14428. }
  14429. function getPublicAssetFilename(hash, config) {
  14430. return publicAssetUrlCache.get(config)?.get(hash);
  14431. }
  14432. const publicAssetUrlCache = new WeakMap();
  14433. const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
  14434. function publicFileToBuiltUrl(url, config) {
  14435. if (config.command !== 'build') {
  14436. // We don't need relative base or renderBuiltUrl support during dev
  14437. return joinUrlSegments(config.base, url);
  14438. }
  14439. const hash = getHash(url);
  14440. let cache = publicAssetUrlCache.get(config);
  14441. if (!cache) {
  14442. cache = new Map();
  14443. publicAssetUrlCache.set(config, cache);
  14444. }
  14445. if (!cache.get(hash)) {
  14446. cache.set(hash, url);
  14447. }
  14448. return `__VITE_PUBLIC_ASSET__${hash}__`;
  14449. }
  14450. const GIT_LFS_PREFIX = Buffer$1.from('version https://git-lfs.github.com');
  14451. function isGitLfsPlaceholder(content) {
  14452. if (content.length < GIT_LFS_PREFIX.length)
  14453. return false;
  14454. // Check whether the content begins with the characteristic string of Git LFS placeholders
  14455. return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
  14456. }
  14457. /**
  14458. * Register an asset to be emitted as part of the bundle (if necessary)
  14459. * and returns the resolved public URL
  14460. */
  14461. async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
  14462. if (!skipPublicCheck && checkPublicFile(id, config)) {
  14463. return publicFileToBuiltUrl(id, config);
  14464. }
  14465. const cache = assetCache.get(config);
  14466. const cached = cache.get(id);
  14467. if (cached) {
  14468. return cached;
  14469. }
  14470. const file = cleanUrl(id);
  14471. const content = await fsp.readFile(file);
  14472. let url;
  14473. if (config.build.lib ||
  14474. (!file.endsWith('.svg') &&
  14475. !file.endsWith('.html') &&
  14476. content.length < Number(config.build.assetsInlineLimit) &&
  14477. !isGitLfsPlaceholder(content))) {
  14478. if (config.build.lib && isGitLfsPlaceholder(content)) {
  14479. config.logger.warn(colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`));
  14480. }
  14481. const mimeType = lookup(file) ?? 'application/octet-stream';
  14482. // base64 inlined as a string
  14483. url = `data:${mimeType};base64,${content.toString('base64')}`;
  14484. }
  14485. else {
  14486. // emit as asset
  14487. const { search, hash } = parse$i(id);
  14488. const postfix = (search || '') + (hash || '');
  14489. const referenceId = pluginContext.emitFile({
  14490. // Ignore directory structure for asset file names
  14491. name: path$o.basename(file),
  14492. type: 'asset',
  14493. source: content,
  14494. });
  14495. const originalName = normalizePath$3(path$o.relative(config.root, file));
  14496. generatedAssets.get(config).set(referenceId, { originalName });
  14497. url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE
  14498. }
  14499. cache.set(id, url);
  14500. return url;
  14501. }
  14502. async function urlToBuiltUrl(url, importer, config, pluginContext) {
  14503. if (checkPublicFile(url, config)) {
  14504. return publicFileToBuiltUrl(url, config);
  14505. }
  14506. const file = url[0] === '/'
  14507. ? path$o.join(config.root, url)
  14508. : path$o.join(path$o.dirname(importer), url);
  14509. return fileToBuiltUrl(file, config, pluginContext,
  14510. // skip public check since we just did it above
  14511. true);
  14512. }
  14513. function manifestPlugin(config) {
  14514. const manifest = {};
  14515. let outputCount;
  14516. return {
  14517. name: 'vite:manifest',
  14518. buildStart() {
  14519. outputCount = 0;
  14520. },
  14521. generateBundle({ format }, bundle) {
  14522. function getChunkName(chunk) {
  14523. if (chunk.facadeModuleId) {
  14524. let name = normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId));
  14525. if (format === 'system' && !chunk.name.includes('-legacy')) {
  14526. const ext = path$o.extname(name);
  14527. const endPos = ext.length !== 0 ? -ext.length : undefined;
  14528. name = name.slice(0, endPos) + `-legacy` + ext;
  14529. }
  14530. return name.replace(/\0/g, '');
  14531. }
  14532. else {
  14533. return `_` + path$o.basename(chunk.fileName);
  14534. }
  14535. }
  14536. function getInternalImports(imports) {
  14537. const filteredImports = [];
  14538. for (const file of imports) {
  14539. if (bundle[file] === undefined) {
  14540. continue;
  14541. }
  14542. filteredImports.push(getChunkName(bundle[file]));
  14543. }
  14544. return filteredImports;
  14545. }
  14546. function createChunk(chunk) {
  14547. const manifestChunk = {
  14548. file: chunk.fileName,
  14549. };
  14550. if (chunk.facadeModuleId) {
  14551. manifestChunk.src = getChunkName(chunk);
  14552. }
  14553. if (chunk.isEntry) {
  14554. manifestChunk.isEntry = true;
  14555. }
  14556. if (chunk.isDynamicEntry) {
  14557. manifestChunk.isDynamicEntry = true;
  14558. }
  14559. if (chunk.imports.length) {
  14560. const internalImports = getInternalImports(chunk.imports);
  14561. if (internalImports.length > 0) {
  14562. manifestChunk.imports = internalImports;
  14563. }
  14564. }
  14565. if (chunk.dynamicImports.length) {
  14566. const internalImports = getInternalImports(chunk.dynamicImports);
  14567. if (internalImports.length > 0) {
  14568. manifestChunk.dynamicImports = internalImports;
  14569. }
  14570. }
  14571. if (chunk.viteMetadata?.importedCss.size) {
  14572. manifestChunk.css = [...chunk.viteMetadata.importedCss];
  14573. }
  14574. if (chunk.viteMetadata?.importedAssets.size) {
  14575. manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
  14576. }
  14577. return manifestChunk;
  14578. }
  14579. function createAsset(asset, src, isEntry) {
  14580. const manifestChunk = {
  14581. file: asset.fileName,
  14582. src,
  14583. };
  14584. if (isEntry)
  14585. manifestChunk.isEntry = true;
  14586. return manifestChunk;
  14587. }
  14588. const fileNameToAssetMeta = new Map();
  14589. const assets = generatedAssets.get(config);
  14590. assets.forEach((asset, referenceId) => {
  14591. const fileName = this.getFileName(referenceId);
  14592. fileNameToAssetMeta.set(fileName, asset);
  14593. });
  14594. const fileNameToAsset = new Map();
  14595. for (const file in bundle) {
  14596. const chunk = bundle[file];
  14597. if (chunk.type === 'chunk') {
  14598. manifest[getChunkName(chunk)] = createChunk(chunk);
  14599. }
  14600. else if (chunk.type === 'asset' && typeof chunk.name === 'string') {
  14601. // Add every unique asset to the manifest, keyed by its original name
  14602. const assetMeta = fileNameToAssetMeta.get(chunk.fileName);
  14603. const src = assetMeta?.originalName ?? chunk.name;
  14604. const asset = createAsset(chunk, src, assetMeta?.isEntry);
  14605. manifest[src] = asset;
  14606. fileNameToAsset.set(chunk.fileName, asset);
  14607. }
  14608. }
  14609. // Add deduplicated assets to the manifest
  14610. assets.forEach(({ originalName }, referenceId) => {
  14611. if (!manifest[originalName]) {
  14612. const fileName = this.getFileName(referenceId);
  14613. const asset = fileNameToAsset.get(fileName);
  14614. if (asset) {
  14615. manifest[originalName] = asset;
  14616. }
  14617. }
  14618. });
  14619. outputCount++;
  14620. const output = config.build.rollupOptions?.output;
  14621. const outputLength = Array.isArray(output) ? output.length : 1;
  14622. if (outputCount >= outputLength) {
  14623. this.emitFile({
  14624. fileName: typeof config.build.manifest === 'string'
  14625. ? config.build.manifest
  14626. : 'manifest.json',
  14627. type: 'asset',
  14628. source: jsonStableStringify$1(manifest, { space: 2 }),
  14629. });
  14630. }
  14631. },
  14632. };
  14633. }
  14634. // This is based on @rollup/plugin-data-uri
  14635. // MIT Licensed https://github.com/rollup/plugins/blob/master/LICENSE
  14636. // ref https://github.com/vitejs/vite/issues/1428#issuecomment-757033808
  14637. const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
  14638. const base64RE = /base64/i;
  14639. const dataUriPrefix = `\0/@data-uri/`;
  14640. /**
  14641. * Build only, since importing from a data URI works natively.
  14642. */
  14643. function dataURIPlugin() {
  14644. let resolved;
  14645. return {
  14646. name: 'vite:data-uri',
  14647. buildStart() {
  14648. resolved = new Map();
  14649. },
  14650. resolveId(id) {
  14651. if (!dataUriRE.test(id)) {
  14652. return;
  14653. }
  14654. const uri = new URL$3(id);
  14655. if (uri.protocol !== 'data:') {
  14656. return;
  14657. }
  14658. const match = uri.pathname.match(dataUriRE);
  14659. if (!match) {
  14660. return;
  14661. }
  14662. const [, mime, format, data] = match;
  14663. if (mime !== 'text/javascript') {
  14664. throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`);
  14665. }
  14666. // decode data
  14667. const base64 = format && base64RE.test(format.substring(1));
  14668. const content = base64
  14669. ? Buffer.from(data, 'base64').toString('utf-8')
  14670. : data;
  14671. resolved.set(id, content);
  14672. return dataUriPrefix + id;
  14673. },
  14674. load(id) {
  14675. if (id.startsWith(dataUriPrefix)) {
  14676. return resolved.get(id.slice(dataUriPrefix.length));
  14677. }
  14678. },
  14679. };
  14680. }
  14681. /* es-module-lexer 1.3.0 */
  14682. const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const D=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,D,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const K=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let D;C.ip()&&(D=J(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),K.push({n:D,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),o=I[0],D=B<0?void 0:E.slice(B,g),K=D?D[0]:"";k.push({s:A,e:Q,ls:B,le:g,n:'"'===o||"'"===o?J(I):I,ln:'"'===K||"'"===K?J(D):D});}function J(A){try{return (0, eval)(A)}catch(A){}}return [K,k,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const init=WebAssembly.compile((E="AGFzbQEAAAABKghgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gAn9/AAMvLgABAQICAgICAgICAgICAgICAgIAAwMDBAQAAAADAAAAAAMDAAUGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUGw8gALfwBBsPIACwdwEwZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAmFpAAgCaWQACQJpcAAKAmVzAAsCZWUADANlbHMADQNlbGUADgJyaQAPAnJlABABZgARBXBhcnNlABILX19oZWFwX2Jhc2UDAQqsPS5oAQF/QQAgADYC9AlBACgC0AkiASAAQQF0aiIAQQA7AQBBACAAQQJqIgA2AvgJQQAgADYC/AlBAEEANgLUCUEAQQA2AuQJQQBBADYC3AlBAEEANgLYCUEAQQA2AuwJQQBBADYC4AkgAQufAQEDf0EAKALkCSEEQQBBACgC/AkiBTYC5AlBACAENgLoCUEAIAVBIGo2AvwJIARBHGpB1AkgBBsgBTYCAEEAKALICSEEQQAoAsQJIQYgBSABNgIAIAUgADYCCCAFIAIgAkECakEAIAYgA0YbIAQgA0YbNgIMIAUgAzYCFCAFQQA2AhAgBSACNgIEIAVBADYCHCAFQQAoAsQJIANGOgAYC1YBAX9BACgC7AkiBEEQakHYCSAEG0EAKAL8CSIENgIAQQAgBDYC7AlBACAEQRRqNgL8CSAEQQA2AhAgBCADNgIMIAQgAjYCCCAEIAE2AgQgBCAANgIACwgAQQAoAoAKCxUAQQAoAtwJKAIAQQAoAtAJa0EBdQseAQF/QQAoAtwJKAIEIgBBACgC0AlrQQF1QX8gABsLFQBBACgC3AkoAghBACgC0AlrQQF1Cx4BAX9BACgC3AkoAgwiAEEAKALQCWtBAXVBfyAAGwseAQF/QQAoAtwJKAIQIgBBACgC0AlrQQF1QX8gABsLOwEBfwJAQQAoAtwJKAIUIgBBACgCxAlHDQBBfw8LAkAgAEEAKALICUcNAEF+DwsgAEEAKALQCWtBAXULCwBBACgC3AktABgLFQBBACgC4AkoAgBBACgC0AlrQQF1CxUAQQAoAuAJKAIEQQAoAtAJa0EBdQseAQF/QQAoAuAJKAIIIgBBACgC0AlrQQF1QX8gABsLHgEBf0EAKALgCSgCDCIAQQAoAtAJa0EBdUF/IAAbCyUBAX9BAEEAKALcCSIAQRxqQdQJIAAbKAIAIgA2AtwJIABBAEcLJQEBf0EAQQAoAuAJIgBBEGpB2AkgABsoAgAiADYC4AkgAEEARwsIAEEALQCECgvmDAEGfyMAQYDQAGsiACQAQQBBAToAhApBAEEAKALMCTYCjApBAEEAKALQCUF+aiIBNgKgCkEAIAFBACgC9AlBAXRqIgI2AqQKQQBBADsBhgpBAEEAOwGICkEAQQA6AJAKQQBBADYCgApBAEEAOgDwCUEAIABBgBBqNgKUCkEAIAA2ApgKQQBBADoAnAoCQAJAAkACQANAQQAgAUECaiIDNgKgCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BiAoNASADEBNFDQEgAUEEakGCCEEKEC0NARAUQQAtAIQKDQFBAEEAKAKgCiIBNgKMCgwHCyADEBNFDQAgAUEEakGMCEEKEC0NABAVC0EAQQAoAqAKNgKMCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAWDAELQQEQFwtBACgCpAohAkEAKAKgCiEBDAALC0EAIQIgAyEBQQAtAPAJDQIMAQtBACABNgKgCkEAQQA6AIQKCwNAQQAgAUECaiIDNgKgCgJAAkACQAJAAkACQAJAAkACQCABQQAoAqQKTw0AIAMvAQAiAkF3akEFSQ0IAkACQAJAAkACQAJAAkACQAJAAkAgAkFgag4KEhEGEREREQUBAgALAkACQAJAAkAgAkGgf2oOCgsUFAMUARQUFAIACyACQYV/ag4DBRMGCQtBAC8BiAoNEiADEBNFDRIgAUEEakGCCEEKEC0NEhAUDBILIAMQE0UNESABQQRqQYwIQQoQLQ0REBUMEQsgAxATRQ0QIAEpAARC7ICEg7COwDlSDRAgAS8BDCIDQXdqIgFBF0sNDkEBIAF0QZ+AgARxRQ0ODA8LQQBBAC8BiAoiAUEBajsBiApBACgClAogAUEDdGoiAUEBNgIAIAFBACgCjAo2AgQMDwtBAC8BiAoiAkUNC0EAIAJBf2oiBDsBiApBAC8BhgoiAkUNDiACQQJ0QQAoApgKakF8aigCACIFKAIUQQAoApQKIARB//8DcUEDdGooAgRHDQ4CQCAFKAIEDQAgBSADNgIEC0EAIAJBf2o7AYYKIAUgAUEEajYCDAwOCwJAQQAoAowKIgEvAQBBKUcNAEEAKALkCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAugJIgM2AuQJAkAgA0UNACADQQA2AhwMAQtBAEEANgLUCQtBAEEALwGICiIDQQFqOwGICkEAKAKUCiADQQN0aiIDQQZBAkEALQCcChs2AgAgAyABNgIEQQBBADoAnAoMDQtBAC8BiAoiAUUNCUEAIAFBf2oiATsBiApBACgClAogAUH//wNxQQN0aigCAEEERg0EDAwLQScQGAwLC0EiEBgMCgsgAkEvRw0JAkACQCABLwEEIgFBKkYNACABQS9HDQEQFgwMC0EBEBcMCwsCQAJAQQAoAowKIgEvAQAiAxAZRQ0AAkACQCADQVVqDgQACAEDCAsgAUF+ai8BAEErRg0GDAcLIAFBfmovAQBBLUYNBQwGCwJAIANB/QBGDQAgA0EpRw0FQQAoApQKQQAvAYgKQQN0aigCBBAaRQ0FDAYLQQAoApQKQQAvAYgKQQN0aiICKAIEEBsNBSACKAIAQQZGDQUMBAsgAUF+ai8BAEFQakH//wNxQQpJDQMMBAtBACgClApBAC8BiAoiAUEDdCIDakEAKAKMCjYCBEEAIAFBAWo7AYgKQQAoApQKIANqQQM2AgALEBwMBwtBAC0A8AlBAC8BhgpBAC8BiApyckUhAgwJCyABEB0NACADRQ0AIANBL0ZBAC0AkApBAEdxDQAgAUF+aiEBQQAoAtAJIQICQANAIAFBAmoiBCACTQ0BQQAgATYCjAogAS8BACEDIAFBfmoiBCEBIAMQHkUNAAsgBEECaiEEC0EBIQUgA0H//wNxEB9FDQEgBEF+aiEBAkADQCABQQJqIgMgAk0NAUEAIAE2AowKIAEvAQAhAyABQX5qIgQhASADEB8NAAsgBEECaiEDCyADECBFDQEQIUEAQQA6AJAKDAULECFBACEFC0EAIAU6AJAKDAMLECJBACECDAULIANBoAFHDQELQQBBAToAnAoLQQBBACgCoAo2AowKC0EAKAKgCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC0AkgAEcNAEEBDwsgAEF+ahAjC/IKAQZ/QQBBACgCoAoiAEEMaiIBNgKgCkEAKALsCSECQQEQJyEDAkACQAJAAkACQAJAAkACQAJAQQAoAqAKIgQgAUcNACADECZFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKgCkEBECchBEEAKAKgCiEFA0ACQAJAIARB//8DcSIDQSJGDQAgA0EnRg0AIAMQKhpBACgCoAohAwwBCyADEBhBAEEAKAKgCkECaiIDNgKgCgtBARAnGgJAIAUgAxArIgRBLEcNAEEAQQAoAqAKQQJqNgKgCkEBECchBAtBACgCoAohAyAEQf0ARg0DIAMgBUYNDyADIQUgA0EAKAKkCk0NAAwPCwtBACAEQQJqNgKgCkEBECcaQQAoAqAKIgMgAxArGgwCC0EAQQA6AIQKAkACQAJAAkACQAJAIANBn39qDgwCCwQBCwMLCwsLCwUACyADQfYARg0EDAoLQQAgBEEOaiIDNgKgCgJAAkACQEEBECdBn39qDgYAEgISEgESC0EAKAKgCiIFKQACQvOA5IPgjcAxUg0RIAUvAQoQH0UNEUEAIAVBCmo2AqAKQQAQJxoLQQAoAqAKIgVBAmpBoghBDhAtDRAgBS8BECICQXdqIgFBF0sNDUEBIAF0QZ+AgARxRQ0NDA4LQQAoAqAKIgUpAAJC7ICEg7COwDlSDQ8gBS8BCiICQXdqIgFBF00NBgwKC0EAIARBCmo2AqAKQQAQJxpBACgCoAohBAtBACAEQRBqNgKgCgJAQQEQJyIEQSpHDQBBAEEAKAKgCkECajYCoApBARAnIQQLQQAoAqAKIQMgBBAqGiADQQAoAqAKIgQgAyAEEAJBAEEAKAKgCkF+ajYCoAoPCwJAIAQpAAJC7ICEg7COwDlSDQAgBC8BChAeRQ0AQQAgBEEKajYCoApBARAnIQRBACgCoAohAyAEECoaIANBACgCoAoiBCADIAQQAkEAQQAoAqAKQX5qNgKgCg8LQQAgBEEEaiIENgKgCgtBACAEQQZqNgKgCkEAQQA6AIQKQQEQJyEEQQAoAqAKIQMgBBAqIQRBACgCoAohAiAEQd//A3EiAUHbAEcNA0EAIAJBAmo2AqAKQQEQJyEFQQAoAqAKIQNBACEEDAQLQQAgA0ECajYCoAoLQQEQJyEEQQAoAqAKIQMCQCAEQeYARw0AIANBAmpBnAhBBhAtDQBBACADQQhqNgKgCiAAQQEQJxApIAJBEGpB2AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2AqAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAqGkEBIQQMAQsCQAJAQQAoAqAKIgQgA0YNACADIAQgAyAEEAJBARAnIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoAqAKIQMCQCAEQSxHDQBBACADQQJqNgKgCkEBECchBUEAKAKgCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCoAoLIAFB2wBHDQJBACACQX5qNgKgCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCoApBARAnIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2AqAKAkBBARAnIgVBKkcNAEEAQQAoAqAKQQJqNgKgCkEBECchBQsgBUEoRg0BC0EAKAKgCiEBIAUQKhpBACgCoAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoAqAKQX5qNgKgCg8LIAQgA0EAQQAQAkEAIARBDGo2AqAKDwsQIgvUBgEEf0EAQQAoAqAKIgBBDGoiATYCoAoCQAJAAkACQAJAAkACQAJAAkACQEEBECciAkFZag4IBAIBBAEBAQMACyACQSJGDQMgAkH7AEYNBAtBACgCoAogAUcNAkEAIABBCmo2AqAKDwtBACgClApBAC8BiAoiAkEDdGoiAUEAKAKgCjYCBEEAIAJBAWo7AYgKIAFBBTYCAEEAKAKMCi8BAEEuRg0DQQBBACgCoAoiAUECajYCoApBARAnIQIgAEEAKAKgCkEAIAEQAUEAQQAvAYYKIgFBAWo7AYYKQQAoApgKIAFBAnRqQQAoAuQJNgIAAkAgAkEiRg0AIAJBJ0YNAEEAQQAoAqAKQX5qNgKgCg8LIAIQGEEAQQAoAqAKQQJqIgI2AqAKAkACQAJAQQEQJ0FXag4EAQICAAILQQBBACgCoApBAmo2AqAKQQEQJxpBACgC5AkiASACNgIEIAFBAToAGCABQQAoAqAKIgI2AhBBACACQX5qNgKgCg8LQQAoAuQJIgEgAjYCBCABQQE6ABhBAEEALwGICkF/ajsBiAogAUEAKAKgCkECajYCDEEAQQAvAYYKQX9qOwGGCg8LQQBBACgCoApBfmo2AqAKDwtBAEEAKAKgCkECajYCoApBARAnQe0ARw0CQQAoAqAKIgJBAmpBlghBBhAtDQICQEEAKAKMCiIBECgNACABLwEAQS5GDQMLIAAgACACQQhqQQAoAsgJEAEPC0EALwGICg0CQQAoAqAKIQJBACgCpAohAwNAIAIgA08NBQJAAkAgAi8BACIBQSdGDQAgAUEiRw0BCyAAIAEQKQ8LQQAgAkECaiICNgKgCgwACwtBACgCoAohAkEALwGICg0CAkADQAJAAkACQCACQQAoAqQKTw0AQQEQJyICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKgCkECajYCoAoLQQEQJyEBQQAoAqAKIQICQCABQeYARw0AIAJBAmpBnAhBBhAtDQgLQQAgAkEIajYCoApBARAnIgJBIkYNAyACQSdGDQMMBwsgAhAYC0EAQQAoAqAKQQJqIgI2AqAKDAALCyAAIAIQKQsPC0EAQQAoAqAKQX5qNgKgCg8LQQAgAkF+ajYCoAoPCxAiC0cBA39BACgCoApBAmohAEEAKAKkCiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2AqAKC5gBAQN/QQBBACgCoAoiAUECajYCoAogAUEGaiEBQQAoAqQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2AqAKDAELIAFBfmohAQtBACABNgKgCg8LIAFBAmohAQwACwuIAQEEf0EAKAKgCiEBQQAoAqQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKgChAiDwtBACABNgKgCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQZYJQQUQJA0AIABBoAlBAxAkDQAgAEGmCUECECQhAQsgAQuDAQECf0EBIQECQAJAAkACQAJAAkAgAC8BACICQUVqDgQFBAQBAAsCQCACQZt/ag4EAwQEAgALIAJBKUYNBCACQfkARw0DIABBfmpBsglBBhAkDwsgAEF+ai8BAEE9Rg8LIABBfmpBqglBBBAkDwsgAEF+akG+CUEDECQPC0EAIQELIAEL3gEBBH9BACgCoAohAEEAKAKkCiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2AqAKQQBBAC8BiAoiAkEBajsBiApBACgClAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCoApBAEEALwGICkF/aiIAOwGICkEAKAKUCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2AqAKCxAiCwu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQboIQQIQJA8LIABBfGpBvghBAxAkDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAlDwsgAEF6akHjABAlDwsgAEF8akHECEEEECQPCyAAQXxqQcwIQQYQJA8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB2AhBBhAkDwsgAEF4akHkCEECECQPCyAAQX5qQegIQQQQJA8LQQEhASAAQX5qIgBB6QAQJQ0EIABB8AhBBRAkDwsgAEF+akHkABAlDwsgAEF+akH6CEEHECQPCyAAQX5qQYgJQQQQJA8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAlDwsgAEF8akGQCUEDECQhAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAmcSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akHoCEEEECQPCyAAQX5qLwEAQfUARw0AIABBfGpBzAhBBhAkIQELIAELcAECfwJAAkADQEEAQQAoAqAKIgBBAmoiATYCoAogAEEAKAKkCk8NAQJAAkACQCABLwEAIgFBpX9qDgIBAgALAkAgAUF2ag4EBAMDBAALIAFBL0cNAgwECxAsGgwBC0EAIABBBGo2AqAKDAALCxAiCws1AQF/QQBBAToA8AlBACgCoAohAEEAQQAoAqQKQQJqNgKgCkEAIABBACgC0AlrQQF1NgKACgtDAQJ/QQEhAQJAIAAvAQAiAkF3akH//wNxQQVJDQAgAkGAAXJBoAFGDQBBACEBIAIQJkUNACACQS5HIAAQKHIPCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALQCSIFSQ0AIAAgASACEC0NAAJAIAAgBUcNAEEBDwsgBBAjIQMLIAMLPQECf0EAIQICQEEAKALQCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAEB4hAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKgCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQFgwCCyAAEBcMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACEB9FDQMMAQsgAkGgAUcNAgtBAEEAKAKgCiIDQQJqIgE2AqAKIANBACgCpApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELiQQBAX8CQCABQSJGDQAgAUEnRg0AECIPC0EAKAKgCiECIAEQGCAAIAJBAmpBACgCoApBACgCxAkQAUEAQQAoAqAKQQJqNgKgCgJAAkACQAJAQQAQJyIBQeEARg0AIAFB9wBGDQFBACgCoAohAQwCC0EAKAKgCiIBQQJqQbAIQQoQLQ0BQQYhAAwCC0EAKAKgCiIBLwECQekARw0AIAEvAQRB9ABHDQBBBCEAIAEvAQZB6ABGDQELQQAgAUF+ajYCoAoPC0EAIAEgAEEBdGo2AqAKAkBBARAnQfsARg0AQQAgATYCoAoPC0EAKAKgCiICIQADQEEAIABBAmo2AqAKAkACQAJAQQEQJyIAQSJGDQAgAEEnRw0BQScQGEEAQQAoAqAKQQJqNgKgCkEBECchAAwCC0EiEBhBAEEAKAKgCkECajYCoApBARAnIQAMAQsgABAqIQALAkAgAEE6Rg0AQQAgATYCoAoPC0EAQQAoAqAKQQJqNgKgCgJAQQEQJyIAQSJGDQAgAEEnRg0AQQAgATYCoAoPCyAAEBhBAEEAKAKgCkECajYCoAoCQAJAQQEQJyIAQSxGDQAgAEH9AEYNAUEAIAE2AqAKDwtBAEEAKAKgCkECajYCoApBARAnQf0ARg0AQQAoAqAKIQAMAQsLQQAoAuQJIgEgAjYCECABQQAoAqAKQQJqNgIMC20BAn8CQAJAA0ACQCAAQf//A3EiAUF3aiICQRdLDQBBASACdEGfgIAEcQ0CCyABQaABRg0BIAAhAiABECYNAkEAIQJBAEEAKAKgCiIAQQJqNgKgCiAALwECIgANAAwCCwsgACECCyACQf//A3ELqwEBBH8CQAJAQQAoAqAKIgIvAQAiA0HhAEYNACABIQQgACEFDAELQQAgAkEEajYCoApBARAnIQJBACgCoAohBQJAAkAgAkEiRg0AIAJBJ0YNACACECoaQQAoAqAKIQQMAQsgAhAYQQBBACgCoApBAmoiBDYCoAoLQQEQJyEDQQAoAqAKIQILAkAgAiAFRg0AIAUgBEEAIAAgACABRiICG0EAIAEgAhsQAgsgAwtyAQR/QQAoAqAKIQBBACgCpAohAQJAAkADQCAAQQJqIQIgACABTw0BAkACQCACLwEAIgNBpH9qDgIBBAALIAIhACADQXZqDgQCAQECAQsgAEEEaiEADAALC0EAIAI2AqAKECJBAA8LQQAgAjYCoApB3QALSQEDf0EAIQMCQCACRQ0AAkADQCAALQAAIgQgAS0AACIFRw0BIAFBAWohASAAQQFqIQAgAkF/aiICDQAMAgsLIAQgBWshAwsgAwsL4gECAEGACAvEAQAAeABwAG8AcgB0AG0AcABvAHIAdABlAHQAYQByAG8AbQB1AG4AYwB0AGkAbwBuAHMAcwBlAHIAdAB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcwAAQcQJCxABAAAAAgAAAAAEAAAwOQAA","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E;
  14683. var convertSourceMap$1 = {};
  14684. (function (exports) {
  14685. Object.defineProperty(exports, 'commentRegex', {
  14686. get: function getCommentRegex () {
  14687. // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
  14688. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
  14689. }
  14690. });
  14691. Object.defineProperty(exports, 'mapFileCommentRegex', {
  14692. get: function getMapFileCommentRegex () {
  14693. // Matches sourceMappingURL in either // or /* comment styles.
  14694. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
  14695. }
  14696. });
  14697. var decodeBase64;
  14698. if (typeof Buffer !== 'undefined') {
  14699. if (typeof Buffer.from === 'function') {
  14700. decodeBase64 = decodeBase64WithBufferFrom;
  14701. } else {
  14702. decodeBase64 = decodeBase64WithNewBuffer;
  14703. }
  14704. } else {
  14705. decodeBase64 = decodeBase64WithAtob;
  14706. }
  14707. function decodeBase64WithBufferFrom(base64) {
  14708. return Buffer.from(base64, 'base64').toString();
  14709. }
  14710. function decodeBase64WithNewBuffer(base64) {
  14711. if (typeof value === 'number') {
  14712. throw new TypeError('The value to decode must not be of type number.');
  14713. }
  14714. return new Buffer(base64, 'base64').toString();
  14715. }
  14716. function decodeBase64WithAtob(base64) {
  14717. return decodeURIComponent(escape(atob(base64)));
  14718. }
  14719. function stripComment(sm) {
  14720. return sm.split(',').pop();
  14721. }
  14722. function readFromFileMap(sm, read) {
  14723. var r = exports.mapFileCommentRegex.exec(sm);
  14724. // for some odd reason //# .. captures in 1 and /* .. */ in 2
  14725. var filename = r[1] || r[2];
  14726. try {
  14727. var sm = read(filename);
  14728. if (sm != null && typeof sm.catch === 'function') {
  14729. return sm.catch(throwError);
  14730. } else {
  14731. return sm;
  14732. }
  14733. } catch (e) {
  14734. throwError(e);
  14735. }
  14736. function throwError(e) {
  14737. throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
  14738. }
  14739. }
  14740. function Converter (sm, opts) {
  14741. opts = opts || {};
  14742. if (opts.hasComment) {
  14743. sm = stripComment(sm);
  14744. }
  14745. if (opts.encoding === 'base64') {
  14746. sm = decodeBase64(sm);
  14747. } else if (opts.encoding === 'uri') {
  14748. sm = decodeURIComponent(sm);
  14749. }
  14750. if (opts.isJSON || opts.encoding) {
  14751. sm = JSON.parse(sm);
  14752. }
  14753. this.sourcemap = sm;
  14754. }
  14755. Converter.prototype.toJSON = function (space) {
  14756. return JSON.stringify(this.sourcemap, null, space);
  14757. };
  14758. if (typeof Buffer !== 'undefined') {
  14759. if (typeof Buffer.from === 'function') {
  14760. Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
  14761. } else {
  14762. Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
  14763. }
  14764. } else {
  14765. Converter.prototype.toBase64 = encodeBase64WithBtoa;
  14766. }
  14767. function encodeBase64WithBufferFrom() {
  14768. var json = this.toJSON();
  14769. return Buffer.from(json, 'utf8').toString('base64');
  14770. }
  14771. function encodeBase64WithNewBuffer() {
  14772. var json = this.toJSON();
  14773. if (typeof json === 'number') {
  14774. throw new TypeError('The json to encode must not be of type number.');
  14775. }
  14776. return new Buffer(json, 'utf8').toString('base64');
  14777. }
  14778. function encodeBase64WithBtoa() {
  14779. var json = this.toJSON();
  14780. return btoa(unescape(encodeURIComponent(json)));
  14781. }
  14782. Converter.prototype.toURI = function () {
  14783. var json = this.toJSON();
  14784. return encodeURIComponent(json);
  14785. };
  14786. Converter.prototype.toComment = function (options) {
  14787. var encoding, content, data;
  14788. if (options != null && options.encoding === 'uri') {
  14789. encoding = '';
  14790. content = this.toURI();
  14791. } else {
  14792. encoding = ';base64';
  14793. content = this.toBase64();
  14794. }
  14795. data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
  14796. return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  14797. };
  14798. // returns copy instead of original
  14799. Converter.prototype.toObject = function () {
  14800. return JSON.parse(this.toJSON());
  14801. };
  14802. Converter.prototype.addProperty = function (key, value) {
  14803. if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
  14804. return this.setProperty(key, value);
  14805. };
  14806. Converter.prototype.setProperty = function (key, value) {
  14807. this.sourcemap[key] = value;
  14808. return this;
  14809. };
  14810. Converter.prototype.getProperty = function (key) {
  14811. return this.sourcemap[key];
  14812. };
  14813. exports.fromObject = function (obj) {
  14814. return new Converter(obj);
  14815. };
  14816. exports.fromJSON = function (json) {
  14817. return new Converter(json, { isJSON: true });
  14818. };
  14819. exports.fromURI = function (uri) {
  14820. return new Converter(uri, { encoding: 'uri' });
  14821. };
  14822. exports.fromBase64 = function (base64) {
  14823. return new Converter(base64, { encoding: 'base64' });
  14824. };
  14825. exports.fromComment = function (comment) {
  14826. var m, encoding;
  14827. comment = comment
  14828. .replace(/^\/\*/g, '//')
  14829. .replace(/\*\/$/g, '');
  14830. m = exports.commentRegex.exec(comment);
  14831. encoding = m && m[4] || 'uri';
  14832. return new Converter(comment, { encoding: encoding, hasComment: true });
  14833. };
  14834. function makeConverter(sm) {
  14835. return new Converter(sm, { isJSON: true });
  14836. }
  14837. exports.fromMapFileComment = function (comment, read) {
  14838. if (typeof read === 'string') {
  14839. throw new Error(
  14840. 'String directory paths are no longer supported with `fromMapFileComment`\n' +
  14841. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  14842. )
  14843. }
  14844. var sm = readFromFileMap(comment, read);
  14845. if (sm != null && typeof sm.then === 'function') {
  14846. return sm.then(makeConverter);
  14847. } else {
  14848. return makeConverter(sm);
  14849. }
  14850. };
  14851. // Finds last sourcemap comment in file or returns null if none was found
  14852. exports.fromSource = function (content) {
  14853. var m = content.match(exports.commentRegex);
  14854. return m ? exports.fromComment(m.pop()) : null;
  14855. };
  14856. // Finds last sourcemap comment in file or returns null if none was found
  14857. exports.fromMapFileSource = function (content, read) {
  14858. if (typeof read === 'string') {
  14859. throw new Error(
  14860. 'String directory paths are no longer supported with `fromMapFileSource`\n' +
  14861. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  14862. )
  14863. }
  14864. var m = content.match(exports.mapFileCommentRegex);
  14865. return m ? exports.fromMapFileComment(m.pop(), read) : null;
  14866. };
  14867. exports.removeComments = function (src) {
  14868. return src.replace(exports.commentRegex, '');
  14869. };
  14870. exports.removeMapFileComments = function (src) {
  14871. return src.replace(exports.mapFileCommentRegex, '');
  14872. };
  14873. exports.generateMapFileComment = function (file, options) {
  14874. var data = 'sourceMappingURL=' + file;
  14875. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  14876. };
  14877. } (convertSourceMap$1));
  14878. var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
  14879. const debug$e = createDebugger('vite:sourcemap', {
  14880. onlyWhenFocused: true,
  14881. });
  14882. // Virtual modules should be prefixed with a null byte to avoid a
  14883. // false positive "missing source" warning. We also check for certain
  14884. // prefixes used for special handling in esbuildDepPlugin.
  14885. const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
  14886. async function injectSourcesContent(map, file, logger) {
  14887. let sourceRoot;
  14888. try {
  14889. // The source root is undefined for virtual modules and permission errors.
  14890. sourceRoot = await fsp.realpath(path$o.resolve(path$o.dirname(file), map.sourceRoot || ''));
  14891. }
  14892. catch { }
  14893. const missingSources = [];
  14894. const sourcesContent = map.sourcesContent || [];
  14895. await Promise.all(map.sources.map(async (sourcePath, index) => {
  14896. let content = null;
  14897. if (sourcePath && !virtualSourceRE.test(sourcePath)) {
  14898. sourcePath = decodeURI(sourcePath);
  14899. if (sourceRoot) {
  14900. sourcePath = path$o.resolve(sourceRoot, sourcePath);
  14901. }
  14902. // inject content from source file when sourcesContent is null
  14903. content =
  14904. sourcesContent[index] ??
  14905. (await fsp.readFile(sourcePath, 'utf-8').catch(() => {
  14906. missingSources.push(sourcePath);
  14907. return null;
  14908. }));
  14909. }
  14910. sourcesContent[index] = content;
  14911. }));
  14912. map.sourcesContent = sourcesContent;
  14913. // Use this command…
  14914. // DEBUG="vite:sourcemap" vite build
  14915. // …to log the missing sources.
  14916. if (missingSources.length) {
  14917. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  14918. debug$e?.(`Missing sources:\n ` + missingSources.join(`\n `));
  14919. }
  14920. }
  14921. function genSourceMapUrl(map) {
  14922. if (typeof map !== 'string') {
  14923. map = JSON.stringify(map);
  14924. }
  14925. return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
  14926. }
  14927. function getCodeWithSourcemap(type, code, map) {
  14928. if (debug$e) {
  14929. code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
  14930. }
  14931. if (type === 'js') {
  14932. code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  14933. }
  14934. else if (type === 'css') {
  14935. code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  14936. }
  14937. return code;
  14938. }
  14939. function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
  14940. let { x_google_ignoreList } = map;
  14941. if (x_google_ignoreList === undefined) {
  14942. x_google_ignoreList = [];
  14943. }
  14944. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  14945. const sourcePath = map.sources[sourcesIndex];
  14946. if (!sourcePath)
  14947. continue;
  14948. const ignoreList = sourcemapIgnoreList(path$o.isAbsolute(sourcePath)
  14949. ? sourcePath
  14950. : path$o.resolve(path$o.dirname(sourcemapPath), sourcePath), sourcemapPath);
  14951. if (logger && typeof ignoreList !== 'boolean') {
  14952. logger.warn('sourcemapIgnoreList function must return a boolean.');
  14953. }
  14954. if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
  14955. x_google_ignoreList.push(sourcesIndex);
  14956. }
  14957. }
  14958. if (x_google_ignoreList.length > 0) {
  14959. if (!map.x_google_ignoreList)
  14960. map.x_google_ignoreList = x_google_ignoreList;
  14961. }
  14962. }
  14963. var tasks = {};
  14964. var utils$g = {};
  14965. var array$1 = {};
  14966. Object.defineProperty(array$1, "__esModule", { value: true });
  14967. array$1.splitWhen = array$1.flatten = void 0;
  14968. function flatten$1(items) {
  14969. return items.reduce((collection, item) => [].concat(collection, item), []);
  14970. }
  14971. array$1.flatten = flatten$1;
  14972. function splitWhen(items, predicate) {
  14973. const result = [[]];
  14974. let groupIndex = 0;
  14975. for (const item of items) {
  14976. if (predicate(item)) {
  14977. groupIndex++;
  14978. result[groupIndex] = [];
  14979. }
  14980. else {
  14981. result[groupIndex].push(item);
  14982. }
  14983. }
  14984. return result;
  14985. }
  14986. array$1.splitWhen = splitWhen;
  14987. var errno$1 = {};
  14988. Object.defineProperty(errno$1, "__esModule", { value: true });
  14989. errno$1.isEnoentCodeError = void 0;
  14990. function isEnoentCodeError(error) {
  14991. return error.code === 'ENOENT';
  14992. }
  14993. errno$1.isEnoentCodeError = isEnoentCodeError;
  14994. var fs$h = {};
  14995. Object.defineProperty(fs$h, "__esModule", { value: true });
  14996. fs$h.createDirentFromStats = void 0;
  14997. let DirentFromStats$1 = class DirentFromStats {
  14998. constructor(name, stats) {
  14999. this.name = name;
  15000. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  15001. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  15002. this.isDirectory = stats.isDirectory.bind(stats);
  15003. this.isFIFO = stats.isFIFO.bind(stats);
  15004. this.isFile = stats.isFile.bind(stats);
  15005. this.isSocket = stats.isSocket.bind(stats);
  15006. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  15007. }
  15008. };
  15009. function createDirentFromStats$1(name, stats) {
  15010. return new DirentFromStats$1(name, stats);
  15011. }
  15012. fs$h.createDirentFromStats = createDirentFromStats$1;
  15013. var path$h = {};
  15014. Object.defineProperty(path$h, "__esModule", { value: true });
  15015. path$h.convertPosixPathToPattern = path$h.convertWindowsPathToPattern = path$h.convertPathToPattern = path$h.escapePosixPath = path$h.escapeWindowsPath = path$h.escape = path$h.removeLeadingDotSegment = path$h.makeAbsolute = path$h.unixify = void 0;
  15016. const os$3 = require$$2;
  15017. const path$g = require$$0$4;
  15018. const IS_WINDOWS_PLATFORM = os$3.platform() === 'win32';
  15019. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  15020. /**
  15021. * All non-escaped special characters.
  15022. * Posix: ()*?[\]{|}, !+@ before (, ! at the beginning, \\ before non-special characters.
  15023. * Windows: (){}, !+@ before (, ! at the beginning.
  15024. */
  15025. const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
  15026. const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([(){}]|^!|[!+@](?=\())/g;
  15027. /**
  15028. * The device path (\\.\ or \\?\).
  15029. * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths
  15030. */
  15031. const DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
  15032. /**
  15033. * All backslashes except those escaping special characters.
  15034. * Windows: !()+@{}
  15035. * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
  15036. */
  15037. const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@{}])/g;
  15038. /**
  15039. * Designed to work only with simple paths: `dir\\file`.
  15040. */
  15041. function unixify(filepath) {
  15042. return filepath.replace(/\\/g, '/');
  15043. }
  15044. path$h.unixify = unixify;
  15045. function makeAbsolute(cwd, filepath) {
  15046. return path$g.resolve(cwd, filepath);
  15047. }
  15048. path$h.makeAbsolute = makeAbsolute;
  15049. function removeLeadingDotSegment(entry) {
  15050. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  15051. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  15052. if (entry.charAt(0) === '.') {
  15053. const secondCharactery = entry.charAt(1);
  15054. if (secondCharactery === '/' || secondCharactery === '\\') {
  15055. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  15056. }
  15057. }
  15058. return entry;
  15059. }
  15060. path$h.removeLeadingDotSegment = removeLeadingDotSegment;
  15061. path$h.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
  15062. function escapeWindowsPath(pattern) {
  15063. return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  15064. }
  15065. path$h.escapeWindowsPath = escapeWindowsPath;
  15066. function escapePosixPath(pattern) {
  15067. return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  15068. }
  15069. path$h.escapePosixPath = escapePosixPath;
  15070. path$h.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
  15071. function convertWindowsPathToPattern(filepath) {
  15072. return escapeWindowsPath(filepath)
  15073. .replace(DOS_DEVICE_PATH_RE, '//$1')
  15074. .replace(WINDOWS_BACKSLASHES_RE, '/');
  15075. }
  15076. path$h.convertWindowsPathToPattern = convertWindowsPathToPattern;
  15077. function convertPosixPathToPattern(filepath) {
  15078. return escapePosixPath(filepath);
  15079. }
  15080. path$h.convertPosixPathToPattern = convertPosixPathToPattern;
  15081. var pattern$1 = {};
  15082. /*!
  15083. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  15084. *
  15085. * Copyright (c) 2014-2016, Jon Schlinkert.
  15086. * Licensed under the MIT License.
  15087. */
  15088. var isExtglob$1 = function isExtglob(str) {
  15089. if (typeof str !== 'string' || str === '') {
  15090. return false;
  15091. }
  15092. var match;
  15093. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  15094. if (match[2]) return true;
  15095. str = str.slice(match.index + match[0].length);
  15096. }
  15097. return false;
  15098. };
  15099. /*!
  15100. * is-glob <https://github.com/jonschlinkert/is-glob>
  15101. *
  15102. * Copyright (c) 2014-2017, Jon Schlinkert.
  15103. * Released under the MIT License.
  15104. */
  15105. var isExtglob = isExtglob$1;
  15106. var chars = { '{': '}', '(': ')', '[': ']'};
  15107. var strictCheck = function(str) {
  15108. if (str[0] === '!') {
  15109. return true;
  15110. }
  15111. var index = 0;
  15112. var pipeIndex = -2;
  15113. var closeSquareIndex = -2;
  15114. var closeCurlyIndex = -2;
  15115. var closeParenIndex = -2;
  15116. var backSlashIndex = -2;
  15117. while (index < str.length) {
  15118. if (str[index] === '*') {
  15119. return true;
  15120. }
  15121. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  15122. return true;
  15123. }
  15124. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  15125. if (closeSquareIndex < index) {
  15126. closeSquareIndex = str.indexOf(']', index);
  15127. }
  15128. if (closeSquareIndex > index) {
  15129. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  15130. return true;
  15131. }
  15132. backSlashIndex = str.indexOf('\\', index);
  15133. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  15134. return true;
  15135. }
  15136. }
  15137. }
  15138. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  15139. closeCurlyIndex = str.indexOf('}', index);
  15140. if (closeCurlyIndex > index) {
  15141. backSlashIndex = str.indexOf('\\', index);
  15142. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  15143. return true;
  15144. }
  15145. }
  15146. }
  15147. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  15148. closeParenIndex = str.indexOf(')', index);
  15149. if (closeParenIndex > index) {
  15150. backSlashIndex = str.indexOf('\\', index);
  15151. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  15152. return true;
  15153. }
  15154. }
  15155. }
  15156. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  15157. if (pipeIndex < index) {
  15158. pipeIndex = str.indexOf('|', index);
  15159. }
  15160. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  15161. closeParenIndex = str.indexOf(')', pipeIndex);
  15162. if (closeParenIndex > pipeIndex) {
  15163. backSlashIndex = str.indexOf('\\', pipeIndex);
  15164. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  15165. return true;
  15166. }
  15167. }
  15168. }
  15169. }
  15170. if (str[index] === '\\') {
  15171. var open = str[index + 1];
  15172. index += 2;
  15173. var close = chars[open];
  15174. if (close) {
  15175. var n = str.indexOf(close, index);
  15176. if (n !== -1) {
  15177. index = n + 1;
  15178. }
  15179. }
  15180. if (str[index] === '!') {
  15181. return true;
  15182. }
  15183. } else {
  15184. index++;
  15185. }
  15186. }
  15187. return false;
  15188. };
  15189. var relaxedCheck = function(str) {
  15190. if (str[0] === '!') {
  15191. return true;
  15192. }
  15193. var index = 0;
  15194. while (index < str.length) {
  15195. if (/[*?{}()[\]]/.test(str[index])) {
  15196. return true;
  15197. }
  15198. if (str[index] === '\\') {
  15199. var open = str[index + 1];
  15200. index += 2;
  15201. var close = chars[open];
  15202. if (close) {
  15203. var n = str.indexOf(close, index);
  15204. if (n !== -1) {
  15205. index = n + 1;
  15206. }
  15207. }
  15208. if (str[index] === '!') {
  15209. return true;
  15210. }
  15211. } else {
  15212. index++;
  15213. }
  15214. }
  15215. return false;
  15216. };
  15217. var isGlob$2 = function isGlob(str, options) {
  15218. if (typeof str !== 'string' || str === '') {
  15219. return false;
  15220. }
  15221. if (isExtglob(str)) {
  15222. return true;
  15223. }
  15224. var check = strictCheck;
  15225. // optionally relax check
  15226. if (options && options.strict === false) {
  15227. check = relaxedCheck;
  15228. }
  15229. return check(str);
  15230. };
  15231. var isGlob$1 = isGlob$2;
  15232. var pathPosixDirname = require$$0$4.posix.dirname;
  15233. var isWin32 = require$$2.platform() === 'win32';
  15234. var slash = '/';
  15235. var backslash = /\\/g;
  15236. var enclosure = /[\{\[].*[\}\]]$/;
  15237. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  15238. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  15239. /**
  15240. * @param {string} str
  15241. * @param {Object} opts
  15242. * @param {boolean} [opts.flipBackslashes=true]
  15243. * @returns {string}
  15244. */
  15245. var globParent$2 = function globParent(str, opts) {
  15246. var options = Object.assign({ flipBackslashes: true }, opts);
  15247. // flip windows path separators
  15248. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  15249. str = str.replace(backslash, slash);
  15250. }
  15251. // special case for strings ending in enclosure containing path separator
  15252. if (enclosure.test(str)) {
  15253. str += slash;
  15254. }
  15255. // preserves full path in case of trailing path separator
  15256. str += 'a';
  15257. // remove path parts that are globby
  15258. do {
  15259. str = pathPosixDirname(str);
  15260. } while (isGlob$1(str) || globby.test(str));
  15261. // remove escape chars and return result
  15262. return str.replace(escaped, '$1');
  15263. };
  15264. var utils$f = {};
  15265. (function (exports) {
  15266. exports.isInteger = num => {
  15267. if (typeof num === 'number') {
  15268. return Number.isInteger(num);
  15269. }
  15270. if (typeof num === 'string' && num.trim() !== '') {
  15271. return Number.isInteger(Number(num));
  15272. }
  15273. return false;
  15274. };
  15275. /**
  15276. * Find a node of the given type
  15277. */
  15278. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  15279. /**
  15280. * Find a node of the given type
  15281. */
  15282. exports.exceedsLimit = (min, max, step = 1, limit) => {
  15283. if (limit === false) return false;
  15284. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  15285. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  15286. };
  15287. /**
  15288. * Escape the given node with '\\' before node.value
  15289. */
  15290. exports.escapeNode = (block, n = 0, type) => {
  15291. let node = block.nodes[n];
  15292. if (!node) return;
  15293. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  15294. if (node.escaped !== true) {
  15295. node.value = '\\' + node.value;
  15296. node.escaped = true;
  15297. }
  15298. }
  15299. };
  15300. /**
  15301. * Returns true if the given brace node should be enclosed in literal braces
  15302. */
  15303. exports.encloseBrace = node => {
  15304. if (node.type !== 'brace') return false;
  15305. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  15306. node.invalid = true;
  15307. return true;
  15308. }
  15309. return false;
  15310. };
  15311. /**
  15312. * Returns true if a brace node is invalid.
  15313. */
  15314. exports.isInvalidBrace = block => {
  15315. if (block.type !== 'brace') return false;
  15316. if (block.invalid === true || block.dollar) return true;
  15317. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  15318. block.invalid = true;
  15319. return true;
  15320. }
  15321. if (block.open !== true || block.close !== true) {
  15322. block.invalid = true;
  15323. return true;
  15324. }
  15325. return false;
  15326. };
  15327. /**
  15328. * Returns true if a node is an open or close node
  15329. */
  15330. exports.isOpenOrClose = node => {
  15331. if (node.type === 'open' || node.type === 'close') {
  15332. return true;
  15333. }
  15334. return node.open === true || node.close === true;
  15335. };
  15336. /**
  15337. * Reduce an array of text nodes.
  15338. */
  15339. exports.reduce = nodes => nodes.reduce((acc, node) => {
  15340. if (node.type === 'text') acc.push(node.value);
  15341. if (node.type === 'range') node.type = 'text';
  15342. return acc;
  15343. }, []);
  15344. /**
  15345. * Flatten an array
  15346. */
  15347. exports.flatten = (...args) => {
  15348. const result = [];
  15349. const flat = arr => {
  15350. for (let i = 0; i < arr.length; i++) {
  15351. let ele = arr[i];
  15352. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  15353. }
  15354. return result;
  15355. };
  15356. flat(args);
  15357. return result;
  15358. };
  15359. } (utils$f));
  15360. const utils$e = utils$f;
  15361. var stringify$7 = (ast, options = {}) => {
  15362. let stringify = (node, parent = {}) => {
  15363. let invalidBlock = options.escapeInvalid && utils$e.isInvalidBrace(parent);
  15364. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  15365. let output = '';
  15366. if (node.value) {
  15367. if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node)) {
  15368. return '\\' + node.value;
  15369. }
  15370. return node.value;
  15371. }
  15372. if (node.value) {
  15373. return node.value;
  15374. }
  15375. if (node.nodes) {
  15376. for (let child of node.nodes) {
  15377. output += stringify(child);
  15378. }
  15379. }
  15380. return output;
  15381. };
  15382. return stringify(ast);
  15383. };
  15384. /*!
  15385. * is-number <https://github.com/jonschlinkert/is-number>
  15386. *
  15387. * Copyright (c) 2014-present, Jon Schlinkert.
  15388. * Released under the MIT License.
  15389. */
  15390. var isNumber$2 = function(num) {
  15391. if (typeof num === 'number') {
  15392. return num - num === 0;
  15393. }
  15394. if (typeof num === 'string' && num.trim() !== '') {
  15395. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  15396. }
  15397. return false;
  15398. };
  15399. /*!
  15400. * to-regex-range <https://github.com/micromatch/to-regex-range>
  15401. *
  15402. * Copyright (c) 2015-present, Jon Schlinkert.
  15403. * Released under the MIT License.
  15404. */
  15405. const isNumber$1 = isNumber$2;
  15406. const toRegexRange$1 = (min, max, options) => {
  15407. if (isNumber$1(min) === false) {
  15408. throw new TypeError('toRegexRange: expected the first argument to be a number');
  15409. }
  15410. if (max === void 0 || min === max) {
  15411. return String(min);
  15412. }
  15413. if (isNumber$1(max) === false) {
  15414. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  15415. }
  15416. let opts = { relaxZeros: true, ...options };
  15417. if (typeof opts.strictZeros === 'boolean') {
  15418. opts.relaxZeros = opts.strictZeros === false;
  15419. }
  15420. let relax = String(opts.relaxZeros);
  15421. let shorthand = String(opts.shorthand);
  15422. let capture = String(opts.capture);
  15423. let wrap = String(opts.wrap);
  15424. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  15425. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  15426. return toRegexRange$1.cache[cacheKey].result;
  15427. }
  15428. let a = Math.min(min, max);
  15429. let b = Math.max(min, max);
  15430. if (Math.abs(a - b) === 1) {
  15431. let result = min + '|' + max;
  15432. if (opts.capture) {
  15433. return `(${result})`;
  15434. }
  15435. if (opts.wrap === false) {
  15436. return result;
  15437. }
  15438. return `(?:${result})`;
  15439. }
  15440. let isPadded = hasPadding(min) || hasPadding(max);
  15441. let state = { min, max, a, b };
  15442. let positives = [];
  15443. let negatives = [];
  15444. if (isPadded) {
  15445. state.isPadded = isPadded;
  15446. state.maxLen = String(state.max).length;
  15447. }
  15448. if (a < 0) {
  15449. let newMin = b < 0 ? Math.abs(b) : 1;
  15450. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  15451. a = state.a = 0;
  15452. }
  15453. if (b >= 0) {
  15454. positives = splitToPatterns(a, b, state, opts);
  15455. }
  15456. state.negatives = negatives;
  15457. state.positives = positives;
  15458. state.result = collatePatterns(negatives, positives);
  15459. if (opts.capture === true) {
  15460. state.result = `(${state.result})`;
  15461. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  15462. state.result = `(?:${state.result})`;
  15463. }
  15464. toRegexRange$1.cache[cacheKey] = state;
  15465. return state.result;
  15466. };
  15467. function collatePatterns(neg, pos, options) {
  15468. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  15469. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  15470. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  15471. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  15472. return subpatterns.join('|');
  15473. }
  15474. function splitToRanges(min, max) {
  15475. let nines = 1;
  15476. let zeros = 1;
  15477. let stop = countNines(min, nines);
  15478. let stops = new Set([max]);
  15479. while (min <= stop && stop <= max) {
  15480. stops.add(stop);
  15481. nines += 1;
  15482. stop = countNines(min, nines);
  15483. }
  15484. stop = countZeros(max + 1, zeros) - 1;
  15485. while (min < stop && stop <= max) {
  15486. stops.add(stop);
  15487. zeros += 1;
  15488. stop = countZeros(max + 1, zeros) - 1;
  15489. }
  15490. stops = [...stops];
  15491. stops.sort(compare);
  15492. return stops;
  15493. }
  15494. /**
  15495. * Convert a range to a regex pattern
  15496. * @param {Number} `start`
  15497. * @param {Number} `stop`
  15498. * @return {String}
  15499. */
  15500. function rangeToPattern(start, stop, options) {
  15501. if (start === stop) {
  15502. return { pattern: start, count: [], digits: 0 };
  15503. }
  15504. let zipped = zip(start, stop);
  15505. let digits = zipped.length;
  15506. let pattern = '';
  15507. let count = 0;
  15508. for (let i = 0; i < digits; i++) {
  15509. let [startDigit, stopDigit] = zipped[i];
  15510. if (startDigit === stopDigit) {
  15511. pattern += startDigit;
  15512. } else if (startDigit !== '0' || stopDigit !== '9') {
  15513. pattern += toCharacterClass(startDigit, stopDigit);
  15514. } else {
  15515. count++;
  15516. }
  15517. }
  15518. if (count) {
  15519. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  15520. }
  15521. return { pattern, count: [count], digits };
  15522. }
  15523. function splitToPatterns(min, max, tok, options) {
  15524. let ranges = splitToRanges(min, max);
  15525. let tokens = [];
  15526. let start = min;
  15527. let prev;
  15528. for (let i = 0; i < ranges.length; i++) {
  15529. let max = ranges[i];
  15530. let obj = rangeToPattern(String(start), String(max), options);
  15531. let zeros = '';
  15532. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  15533. if (prev.count.length > 1) {
  15534. prev.count.pop();
  15535. }
  15536. prev.count.push(obj.count[0]);
  15537. prev.string = prev.pattern + toQuantifier(prev.count);
  15538. start = max + 1;
  15539. continue;
  15540. }
  15541. if (tok.isPadded) {
  15542. zeros = padZeros(max, tok, options);
  15543. }
  15544. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  15545. tokens.push(obj);
  15546. start = max + 1;
  15547. prev = obj;
  15548. }
  15549. return tokens;
  15550. }
  15551. function filterPatterns(arr, comparison, prefix, intersection, options) {
  15552. let result = [];
  15553. for (let ele of arr) {
  15554. let { string } = ele;
  15555. // only push if _both_ are negative...
  15556. if (!intersection && !contains(comparison, 'string', string)) {
  15557. result.push(prefix + string);
  15558. }
  15559. // or _both_ are positive
  15560. if (intersection && contains(comparison, 'string', string)) {
  15561. result.push(prefix + string);
  15562. }
  15563. }
  15564. return result;
  15565. }
  15566. /**
  15567. * Zip strings
  15568. */
  15569. function zip(a, b) {
  15570. let arr = [];
  15571. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  15572. return arr;
  15573. }
  15574. function compare(a, b) {
  15575. return a > b ? 1 : b > a ? -1 : 0;
  15576. }
  15577. function contains(arr, key, val) {
  15578. return arr.some(ele => ele[key] === val);
  15579. }
  15580. function countNines(min, len) {
  15581. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  15582. }
  15583. function countZeros(integer, zeros) {
  15584. return integer - (integer % Math.pow(10, zeros));
  15585. }
  15586. function toQuantifier(digits) {
  15587. let [start = 0, stop = ''] = digits;
  15588. if (stop || start > 1) {
  15589. return `{${start + (stop ? ',' + stop : '')}}`;
  15590. }
  15591. return '';
  15592. }
  15593. function toCharacterClass(a, b, options) {
  15594. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  15595. }
  15596. function hasPadding(str) {
  15597. return /^-?(0+)\d/.test(str);
  15598. }
  15599. function padZeros(value, tok, options) {
  15600. if (!tok.isPadded) {
  15601. return value;
  15602. }
  15603. let diff = Math.abs(tok.maxLen - String(value).length);
  15604. let relax = options.relaxZeros !== false;
  15605. switch (diff) {
  15606. case 0:
  15607. return '';
  15608. case 1:
  15609. return relax ? '0?' : '0';
  15610. case 2:
  15611. return relax ? '0{0,2}' : '00';
  15612. default: {
  15613. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  15614. }
  15615. }
  15616. }
  15617. /**
  15618. * Cache
  15619. */
  15620. toRegexRange$1.cache = {};
  15621. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  15622. /**
  15623. * Expose `toRegexRange`
  15624. */
  15625. var toRegexRange_1 = toRegexRange$1;
  15626. /*!
  15627. * fill-range <https://github.com/jonschlinkert/fill-range>
  15628. *
  15629. * Copyright (c) 2014-present, Jon Schlinkert.
  15630. * Licensed under the MIT License.
  15631. */
  15632. const util$1 = require$$0$6;
  15633. const toRegexRange = toRegexRange_1;
  15634. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  15635. const transform = toNumber => {
  15636. return value => toNumber === true ? Number(value) : String(value);
  15637. };
  15638. const isValidValue = value => {
  15639. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  15640. };
  15641. const isNumber = num => Number.isInteger(+num);
  15642. const zeros = input => {
  15643. let value = `${input}`;
  15644. let index = -1;
  15645. if (value[0] === '-') value = value.slice(1);
  15646. if (value === '0') return false;
  15647. while (value[++index] === '0');
  15648. return index > 0;
  15649. };
  15650. const stringify$6 = (start, end, options) => {
  15651. if (typeof start === 'string' || typeof end === 'string') {
  15652. return true;
  15653. }
  15654. return options.stringify === true;
  15655. };
  15656. const pad = (input, maxLength, toNumber) => {
  15657. if (maxLength > 0) {
  15658. let dash = input[0] === '-' ? '-' : '';
  15659. if (dash) input = input.slice(1);
  15660. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  15661. }
  15662. if (toNumber === false) {
  15663. return String(input);
  15664. }
  15665. return input;
  15666. };
  15667. const toMaxLen = (input, maxLength) => {
  15668. let negative = input[0] === '-' ? '-' : '';
  15669. if (negative) {
  15670. input = input.slice(1);
  15671. maxLength--;
  15672. }
  15673. while (input.length < maxLength) input = '0' + input;
  15674. return negative ? ('-' + input) : input;
  15675. };
  15676. const toSequence = (parts, options) => {
  15677. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  15678. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  15679. let prefix = options.capture ? '' : '?:';
  15680. let positives = '';
  15681. let negatives = '';
  15682. let result;
  15683. if (parts.positives.length) {
  15684. positives = parts.positives.join('|');
  15685. }
  15686. if (parts.negatives.length) {
  15687. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  15688. }
  15689. if (positives && negatives) {
  15690. result = `${positives}|${negatives}`;
  15691. } else {
  15692. result = positives || negatives;
  15693. }
  15694. if (options.wrap) {
  15695. return `(${prefix}${result})`;
  15696. }
  15697. return result;
  15698. };
  15699. const toRange = (a, b, isNumbers, options) => {
  15700. if (isNumbers) {
  15701. return toRegexRange(a, b, { wrap: false, ...options });
  15702. }
  15703. let start = String.fromCharCode(a);
  15704. if (a === b) return start;
  15705. let stop = String.fromCharCode(b);
  15706. return `[${start}-${stop}]`;
  15707. };
  15708. const toRegex = (start, end, options) => {
  15709. if (Array.isArray(start)) {
  15710. let wrap = options.wrap === true;
  15711. let prefix = options.capture ? '' : '?:';
  15712. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  15713. }
  15714. return toRegexRange(start, end, options);
  15715. };
  15716. const rangeError = (...args) => {
  15717. return new RangeError('Invalid range arguments: ' + util$1.inspect(...args));
  15718. };
  15719. const invalidRange = (start, end, options) => {
  15720. if (options.strictRanges === true) throw rangeError([start, end]);
  15721. return [];
  15722. };
  15723. const invalidStep = (step, options) => {
  15724. if (options.strictRanges === true) {
  15725. throw new TypeError(`Expected step "${step}" to be a number`);
  15726. }
  15727. return [];
  15728. };
  15729. const fillNumbers = (start, end, step = 1, options = {}) => {
  15730. let a = Number(start);
  15731. let b = Number(end);
  15732. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  15733. if (options.strictRanges === true) throw rangeError([start, end]);
  15734. return [];
  15735. }
  15736. // fix negative zero
  15737. if (a === 0) a = 0;
  15738. if (b === 0) b = 0;
  15739. let descending = a > b;
  15740. let startString = String(start);
  15741. let endString = String(end);
  15742. let stepString = String(step);
  15743. step = Math.max(Math.abs(step), 1);
  15744. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  15745. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  15746. let toNumber = padded === false && stringify$6(start, end, options) === false;
  15747. let format = options.transform || transform(toNumber);
  15748. if (options.toRegex && step === 1) {
  15749. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  15750. }
  15751. let parts = { negatives: [], positives: [] };
  15752. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  15753. let range = [];
  15754. let index = 0;
  15755. while (descending ? a >= b : a <= b) {
  15756. if (options.toRegex === true && step > 1) {
  15757. push(a);
  15758. } else {
  15759. range.push(pad(format(a, index), maxLen, toNumber));
  15760. }
  15761. a = descending ? a - step : a + step;
  15762. index++;
  15763. }
  15764. if (options.toRegex === true) {
  15765. return step > 1
  15766. ? toSequence(parts, options)
  15767. : toRegex(range, null, { wrap: false, ...options });
  15768. }
  15769. return range;
  15770. };
  15771. const fillLetters = (start, end, step = 1, options = {}) => {
  15772. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  15773. return invalidRange(start, end, options);
  15774. }
  15775. let format = options.transform || (val => String.fromCharCode(val));
  15776. let a = `${start}`.charCodeAt(0);
  15777. let b = `${end}`.charCodeAt(0);
  15778. let descending = a > b;
  15779. let min = Math.min(a, b);
  15780. let max = Math.max(a, b);
  15781. if (options.toRegex && step === 1) {
  15782. return toRange(min, max, false, options);
  15783. }
  15784. let range = [];
  15785. let index = 0;
  15786. while (descending ? a >= b : a <= b) {
  15787. range.push(format(a, index));
  15788. a = descending ? a - step : a + step;
  15789. index++;
  15790. }
  15791. if (options.toRegex === true) {
  15792. return toRegex(range, null, { wrap: false, options });
  15793. }
  15794. return range;
  15795. };
  15796. const fill$2 = (start, end, step, options = {}) => {
  15797. if (end == null && isValidValue(start)) {
  15798. return [start];
  15799. }
  15800. if (!isValidValue(start) || !isValidValue(end)) {
  15801. return invalidRange(start, end, options);
  15802. }
  15803. if (typeof step === 'function') {
  15804. return fill$2(start, end, 1, { transform: step });
  15805. }
  15806. if (isObject(step)) {
  15807. return fill$2(start, end, 0, step);
  15808. }
  15809. let opts = { ...options };
  15810. if (opts.capture === true) opts.wrap = true;
  15811. step = step || opts.step || 1;
  15812. if (!isNumber(step)) {
  15813. if (step != null && !isObject(step)) return invalidStep(step, opts);
  15814. return fill$2(start, end, 1, step);
  15815. }
  15816. if (isNumber(start) && isNumber(end)) {
  15817. return fillNumbers(start, end, step, opts);
  15818. }
  15819. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  15820. };
  15821. var fillRange = fill$2;
  15822. const fill$1 = fillRange;
  15823. const utils$d = utils$f;
  15824. const compile$1 = (ast, options = {}) => {
  15825. let walk = (node, parent = {}) => {
  15826. let invalidBlock = utils$d.isInvalidBrace(parent);
  15827. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  15828. let invalid = invalidBlock === true || invalidNode === true;
  15829. let prefix = options.escapeInvalid === true ? '\\' : '';
  15830. let output = '';
  15831. if (node.isOpen === true) {
  15832. return prefix + node.value;
  15833. }
  15834. if (node.isClose === true) {
  15835. return prefix + node.value;
  15836. }
  15837. if (node.type === 'open') {
  15838. return invalid ? (prefix + node.value) : '(';
  15839. }
  15840. if (node.type === 'close') {
  15841. return invalid ? (prefix + node.value) : ')';
  15842. }
  15843. if (node.type === 'comma') {
  15844. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  15845. }
  15846. if (node.value) {
  15847. return node.value;
  15848. }
  15849. if (node.nodes && node.ranges > 0) {
  15850. let args = utils$d.reduce(node.nodes);
  15851. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  15852. if (range.length !== 0) {
  15853. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  15854. }
  15855. }
  15856. if (node.nodes) {
  15857. for (let child of node.nodes) {
  15858. output += walk(child, node);
  15859. }
  15860. }
  15861. return output;
  15862. };
  15863. return walk(ast);
  15864. };
  15865. var compile_1 = compile$1;
  15866. const fill = fillRange;
  15867. const stringify$5 = stringify$7;
  15868. const utils$c = utils$f;
  15869. const append$1 = (queue = '', stash = '', enclose = false) => {
  15870. let result = [];
  15871. queue = [].concat(queue);
  15872. stash = [].concat(stash);
  15873. if (!stash.length) return queue;
  15874. if (!queue.length) {
  15875. return enclose ? utils$c.flatten(stash).map(ele => `{${ele}}`) : stash;
  15876. }
  15877. for (let item of queue) {
  15878. if (Array.isArray(item)) {
  15879. for (let value of item) {
  15880. result.push(append$1(value, stash, enclose));
  15881. }
  15882. } else {
  15883. for (let ele of stash) {
  15884. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  15885. result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele));
  15886. }
  15887. }
  15888. }
  15889. return utils$c.flatten(result);
  15890. };
  15891. const expand$2 = (ast, options = {}) => {
  15892. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  15893. let walk = (node, parent = {}) => {
  15894. node.queue = [];
  15895. let p = parent;
  15896. let q = parent.queue;
  15897. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  15898. p = p.parent;
  15899. q = p.queue;
  15900. }
  15901. if (node.invalid || node.dollar) {
  15902. q.push(append$1(q.pop(), stringify$5(node, options)));
  15903. return;
  15904. }
  15905. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  15906. q.push(append$1(q.pop(), ['{}']));
  15907. return;
  15908. }
  15909. if (node.nodes && node.ranges > 0) {
  15910. let args = utils$c.reduce(node.nodes);
  15911. if (utils$c.exceedsLimit(...args, options.step, rangeLimit)) {
  15912. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  15913. }
  15914. let range = fill(...args, options);
  15915. if (range.length === 0) {
  15916. range = stringify$5(node, options);
  15917. }
  15918. q.push(append$1(q.pop(), range));
  15919. node.nodes = [];
  15920. return;
  15921. }
  15922. let enclose = utils$c.encloseBrace(node);
  15923. let queue = node.queue;
  15924. let block = node;
  15925. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  15926. block = block.parent;
  15927. queue = block.queue;
  15928. }
  15929. for (let i = 0; i < node.nodes.length; i++) {
  15930. let child = node.nodes[i];
  15931. if (child.type === 'comma' && node.type === 'brace') {
  15932. if (i === 1) queue.push('');
  15933. queue.push('');
  15934. continue;
  15935. }
  15936. if (child.type === 'close') {
  15937. q.push(append$1(q.pop(), queue, enclose));
  15938. continue;
  15939. }
  15940. if (child.value && child.type !== 'open') {
  15941. queue.push(append$1(queue.pop(), child.value));
  15942. continue;
  15943. }
  15944. if (child.nodes) {
  15945. walk(child, node);
  15946. }
  15947. }
  15948. return queue;
  15949. };
  15950. return utils$c.flatten(walk(ast));
  15951. };
  15952. var expand_1$1 = expand$2;
  15953. var constants$3 = {
  15954. MAX_LENGTH: 1024 * 64,
  15955. // Digits
  15956. CHAR_0: '0', /* 0 */
  15957. CHAR_9: '9', /* 9 */
  15958. // Alphabet chars.
  15959. CHAR_UPPERCASE_A: 'A', /* A */
  15960. CHAR_LOWERCASE_A: 'a', /* a */
  15961. CHAR_UPPERCASE_Z: 'Z', /* Z */
  15962. CHAR_LOWERCASE_Z: 'z', /* z */
  15963. CHAR_LEFT_PARENTHESES: '(', /* ( */
  15964. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  15965. CHAR_ASTERISK: '*', /* * */
  15966. // Non-alphabetic chars.
  15967. CHAR_AMPERSAND: '&', /* & */
  15968. CHAR_AT: '@', /* @ */
  15969. CHAR_BACKSLASH: '\\', /* \ */
  15970. CHAR_BACKTICK: '`', /* ` */
  15971. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  15972. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  15973. CHAR_COLON: ':', /* : */
  15974. CHAR_COMMA: ',', /* , */
  15975. CHAR_DOLLAR: '$', /* . */
  15976. CHAR_DOT: '.', /* . */
  15977. CHAR_DOUBLE_QUOTE: '"', /* " */
  15978. CHAR_EQUAL: '=', /* = */
  15979. CHAR_EXCLAMATION_MARK: '!', /* ! */
  15980. CHAR_FORM_FEED: '\f', /* \f */
  15981. CHAR_FORWARD_SLASH: '/', /* / */
  15982. CHAR_HASH: '#', /* # */
  15983. CHAR_HYPHEN_MINUS: '-', /* - */
  15984. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  15985. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  15986. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  15987. CHAR_LINE_FEED: '\n', /* \n */
  15988. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  15989. CHAR_PERCENT: '%', /* % */
  15990. CHAR_PLUS: '+', /* + */
  15991. CHAR_QUESTION_MARK: '?', /* ? */
  15992. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  15993. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  15994. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  15995. CHAR_SEMICOLON: ';', /* ; */
  15996. CHAR_SINGLE_QUOTE: '\'', /* ' */
  15997. CHAR_SPACE: ' ', /* */
  15998. CHAR_TAB: '\t', /* \t */
  15999. CHAR_UNDERSCORE: '_', /* _ */
  16000. CHAR_VERTICAL_LINE: '|', /* | */
  16001. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  16002. };
  16003. const stringify$4 = stringify$7;
  16004. /**
  16005. * Constants
  16006. */
  16007. const {
  16008. MAX_LENGTH,
  16009. CHAR_BACKSLASH, /* \ */
  16010. CHAR_BACKTICK, /* ` */
  16011. CHAR_COMMA, /* , */
  16012. CHAR_DOT, /* . */
  16013. CHAR_LEFT_PARENTHESES, /* ( */
  16014. CHAR_RIGHT_PARENTHESES, /* ) */
  16015. CHAR_LEFT_CURLY_BRACE, /* { */
  16016. CHAR_RIGHT_CURLY_BRACE, /* } */
  16017. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  16018. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  16019. CHAR_DOUBLE_QUOTE, /* " */
  16020. CHAR_SINGLE_QUOTE, /* ' */
  16021. CHAR_NO_BREAK_SPACE,
  16022. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  16023. } = constants$3;
  16024. /**
  16025. * parse
  16026. */
  16027. const parse$d = (input, options = {}) => {
  16028. if (typeof input !== 'string') {
  16029. throw new TypeError('Expected a string');
  16030. }
  16031. let opts = options || {};
  16032. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  16033. if (input.length > max) {
  16034. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  16035. }
  16036. let ast = { type: 'root', input, nodes: [] };
  16037. let stack = [ast];
  16038. let block = ast;
  16039. let prev = ast;
  16040. let brackets = 0;
  16041. let length = input.length;
  16042. let index = 0;
  16043. let depth = 0;
  16044. let value;
  16045. /**
  16046. * Helpers
  16047. */
  16048. const advance = () => input[index++];
  16049. const push = node => {
  16050. if (node.type === 'text' && prev.type === 'dot') {
  16051. prev.type = 'text';
  16052. }
  16053. if (prev && prev.type === 'text' && node.type === 'text') {
  16054. prev.value += node.value;
  16055. return;
  16056. }
  16057. block.nodes.push(node);
  16058. node.parent = block;
  16059. node.prev = prev;
  16060. prev = node;
  16061. return node;
  16062. };
  16063. push({ type: 'bos' });
  16064. while (index < length) {
  16065. block = stack[stack.length - 1];
  16066. value = advance();
  16067. /**
  16068. * Invalid chars
  16069. */
  16070. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  16071. continue;
  16072. }
  16073. /**
  16074. * Escaped chars
  16075. */
  16076. if (value === CHAR_BACKSLASH) {
  16077. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  16078. continue;
  16079. }
  16080. /**
  16081. * Right square bracket (literal): ']'
  16082. */
  16083. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  16084. push({ type: 'text', value: '\\' + value });
  16085. continue;
  16086. }
  16087. /**
  16088. * Left square bracket: '['
  16089. */
  16090. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  16091. brackets++;
  16092. let next;
  16093. while (index < length && (next = advance())) {
  16094. value += next;
  16095. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  16096. brackets++;
  16097. continue;
  16098. }
  16099. if (next === CHAR_BACKSLASH) {
  16100. value += advance();
  16101. continue;
  16102. }
  16103. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  16104. brackets--;
  16105. if (brackets === 0) {
  16106. break;
  16107. }
  16108. }
  16109. }
  16110. push({ type: 'text', value });
  16111. continue;
  16112. }
  16113. /**
  16114. * Parentheses
  16115. */
  16116. if (value === CHAR_LEFT_PARENTHESES) {
  16117. block = push({ type: 'paren', nodes: [] });
  16118. stack.push(block);
  16119. push({ type: 'text', value });
  16120. continue;
  16121. }
  16122. if (value === CHAR_RIGHT_PARENTHESES) {
  16123. if (block.type !== 'paren') {
  16124. push({ type: 'text', value });
  16125. continue;
  16126. }
  16127. block = stack.pop();
  16128. push({ type: 'text', value });
  16129. block = stack[stack.length - 1];
  16130. continue;
  16131. }
  16132. /**
  16133. * Quotes: '|"|`
  16134. */
  16135. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  16136. let open = value;
  16137. let next;
  16138. if (options.keepQuotes !== true) {
  16139. value = '';
  16140. }
  16141. while (index < length && (next = advance())) {
  16142. if (next === CHAR_BACKSLASH) {
  16143. value += next + advance();
  16144. continue;
  16145. }
  16146. if (next === open) {
  16147. if (options.keepQuotes === true) value += next;
  16148. break;
  16149. }
  16150. value += next;
  16151. }
  16152. push({ type: 'text', value });
  16153. continue;
  16154. }
  16155. /**
  16156. * Left curly brace: '{'
  16157. */
  16158. if (value === CHAR_LEFT_CURLY_BRACE) {
  16159. depth++;
  16160. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  16161. let brace = {
  16162. type: 'brace',
  16163. open: true,
  16164. close: false,
  16165. dollar,
  16166. depth,
  16167. commas: 0,
  16168. ranges: 0,
  16169. nodes: []
  16170. };
  16171. block = push(brace);
  16172. stack.push(block);
  16173. push({ type: 'open', value });
  16174. continue;
  16175. }
  16176. /**
  16177. * Right curly brace: '}'
  16178. */
  16179. if (value === CHAR_RIGHT_CURLY_BRACE) {
  16180. if (block.type !== 'brace') {
  16181. push({ type: 'text', value });
  16182. continue;
  16183. }
  16184. let type = 'close';
  16185. block = stack.pop();
  16186. block.close = true;
  16187. push({ type, value });
  16188. depth--;
  16189. block = stack[stack.length - 1];
  16190. continue;
  16191. }
  16192. /**
  16193. * Comma: ','
  16194. */
  16195. if (value === CHAR_COMMA && depth > 0) {
  16196. if (block.ranges > 0) {
  16197. block.ranges = 0;
  16198. let open = block.nodes.shift();
  16199. block.nodes = [open, { type: 'text', value: stringify$4(block) }];
  16200. }
  16201. push({ type: 'comma', value });
  16202. block.commas++;
  16203. continue;
  16204. }
  16205. /**
  16206. * Dot: '.'
  16207. */
  16208. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  16209. let siblings = block.nodes;
  16210. if (depth === 0 || siblings.length === 0) {
  16211. push({ type: 'text', value });
  16212. continue;
  16213. }
  16214. if (prev.type === 'dot') {
  16215. block.range = [];
  16216. prev.value += value;
  16217. prev.type = 'range';
  16218. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  16219. block.invalid = true;
  16220. block.ranges = 0;
  16221. prev.type = 'text';
  16222. continue;
  16223. }
  16224. block.ranges++;
  16225. block.args = [];
  16226. continue;
  16227. }
  16228. if (prev.type === 'range') {
  16229. siblings.pop();
  16230. let before = siblings[siblings.length - 1];
  16231. before.value += prev.value + value;
  16232. prev = before;
  16233. block.ranges--;
  16234. continue;
  16235. }
  16236. push({ type: 'dot', value });
  16237. continue;
  16238. }
  16239. /**
  16240. * Text
  16241. */
  16242. push({ type: 'text', value });
  16243. }
  16244. // Mark imbalanced braces and brackets as invalid
  16245. do {
  16246. block = stack.pop();
  16247. if (block.type !== 'root') {
  16248. block.nodes.forEach(node => {
  16249. if (!node.nodes) {
  16250. if (node.type === 'open') node.isOpen = true;
  16251. if (node.type === 'close') node.isClose = true;
  16252. if (!node.nodes) node.type = 'text';
  16253. node.invalid = true;
  16254. }
  16255. });
  16256. // get the location of the block on parent.nodes (block's siblings)
  16257. let parent = stack[stack.length - 1];
  16258. let index = parent.nodes.indexOf(block);
  16259. // replace the (invalid) block with it's nodes
  16260. parent.nodes.splice(index, 1, ...block.nodes);
  16261. }
  16262. } while (stack.length > 0);
  16263. push({ type: 'eos' });
  16264. return ast;
  16265. };
  16266. var parse_1$2 = parse$d;
  16267. const stringify$3 = stringify$7;
  16268. const compile = compile_1;
  16269. const expand$1 = expand_1$1;
  16270. const parse$c = parse_1$2;
  16271. /**
  16272. * Expand the given pattern or create a regex-compatible string.
  16273. *
  16274. * ```js
  16275. * const braces = require('braces');
  16276. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  16277. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  16278. * ```
  16279. * @param {String} `str`
  16280. * @param {Object} `options`
  16281. * @return {String}
  16282. * @api public
  16283. */
  16284. const braces$2 = (input, options = {}) => {
  16285. let output = [];
  16286. if (Array.isArray(input)) {
  16287. for (let pattern of input) {
  16288. let result = braces$2.create(pattern, options);
  16289. if (Array.isArray(result)) {
  16290. output.push(...result);
  16291. } else {
  16292. output.push(result);
  16293. }
  16294. }
  16295. } else {
  16296. output = [].concat(braces$2.create(input, options));
  16297. }
  16298. if (options && options.expand === true && options.nodupes === true) {
  16299. output = [...new Set(output)];
  16300. }
  16301. return output;
  16302. };
  16303. /**
  16304. * Parse the given `str` with the given `options`.
  16305. *
  16306. * ```js
  16307. * // braces.parse(pattern, [, options]);
  16308. * const ast = braces.parse('a/{b,c}/d');
  16309. * console.log(ast);
  16310. * ```
  16311. * @param {String} pattern Brace pattern to parse
  16312. * @param {Object} options
  16313. * @return {Object} Returns an AST
  16314. * @api public
  16315. */
  16316. braces$2.parse = (input, options = {}) => parse$c(input, options);
  16317. /**
  16318. * Creates a braces string from an AST, or an AST node.
  16319. *
  16320. * ```js
  16321. * const braces = require('braces');
  16322. * let ast = braces.parse('foo/{a,b}/bar');
  16323. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  16324. * ```
  16325. * @param {String} `input` Brace pattern or AST.
  16326. * @param {Object} `options`
  16327. * @return {Array} Returns an array of expanded values.
  16328. * @api public
  16329. */
  16330. braces$2.stringify = (input, options = {}) => {
  16331. if (typeof input === 'string') {
  16332. return stringify$3(braces$2.parse(input, options), options);
  16333. }
  16334. return stringify$3(input, options);
  16335. };
  16336. /**
  16337. * Compiles a brace pattern into a regex-compatible, optimized string.
  16338. * This method is called by the main [braces](#braces) function by default.
  16339. *
  16340. * ```js
  16341. * const braces = require('braces');
  16342. * console.log(braces.compile('a/{b,c}/d'));
  16343. * //=> ['a/(b|c)/d']
  16344. * ```
  16345. * @param {String} `input` Brace pattern or AST.
  16346. * @param {Object} `options`
  16347. * @return {Array} Returns an array of expanded values.
  16348. * @api public
  16349. */
  16350. braces$2.compile = (input, options = {}) => {
  16351. if (typeof input === 'string') {
  16352. input = braces$2.parse(input, options);
  16353. }
  16354. return compile(input, options);
  16355. };
  16356. /**
  16357. * Expands a brace pattern into an array. This method is called by the
  16358. * main [braces](#braces) function when `options.expand` is true. Before
  16359. * using this method it's recommended that you read the [performance notes](#performance))
  16360. * and advantages of using [.compile](#compile) instead.
  16361. *
  16362. * ```js
  16363. * const braces = require('braces');
  16364. * console.log(braces.expand('a/{b,c}/d'));
  16365. * //=> ['a/b/d', 'a/c/d'];
  16366. * ```
  16367. * @param {String} `pattern` Brace pattern
  16368. * @param {Object} `options`
  16369. * @return {Array} Returns an array of expanded values.
  16370. * @api public
  16371. */
  16372. braces$2.expand = (input, options = {}) => {
  16373. if (typeof input === 'string') {
  16374. input = braces$2.parse(input, options);
  16375. }
  16376. let result = expand$1(input, options);
  16377. // filter out empty strings if specified
  16378. if (options.noempty === true) {
  16379. result = result.filter(Boolean);
  16380. }
  16381. // filter out duplicates if specified
  16382. if (options.nodupes === true) {
  16383. result = [...new Set(result)];
  16384. }
  16385. return result;
  16386. };
  16387. /**
  16388. * Processes a brace pattern and returns either an expanded array
  16389. * (if `options.expand` is true), a highly optimized regex-compatible string.
  16390. * This method is called by the main [braces](#braces) function.
  16391. *
  16392. * ```js
  16393. * const braces = require('braces');
  16394. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  16395. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  16396. * ```
  16397. * @param {String} `pattern` Brace pattern
  16398. * @param {Object} `options`
  16399. * @return {Array} Returns an array of expanded values.
  16400. * @api public
  16401. */
  16402. braces$2.create = (input, options = {}) => {
  16403. if (input === '' || input.length < 3) {
  16404. return [input];
  16405. }
  16406. return options.expand !== true
  16407. ? braces$2.compile(input, options)
  16408. : braces$2.expand(input, options);
  16409. };
  16410. /**
  16411. * Expose "braces"
  16412. */
  16413. var braces_1 = braces$2;
  16414. const util = require$$0$6;
  16415. const braces$1 = braces_1;
  16416. const picomatch$2 = picomatch$3;
  16417. const utils$b = utils$k;
  16418. const isEmptyString = val => val === '' || val === './';
  16419. /**
  16420. * Returns an array of strings that match one or more glob patterns.
  16421. *
  16422. * ```js
  16423. * const mm = require('micromatch');
  16424. * // mm(list, patterns[, options]);
  16425. *
  16426. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  16427. * //=> [ 'a.js' ]
  16428. * ```
  16429. * @param {String|Array<string>} `list` List of strings to match.
  16430. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
  16431. * @param {Object} `options` See available [options](#options)
  16432. * @return {Array} Returns an array of matches
  16433. * @summary false
  16434. * @api public
  16435. */
  16436. const micromatch$1 = (list, patterns, options) => {
  16437. patterns = [].concat(patterns);
  16438. list = [].concat(list);
  16439. let omit = new Set();
  16440. let keep = new Set();
  16441. let items = new Set();
  16442. let negatives = 0;
  16443. let onResult = state => {
  16444. items.add(state.output);
  16445. if (options && options.onResult) {
  16446. options.onResult(state);
  16447. }
  16448. };
  16449. for (let i = 0; i < patterns.length; i++) {
  16450. let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true);
  16451. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  16452. if (negated) negatives++;
  16453. for (let item of list) {
  16454. let matched = isMatch(item, true);
  16455. let match = negated ? !matched.isMatch : matched.isMatch;
  16456. if (!match) continue;
  16457. if (negated) {
  16458. omit.add(matched.output);
  16459. } else {
  16460. omit.delete(matched.output);
  16461. keep.add(matched.output);
  16462. }
  16463. }
  16464. }
  16465. let result = negatives === patterns.length ? [...items] : [...keep];
  16466. let matches = result.filter(item => !omit.has(item));
  16467. if (options && matches.length === 0) {
  16468. if (options.failglob === true) {
  16469. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  16470. }
  16471. if (options.nonull === true || options.nullglob === true) {
  16472. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  16473. }
  16474. }
  16475. return matches;
  16476. };
  16477. /**
  16478. * Backwards compatibility
  16479. */
  16480. micromatch$1.match = micromatch$1;
  16481. /**
  16482. * Returns a matcher function from the given glob `pattern` and `options`.
  16483. * The returned function takes a string to match as its only argument and returns
  16484. * true if the string is a match.
  16485. *
  16486. * ```js
  16487. * const mm = require('micromatch');
  16488. * // mm.matcher(pattern[, options]);
  16489. *
  16490. * const isMatch = mm.matcher('*.!(*a)');
  16491. * console.log(isMatch('a.a')); //=> false
  16492. * console.log(isMatch('a.b')); //=> true
  16493. * ```
  16494. * @param {String} `pattern` Glob pattern
  16495. * @param {Object} `options`
  16496. * @return {Function} Returns a matcher function.
  16497. * @api public
  16498. */
  16499. micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options);
  16500. /**
  16501. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  16502. *
  16503. * ```js
  16504. * const mm = require('micromatch');
  16505. * // mm.isMatch(string, patterns[, options]);
  16506. *
  16507. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  16508. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  16509. * ```
  16510. * @param {String} `str` The string to test.
  16511. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16512. * @param {Object} `[options]` See available [options](#options).
  16513. * @return {Boolean} Returns true if any patterns match `str`
  16514. * @api public
  16515. */
  16516. micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
  16517. /**
  16518. * Backwards compatibility
  16519. */
  16520. micromatch$1.any = micromatch$1.isMatch;
  16521. /**
  16522. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  16523. *
  16524. * ```js
  16525. * const mm = require('micromatch');
  16526. * // mm.not(list, patterns[, options]);
  16527. *
  16528. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  16529. * //=> ['b.b', 'c.c']
  16530. * ```
  16531. * @param {Array} `list` Array of strings to match.
  16532. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  16533. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16534. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  16535. * @api public
  16536. */
  16537. micromatch$1.not = (list, patterns, options = {}) => {
  16538. patterns = [].concat(patterns).map(String);
  16539. let result = new Set();
  16540. let items = [];
  16541. let onResult = state => {
  16542. if (options.onResult) options.onResult(state);
  16543. items.push(state.output);
  16544. };
  16545. let matches = new Set(micromatch$1(list, patterns, { ...options, onResult }));
  16546. for (let item of items) {
  16547. if (!matches.has(item)) {
  16548. result.add(item);
  16549. }
  16550. }
  16551. return [...result];
  16552. };
  16553. /**
  16554. * Returns true if the given `string` contains the given pattern. Similar
  16555. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  16556. *
  16557. * ```js
  16558. * var mm = require('micromatch');
  16559. * // mm.contains(string, pattern[, options]);
  16560. *
  16561. * console.log(mm.contains('aa/bb/cc', '*b'));
  16562. * //=> true
  16563. * console.log(mm.contains('aa/bb/cc', '*d'));
  16564. * //=> false
  16565. * ```
  16566. * @param {String} `str` The string to match.
  16567. * @param {String|Array} `patterns` Glob pattern to use for matching.
  16568. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16569. * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
  16570. * @api public
  16571. */
  16572. micromatch$1.contains = (str, pattern, options) => {
  16573. if (typeof str !== 'string') {
  16574. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  16575. }
  16576. if (Array.isArray(pattern)) {
  16577. return pattern.some(p => micromatch$1.contains(str, p, options));
  16578. }
  16579. if (typeof pattern === 'string') {
  16580. if (isEmptyString(str) || isEmptyString(pattern)) {
  16581. return false;
  16582. }
  16583. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  16584. return true;
  16585. }
  16586. }
  16587. return micromatch$1.isMatch(str, pattern, { ...options, contains: true });
  16588. };
  16589. /**
  16590. * Filter the keys of the given object with the given `glob` pattern
  16591. * and `options`. Does not attempt to match nested keys. If you need this feature,
  16592. * use [glob-object][] instead.
  16593. *
  16594. * ```js
  16595. * const mm = require('micromatch');
  16596. * // mm.matchKeys(object, patterns[, options]);
  16597. *
  16598. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  16599. * console.log(mm.matchKeys(obj, '*b'));
  16600. * //=> { ab: 'b' }
  16601. * ```
  16602. * @param {Object} `object` The object with keys to filter.
  16603. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16604. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16605. * @return {Object} Returns an object with only keys that match the given patterns.
  16606. * @api public
  16607. */
  16608. micromatch$1.matchKeys = (obj, patterns, options) => {
  16609. if (!utils$b.isObject(obj)) {
  16610. throw new TypeError('Expected the first argument to be an object');
  16611. }
  16612. let keys = micromatch$1(Object.keys(obj), patterns, options);
  16613. let res = {};
  16614. for (let key of keys) res[key] = obj[key];
  16615. return res;
  16616. };
  16617. /**
  16618. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  16619. *
  16620. * ```js
  16621. * const mm = require('micromatch');
  16622. * // mm.some(list, patterns[, options]);
  16623. *
  16624. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  16625. * // true
  16626. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  16627. * // false
  16628. * ```
  16629. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  16630. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16631. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16632. * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
  16633. * @api public
  16634. */
  16635. micromatch$1.some = (list, patterns, options) => {
  16636. let items = [].concat(list);
  16637. for (let pattern of [].concat(patterns)) {
  16638. let isMatch = picomatch$2(String(pattern), options);
  16639. if (items.some(item => isMatch(item))) {
  16640. return true;
  16641. }
  16642. }
  16643. return false;
  16644. };
  16645. /**
  16646. * Returns true if every string in the given `list` matches
  16647. * any of the given glob `patterns`.
  16648. *
  16649. * ```js
  16650. * const mm = require('micromatch');
  16651. * // mm.every(list, patterns[, options]);
  16652. *
  16653. * console.log(mm.every('foo.js', ['foo.js']));
  16654. * // true
  16655. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  16656. * // true
  16657. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  16658. * // false
  16659. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  16660. * // false
  16661. * ```
  16662. * @param {String|Array} `list` The string or array of strings to test.
  16663. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16664. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16665. * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
  16666. * @api public
  16667. */
  16668. micromatch$1.every = (list, patterns, options) => {
  16669. let items = [].concat(list);
  16670. for (let pattern of [].concat(patterns)) {
  16671. let isMatch = picomatch$2(String(pattern), options);
  16672. if (!items.every(item => isMatch(item))) {
  16673. return false;
  16674. }
  16675. }
  16676. return true;
  16677. };
  16678. /**
  16679. * Returns true if **all** of the given `patterns` match
  16680. * the specified string.
  16681. *
  16682. * ```js
  16683. * const mm = require('micromatch');
  16684. * // mm.all(string, patterns[, options]);
  16685. *
  16686. * console.log(mm.all('foo.js', ['foo.js']));
  16687. * // true
  16688. *
  16689. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  16690. * // false
  16691. *
  16692. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  16693. * // true
  16694. *
  16695. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  16696. * // true
  16697. * ```
  16698. * @param {String|Array} `str` The string to test.
  16699. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16700. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16701. * @return {Boolean} Returns true if any patterns match `str`
  16702. * @api public
  16703. */
  16704. micromatch$1.all = (str, patterns, options) => {
  16705. if (typeof str !== 'string') {
  16706. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  16707. }
  16708. return [].concat(patterns).every(p => picomatch$2(p, options)(str));
  16709. };
  16710. /**
  16711. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  16712. *
  16713. * ```js
  16714. * const mm = require('micromatch');
  16715. * // mm.capture(pattern, string[, options]);
  16716. *
  16717. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  16718. * //=> ['foo']
  16719. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  16720. * //=> null
  16721. * ```
  16722. * @param {String} `glob` Glob pattern to use for matching.
  16723. * @param {String} `input` String to match
  16724. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16725. * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  16726. * @api public
  16727. */
  16728. micromatch$1.capture = (glob, input, options) => {
  16729. let posix = utils$b.isWindows(options);
  16730. let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true });
  16731. let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input);
  16732. if (match) {
  16733. return match.slice(1).map(v => v === void 0 ? '' : v);
  16734. }
  16735. };
  16736. /**
  16737. * Create a regular expression from the given glob `pattern`.
  16738. *
  16739. * ```js
  16740. * const mm = require('micromatch');
  16741. * // mm.makeRe(pattern[, options]);
  16742. *
  16743. * console.log(mm.makeRe('*.js'));
  16744. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  16745. * ```
  16746. * @param {String} `pattern` A glob pattern to convert to regex.
  16747. * @param {Object} `options`
  16748. * @return {RegExp} Returns a regex created from the given pattern.
  16749. * @api public
  16750. */
  16751. micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args);
  16752. /**
  16753. * Scan a glob pattern to separate the pattern into segments. Used
  16754. * by the [split](#split) method.
  16755. *
  16756. * ```js
  16757. * const mm = require('micromatch');
  16758. * const state = mm.scan(pattern[, options]);
  16759. * ```
  16760. * @param {String} `pattern`
  16761. * @param {Object} `options`
  16762. * @return {Object} Returns an object with
  16763. * @api public
  16764. */
  16765. micromatch$1.scan = (...args) => picomatch$2.scan(...args);
  16766. /**
  16767. * Parse a glob pattern to create the source string for a regular
  16768. * expression.
  16769. *
  16770. * ```js
  16771. * const mm = require('micromatch');
  16772. * const state = mm.parse(pattern[, options]);
  16773. * ```
  16774. * @param {String} `glob`
  16775. * @param {Object} `options`
  16776. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  16777. * @api public
  16778. */
  16779. micromatch$1.parse = (patterns, options) => {
  16780. let res = [];
  16781. for (let pattern of [].concat(patterns || [])) {
  16782. for (let str of braces$1(String(pattern), options)) {
  16783. res.push(picomatch$2.parse(str, options));
  16784. }
  16785. }
  16786. return res;
  16787. };
  16788. /**
  16789. * Process the given brace `pattern`.
  16790. *
  16791. * ```js
  16792. * const { braces } = require('micromatch');
  16793. * console.log(braces('foo/{a,b,c}/bar'));
  16794. * //=> [ 'foo/(a|b|c)/bar' ]
  16795. *
  16796. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  16797. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  16798. * ```
  16799. * @param {String} `pattern` String with brace pattern to process.
  16800. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  16801. * @return {Array}
  16802. * @api public
  16803. */
  16804. micromatch$1.braces = (pattern, options) => {
  16805. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  16806. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  16807. return [pattern];
  16808. }
  16809. return braces$1(pattern, options);
  16810. };
  16811. /**
  16812. * Expand braces
  16813. */
  16814. micromatch$1.braceExpand = (pattern, options) => {
  16815. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  16816. return micromatch$1.braces(pattern, { ...options, expand: true });
  16817. };
  16818. /**
  16819. * Expose micromatch
  16820. */
  16821. var micromatch_1 = micromatch$1;
  16822. var micromatch$2 = /*@__PURE__*/getDefaultExportFromCjs(micromatch_1);
  16823. Object.defineProperty(pattern$1, "__esModule", { value: true });
  16824. pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
  16825. const path$f = require$$0$4;
  16826. const globParent$1 = globParent$2;
  16827. const micromatch = micromatch_1;
  16828. const GLOBSTAR$1 = '**';
  16829. const ESCAPE_SYMBOL = '\\';
  16830. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  16831. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
  16832. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
  16833. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
  16834. const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
  16835. /**
  16836. * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string.
  16837. * The latter is due to the presence of the device path at the beginning of the UNC path.
  16838. */
  16839. const DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g;
  16840. function isStaticPattern(pattern, options = {}) {
  16841. return !isDynamicPattern(pattern, options);
  16842. }
  16843. pattern$1.isStaticPattern = isStaticPattern;
  16844. function isDynamicPattern(pattern, options = {}) {
  16845. /**
  16846. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  16847. * An empty string cannot be a dynamic pattern.
  16848. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  16849. */
  16850. if (pattern === '') {
  16851. return false;
  16852. }
  16853. /**
  16854. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  16855. * filepath directly (without read directory).
  16856. */
  16857. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  16858. return true;
  16859. }
  16860. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  16861. return true;
  16862. }
  16863. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  16864. return true;
  16865. }
  16866. if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
  16867. return true;
  16868. }
  16869. return false;
  16870. }
  16871. pattern$1.isDynamicPattern = isDynamicPattern;
  16872. function hasBraceExpansion(pattern) {
  16873. const openingBraceIndex = pattern.indexOf('{');
  16874. if (openingBraceIndex === -1) {
  16875. return false;
  16876. }
  16877. const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
  16878. if (closingBraceIndex === -1) {
  16879. return false;
  16880. }
  16881. const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
  16882. return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
  16883. }
  16884. function convertToPositivePattern(pattern) {
  16885. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  16886. }
  16887. pattern$1.convertToPositivePattern = convertToPositivePattern;
  16888. function convertToNegativePattern(pattern) {
  16889. return '!' + pattern;
  16890. }
  16891. pattern$1.convertToNegativePattern = convertToNegativePattern;
  16892. function isNegativePattern(pattern) {
  16893. return pattern.startsWith('!') && pattern[1] !== '(';
  16894. }
  16895. pattern$1.isNegativePattern = isNegativePattern;
  16896. function isPositivePattern(pattern) {
  16897. return !isNegativePattern(pattern);
  16898. }
  16899. pattern$1.isPositivePattern = isPositivePattern;
  16900. function getNegativePatterns(patterns) {
  16901. return patterns.filter(isNegativePattern);
  16902. }
  16903. pattern$1.getNegativePatterns = getNegativePatterns;
  16904. function getPositivePatterns$1(patterns) {
  16905. return patterns.filter(isPositivePattern);
  16906. }
  16907. pattern$1.getPositivePatterns = getPositivePatterns$1;
  16908. /**
  16909. * Returns patterns that can be applied inside the current directory.
  16910. *
  16911. * @example
  16912. * // ['./*', '*', 'a/*']
  16913. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  16914. */
  16915. function getPatternsInsideCurrentDirectory(patterns) {
  16916. return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
  16917. }
  16918. pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
  16919. /**
  16920. * Returns patterns to be expanded relative to (outside) the current directory.
  16921. *
  16922. * @example
  16923. * // ['../*', './../*']
  16924. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  16925. */
  16926. function getPatternsOutsideCurrentDirectory(patterns) {
  16927. return patterns.filter(isPatternRelatedToParentDirectory);
  16928. }
  16929. pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
  16930. function isPatternRelatedToParentDirectory(pattern) {
  16931. return pattern.startsWith('..') || pattern.startsWith('./..');
  16932. }
  16933. pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
  16934. function getBaseDirectory(pattern) {
  16935. return globParent$1(pattern, { flipBackslashes: false });
  16936. }
  16937. pattern$1.getBaseDirectory = getBaseDirectory;
  16938. function hasGlobStar(pattern) {
  16939. return pattern.includes(GLOBSTAR$1);
  16940. }
  16941. pattern$1.hasGlobStar = hasGlobStar;
  16942. function endsWithSlashGlobStar(pattern) {
  16943. return pattern.endsWith('/' + GLOBSTAR$1);
  16944. }
  16945. pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
  16946. function isAffectDepthOfReadingPattern(pattern) {
  16947. const basename = path$f.basename(pattern);
  16948. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  16949. }
  16950. pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  16951. function expandPatternsWithBraceExpansion(patterns) {
  16952. return patterns.reduce((collection, pattern) => {
  16953. return collection.concat(expandBraceExpansion(pattern));
  16954. }, []);
  16955. }
  16956. pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  16957. function expandBraceExpansion(pattern) {
  16958. const patterns = micromatch.braces(pattern, { expand: true, nodupes: true });
  16959. /**
  16960. * Sort the patterns by length so that the same depth patterns are processed side by side.
  16961. * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']`
  16962. */
  16963. patterns.sort((a, b) => a.length - b.length);
  16964. /**
  16965. * Micromatch can return an empty string in the case of patterns like `{a,}`.
  16966. */
  16967. return patterns.filter((pattern) => pattern !== '');
  16968. }
  16969. pattern$1.expandBraceExpansion = expandBraceExpansion;
  16970. function getPatternParts(pattern, options) {
  16971. let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
  16972. /**
  16973. * The scan method returns an empty array in some cases.
  16974. * See micromatch/picomatch#58 for more details.
  16975. */
  16976. if (parts.length === 0) {
  16977. parts = [pattern];
  16978. }
  16979. /**
  16980. * The scan method does not return an empty part for the pattern with a forward slash.
  16981. * This is another part of micromatch/picomatch#58.
  16982. */
  16983. if (parts[0].startsWith('/')) {
  16984. parts[0] = parts[0].slice(1);
  16985. parts.unshift('');
  16986. }
  16987. return parts;
  16988. }
  16989. pattern$1.getPatternParts = getPatternParts;
  16990. function makeRe(pattern, options) {
  16991. return micromatch.makeRe(pattern, options);
  16992. }
  16993. pattern$1.makeRe = makeRe;
  16994. function convertPatternsToRe(patterns, options) {
  16995. return patterns.map((pattern) => makeRe(pattern, options));
  16996. }
  16997. pattern$1.convertPatternsToRe = convertPatternsToRe;
  16998. function matchAny(entry, patternsRe) {
  16999. return patternsRe.some((patternRe) => patternRe.test(entry));
  17000. }
  17001. pattern$1.matchAny = matchAny;
  17002. /**
  17003. * This package only works with forward slashes as a path separator.
  17004. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
  17005. */
  17006. function removeDuplicateSlashes(pattern) {
  17007. return pattern.replace(DOUBLE_SLASH_RE$1, '/');
  17008. }
  17009. pattern$1.removeDuplicateSlashes = removeDuplicateSlashes;
  17010. var stream$4 = {};
  17011. /*
  17012. * merge2
  17013. * https://github.com/teambition/merge2
  17014. *
  17015. * Copyright (c) 2014-2020 Teambition
  17016. * Licensed under the MIT license.
  17017. */
  17018. const Stream = require$$0$7;
  17019. const PassThrough = Stream.PassThrough;
  17020. const slice = Array.prototype.slice;
  17021. var merge2_1 = merge2$1;
  17022. function merge2$1 () {
  17023. const streamsQueue = [];
  17024. const args = slice.call(arguments);
  17025. let merging = false;
  17026. let options = args[args.length - 1];
  17027. if (options && !Array.isArray(options) && options.pipe == null) {
  17028. args.pop();
  17029. } else {
  17030. options = {};
  17031. }
  17032. const doEnd = options.end !== false;
  17033. const doPipeError = options.pipeError === true;
  17034. if (options.objectMode == null) {
  17035. options.objectMode = true;
  17036. }
  17037. if (options.highWaterMark == null) {
  17038. options.highWaterMark = 64 * 1024;
  17039. }
  17040. const mergedStream = PassThrough(options);
  17041. function addStream () {
  17042. for (let i = 0, len = arguments.length; i < len; i++) {
  17043. streamsQueue.push(pauseStreams(arguments[i], options));
  17044. }
  17045. mergeStream();
  17046. return this
  17047. }
  17048. function mergeStream () {
  17049. if (merging) {
  17050. return
  17051. }
  17052. merging = true;
  17053. let streams = streamsQueue.shift();
  17054. if (!streams) {
  17055. process.nextTick(endStream);
  17056. return
  17057. }
  17058. if (!Array.isArray(streams)) {
  17059. streams = [streams];
  17060. }
  17061. let pipesCount = streams.length + 1;
  17062. function next () {
  17063. if (--pipesCount > 0) {
  17064. return
  17065. }
  17066. merging = false;
  17067. mergeStream();
  17068. }
  17069. function pipe (stream) {
  17070. function onend () {
  17071. stream.removeListener('merge2UnpipeEnd', onend);
  17072. stream.removeListener('end', onend);
  17073. if (doPipeError) {
  17074. stream.removeListener('error', onerror);
  17075. }
  17076. next();
  17077. }
  17078. function onerror (err) {
  17079. mergedStream.emit('error', err);
  17080. }
  17081. // skip ended stream
  17082. if (stream._readableState.endEmitted) {
  17083. return next()
  17084. }
  17085. stream.on('merge2UnpipeEnd', onend);
  17086. stream.on('end', onend);
  17087. if (doPipeError) {
  17088. stream.on('error', onerror);
  17089. }
  17090. stream.pipe(mergedStream, { end: false });
  17091. // compatible for old stream
  17092. stream.resume();
  17093. }
  17094. for (let i = 0; i < streams.length; i++) {
  17095. pipe(streams[i]);
  17096. }
  17097. next();
  17098. }
  17099. function endStream () {
  17100. merging = false;
  17101. // emit 'queueDrain' when all streams merged.
  17102. mergedStream.emit('queueDrain');
  17103. if (doEnd) {
  17104. mergedStream.end();
  17105. }
  17106. }
  17107. mergedStream.setMaxListeners(0);
  17108. mergedStream.add = addStream;
  17109. mergedStream.on('unpipe', function (stream) {
  17110. stream.emit('merge2UnpipeEnd');
  17111. });
  17112. if (args.length) {
  17113. addStream.apply(null, args);
  17114. }
  17115. return mergedStream
  17116. }
  17117. // check and pause streams for pipe.
  17118. function pauseStreams (streams, options) {
  17119. if (!Array.isArray(streams)) {
  17120. // Backwards-compat with old-style streams
  17121. if (!streams._readableState && streams.pipe) {
  17122. streams = streams.pipe(PassThrough(options));
  17123. }
  17124. if (!streams._readableState || !streams.pause || !streams.pipe) {
  17125. throw new Error('Only readable stream can be merged.')
  17126. }
  17127. streams.pause();
  17128. } else {
  17129. for (let i = 0, len = streams.length; i < len; i++) {
  17130. streams[i] = pauseStreams(streams[i], options);
  17131. }
  17132. }
  17133. return streams
  17134. }
  17135. Object.defineProperty(stream$4, "__esModule", { value: true });
  17136. stream$4.merge = void 0;
  17137. const merge2 = merge2_1;
  17138. function merge$1(streams) {
  17139. const mergedStream = merge2(streams);
  17140. streams.forEach((stream) => {
  17141. stream.once('error', (error) => mergedStream.emit('error', error));
  17142. });
  17143. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  17144. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  17145. return mergedStream;
  17146. }
  17147. stream$4.merge = merge$1;
  17148. function propagateCloseEventToSources(streams) {
  17149. streams.forEach((stream) => stream.emit('close'));
  17150. }
  17151. var string$2 = {};
  17152. Object.defineProperty(string$2, "__esModule", { value: true });
  17153. string$2.isEmpty = string$2.isString = void 0;
  17154. function isString(input) {
  17155. return typeof input === 'string';
  17156. }
  17157. string$2.isString = isString;
  17158. function isEmpty$1(input) {
  17159. return input === '';
  17160. }
  17161. string$2.isEmpty = isEmpty$1;
  17162. Object.defineProperty(utils$g, "__esModule", { value: true });
  17163. utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0;
  17164. const array = array$1;
  17165. utils$g.array = array;
  17166. const errno = errno$1;
  17167. utils$g.errno = errno;
  17168. const fs$g = fs$h;
  17169. utils$g.fs = fs$g;
  17170. const path$e = path$h;
  17171. utils$g.path = path$e;
  17172. const pattern = pattern$1;
  17173. utils$g.pattern = pattern;
  17174. const stream$3 = stream$4;
  17175. utils$g.stream = stream$3;
  17176. const string$1 = string$2;
  17177. utils$g.string = string$1;
  17178. Object.defineProperty(tasks, "__esModule", { value: true });
  17179. tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
  17180. const utils$a = utils$g;
  17181. function generate(input, settings) {
  17182. const patterns = processPatterns(input, settings);
  17183. const ignore = processPatterns(settings.ignore, settings);
  17184. const positivePatterns = getPositivePatterns(patterns);
  17185. const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
  17186. const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings));
  17187. const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings));
  17188. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
  17189. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
  17190. return staticTasks.concat(dynamicTasks);
  17191. }
  17192. tasks.generate = generate;
  17193. function processPatterns(input, settings) {
  17194. let patterns = input;
  17195. /**
  17196. * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry
  17197. * and some problems with the micromatch package (see fast-glob issues: #365, #394).
  17198. *
  17199. * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown
  17200. * in matching in the case of a large set of patterns after expansion.
  17201. */
  17202. if (settings.braceExpansion) {
  17203. patterns = utils$a.pattern.expandPatternsWithBraceExpansion(patterns);
  17204. }
  17205. /**
  17206. * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used
  17207. * at any nesting level.
  17208. *
  17209. * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change
  17210. * the pattern in the filter before creating a regular expression. There is no need to change the patterns
  17211. * in the application. Only on the input.
  17212. */
  17213. if (settings.baseNameMatch) {
  17214. patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`);
  17215. }
  17216. /**
  17217. * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion.
  17218. */
  17219. return patterns.map((pattern) => utils$a.pattern.removeDuplicateSlashes(pattern));
  17220. }
  17221. /**
  17222. * Returns tasks grouped by basic pattern directories.
  17223. *
  17224. * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
  17225. * This is necessary because directory traversal starts at the base directory and goes deeper.
  17226. */
  17227. function convertPatternsToTasks(positive, negative, dynamic) {
  17228. const tasks = [];
  17229. const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
  17230. const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
  17231. const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
  17232. const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
  17233. tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
  17234. /*
  17235. * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
  17236. * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
  17237. */
  17238. if ('.' in insideCurrentDirectoryGroup) {
  17239. tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
  17240. }
  17241. else {
  17242. tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
  17243. }
  17244. return tasks;
  17245. }
  17246. tasks.convertPatternsToTasks = convertPatternsToTasks;
  17247. function getPositivePatterns(patterns) {
  17248. return utils$a.pattern.getPositivePatterns(patterns);
  17249. }
  17250. tasks.getPositivePatterns = getPositivePatterns;
  17251. function getNegativePatternsAsPositive(patterns, ignore) {
  17252. const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
  17253. const positive = negative.map(utils$a.pattern.convertToPositivePattern);
  17254. return positive;
  17255. }
  17256. tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  17257. function groupPatternsByBaseDirectory(patterns) {
  17258. const group = {};
  17259. return patterns.reduce((collection, pattern) => {
  17260. const base = utils$a.pattern.getBaseDirectory(pattern);
  17261. if (base in collection) {
  17262. collection[base].push(pattern);
  17263. }
  17264. else {
  17265. collection[base] = [pattern];
  17266. }
  17267. return collection;
  17268. }, group);
  17269. }
  17270. tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  17271. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  17272. return Object.keys(positive).map((base) => {
  17273. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  17274. });
  17275. }
  17276. tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  17277. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  17278. return {
  17279. dynamic,
  17280. positive,
  17281. negative,
  17282. base,
  17283. patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
  17284. };
  17285. }
  17286. tasks.convertPatternGroupToTask = convertPatternGroupToTask;
  17287. var async$7 = {};
  17288. var async$6 = {};
  17289. var out$3 = {};
  17290. var async$5 = {};
  17291. var async$4 = {};
  17292. var out$2 = {};
  17293. var async$3 = {};
  17294. var out$1 = {};
  17295. var async$2 = {};
  17296. Object.defineProperty(async$2, "__esModule", { value: true });
  17297. async$2.read = void 0;
  17298. function read$3(path, settings, callback) {
  17299. settings.fs.lstat(path, (lstatError, lstat) => {
  17300. if (lstatError !== null) {
  17301. callFailureCallback$2(callback, lstatError);
  17302. return;
  17303. }
  17304. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  17305. callSuccessCallback$2(callback, lstat);
  17306. return;
  17307. }
  17308. settings.fs.stat(path, (statError, stat) => {
  17309. if (statError !== null) {
  17310. if (settings.throwErrorOnBrokenSymbolicLink) {
  17311. callFailureCallback$2(callback, statError);
  17312. return;
  17313. }
  17314. callSuccessCallback$2(callback, lstat);
  17315. return;
  17316. }
  17317. if (settings.markSymbolicLink) {
  17318. stat.isSymbolicLink = () => true;
  17319. }
  17320. callSuccessCallback$2(callback, stat);
  17321. });
  17322. });
  17323. }
  17324. async$2.read = read$3;
  17325. function callFailureCallback$2(callback, error) {
  17326. callback(error);
  17327. }
  17328. function callSuccessCallback$2(callback, result) {
  17329. callback(null, result);
  17330. }
  17331. var sync$8 = {};
  17332. Object.defineProperty(sync$8, "__esModule", { value: true });
  17333. sync$8.read = void 0;
  17334. function read$2(path, settings) {
  17335. const lstat = settings.fs.lstatSync(path);
  17336. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  17337. return lstat;
  17338. }
  17339. try {
  17340. const stat = settings.fs.statSync(path);
  17341. if (settings.markSymbolicLink) {
  17342. stat.isSymbolicLink = () => true;
  17343. }
  17344. return stat;
  17345. }
  17346. catch (error) {
  17347. if (!settings.throwErrorOnBrokenSymbolicLink) {
  17348. return lstat;
  17349. }
  17350. throw error;
  17351. }
  17352. }
  17353. sync$8.read = read$2;
  17354. var settings$3 = {};
  17355. var fs$f = {};
  17356. (function (exports) {
  17357. Object.defineProperty(exports, "__esModule", { value: true });
  17358. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  17359. const fs = require$$0__default;
  17360. exports.FILE_SYSTEM_ADAPTER = {
  17361. lstat: fs.lstat,
  17362. stat: fs.stat,
  17363. lstatSync: fs.lstatSync,
  17364. statSync: fs.statSync
  17365. };
  17366. function createFileSystemAdapter(fsMethods) {
  17367. if (fsMethods === undefined) {
  17368. return exports.FILE_SYSTEM_ADAPTER;
  17369. }
  17370. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  17371. }
  17372. exports.createFileSystemAdapter = createFileSystemAdapter;
  17373. } (fs$f));
  17374. Object.defineProperty(settings$3, "__esModule", { value: true });
  17375. const fs$e = fs$f;
  17376. let Settings$2 = class Settings {
  17377. constructor(_options = {}) {
  17378. this._options = _options;
  17379. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  17380. this.fs = fs$e.createFileSystemAdapter(this._options.fs);
  17381. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  17382. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  17383. }
  17384. _getValue(option, value) {
  17385. return option !== null && option !== void 0 ? option : value;
  17386. }
  17387. };
  17388. settings$3.default = Settings$2;
  17389. Object.defineProperty(out$1, "__esModule", { value: true });
  17390. out$1.statSync = out$1.stat = out$1.Settings = void 0;
  17391. const async$1 = async$2;
  17392. const sync$7 = sync$8;
  17393. const settings_1$3 = settings$3;
  17394. out$1.Settings = settings_1$3.default;
  17395. function stat$4(path, optionsOrSettingsOrCallback, callback) {
  17396. if (typeof optionsOrSettingsOrCallback === 'function') {
  17397. async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback);
  17398. return;
  17399. }
  17400. async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
  17401. }
  17402. out$1.stat = stat$4;
  17403. function statSync(path, optionsOrSettings) {
  17404. const settings = getSettings$2(optionsOrSettings);
  17405. return sync$7.read(path, settings);
  17406. }
  17407. out$1.statSync = statSync;
  17408. function getSettings$2(settingsOrOptions = {}) {
  17409. if (settingsOrOptions instanceof settings_1$3.default) {
  17410. return settingsOrOptions;
  17411. }
  17412. return new settings_1$3.default(settingsOrOptions);
  17413. }
  17414. /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  17415. let promise;
  17416. var queueMicrotask_1 = typeof queueMicrotask === 'function'
  17417. ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
  17418. // reuse resolved promise, and allocate it lazily
  17419. : cb => (promise || (promise = Promise.resolve()))
  17420. .then(cb)
  17421. .catch(err => setTimeout(() => { throw err }, 0));
  17422. /*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  17423. var runParallel_1 = runParallel;
  17424. const queueMicrotask$1 = queueMicrotask_1;
  17425. function runParallel (tasks, cb) {
  17426. let results, pending, keys;
  17427. let isSync = true;
  17428. if (Array.isArray(tasks)) {
  17429. results = [];
  17430. pending = tasks.length;
  17431. } else {
  17432. keys = Object.keys(tasks);
  17433. results = {};
  17434. pending = keys.length;
  17435. }
  17436. function done (err) {
  17437. function end () {
  17438. if (cb) cb(err, results);
  17439. cb = null;
  17440. }
  17441. if (isSync) queueMicrotask$1(end);
  17442. else end();
  17443. }
  17444. function each (i, err, result) {
  17445. results[i] = result;
  17446. if (--pending === 0 || err) {
  17447. done(err);
  17448. }
  17449. }
  17450. if (!pending) {
  17451. // empty
  17452. done(null);
  17453. } else if (keys) {
  17454. // object
  17455. keys.forEach(function (key) {
  17456. tasks[key](function (err, result) { each(key, err, result); });
  17457. });
  17458. } else {
  17459. // array
  17460. tasks.forEach(function (task, i) {
  17461. task(function (err, result) { each(i, err, result); });
  17462. });
  17463. }
  17464. isSync = false;
  17465. }
  17466. var constants$2 = {};
  17467. Object.defineProperty(constants$2, "__esModule", { value: true });
  17468. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
  17469. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  17470. if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
  17471. throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
  17472. }
  17473. const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  17474. const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  17475. const SUPPORTED_MAJOR_VERSION = 10;
  17476. const SUPPORTED_MINOR_VERSION = 10;
  17477. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  17478. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  17479. /**
  17480. * IS `true` for Node.js 10.10 and greater.
  17481. */
  17482. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  17483. var utils$9 = {};
  17484. var fs$d = {};
  17485. Object.defineProperty(fs$d, "__esModule", { value: true });
  17486. fs$d.createDirentFromStats = void 0;
  17487. class DirentFromStats {
  17488. constructor(name, stats) {
  17489. this.name = name;
  17490. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  17491. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  17492. this.isDirectory = stats.isDirectory.bind(stats);
  17493. this.isFIFO = stats.isFIFO.bind(stats);
  17494. this.isFile = stats.isFile.bind(stats);
  17495. this.isSocket = stats.isSocket.bind(stats);
  17496. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  17497. }
  17498. }
  17499. function createDirentFromStats(name, stats) {
  17500. return new DirentFromStats(name, stats);
  17501. }
  17502. fs$d.createDirentFromStats = createDirentFromStats;
  17503. Object.defineProperty(utils$9, "__esModule", { value: true });
  17504. utils$9.fs = void 0;
  17505. const fs$c = fs$d;
  17506. utils$9.fs = fs$c;
  17507. var common$a = {};
  17508. Object.defineProperty(common$a, "__esModule", { value: true });
  17509. common$a.joinPathSegments = void 0;
  17510. function joinPathSegments$1(a, b, separator) {
  17511. /**
  17512. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  17513. */
  17514. if (a.endsWith(separator)) {
  17515. return a + b;
  17516. }
  17517. return a + separator + b;
  17518. }
  17519. common$a.joinPathSegments = joinPathSegments$1;
  17520. Object.defineProperty(async$3, "__esModule", { value: true });
  17521. async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0;
  17522. const fsStat$5 = out$1;
  17523. const rpl = runParallel_1;
  17524. const constants_1$1 = constants$2;
  17525. const utils$8 = utils$9;
  17526. const common$9 = common$a;
  17527. function read$1(directory, settings, callback) {
  17528. if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  17529. readdirWithFileTypes$1(directory, settings, callback);
  17530. return;
  17531. }
  17532. readdir$3(directory, settings, callback);
  17533. }
  17534. async$3.read = read$1;
  17535. function readdirWithFileTypes$1(directory, settings, callback) {
  17536. settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
  17537. if (readdirError !== null) {
  17538. callFailureCallback$1(callback, readdirError);
  17539. return;
  17540. }
  17541. const entries = dirents.map((dirent) => ({
  17542. dirent,
  17543. name: dirent.name,
  17544. path: common$9.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  17545. }));
  17546. if (!settings.followSymbolicLinks) {
  17547. callSuccessCallback$1(callback, entries);
  17548. return;
  17549. }
  17550. const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
  17551. rpl(tasks, (rplError, rplEntries) => {
  17552. if (rplError !== null) {
  17553. callFailureCallback$1(callback, rplError);
  17554. return;
  17555. }
  17556. callSuccessCallback$1(callback, rplEntries);
  17557. });
  17558. });
  17559. }
  17560. async$3.readdirWithFileTypes = readdirWithFileTypes$1;
  17561. function makeRplTaskEntry(entry, settings) {
  17562. return (done) => {
  17563. if (!entry.dirent.isSymbolicLink()) {
  17564. done(null, entry);
  17565. return;
  17566. }
  17567. settings.fs.stat(entry.path, (statError, stats) => {
  17568. if (statError !== null) {
  17569. if (settings.throwErrorOnBrokenSymbolicLink) {
  17570. done(statError);
  17571. return;
  17572. }
  17573. done(null, entry);
  17574. return;
  17575. }
  17576. entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats);
  17577. done(null, entry);
  17578. });
  17579. };
  17580. }
  17581. function readdir$3(directory, settings, callback) {
  17582. settings.fs.readdir(directory, (readdirError, names) => {
  17583. if (readdirError !== null) {
  17584. callFailureCallback$1(callback, readdirError);
  17585. return;
  17586. }
  17587. const tasks = names.map((name) => {
  17588. const path = common$9.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  17589. return (done) => {
  17590. fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => {
  17591. if (error !== null) {
  17592. done(error);
  17593. return;
  17594. }
  17595. const entry = {
  17596. name,
  17597. path,
  17598. dirent: utils$8.fs.createDirentFromStats(name, stats)
  17599. };
  17600. if (settings.stats) {
  17601. entry.stats = stats;
  17602. }
  17603. done(null, entry);
  17604. });
  17605. };
  17606. });
  17607. rpl(tasks, (rplError, entries) => {
  17608. if (rplError !== null) {
  17609. callFailureCallback$1(callback, rplError);
  17610. return;
  17611. }
  17612. callSuccessCallback$1(callback, entries);
  17613. });
  17614. });
  17615. }
  17616. async$3.readdir = readdir$3;
  17617. function callFailureCallback$1(callback, error) {
  17618. callback(error);
  17619. }
  17620. function callSuccessCallback$1(callback, result) {
  17621. callback(null, result);
  17622. }
  17623. var sync$6 = {};
  17624. Object.defineProperty(sync$6, "__esModule", { value: true });
  17625. sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0;
  17626. const fsStat$4 = out$1;
  17627. const constants_1 = constants$2;
  17628. const utils$7 = utils$9;
  17629. const common$8 = common$a;
  17630. function read(directory, settings) {
  17631. if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  17632. return readdirWithFileTypes(directory, settings);
  17633. }
  17634. return readdir$2(directory, settings);
  17635. }
  17636. sync$6.read = read;
  17637. function readdirWithFileTypes(directory, settings) {
  17638. const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
  17639. return dirents.map((dirent) => {
  17640. const entry = {
  17641. dirent,
  17642. name: dirent.name,
  17643. path: common$8.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  17644. };
  17645. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  17646. try {
  17647. const stats = settings.fs.statSync(entry.path);
  17648. entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats);
  17649. }
  17650. catch (error) {
  17651. if (settings.throwErrorOnBrokenSymbolicLink) {
  17652. throw error;
  17653. }
  17654. }
  17655. }
  17656. return entry;
  17657. });
  17658. }
  17659. sync$6.readdirWithFileTypes = readdirWithFileTypes;
  17660. function readdir$2(directory, settings) {
  17661. const names = settings.fs.readdirSync(directory);
  17662. return names.map((name) => {
  17663. const entryPath = common$8.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  17664. const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings);
  17665. const entry = {
  17666. name,
  17667. path: entryPath,
  17668. dirent: utils$7.fs.createDirentFromStats(name, stats)
  17669. };
  17670. if (settings.stats) {
  17671. entry.stats = stats;
  17672. }
  17673. return entry;
  17674. });
  17675. }
  17676. sync$6.readdir = readdir$2;
  17677. var settings$2 = {};
  17678. var fs$b = {};
  17679. (function (exports) {
  17680. Object.defineProperty(exports, "__esModule", { value: true });
  17681. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  17682. const fs = require$$0__default;
  17683. exports.FILE_SYSTEM_ADAPTER = {
  17684. lstat: fs.lstat,
  17685. stat: fs.stat,
  17686. lstatSync: fs.lstatSync,
  17687. statSync: fs.statSync,
  17688. readdir: fs.readdir,
  17689. readdirSync: fs.readdirSync
  17690. };
  17691. function createFileSystemAdapter(fsMethods) {
  17692. if (fsMethods === undefined) {
  17693. return exports.FILE_SYSTEM_ADAPTER;
  17694. }
  17695. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  17696. }
  17697. exports.createFileSystemAdapter = createFileSystemAdapter;
  17698. } (fs$b));
  17699. Object.defineProperty(settings$2, "__esModule", { value: true });
  17700. const path$d = require$$0$4;
  17701. const fsStat$3 = out$1;
  17702. const fs$a = fs$b;
  17703. let Settings$1 = class Settings {
  17704. constructor(_options = {}) {
  17705. this._options = _options;
  17706. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  17707. this.fs = fs$a.createFileSystemAdapter(this._options.fs);
  17708. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep);
  17709. this.stats = this._getValue(this._options.stats, false);
  17710. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  17711. this.fsStatSettings = new fsStat$3.Settings({
  17712. followSymbolicLink: this.followSymbolicLinks,
  17713. fs: this.fs,
  17714. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  17715. });
  17716. }
  17717. _getValue(option, value) {
  17718. return option !== null && option !== void 0 ? option : value;
  17719. }
  17720. };
  17721. settings$2.default = Settings$1;
  17722. Object.defineProperty(out$2, "__esModule", { value: true });
  17723. out$2.Settings = out$2.scandirSync = out$2.scandir = void 0;
  17724. const async = async$3;
  17725. const sync$5 = sync$6;
  17726. const settings_1$2 = settings$2;
  17727. out$2.Settings = settings_1$2.default;
  17728. function scandir(path, optionsOrSettingsOrCallback, callback) {
  17729. if (typeof optionsOrSettingsOrCallback === 'function') {
  17730. async.read(path, getSettings$1(), optionsOrSettingsOrCallback);
  17731. return;
  17732. }
  17733. async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
  17734. }
  17735. out$2.scandir = scandir;
  17736. function scandirSync(path, optionsOrSettings) {
  17737. const settings = getSettings$1(optionsOrSettings);
  17738. return sync$5.read(path, settings);
  17739. }
  17740. out$2.scandirSync = scandirSync;
  17741. function getSettings$1(settingsOrOptions = {}) {
  17742. if (settingsOrOptions instanceof settings_1$2.default) {
  17743. return settingsOrOptions;
  17744. }
  17745. return new settings_1$2.default(settingsOrOptions);
  17746. }
  17747. var queue = {exports: {}};
  17748. function reusify$1 (Constructor) {
  17749. var head = new Constructor();
  17750. var tail = head;
  17751. function get () {
  17752. var current = head;
  17753. if (current.next) {
  17754. head = current.next;
  17755. } else {
  17756. head = new Constructor();
  17757. tail = head;
  17758. }
  17759. current.next = null;
  17760. return current
  17761. }
  17762. function release (obj) {
  17763. tail.next = obj;
  17764. tail = obj;
  17765. }
  17766. return {
  17767. get: get,
  17768. release: release
  17769. }
  17770. }
  17771. var reusify_1 = reusify$1;
  17772. /* eslint-disable no-var */
  17773. var reusify = reusify_1;
  17774. function fastqueue (context, worker, concurrency) {
  17775. if (typeof context === 'function') {
  17776. concurrency = worker;
  17777. worker = context;
  17778. context = null;
  17779. }
  17780. if (concurrency < 1) {
  17781. throw new Error('fastqueue concurrency must be greater than 1')
  17782. }
  17783. var cache = reusify(Task);
  17784. var queueHead = null;
  17785. var queueTail = null;
  17786. var _running = 0;
  17787. var errorHandler = null;
  17788. var self = {
  17789. push: push,
  17790. drain: noop$4,
  17791. saturated: noop$4,
  17792. pause: pause,
  17793. paused: false,
  17794. concurrency: concurrency,
  17795. running: running,
  17796. resume: resume,
  17797. idle: idle,
  17798. length: length,
  17799. getQueue: getQueue,
  17800. unshift: unshift,
  17801. empty: noop$4,
  17802. kill: kill,
  17803. killAndDrain: killAndDrain,
  17804. error: error
  17805. };
  17806. return self
  17807. function running () {
  17808. return _running
  17809. }
  17810. function pause () {
  17811. self.paused = true;
  17812. }
  17813. function length () {
  17814. var current = queueHead;
  17815. var counter = 0;
  17816. while (current) {
  17817. current = current.next;
  17818. counter++;
  17819. }
  17820. return counter
  17821. }
  17822. function getQueue () {
  17823. var current = queueHead;
  17824. var tasks = [];
  17825. while (current) {
  17826. tasks.push(current.value);
  17827. current = current.next;
  17828. }
  17829. return tasks
  17830. }
  17831. function resume () {
  17832. if (!self.paused) return
  17833. self.paused = false;
  17834. for (var i = 0; i < self.concurrency; i++) {
  17835. _running++;
  17836. release();
  17837. }
  17838. }
  17839. function idle () {
  17840. return _running === 0 && self.length() === 0
  17841. }
  17842. function push (value, done) {
  17843. var current = cache.get();
  17844. current.context = context;
  17845. current.release = release;
  17846. current.value = value;
  17847. current.callback = done || noop$4;
  17848. current.errorHandler = errorHandler;
  17849. if (_running === self.concurrency || self.paused) {
  17850. if (queueTail) {
  17851. queueTail.next = current;
  17852. queueTail = current;
  17853. } else {
  17854. queueHead = current;
  17855. queueTail = current;
  17856. self.saturated();
  17857. }
  17858. } else {
  17859. _running++;
  17860. worker.call(context, current.value, current.worked);
  17861. }
  17862. }
  17863. function unshift (value, done) {
  17864. var current = cache.get();
  17865. current.context = context;
  17866. current.release = release;
  17867. current.value = value;
  17868. current.callback = done || noop$4;
  17869. if (_running === self.concurrency || self.paused) {
  17870. if (queueHead) {
  17871. current.next = queueHead;
  17872. queueHead = current;
  17873. } else {
  17874. queueHead = current;
  17875. queueTail = current;
  17876. self.saturated();
  17877. }
  17878. } else {
  17879. _running++;
  17880. worker.call(context, current.value, current.worked);
  17881. }
  17882. }
  17883. function release (holder) {
  17884. if (holder) {
  17885. cache.release(holder);
  17886. }
  17887. var next = queueHead;
  17888. if (next) {
  17889. if (!self.paused) {
  17890. if (queueTail === queueHead) {
  17891. queueTail = null;
  17892. }
  17893. queueHead = next.next;
  17894. next.next = null;
  17895. worker.call(context, next.value, next.worked);
  17896. if (queueTail === null) {
  17897. self.empty();
  17898. }
  17899. } else {
  17900. _running--;
  17901. }
  17902. } else if (--_running === 0) {
  17903. self.drain();
  17904. }
  17905. }
  17906. function kill () {
  17907. queueHead = null;
  17908. queueTail = null;
  17909. self.drain = noop$4;
  17910. }
  17911. function killAndDrain () {
  17912. queueHead = null;
  17913. queueTail = null;
  17914. self.drain();
  17915. self.drain = noop$4;
  17916. }
  17917. function error (handler) {
  17918. errorHandler = handler;
  17919. }
  17920. }
  17921. function noop$4 () {}
  17922. function Task () {
  17923. this.value = null;
  17924. this.callback = noop$4;
  17925. this.next = null;
  17926. this.release = noop$4;
  17927. this.context = null;
  17928. this.errorHandler = null;
  17929. var self = this;
  17930. this.worked = function worked (err, result) {
  17931. var callback = self.callback;
  17932. var errorHandler = self.errorHandler;
  17933. var val = self.value;
  17934. self.value = null;
  17935. self.callback = noop$4;
  17936. if (self.errorHandler) {
  17937. errorHandler(err, val);
  17938. }
  17939. callback.call(self.context, err, result);
  17940. self.release(self);
  17941. };
  17942. }
  17943. function queueAsPromised (context, worker, concurrency) {
  17944. if (typeof context === 'function') {
  17945. concurrency = worker;
  17946. worker = context;
  17947. context = null;
  17948. }
  17949. function asyncWrapper (arg, cb) {
  17950. worker.call(this, arg)
  17951. .then(function (res) {
  17952. cb(null, res);
  17953. }, cb);
  17954. }
  17955. var queue = fastqueue(context, asyncWrapper, concurrency);
  17956. var pushCb = queue.push;
  17957. var unshiftCb = queue.unshift;
  17958. queue.push = push;
  17959. queue.unshift = unshift;
  17960. queue.drained = drained;
  17961. return queue
  17962. function push (value) {
  17963. var p = new Promise(function (resolve, reject) {
  17964. pushCb(value, function (err, result) {
  17965. if (err) {
  17966. reject(err);
  17967. return
  17968. }
  17969. resolve(result);
  17970. });
  17971. });
  17972. // Let's fork the promise chain to
  17973. // make the error bubble up to the user but
  17974. // not lead to a unhandledRejection
  17975. p.catch(noop$4);
  17976. return p
  17977. }
  17978. function unshift (value) {
  17979. var p = new Promise(function (resolve, reject) {
  17980. unshiftCb(value, function (err, result) {
  17981. if (err) {
  17982. reject(err);
  17983. return
  17984. }
  17985. resolve(result);
  17986. });
  17987. });
  17988. // Let's fork the promise chain to
  17989. // make the error bubble up to the user but
  17990. // not lead to a unhandledRejection
  17991. p.catch(noop$4);
  17992. return p
  17993. }
  17994. function drained () {
  17995. var previousDrain = queue.drain;
  17996. var p = new Promise(function (resolve) {
  17997. queue.drain = function () {
  17998. previousDrain();
  17999. resolve();
  18000. };
  18001. });
  18002. return p
  18003. }
  18004. }
  18005. queue.exports = fastqueue;
  18006. queue.exports.promise = queueAsPromised;
  18007. var queueExports = queue.exports;
  18008. var common$7 = {};
  18009. Object.defineProperty(common$7, "__esModule", { value: true });
  18010. common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0;
  18011. function isFatalError(settings, error) {
  18012. if (settings.errorFilter === null) {
  18013. return true;
  18014. }
  18015. return !settings.errorFilter(error);
  18016. }
  18017. common$7.isFatalError = isFatalError;
  18018. function isAppliedFilter(filter, value) {
  18019. return filter === null || filter(value);
  18020. }
  18021. common$7.isAppliedFilter = isAppliedFilter;
  18022. function replacePathSegmentSeparator(filepath, separator) {
  18023. return filepath.split(/[/\\]/).join(separator);
  18024. }
  18025. common$7.replacePathSegmentSeparator = replacePathSegmentSeparator;
  18026. function joinPathSegments(a, b, separator) {
  18027. if (a === '') {
  18028. return b;
  18029. }
  18030. /**
  18031. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  18032. */
  18033. if (a.endsWith(separator)) {
  18034. return a + b;
  18035. }
  18036. return a + separator + b;
  18037. }
  18038. common$7.joinPathSegments = joinPathSegments;
  18039. var reader$1 = {};
  18040. Object.defineProperty(reader$1, "__esModule", { value: true });
  18041. const common$6 = common$7;
  18042. let Reader$1 = class Reader {
  18043. constructor(_root, _settings) {
  18044. this._root = _root;
  18045. this._settings = _settings;
  18046. this._root = common$6.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  18047. }
  18048. };
  18049. reader$1.default = Reader$1;
  18050. Object.defineProperty(async$4, "__esModule", { value: true });
  18051. const events_1 = require$$0$5;
  18052. const fsScandir$2 = out$2;
  18053. const fastq = queueExports;
  18054. const common$5 = common$7;
  18055. const reader_1$4 = reader$1;
  18056. class AsyncReader extends reader_1$4.default {
  18057. constructor(_root, _settings) {
  18058. super(_root, _settings);
  18059. this._settings = _settings;
  18060. this._scandir = fsScandir$2.scandir;
  18061. this._emitter = new events_1.EventEmitter();
  18062. this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
  18063. this._isFatalError = false;
  18064. this._isDestroyed = false;
  18065. this._queue.drain = () => {
  18066. if (!this._isFatalError) {
  18067. this._emitter.emit('end');
  18068. }
  18069. };
  18070. }
  18071. read() {
  18072. this._isFatalError = false;
  18073. this._isDestroyed = false;
  18074. setImmediate(() => {
  18075. this._pushToQueue(this._root, this._settings.basePath);
  18076. });
  18077. return this._emitter;
  18078. }
  18079. get isDestroyed() {
  18080. return this._isDestroyed;
  18081. }
  18082. destroy() {
  18083. if (this._isDestroyed) {
  18084. throw new Error('The reader is already destroyed');
  18085. }
  18086. this._isDestroyed = true;
  18087. this._queue.killAndDrain();
  18088. }
  18089. onEntry(callback) {
  18090. this._emitter.on('entry', callback);
  18091. }
  18092. onError(callback) {
  18093. this._emitter.once('error', callback);
  18094. }
  18095. onEnd(callback) {
  18096. this._emitter.once('end', callback);
  18097. }
  18098. _pushToQueue(directory, base) {
  18099. const queueItem = { directory, base };
  18100. this._queue.push(queueItem, (error) => {
  18101. if (error !== null) {
  18102. this._handleError(error);
  18103. }
  18104. });
  18105. }
  18106. _worker(item, done) {
  18107. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  18108. if (error !== null) {
  18109. done(error, undefined);
  18110. return;
  18111. }
  18112. for (const entry of entries) {
  18113. this._handleEntry(entry, item.base);
  18114. }
  18115. done(null, undefined);
  18116. });
  18117. }
  18118. _handleError(error) {
  18119. if (this._isDestroyed || !common$5.isFatalError(this._settings, error)) {
  18120. return;
  18121. }
  18122. this._isFatalError = true;
  18123. this._isDestroyed = true;
  18124. this._emitter.emit('error', error);
  18125. }
  18126. _handleEntry(entry, base) {
  18127. if (this._isDestroyed || this._isFatalError) {
  18128. return;
  18129. }
  18130. const fullpath = entry.path;
  18131. if (base !== undefined) {
  18132. entry.path = common$5.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  18133. }
  18134. if (common$5.isAppliedFilter(this._settings.entryFilter, entry)) {
  18135. this._emitEntry(entry);
  18136. }
  18137. if (entry.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry)) {
  18138. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  18139. }
  18140. }
  18141. _emitEntry(entry) {
  18142. this._emitter.emit('entry', entry);
  18143. }
  18144. }
  18145. async$4.default = AsyncReader;
  18146. Object.defineProperty(async$5, "__esModule", { value: true });
  18147. const async_1$4 = async$4;
  18148. class AsyncProvider {
  18149. constructor(_root, _settings) {
  18150. this._root = _root;
  18151. this._settings = _settings;
  18152. this._reader = new async_1$4.default(this._root, this._settings);
  18153. this._storage = [];
  18154. }
  18155. read(callback) {
  18156. this._reader.onError((error) => {
  18157. callFailureCallback(callback, error);
  18158. });
  18159. this._reader.onEntry((entry) => {
  18160. this._storage.push(entry);
  18161. });
  18162. this._reader.onEnd(() => {
  18163. callSuccessCallback(callback, this._storage);
  18164. });
  18165. this._reader.read();
  18166. }
  18167. }
  18168. async$5.default = AsyncProvider;
  18169. function callFailureCallback(callback, error) {
  18170. callback(error);
  18171. }
  18172. function callSuccessCallback(callback, entries) {
  18173. callback(null, entries);
  18174. }
  18175. var stream$2 = {};
  18176. Object.defineProperty(stream$2, "__esModule", { value: true });
  18177. const stream_1$5 = require$$0$7;
  18178. const async_1$3 = async$4;
  18179. class StreamProvider {
  18180. constructor(_root, _settings) {
  18181. this._root = _root;
  18182. this._settings = _settings;
  18183. this._reader = new async_1$3.default(this._root, this._settings);
  18184. this._stream = new stream_1$5.Readable({
  18185. objectMode: true,
  18186. read: () => { },
  18187. destroy: () => {
  18188. if (!this._reader.isDestroyed) {
  18189. this._reader.destroy();
  18190. }
  18191. }
  18192. });
  18193. }
  18194. read() {
  18195. this._reader.onError((error) => {
  18196. this._stream.emit('error', error);
  18197. });
  18198. this._reader.onEntry((entry) => {
  18199. this._stream.push(entry);
  18200. });
  18201. this._reader.onEnd(() => {
  18202. this._stream.push(null);
  18203. });
  18204. this._reader.read();
  18205. return this._stream;
  18206. }
  18207. }
  18208. stream$2.default = StreamProvider;
  18209. var sync$4 = {};
  18210. var sync$3 = {};
  18211. Object.defineProperty(sync$3, "__esModule", { value: true });
  18212. const fsScandir$1 = out$2;
  18213. const common$4 = common$7;
  18214. const reader_1$3 = reader$1;
  18215. class SyncReader extends reader_1$3.default {
  18216. constructor() {
  18217. super(...arguments);
  18218. this._scandir = fsScandir$1.scandirSync;
  18219. this._storage = [];
  18220. this._queue = new Set();
  18221. }
  18222. read() {
  18223. this._pushToQueue(this._root, this._settings.basePath);
  18224. this._handleQueue();
  18225. return this._storage;
  18226. }
  18227. _pushToQueue(directory, base) {
  18228. this._queue.add({ directory, base });
  18229. }
  18230. _handleQueue() {
  18231. for (const item of this._queue.values()) {
  18232. this._handleDirectory(item.directory, item.base);
  18233. }
  18234. }
  18235. _handleDirectory(directory, base) {
  18236. try {
  18237. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  18238. for (const entry of entries) {
  18239. this._handleEntry(entry, base);
  18240. }
  18241. }
  18242. catch (error) {
  18243. this._handleError(error);
  18244. }
  18245. }
  18246. _handleError(error) {
  18247. if (!common$4.isFatalError(this._settings, error)) {
  18248. return;
  18249. }
  18250. throw error;
  18251. }
  18252. _handleEntry(entry, base) {
  18253. const fullpath = entry.path;
  18254. if (base !== undefined) {
  18255. entry.path = common$4.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  18256. }
  18257. if (common$4.isAppliedFilter(this._settings.entryFilter, entry)) {
  18258. this._pushToStorage(entry);
  18259. }
  18260. if (entry.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry)) {
  18261. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  18262. }
  18263. }
  18264. _pushToStorage(entry) {
  18265. this._storage.push(entry);
  18266. }
  18267. }
  18268. sync$3.default = SyncReader;
  18269. Object.defineProperty(sync$4, "__esModule", { value: true });
  18270. const sync_1$3 = sync$3;
  18271. class SyncProvider {
  18272. constructor(_root, _settings) {
  18273. this._root = _root;
  18274. this._settings = _settings;
  18275. this._reader = new sync_1$3.default(this._root, this._settings);
  18276. }
  18277. read() {
  18278. return this._reader.read();
  18279. }
  18280. }
  18281. sync$4.default = SyncProvider;
  18282. var settings$1 = {};
  18283. Object.defineProperty(settings$1, "__esModule", { value: true });
  18284. const path$c = require$$0$4;
  18285. const fsScandir = out$2;
  18286. class Settings {
  18287. constructor(_options = {}) {
  18288. this._options = _options;
  18289. this.basePath = this._getValue(this._options.basePath, undefined);
  18290. this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
  18291. this.deepFilter = this._getValue(this._options.deepFilter, null);
  18292. this.entryFilter = this._getValue(this._options.entryFilter, null);
  18293. this.errorFilter = this._getValue(this._options.errorFilter, null);
  18294. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$c.sep);
  18295. this.fsScandirSettings = new fsScandir.Settings({
  18296. followSymbolicLinks: this._options.followSymbolicLinks,
  18297. fs: this._options.fs,
  18298. pathSegmentSeparator: this._options.pathSegmentSeparator,
  18299. stats: this._options.stats,
  18300. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  18301. });
  18302. }
  18303. _getValue(option, value) {
  18304. return option !== null && option !== void 0 ? option : value;
  18305. }
  18306. }
  18307. settings$1.default = Settings;
  18308. Object.defineProperty(out$3, "__esModule", { value: true });
  18309. out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0;
  18310. const async_1$2 = async$5;
  18311. const stream_1$4 = stream$2;
  18312. const sync_1$2 = sync$4;
  18313. const settings_1$1 = settings$1;
  18314. out$3.Settings = settings_1$1.default;
  18315. function walk$2(directory, optionsOrSettingsOrCallback, callback) {
  18316. if (typeof optionsOrSettingsOrCallback === 'function') {
  18317. new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  18318. return;
  18319. }
  18320. new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  18321. }
  18322. out$3.walk = walk$2;
  18323. function walkSync(directory, optionsOrSettings) {
  18324. const settings = getSettings(optionsOrSettings);
  18325. const provider = new sync_1$2.default(directory, settings);
  18326. return provider.read();
  18327. }
  18328. out$3.walkSync = walkSync;
  18329. function walkStream(directory, optionsOrSettings) {
  18330. const settings = getSettings(optionsOrSettings);
  18331. const provider = new stream_1$4.default(directory, settings);
  18332. return provider.read();
  18333. }
  18334. out$3.walkStream = walkStream;
  18335. function getSettings(settingsOrOptions = {}) {
  18336. if (settingsOrOptions instanceof settings_1$1.default) {
  18337. return settingsOrOptions;
  18338. }
  18339. return new settings_1$1.default(settingsOrOptions);
  18340. }
  18341. var reader = {};
  18342. Object.defineProperty(reader, "__esModule", { value: true });
  18343. const path$b = require$$0$4;
  18344. const fsStat$2 = out$1;
  18345. const utils$6 = utils$g;
  18346. class Reader {
  18347. constructor(_settings) {
  18348. this._settings = _settings;
  18349. this._fsStatSettings = new fsStat$2.Settings({
  18350. followSymbolicLink: this._settings.followSymbolicLinks,
  18351. fs: this._settings.fs,
  18352. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  18353. });
  18354. }
  18355. _getFullEntryPath(filepath) {
  18356. return path$b.resolve(this._settings.cwd, filepath);
  18357. }
  18358. _makeEntry(stats, pattern) {
  18359. const entry = {
  18360. name: pattern,
  18361. path: pattern,
  18362. dirent: utils$6.fs.createDirentFromStats(pattern, stats)
  18363. };
  18364. if (this._settings.stats) {
  18365. entry.stats = stats;
  18366. }
  18367. return entry;
  18368. }
  18369. _isFatalError(error) {
  18370. return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  18371. }
  18372. }
  18373. reader.default = Reader;
  18374. var stream$1 = {};
  18375. Object.defineProperty(stream$1, "__esModule", { value: true });
  18376. const stream_1$3 = require$$0$7;
  18377. const fsStat$1 = out$1;
  18378. const fsWalk$2 = out$3;
  18379. const reader_1$2 = reader;
  18380. class ReaderStream extends reader_1$2.default {
  18381. constructor() {
  18382. super(...arguments);
  18383. this._walkStream = fsWalk$2.walkStream;
  18384. this._stat = fsStat$1.stat;
  18385. }
  18386. dynamic(root, options) {
  18387. return this._walkStream(root, options);
  18388. }
  18389. static(patterns, options) {
  18390. const filepaths = patterns.map(this._getFullEntryPath, this);
  18391. const stream = new stream_1$3.PassThrough({ objectMode: true });
  18392. stream._write = (index, _enc, done) => {
  18393. return this._getEntry(filepaths[index], patterns[index], options)
  18394. .then((entry) => {
  18395. if (entry !== null && options.entryFilter(entry)) {
  18396. stream.push(entry);
  18397. }
  18398. if (index === filepaths.length - 1) {
  18399. stream.end();
  18400. }
  18401. done();
  18402. })
  18403. .catch(done);
  18404. };
  18405. for (let i = 0; i < filepaths.length; i++) {
  18406. stream.write(i);
  18407. }
  18408. return stream;
  18409. }
  18410. _getEntry(filepath, pattern, options) {
  18411. return this._getStat(filepath)
  18412. .then((stats) => this._makeEntry(stats, pattern))
  18413. .catch((error) => {
  18414. if (options.errorFilter(error)) {
  18415. return null;
  18416. }
  18417. throw error;
  18418. });
  18419. }
  18420. _getStat(filepath) {
  18421. return new Promise((resolve, reject) => {
  18422. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  18423. return error === null ? resolve(stats) : reject(error);
  18424. });
  18425. });
  18426. }
  18427. }
  18428. stream$1.default = ReaderStream;
  18429. Object.defineProperty(async$6, "__esModule", { value: true });
  18430. const fsWalk$1 = out$3;
  18431. const reader_1$1 = reader;
  18432. const stream_1$2 = stream$1;
  18433. class ReaderAsync extends reader_1$1.default {
  18434. constructor() {
  18435. super(...arguments);
  18436. this._walkAsync = fsWalk$1.walk;
  18437. this._readerStream = new stream_1$2.default(this._settings);
  18438. }
  18439. dynamic(root, options) {
  18440. return new Promise((resolve, reject) => {
  18441. this._walkAsync(root, options, (error, entries) => {
  18442. if (error === null) {
  18443. resolve(entries);
  18444. }
  18445. else {
  18446. reject(error);
  18447. }
  18448. });
  18449. });
  18450. }
  18451. async static(patterns, options) {
  18452. const entries = [];
  18453. const stream = this._readerStream.static(patterns, options);
  18454. // After #235, replace it with an asynchronous iterator.
  18455. return new Promise((resolve, reject) => {
  18456. stream.once('error', reject);
  18457. stream.on('data', (entry) => entries.push(entry));
  18458. stream.once('end', () => resolve(entries));
  18459. });
  18460. }
  18461. }
  18462. async$6.default = ReaderAsync;
  18463. var provider = {};
  18464. var deep = {};
  18465. var partial = {};
  18466. var matcher = {};
  18467. Object.defineProperty(matcher, "__esModule", { value: true });
  18468. const utils$5 = utils$g;
  18469. class Matcher {
  18470. constructor(_patterns, _settings, _micromatchOptions) {
  18471. this._patterns = _patterns;
  18472. this._settings = _settings;
  18473. this._micromatchOptions = _micromatchOptions;
  18474. this._storage = [];
  18475. this._fillStorage();
  18476. }
  18477. _fillStorage() {
  18478. for (const pattern of this._patterns) {
  18479. const segments = this._getPatternSegments(pattern);
  18480. const sections = this._splitSegmentsIntoSections(segments);
  18481. this._storage.push({
  18482. complete: sections.length <= 1,
  18483. pattern,
  18484. segments,
  18485. sections
  18486. });
  18487. }
  18488. }
  18489. _getPatternSegments(pattern) {
  18490. const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions);
  18491. return parts.map((part) => {
  18492. const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
  18493. if (!dynamic) {
  18494. return {
  18495. dynamic: false,
  18496. pattern: part
  18497. };
  18498. }
  18499. return {
  18500. dynamic: true,
  18501. pattern: part,
  18502. patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
  18503. };
  18504. });
  18505. }
  18506. _splitSegmentsIntoSections(segments) {
  18507. return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
  18508. }
  18509. }
  18510. matcher.default = Matcher;
  18511. Object.defineProperty(partial, "__esModule", { value: true });
  18512. const matcher_1 = matcher;
  18513. class PartialMatcher extends matcher_1.default {
  18514. match(filepath) {
  18515. const parts = filepath.split('/');
  18516. const levels = parts.length;
  18517. const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
  18518. for (const pattern of patterns) {
  18519. const section = pattern.sections[0];
  18520. /**
  18521. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  18522. * but only if the level has reached the end of the first group.
  18523. *
  18524. * fixtures/{a,b}/**
  18525. * ^ true/false ^ always true
  18526. */
  18527. if (!pattern.complete && levels > section.length) {
  18528. return true;
  18529. }
  18530. const match = parts.every((part, index) => {
  18531. const segment = pattern.segments[index];
  18532. if (segment.dynamic && segment.patternRe.test(part)) {
  18533. return true;
  18534. }
  18535. if (!segment.dynamic && segment.pattern === part) {
  18536. return true;
  18537. }
  18538. return false;
  18539. });
  18540. if (match) {
  18541. return true;
  18542. }
  18543. }
  18544. return false;
  18545. }
  18546. }
  18547. partial.default = PartialMatcher;
  18548. Object.defineProperty(deep, "__esModule", { value: true });
  18549. const utils$4 = utils$g;
  18550. const partial_1 = partial;
  18551. class DeepFilter {
  18552. constructor(_settings, _micromatchOptions) {
  18553. this._settings = _settings;
  18554. this._micromatchOptions = _micromatchOptions;
  18555. }
  18556. getFilter(basePath, positive, negative) {
  18557. const matcher = this._getMatcher(positive);
  18558. const negativeRe = this._getNegativePatternsRe(negative);
  18559. return (entry) => this._filter(basePath, entry, matcher, negativeRe);
  18560. }
  18561. _getMatcher(patterns) {
  18562. return new partial_1.default(patterns, this._settings, this._micromatchOptions);
  18563. }
  18564. _getNegativePatternsRe(patterns) {
  18565. const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
  18566. return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  18567. }
  18568. _filter(basePath, entry, matcher, negativeRe) {
  18569. if (this._isSkippedByDeep(basePath, entry.path)) {
  18570. return false;
  18571. }
  18572. if (this._isSkippedSymbolicLink(entry)) {
  18573. return false;
  18574. }
  18575. const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
  18576. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  18577. return false;
  18578. }
  18579. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  18580. }
  18581. _isSkippedByDeep(basePath, entryPath) {
  18582. /**
  18583. * Avoid unnecessary depth calculations when it doesn't matter.
  18584. */
  18585. if (this._settings.deep === Infinity) {
  18586. return false;
  18587. }
  18588. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  18589. }
  18590. _getEntryLevel(basePath, entryPath) {
  18591. const entryPathDepth = entryPath.split('/').length;
  18592. if (basePath === '') {
  18593. return entryPathDepth;
  18594. }
  18595. const basePathDepth = basePath.split('/').length;
  18596. return entryPathDepth - basePathDepth;
  18597. }
  18598. _isSkippedSymbolicLink(entry) {
  18599. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  18600. }
  18601. _isSkippedByPositivePatterns(entryPath, matcher) {
  18602. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  18603. }
  18604. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  18605. return !utils$4.pattern.matchAny(entryPath, patternsRe);
  18606. }
  18607. }
  18608. deep.default = DeepFilter;
  18609. var entry$1 = {};
  18610. Object.defineProperty(entry$1, "__esModule", { value: true });
  18611. const utils$3 = utils$g;
  18612. class EntryFilter {
  18613. constructor(_settings, _micromatchOptions) {
  18614. this._settings = _settings;
  18615. this._micromatchOptions = _micromatchOptions;
  18616. this.index = new Map();
  18617. }
  18618. getFilter(positive, negative) {
  18619. const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  18620. const negativeRe = utils$3.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true }));
  18621. return (entry) => this._filter(entry, positiveRe, negativeRe);
  18622. }
  18623. _filter(entry, positiveRe, negativeRe) {
  18624. const filepath = utils$3.path.removeLeadingDotSegment(entry.path);
  18625. if (this._settings.unique && this._isDuplicateEntry(filepath)) {
  18626. return false;
  18627. }
  18628. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  18629. return false;
  18630. }
  18631. if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) {
  18632. return false;
  18633. }
  18634. const isDirectory = entry.dirent.isDirectory();
  18635. const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory);
  18636. if (this._settings.unique && isMatched) {
  18637. this._createIndexRecord(filepath);
  18638. }
  18639. return isMatched;
  18640. }
  18641. _isDuplicateEntry(filepath) {
  18642. return this.index.has(filepath);
  18643. }
  18644. _createIndexRecord(filepath) {
  18645. this.index.set(filepath, undefined);
  18646. }
  18647. _onlyFileFilter(entry) {
  18648. return this._settings.onlyFiles && !entry.dirent.isFile();
  18649. }
  18650. _onlyDirectoryFilter(entry) {
  18651. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  18652. }
  18653. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  18654. if (!this._settings.absolute) {
  18655. return false;
  18656. }
  18657. const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
  18658. return utils$3.pattern.matchAny(fullpath, patternsRe);
  18659. }
  18660. _isMatchToPatterns(filepath, patternsRe, isDirectory) {
  18661. // Trying to match files and directories by patterns.
  18662. const isMatched = utils$3.pattern.matchAny(filepath, patternsRe);
  18663. // A pattern with a trailling slash can be used for directory matching.
  18664. // To apply such pattern, we need to add a tralling slash to the path.
  18665. if (!isMatched && isDirectory) {
  18666. return utils$3.pattern.matchAny(filepath + '/', patternsRe);
  18667. }
  18668. return isMatched;
  18669. }
  18670. }
  18671. entry$1.default = EntryFilter;
  18672. var error$2 = {};
  18673. Object.defineProperty(error$2, "__esModule", { value: true });
  18674. const utils$2 = utils$g;
  18675. class ErrorFilter {
  18676. constructor(_settings) {
  18677. this._settings = _settings;
  18678. }
  18679. getFilter() {
  18680. return (error) => this._isNonFatalError(error);
  18681. }
  18682. _isNonFatalError(error) {
  18683. return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  18684. }
  18685. }
  18686. error$2.default = ErrorFilter;
  18687. var entry = {};
  18688. Object.defineProperty(entry, "__esModule", { value: true });
  18689. const utils$1 = utils$g;
  18690. class EntryTransformer {
  18691. constructor(_settings) {
  18692. this._settings = _settings;
  18693. }
  18694. getTransformer() {
  18695. return (entry) => this._transform(entry);
  18696. }
  18697. _transform(entry) {
  18698. let filepath = entry.path;
  18699. if (this._settings.absolute) {
  18700. filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
  18701. filepath = utils$1.path.unixify(filepath);
  18702. }
  18703. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  18704. filepath += '/';
  18705. }
  18706. if (!this._settings.objectMode) {
  18707. return filepath;
  18708. }
  18709. return Object.assign(Object.assign({}, entry), { path: filepath });
  18710. }
  18711. }
  18712. entry.default = EntryTransformer;
  18713. Object.defineProperty(provider, "__esModule", { value: true });
  18714. const path$a = require$$0$4;
  18715. const deep_1 = deep;
  18716. const entry_1 = entry$1;
  18717. const error_1 = error$2;
  18718. const entry_2 = entry;
  18719. class Provider {
  18720. constructor(_settings) {
  18721. this._settings = _settings;
  18722. this.errorFilter = new error_1.default(this._settings);
  18723. this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
  18724. this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
  18725. this.entryTransformer = new entry_2.default(this._settings);
  18726. }
  18727. _getRootDirectory(task) {
  18728. return path$a.resolve(this._settings.cwd, task.base);
  18729. }
  18730. _getReaderOptions(task) {
  18731. const basePath = task.base === '.' ? '' : task.base;
  18732. return {
  18733. basePath,
  18734. pathSegmentSeparator: '/',
  18735. concurrency: this._settings.concurrency,
  18736. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  18737. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  18738. errorFilter: this.errorFilter.getFilter(),
  18739. followSymbolicLinks: this._settings.followSymbolicLinks,
  18740. fs: this._settings.fs,
  18741. stats: this._settings.stats,
  18742. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  18743. transform: this.entryTransformer.getTransformer()
  18744. };
  18745. }
  18746. _getMicromatchOptions() {
  18747. return {
  18748. dot: this._settings.dot,
  18749. matchBase: this._settings.baseNameMatch,
  18750. nobrace: !this._settings.braceExpansion,
  18751. nocase: !this._settings.caseSensitiveMatch,
  18752. noext: !this._settings.extglob,
  18753. noglobstar: !this._settings.globstar,
  18754. posix: true,
  18755. strictSlashes: false
  18756. };
  18757. }
  18758. }
  18759. provider.default = Provider;
  18760. Object.defineProperty(async$7, "__esModule", { value: true });
  18761. const async_1$1 = async$6;
  18762. const provider_1$2 = provider;
  18763. class ProviderAsync extends provider_1$2.default {
  18764. constructor() {
  18765. super(...arguments);
  18766. this._reader = new async_1$1.default(this._settings);
  18767. }
  18768. async read(task) {
  18769. const root = this._getRootDirectory(task);
  18770. const options = this._getReaderOptions(task);
  18771. const entries = await this.api(root, task, options);
  18772. return entries.map((entry) => options.transform(entry));
  18773. }
  18774. api(root, task, options) {
  18775. if (task.dynamic) {
  18776. return this._reader.dynamic(root, options);
  18777. }
  18778. return this._reader.static(task.patterns, options);
  18779. }
  18780. }
  18781. async$7.default = ProviderAsync;
  18782. var stream = {};
  18783. Object.defineProperty(stream, "__esModule", { value: true });
  18784. const stream_1$1 = require$$0$7;
  18785. const stream_2 = stream$1;
  18786. const provider_1$1 = provider;
  18787. class ProviderStream extends provider_1$1.default {
  18788. constructor() {
  18789. super(...arguments);
  18790. this._reader = new stream_2.default(this._settings);
  18791. }
  18792. read(task) {
  18793. const root = this._getRootDirectory(task);
  18794. const options = this._getReaderOptions(task);
  18795. const source = this.api(root, task, options);
  18796. const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } });
  18797. source
  18798. .once('error', (error) => destination.emit('error', error))
  18799. .on('data', (entry) => destination.emit('data', options.transform(entry)))
  18800. .once('end', () => destination.emit('end'));
  18801. destination
  18802. .once('close', () => source.destroy());
  18803. return destination;
  18804. }
  18805. api(root, task, options) {
  18806. if (task.dynamic) {
  18807. return this._reader.dynamic(root, options);
  18808. }
  18809. return this._reader.static(task.patterns, options);
  18810. }
  18811. }
  18812. stream.default = ProviderStream;
  18813. var sync$2 = {};
  18814. var sync$1 = {};
  18815. Object.defineProperty(sync$1, "__esModule", { value: true });
  18816. const fsStat = out$1;
  18817. const fsWalk = out$3;
  18818. const reader_1 = reader;
  18819. class ReaderSync extends reader_1.default {
  18820. constructor() {
  18821. super(...arguments);
  18822. this._walkSync = fsWalk.walkSync;
  18823. this._statSync = fsStat.statSync;
  18824. }
  18825. dynamic(root, options) {
  18826. return this._walkSync(root, options);
  18827. }
  18828. static(patterns, options) {
  18829. const entries = [];
  18830. for (const pattern of patterns) {
  18831. const filepath = this._getFullEntryPath(pattern);
  18832. const entry = this._getEntry(filepath, pattern, options);
  18833. if (entry === null || !options.entryFilter(entry)) {
  18834. continue;
  18835. }
  18836. entries.push(entry);
  18837. }
  18838. return entries;
  18839. }
  18840. _getEntry(filepath, pattern, options) {
  18841. try {
  18842. const stats = this._getStat(filepath);
  18843. return this._makeEntry(stats, pattern);
  18844. }
  18845. catch (error) {
  18846. if (options.errorFilter(error)) {
  18847. return null;
  18848. }
  18849. throw error;
  18850. }
  18851. }
  18852. _getStat(filepath) {
  18853. return this._statSync(filepath, this._fsStatSettings);
  18854. }
  18855. }
  18856. sync$1.default = ReaderSync;
  18857. Object.defineProperty(sync$2, "__esModule", { value: true });
  18858. const sync_1$1 = sync$1;
  18859. const provider_1 = provider;
  18860. class ProviderSync extends provider_1.default {
  18861. constructor() {
  18862. super(...arguments);
  18863. this._reader = new sync_1$1.default(this._settings);
  18864. }
  18865. read(task) {
  18866. const root = this._getRootDirectory(task);
  18867. const options = this._getReaderOptions(task);
  18868. const entries = this.api(root, task, options);
  18869. return entries.map(options.transform);
  18870. }
  18871. api(root, task, options) {
  18872. if (task.dynamic) {
  18873. return this._reader.dynamic(root, options);
  18874. }
  18875. return this._reader.static(task.patterns, options);
  18876. }
  18877. }
  18878. sync$2.default = ProviderSync;
  18879. var settings = {};
  18880. (function (exports) {
  18881. Object.defineProperty(exports, "__esModule", { value: true });
  18882. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  18883. const fs = require$$0__default;
  18884. const os = require$$2;
  18885. /**
  18886. * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
  18887. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
  18888. */
  18889. const CPU_COUNT = Math.max(os.cpus().length, 1);
  18890. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  18891. lstat: fs.lstat,
  18892. lstatSync: fs.lstatSync,
  18893. stat: fs.stat,
  18894. statSync: fs.statSync,
  18895. readdir: fs.readdir,
  18896. readdirSync: fs.readdirSync
  18897. };
  18898. class Settings {
  18899. constructor(_options = {}) {
  18900. this._options = _options;
  18901. this.absolute = this._getValue(this._options.absolute, false);
  18902. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  18903. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  18904. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  18905. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  18906. this.cwd = this._getValue(this._options.cwd, process.cwd());
  18907. this.deep = this._getValue(this._options.deep, Infinity);
  18908. this.dot = this._getValue(this._options.dot, false);
  18909. this.extglob = this._getValue(this._options.extglob, true);
  18910. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  18911. this.fs = this._getFileSystemMethods(this._options.fs);
  18912. this.globstar = this._getValue(this._options.globstar, true);
  18913. this.ignore = this._getValue(this._options.ignore, []);
  18914. this.markDirectories = this._getValue(this._options.markDirectories, false);
  18915. this.objectMode = this._getValue(this._options.objectMode, false);
  18916. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  18917. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  18918. this.stats = this._getValue(this._options.stats, false);
  18919. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  18920. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  18921. this.unique = this._getValue(this._options.unique, true);
  18922. if (this.onlyDirectories) {
  18923. this.onlyFiles = false;
  18924. }
  18925. if (this.stats) {
  18926. this.objectMode = true;
  18927. }
  18928. // Remove the cast to the array in the next major (#404).
  18929. this.ignore = [].concat(this.ignore);
  18930. }
  18931. _getValue(option, value) {
  18932. return option === undefined ? value : option;
  18933. }
  18934. _getFileSystemMethods(methods = {}) {
  18935. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  18936. }
  18937. }
  18938. exports.default = Settings;
  18939. } (settings));
  18940. const taskManager = tasks;
  18941. const async_1 = async$7;
  18942. const stream_1 = stream;
  18943. const sync_1 = sync$2;
  18944. const settings_1 = settings;
  18945. const utils = utils$g;
  18946. async function FastGlob(source, options) {
  18947. assertPatternsInput(source);
  18948. const works = getWorks(source, async_1.default, options);
  18949. const result = await Promise.all(works);
  18950. return utils.array.flatten(result);
  18951. }
  18952. // https://github.com/typescript-eslint/typescript-eslint/issues/60
  18953. // eslint-disable-next-line no-redeclare
  18954. (function (FastGlob) {
  18955. FastGlob.glob = FastGlob;
  18956. FastGlob.globSync = sync;
  18957. FastGlob.globStream = stream;
  18958. FastGlob.async = FastGlob;
  18959. function sync(source, options) {
  18960. assertPatternsInput(source);
  18961. const works = getWorks(source, sync_1.default, options);
  18962. return utils.array.flatten(works);
  18963. }
  18964. FastGlob.sync = sync;
  18965. function stream(source, options) {
  18966. assertPatternsInput(source);
  18967. const works = getWorks(source, stream_1.default, options);
  18968. /**
  18969. * The stream returned by the provider cannot work with an asynchronous iterator.
  18970. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  18971. * This affects performance (+25%). I don't see best solution right now.
  18972. */
  18973. return utils.stream.merge(works);
  18974. }
  18975. FastGlob.stream = stream;
  18976. function generateTasks(source, options) {
  18977. assertPatternsInput(source);
  18978. const patterns = [].concat(source);
  18979. const settings = new settings_1.default(options);
  18980. return taskManager.generate(patterns, settings);
  18981. }
  18982. FastGlob.generateTasks = generateTasks;
  18983. function isDynamicPattern(source, options) {
  18984. assertPatternsInput(source);
  18985. const settings = new settings_1.default(options);
  18986. return utils.pattern.isDynamicPattern(source, settings);
  18987. }
  18988. FastGlob.isDynamicPattern = isDynamicPattern;
  18989. function escapePath(source) {
  18990. assertPatternsInput(source);
  18991. return utils.path.escape(source);
  18992. }
  18993. FastGlob.escapePath = escapePath;
  18994. function convertPathToPattern(source) {
  18995. assertPatternsInput(source);
  18996. return utils.path.convertPathToPattern(source);
  18997. }
  18998. FastGlob.convertPathToPattern = convertPathToPattern;
  18999. (function (posix) {
  19000. function escapePath(source) {
  19001. assertPatternsInput(source);
  19002. return utils.path.escapePosixPath(source);
  19003. }
  19004. posix.escapePath = escapePath;
  19005. function convertPathToPattern(source) {
  19006. assertPatternsInput(source);
  19007. return utils.path.convertPosixPathToPattern(source);
  19008. }
  19009. posix.convertPathToPattern = convertPathToPattern;
  19010. })(FastGlob.posix || (FastGlob.posix = {}));
  19011. (function (win32) {
  19012. function escapePath(source) {
  19013. assertPatternsInput(source);
  19014. return utils.path.escapeWindowsPath(source);
  19015. }
  19016. win32.escapePath = escapePath;
  19017. function convertPathToPattern(source) {
  19018. assertPatternsInput(source);
  19019. return utils.path.convertWindowsPathToPattern(source);
  19020. }
  19021. win32.convertPathToPattern = convertPathToPattern;
  19022. })(FastGlob.win32 || (FastGlob.win32 = {}));
  19023. })(FastGlob || (FastGlob = {}));
  19024. function getWorks(source, _Provider, options) {
  19025. const patterns = [].concat(source);
  19026. const settings = new settings_1.default(options);
  19027. const tasks = taskManager.generate(patterns, settings);
  19028. const provider = new _Provider(settings);
  19029. return tasks.map(provider.read, provider);
  19030. }
  19031. function assertPatternsInput(input) {
  19032. const source = [].concat(input);
  19033. const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
  19034. if (!isValidSource) {
  19035. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  19036. }
  19037. }
  19038. var out = FastGlob;
  19039. var glob = /*@__PURE__*/getDefaultExportFromCjs(out);
  19040. function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;for(t in i)n&&t.length<n.length||("/"===t[t.length-1]&&l.startsWith(t)?(u=l.substring(t.length),n=t):t.length>1&&(r=t.indexOf("*",1),~r&&(e=RegExp("^"+t.substring(0,r)+"(.*)"+t.substring(1+r)).exec(l),e&&e[1]&&(u=e[1],n=t))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t<i;t++)e[t]=o.test(r=e[t])?r.replace(o,n):f.test(r)?r+n:r;}(s,u),s}function r(e,n,r){if(e===n||"."===n)return ".";let t=e+"/",i=t.length,o=n.slice(0,i)===t,f=o?n.slice(i):n;return "#"===f[0]?f:o||!r?"./"===f.slice(0,2)?f:"./"+f:f}function t(e,n,r){if(e){if("string"==typeof e)return r&&r.add(e),[e];let i,o;if(Array.isArray(e)){for(o=r||new Set,i=0;i<e.length;i++)t(e[i],n,o);if(!r&&o.size)return [...o]}else for(i in e)if(n.has(i))return t(e[i],n,r)}}function o(e,r,t){let i,o=e.exports;if(o){if("string"==typeof o)o={".":o};else for(i in o){"."!==i[0]&&(o={".":o});break}return n(e.name,o,r||".",t)}}function f(e,r,t){if(e.imports)return n(e.name,e.imports,r,t)}
  19041. // This file was generated. Do not modify manually!
  19042. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  19043. // This file was generated. Do not modify manually!
  19044. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
  19045. // This file was generated. Do not modify manually!
  19046. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  19047. // This file was generated. Do not modify manually!
  19048. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  19049. // These are a run-length and offset encoded representation of the
  19050. // >0xffff code points that are a valid part of identifiers. The
  19051. // offset starts at 0x10000, and each pair of numbers represents an
  19052. // offset to the next range, and then a size of the range.
  19053. // Reserved word lists for various dialects of the language
  19054. var reservedWords = {
  19055. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  19056. 5: "class enum extends super const export import",
  19057. 6: "enum",
  19058. strict: "implements interface let package private protected public static yield",
  19059. strictBind: "eval arguments"
  19060. };
  19061. // And the keywords
  19062. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  19063. var keywords$1 = {
  19064. 5: ecma5AndLessKeywords,
  19065. "5module": ecma5AndLessKeywords + " export import",
  19066. 6: ecma5AndLessKeywords + " const class extends export import super"
  19067. };
  19068. var keywordRelationalOperator = /^in(stanceof)?$/;
  19069. // ## Character categories
  19070. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  19071. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  19072. // This has a complexity linear to the value of the code. The
  19073. // assumption is that looking up astral identifier characters is
  19074. // rare.
  19075. function isInAstralSet(code, set) {
  19076. var pos = 0x10000;
  19077. for (var i = 0; i < set.length; i += 2) {
  19078. pos += set[i];
  19079. if (pos > code) { return false }
  19080. pos += set[i + 1];
  19081. if (pos >= code) { return true }
  19082. }
  19083. return false
  19084. }
  19085. // Test whether a given character code starts an identifier.
  19086. function isIdentifierStart(code, astral) {
  19087. if (code < 65) { return code === 36 }
  19088. if (code < 91) { return true }
  19089. if (code < 97) { return code === 95 }
  19090. if (code < 123) { return true }
  19091. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  19092. if (astral === false) { return false }
  19093. return isInAstralSet(code, astralIdentifierStartCodes)
  19094. }
  19095. // Test whether a given character is part of an identifier.
  19096. function isIdentifierChar(code, astral) {
  19097. if (code < 48) { return code === 36 }
  19098. if (code < 58) { return true }
  19099. if (code < 65) { return false }
  19100. if (code < 91) { return true }
  19101. if (code < 97) { return code === 95 }
  19102. if (code < 123) { return true }
  19103. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  19104. if (astral === false) { return false }
  19105. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  19106. }
  19107. // ## Token types
  19108. // The assignment of fine-grained, information-carrying type objects
  19109. // allows the tokenizer to store the information it has about a
  19110. // token in a way that is very cheap for the parser to look up.
  19111. // All token type variables start with an underscore, to make them
  19112. // easy to recognize.
  19113. // The `beforeExpr` property is used to disambiguate between regular
  19114. // expressions and divisions. It is set on all token types that can
  19115. // be followed by an expression (thus, a slash after them would be a
  19116. // regular expression).
  19117. //
  19118. // The `startsExpr` property is used to check if the token ends a
  19119. // `yield` expression. It is set on all token types that either can
  19120. // directly start an expression (like a quotation mark) or can
  19121. // continue an expression (like the body of a string).
  19122. //
  19123. // `isLoop` marks a keyword as starting a loop, which is important
  19124. // to know when parsing a label, in order to allow or disallow
  19125. // continue jumps to that label.
  19126. var TokenType = function TokenType(label, conf) {
  19127. if ( conf === void 0 ) conf = {};
  19128. this.label = label;
  19129. this.keyword = conf.keyword;
  19130. this.beforeExpr = !!conf.beforeExpr;
  19131. this.startsExpr = !!conf.startsExpr;
  19132. this.isLoop = !!conf.isLoop;
  19133. this.isAssign = !!conf.isAssign;
  19134. this.prefix = !!conf.prefix;
  19135. this.postfix = !!conf.postfix;
  19136. this.binop = conf.binop || null;
  19137. this.updateContext = null;
  19138. };
  19139. function binop(name, prec) {
  19140. return new TokenType(name, {beforeExpr: true, binop: prec})
  19141. }
  19142. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  19143. // Map keyword names to token types.
  19144. var keywords$2 = {};
  19145. // Succinct definitions of keyword token types
  19146. function kw(name, options) {
  19147. if ( options === void 0 ) options = {};
  19148. options.keyword = name;
  19149. return keywords$2[name] = new TokenType(name, options)
  19150. }
  19151. var types$1 = {
  19152. num: new TokenType("num", startsExpr),
  19153. regexp: new TokenType("regexp", startsExpr),
  19154. string: new TokenType("string", startsExpr),
  19155. name: new TokenType("name", startsExpr),
  19156. privateId: new TokenType("privateId", startsExpr),
  19157. eof: new TokenType("eof"),
  19158. // Punctuation token types.
  19159. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  19160. bracketR: new TokenType("]"),
  19161. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  19162. braceR: new TokenType("}"),
  19163. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  19164. parenR: new TokenType(")"),
  19165. comma: new TokenType(",", beforeExpr),
  19166. semi: new TokenType(";", beforeExpr),
  19167. colon: new TokenType(":", beforeExpr),
  19168. dot: new TokenType("."),
  19169. question: new TokenType("?", beforeExpr),
  19170. questionDot: new TokenType("?."),
  19171. arrow: new TokenType("=>", beforeExpr),
  19172. template: new TokenType("template"),
  19173. invalidTemplate: new TokenType("invalidTemplate"),
  19174. ellipsis: new TokenType("...", beforeExpr),
  19175. backQuote: new TokenType("`", startsExpr),
  19176. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  19177. // Operators. These carry several kinds of properties to help the
  19178. // parser use them properly (the presence of these properties is
  19179. // what categorizes them as operators).
  19180. //
  19181. // `binop`, when present, specifies that this operator is a binary
  19182. // operator, and will refer to its precedence.
  19183. //
  19184. // `prefix` and `postfix` mark the operator as a prefix or postfix
  19185. // unary operator.
  19186. //
  19187. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  19188. // binary operators with a very low precedence, that should result
  19189. // in AssignmentExpression nodes.
  19190. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  19191. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  19192. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  19193. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  19194. logicalOR: binop("||", 1),
  19195. logicalAND: binop("&&", 2),
  19196. bitwiseOR: binop("|", 3),
  19197. bitwiseXOR: binop("^", 4),
  19198. bitwiseAND: binop("&", 5),
  19199. equality: binop("==/!=/===/!==", 6),
  19200. relational: binop("</>/<=/>=", 7),
  19201. bitShift: binop("<</>>/>>>", 8),
  19202. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  19203. modulo: binop("%", 10),
  19204. star: binop("*", 10),
  19205. slash: binop("/", 10),
  19206. starstar: new TokenType("**", {beforeExpr: true}),
  19207. coalesce: binop("??", 1),
  19208. // Keyword token types.
  19209. _break: kw("break"),
  19210. _case: kw("case", beforeExpr),
  19211. _catch: kw("catch"),
  19212. _continue: kw("continue"),
  19213. _debugger: kw("debugger"),
  19214. _default: kw("default", beforeExpr),
  19215. _do: kw("do", {isLoop: true, beforeExpr: true}),
  19216. _else: kw("else", beforeExpr),
  19217. _finally: kw("finally"),
  19218. _for: kw("for", {isLoop: true}),
  19219. _function: kw("function", startsExpr),
  19220. _if: kw("if"),
  19221. _return: kw("return", beforeExpr),
  19222. _switch: kw("switch"),
  19223. _throw: kw("throw", beforeExpr),
  19224. _try: kw("try"),
  19225. _var: kw("var"),
  19226. _const: kw("const"),
  19227. _while: kw("while", {isLoop: true}),
  19228. _with: kw("with"),
  19229. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  19230. _this: kw("this", startsExpr),
  19231. _super: kw("super", startsExpr),
  19232. _class: kw("class", startsExpr),
  19233. _extends: kw("extends", beforeExpr),
  19234. _export: kw("export"),
  19235. _import: kw("import", startsExpr),
  19236. _null: kw("null", startsExpr),
  19237. _true: kw("true", startsExpr),
  19238. _false: kw("false", startsExpr),
  19239. _in: kw("in", {beforeExpr: true, binop: 7}),
  19240. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  19241. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  19242. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  19243. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  19244. };
  19245. // Matches a whole line break (where CRLF is considered a single
  19246. // line break). Used to count lines.
  19247. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  19248. var lineBreakG = new RegExp(lineBreak.source, "g");
  19249. function isNewLine(code) {
  19250. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  19251. }
  19252. function nextLineBreak(code, from, end) {
  19253. if ( end === void 0 ) end = code.length;
  19254. for (var i = from; i < end; i++) {
  19255. var next = code.charCodeAt(i);
  19256. if (isNewLine(next))
  19257. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  19258. }
  19259. return -1
  19260. }
  19261. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  19262. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  19263. var ref = Object.prototype;
  19264. var hasOwnProperty$1 = ref.hasOwnProperty;
  19265. var toString$1 = ref.toString;
  19266. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  19267. hasOwnProperty$1.call(obj, propName)
  19268. ); });
  19269. var isArray = Array.isArray || (function (obj) { return (
  19270. toString$1.call(obj) === "[object Array]"
  19271. ); });
  19272. function wordsRegexp(words) {
  19273. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  19274. }
  19275. function codePointToString(code) {
  19276. // UTF-16 Decoding
  19277. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  19278. code -= 0x10000;
  19279. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  19280. }
  19281. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  19282. // These are used when `options.locations` is on, for the
  19283. // `startLoc` and `endLoc` properties.
  19284. var Position = function Position(line, col) {
  19285. this.line = line;
  19286. this.column = col;
  19287. };
  19288. Position.prototype.offset = function offset (n) {
  19289. return new Position(this.line, this.column + n)
  19290. };
  19291. var SourceLocation = function SourceLocation(p, start, end) {
  19292. this.start = start;
  19293. this.end = end;
  19294. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  19295. };
  19296. // The `getLineInfo` function is mostly useful when the
  19297. // `locations` option is off (for performance reasons) and you
  19298. // want to find the line/column position for a given character
  19299. // offset. `input` should be the code string that the offset refers
  19300. // into.
  19301. function getLineInfo(input, offset) {
  19302. for (var line = 1, cur = 0;;) {
  19303. var nextBreak = nextLineBreak(input, cur, offset);
  19304. if (nextBreak < 0) { return new Position(line, offset - cur) }
  19305. ++line;
  19306. cur = nextBreak;
  19307. }
  19308. }
  19309. // A second argument must be given to configure the parser process.
  19310. // These options are recognized (only `ecmaVersion` is required):
  19311. var defaultOptions = {
  19312. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  19313. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  19314. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  19315. // (the latest version the library supports). This influences
  19316. // support for strict mode, the set of reserved words, and support
  19317. // for new syntax features.
  19318. ecmaVersion: null,
  19319. // `sourceType` indicates the mode the code should be parsed in.
  19320. // Can be either `"script"` or `"module"`. This influences global
  19321. // strict mode and parsing of `import` and `export` declarations.
  19322. sourceType: "script",
  19323. // `onInsertedSemicolon` can be a callback that will be called
  19324. // when a semicolon is automatically inserted. It will be passed
  19325. // the position of the comma as an offset, and if `locations` is
  19326. // enabled, it is given the location as a `{line, column}` object
  19327. // as second argument.
  19328. onInsertedSemicolon: null,
  19329. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  19330. // trailing commas.
  19331. onTrailingComma: null,
  19332. // By default, reserved words are only enforced if ecmaVersion >= 5.
  19333. // Set `allowReserved` to a boolean value to explicitly turn this on
  19334. // an off. When this option has the value "never", reserved words
  19335. // and keywords can also not be used as property names.
  19336. allowReserved: null,
  19337. // When enabled, a return at the top level is not considered an
  19338. // error.
  19339. allowReturnOutsideFunction: false,
  19340. // When enabled, import/export statements are not constrained to
  19341. // appearing at the top of the program, and an import.meta expression
  19342. // in a script isn't considered an error.
  19343. allowImportExportEverywhere: false,
  19344. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  19345. // When enabled, await identifiers are allowed to appear at the top-level scope,
  19346. // but they are still not allowed in non-async functions.
  19347. allowAwaitOutsideFunction: null,
  19348. // When enabled, super identifiers are not constrained to
  19349. // appearing in methods and do not raise an error when they appear elsewhere.
  19350. allowSuperOutsideMethod: null,
  19351. // When enabled, hashbang directive in the beginning of file is
  19352. // allowed and treated as a line comment. Enabled by default when
  19353. // `ecmaVersion` >= 2023.
  19354. allowHashBang: false,
  19355. // By default, the parser will verify that private properties are
  19356. // only used in places where they are valid and have been declared.
  19357. // Set this to false to turn such checks off.
  19358. checkPrivateFields: true,
  19359. // When `locations` is on, `loc` properties holding objects with
  19360. // `start` and `end` properties in `{line, column}` form (with
  19361. // line being 1-based and column 0-based) will be attached to the
  19362. // nodes.
  19363. locations: false,
  19364. // A function can be passed as `onToken` option, which will
  19365. // cause Acorn to call that function with object in the same
  19366. // format as tokens returned from `tokenizer().getToken()`. Note
  19367. // that you are not allowed to call the parser from the
  19368. // callback—that will corrupt its internal state.
  19369. onToken: null,
  19370. // A function can be passed as `onComment` option, which will
  19371. // cause Acorn to call that function with `(block, text, start,
  19372. // end)` parameters whenever a comment is skipped. `block` is a
  19373. // boolean indicating whether this is a block (`/* */`) comment,
  19374. // `text` is the content of the comment, and `start` and `end` are
  19375. // character offsets that denote the start and end of the comment.
  19376. // When the `locations` option is on, two more parameters are
  19377. // passed, the full `{line, column}` locations of the start and
  19378. // end of the comments. Note that you are not allowed to call the
  19379. // parser from the callback—that will corrupt its internal state.
  19380. onComment: null,
  19381. // Nodes have their start and end characters offsets recorded in
  19382. // `start` and `end` properties (directly on the node, rather than
  19383. // the `loc` object, which holds line/column data. To also add a
  19384. // [semi-standardized][range] `range` property holding a `[start,
  19385. // end]` array with the same numbers, set the `ranges` option to
  19386. // `true`.
  19387. //
  19388. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  19389. ranges: false,
  19390. // It is possible to parse multiple files into a single AST by
  19391. // passing the tree produced by parsing the first file as
  19392. // `program` option in subsequent parses. This will add the
  19393. // toplevel forms of the parsed file to the `Program` (top) node
  19394. // of an existing parse tree.
  19395. program: null,
  19396. // When `locations` is on, you can pass this to record the source
  19397. // file in every node's `loc` object.
  19398. sourceFile: null,
  19399. // This value, if given, is stored in every node, whether
  19400. // `locations` is on or off.
  19401. directSourceFile: null,
  19402. // When enabled, parenthesized expressions are represented by
  19403. // (non-standard) ParenthesizedExpression nodes
  19404. preserveParens: false
  19405. };
  19406. // Interpret and default an options object
  19407. var warnedAboutEcmaVersion = false;
  19408. function getOptions(opts) {
  19409. var options = {};
  19410. for (var opt in defaultOptions)
  19411. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  19412. if (options.ecmaVersion === "latest") {
  19413. options.ecmaVersion = 1e8;
  19414. } else if (options.ecmaVersion == null) {
  19415. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  19416. warnedAboutEcmaVersion = true;
  19417. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  19418. }
  19419. options.ecmaVersion = 11;
  19420. } else if (options.ecmaVersion >= 2015) {
  19421. options.ecmaVersion -= 2009;
  19422. }
  19423. if (options.allowReserved == null)
  19424. { options.allowReserved = options.ecmaVersion < 5; }
  19425. if (!opts || opts.allowHashBang == null)
  19426. { options.allowHashBang = options.ecmaVersion >= 14; }
  19427. if (isArray(options.onToken)) {
  19428. var tokens = options.onToken;
  19429. options.onToken = function (token) { return tokens.push(token); };
  19430. }
  19431. if (isArray(options.onComment))
  19432. { options.onComment = pushComment(options, options.onComment); }
  19433. return options
  19434. }
  19435. function pushComment(options, array) {
  19436. return function(block, text, start, end, startLoc, endLoc) {
  19437. var comment = {
  19438. type: block ? "Block" : "Line",
  19439. value: text,
  19440. start: start,
  19441. end: end
  19442. };
  19443. if (options.locations)
  19444. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  19445. if (options.ranges)
  19446. { comment.range = [start, end]; }
  19447. array.push(comment);
  19448. }
  19449. }
  19450. // Each scope gets a bitset that may contain these flags
  19451. var
  19452. SCOPE_TOP = 1,
  19453. SCOPE_FUNCTION = 2,
  19454. SCOPE_ASYNC = 4,
  19455. SCOPE_GENERATOR = 8,
  19456. SCOPE_ARROW = 16,
  19457. SCOPE_SIMPLE_CATCH = 32,
  19458. SCOPE_SUPER = 64,
  19459. SCOPE_DIRECT_SUPER = 128,
  19460. SCOPE_CLASS_STATIC_BLOCK = 256,
  19461. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  19462. function functionFlags(async, generator) {
  19463. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  19464. }
  19465. // Used in checkLVal* and declareName to determine the type of a binding
  19466. var
  19467. BIND_NONE = 0, // Not a binding
  19468. BIND_VAR = 1, // Var-style binding
  19469. BIND_LEXICAL = 2, // Let- or const-style binding
  19470. BIND_FUNCTION = 3, // Function declaration
  19471. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  19472. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  19473. var Parser$1 = function Parser(options, input, startPos) {
  19474. this.options = options = getOptions(options);
  19475. this.sourceFile = options.sourceFile;
  19476. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  19477. var reserved = "";
  19478. if (options.allowReserved !== true) {
  19479. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  19480. if (options.sourceType === "module") { reserved += " await"; }
  19481. }
  19482. this.reservedWords = wordsRegexp(reserved);
  19483. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  19484. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  19485. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  19486. this.input = String(input);
  19487. // Used to signal to callers of `readWord1` whether the word
  19488. // contained any escape sequences. This is needed because words with
  19489. // escape sequences must not be interpreted as keywords.
  19490. this.containsEsc = false;
  19491. // Set up token state
  19492. // The current position of the tokenizer in the input.
  19493. if (startPos) {
  19494. this.pos = startPos;
  19495. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  19496. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  19497. } else {
  19498. this.pos = this.lineStart = 0;
  19499. this.curLine = 1;
  19500. }
  19501. // Properties of the current token:
  19502. // Its type
  19503. this.type = types$1.eof;
  19504. // For tokens that include more information than their type, the value
  19505. this.value = null;
  19506. // Its start and end offset
  19507. this.start = this.end = this.pos;
  19508. // And, if locations are used, the {line, column} object
  19509. // corresponding to those offsets
  19510. this.startLoc = this.endLoc = this.curPosition();
  19511. // Position information for the previous token
  19512. this.lastTokEndLoc = this.lastTokStartLoc = null;
  19513. this.lastTokStart = this.lastTokEnd = this.pos;
  19514. // The context stack is used to superficially track syntactic
  19515. // context to predict whether a regular expression is allowed in a
  19516. // given position.
  19517. this.context = this.initialContext();
  19518. this.exprAllowed = true;
  19519. // Figure out if it's a module code.
  19520. this.inModule = options.sourceType === "module";
  19521. this.strict = this.inModule || this.strictDirective(this.pos);
  19522. // Used to signify the start of a potential arrow function
  19523. this.potentialArrowAt = -1;
  19524. this.potentialArrowInForAwait = false;
  19525. // Positions to delayed-check that yield/await does not exist in default parameters.
  19526. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  19527. // Labels in scope.
  19528. this.labels = [];
  19529. // Thus-far undefined exports.
  19530. this.undefinedExports = Object.create(null);
  19531. // If enabled, skip leading hashbang line.
  19532. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  19533. { this.skipLineComment(2); }
  19534. // Scope tracking for duplicate variable names (see scope.js)
  19535. this.scopeStack = [];
  19536. this.enterScope(SCOPE_TOP);
  19537. // For RegExp validation
  19538. this.regexpState = null;
  19539. // The stack of private names.
  19540. // Each element has two properties: 'declared' and 'used'.
  19541. // When it exited from the outermost class definition, all used private names must be declared.
  19542. this.privateNameStack = [];
  19543. };
  19544. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
  19545. Parser$1.prototype.parse = function parse () {
  19546. var node = this.options.program || this.startNode();
  19547. this.nextToken();
  19548. return this.parseTopLevel(node)
  19549. };
  19550. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  19551. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  19552. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  19553. prototypeAccessors.canAwait.get = function () {
  19554. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  19555. var scope = this.scopeStack[i];
  19556. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  19557. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  19558. }
  19559. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  19560. };
  19561. prototypeAccessors.allowSuper.get = function () {
  19562. var ref = this.currentThisScope();
  19563. var flags = ref.flags;
  19564. var inClassFieldInit = ref.inClassFieldInit;
  19565. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  19566. };
  19567. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  19568. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  19569. prototypeAccessors.allowNewDotTarget.get = function () {
  19570. var ref = this.currentThisScope();
  19571. var flags = ref.flags;
  19572. var inClassFieldInit = ref.inClassFieldInit;
  19573. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  19574. };
  19575. prototypeAccessors.inClassStaticBlock.get = function () {
  19576. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  19577. };
  19578. Parser$1.extend = function extend () {
  19579. var plugins = [], len = arguments.length;
  19580. while ( len-- ) plugins[ len ] = arguments[ len ];
  19581. var cls = this;
  19582. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  19583. return cls
  19584. };
  19585. Parser$1.parse = function parse (input, options) {
  19586. return new this(options, input).parse()
  19587. };
  19588. Parser$1.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  19589. var parser = new this(options, input, pos);
  19590. parser.nextToken();
  19591. return parser.parseExpression()
  19592. };
  19593. Parser$1.tokenizer = function tokenizer (input, options) {
  19594. return new this(options, input)
  19595. };
  19596. Object.defineProperties( Parser$1.prototype, prototypeAccessors );
  19597. var pp$9 = Parser$1.prototype;
  19598. // ## Parser utilities
  19599. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  19600. pp$9.strictDirective = function(start) {
  19601. if (this.options.ecmaVersion < 5) { return false }
  19602. for (;;) {
  19603. // Try to find string literal.
  19604. skipWhiteSpace.lastIndex = start;
  19605. start += skipWhiteSpace.exec(this.input)[0].length;
  19606. var match = literal.exec(this.input.slice(start));
  19607. if (!match) { return false }
  19608. if ((match[1] || match[2]) === "use strict") {
  19609. skipWhiteSpace.lastIndex = start + match[0].length;
  19610. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  19611. var next = this.input.charAt(end);
  19612. return next === ";" || next === "}" ||
  19613. (lineBreak.test(spaceAfter[0]) &&
  19614. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  19615. }
  19616. start += match[0].length;
  19617. // Skip semicolon, if any.
  19618. skipWhiteSpace.lastIndex = start;
  19619. start += skipWhiteSpace.exec(this.input)[0].length;
  19620. if (this.input[start] === ";")
  19621. { start++; }
  19622. }
  19623. };
  19624. // Predicate that tests whether the next token is of the given
  19625. // type, and if yes, consumes it as a side effect.
  19626. pp$9.eat = function(type) {
  19627. if (this.type === type) {
  19628. this.next();
  19629. return true
  19630. } else {
  19631. return false
  19632. }
  19633. };
  19634. // Tests whether parsed token is a contextual keyword.
  19635. pp$9.isContextual = function(name) {
  19636. return this.type === types$1.name && this.value === name && !this.containsEsc
  19637. };
  19638. // Consumes contextual keyword if possible.
  19639. pp$9.eatContextual = function(name) {
  19640. if (!this.isContextual(name)) { return false }
  19641. this.next();
  19642. return true
  19643. };
  19644. // Asserts that following token is given contextual keyword.
  19645. pp$9.expectContextual = function(name) {
  19646. if (!this.eatContextual(name)) { this.unexpected(); }
  19647. };
  19648. // Test whether a semicolon can be inserted at the current position.
  19649. pp$9.canInsertSemicolon = function() {
  19650. return this.type === types$1.eof ||
  19651. this.type === types$1.braceR ||
  19652. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  19653. };
  19654. pp$9.insertSemicolon = function() {
  19655. if (this.canInsertSemicolon()) {
  19656. if (this.options.onInsertedSemicolon)
  19657. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  19658. return true
  19659. }
  19660. };
  19661. // Consume a semicolon, or, failing that, see if we are allowed to
  19662. // pretend that there is a semicolon at this position.
  19663. pp$9.semicolon = function() {
  19664. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  19665. };
  19666. pp$9.afterTrailingComma = function(tokType, notNext) {
  19667. if (this.type === tokType) {
  19668. if (this.options.onTrailingComma)
  19669. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  19670. if (!notNext)
  19671. { this.next(); }
  19672. return true
  19673. }
  19674. };
  19675. // Expect a token of a given type. If found, consume it, otherwise,
  19676. // raise an unexpected token error.
  19677. pp$9.expect = function(type) {
  19678. this.eat(type) || this.unexpected();
  19679. };
  19680. // Raise an unexpected token error.
  19681. pp$9.unexpected = function(pos) {
  19682. this.raise(pos != null ? pos : this.start, "Unexpected token");
  19683. };
  19684. var DestructuringErrors = function DestructuringErrors() {
  19685. this.shorthandAssign =
  19686. this.trailingComma =
  19687. this.parenthesizedAssign =
  19688. this.parenthesizedBind =
  19689. this.doubleProto =
  19690. -1;
  19691. };
  19692. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  19693. if (!refDestructuringErrors) { return }
  19694. if (refDestructuringErrors.trailingComma > -1)
  19695. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  19696. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  19697. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  19698. };
  19699. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  19700. if (!refDestructuringErrors) { return false }
  19701. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  19702. var doubleProto = refDestructuringErrors.doubleProto;
  19703. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  19704. if (shorthandAssign >= 0)
  19705. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  19706. if (doubleProto >= 0)
  19707. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  19708. };
  19709. pp$9.checkYieldAwaitInDefaultParams = function() {
  19710. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  19711. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  19712. if (this.awaitPos)
  19713. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  19714. };
  19715. pp$9.isSimpleAssignTarget = function(expr) {
  19716. if (expr.type === "ParenthesizedExpression")
  19717. { return this.isSimpleAssignTarget(expr.expression) }
  19718. return expr.type === "Identifier" || expr.type === "MemberExpression"
  19719. };
  19720. var pp$8 = Parser$1.prototype;
  19721. // ### Statement parsing
  19722. // Parse a program. Initializes the parser, reads any number of
  19723. // statements, and wraps them in a Program node. Optionally takes a
  19724. // `program` argument. If present, the statements will be appended
  19725. // to its body instead of creating a new node.
  19726. pp$8.parseTopLevel = function(node) {
  19727. var exports = Object.create(null);
  19728. if (!node.body) { node.body = []; }
  19729. while (this.type !== types$1.eof) {
  19730. var stmt = this.parseStatement(null, true, exports);
  19731. node.body.push(stmt);
  19732. }
  19733. if (this.inModule)
  19734. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  19735. {
  19736. var name = list[i];
  19737. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  19738. } }
  19739. this.adaptDirectivePrologue(node.body);
  19740. this.next();
  19741. node.sourceType = this.options.sourceType;
  19742. return this.finishNode(node, "Program")
  19743. };
  19744. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  19745. pp$8.isLet = function(context) {
  19746. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  19747. skipWhiteSpace.lastIndex = this.pos;
  19748. var skip = skipWhiteSpace.exec(this.input);
  19749. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  19750. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  19751. // Statement) is allowed here. If context is not empty then only a Statement
  19752. // is allowed. However, `let [` is an explicit negative lookahead for
  19753. // ExpressionStatement, so special-case it first.
  19754. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  19755. if (context) { return false }
  19756. if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  19757. if (isIdentifierStart(nextCh, true)) {
  19758. var pos = next + 1;
  19759. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  19760. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  19761. var ident = this.input.slice(next, pos);
  19762. if (!keywordRelationalOperator.test(ident)) { return true }
  19763. }
  19764. return false
  19765. };
  19766. // check 'async [no LineTerminator here] function'
  19767. // - 'async /*foo*/ function' is OK.
  19768. // - 'async /*\n*/ function' is invalid.
  19769. pp$8.isAsyncFunction = function() {
  19770. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  19771. { return false }
  19772. skipWhiteSpace.lastIndex = this.pos;
  19773. var skip = skipWhiteSpace.exec(this.input);
  19774. var next = this.pos + skip[0].length, after;
  19775. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  19776. this.input.slice(next, next + 8) === "function" &&
  19777. (next + 8 === this.input.length ||
  19778. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  19779. };
  19780. // Parse a single statement.
  19781. //
  19782. // If expecting a statement and finding a slash operator, parse a
  19783. // regular expression literal. This is to handle cases like
  19784. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  19785. // does not help.
  19786. pp$8.parseStatement = function(context, topLevel, exports) {
  19787. var starttype = this.type, node = this.startNode(), kind;
  19788. if (this.isLet(context)) {
  19789. starttype = types$1._var;
  19790. kind = "let";
  19791. }
  19792. // Most types of statements are recognized by the keyword they
  19793. // start with. Many are trivial to parse, some require a bit of
  19794. // complexity.
  19795. switch (starttype) {
  19796. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  19797. case types$1._debugger: return this.parseDebuggerStatement(node)
  19798. case types$1._do: return this.parseDoStatement(node)
  19799. case types$1._for: return this.parseForStatement(node)
  19800. case types$1._function:
  19801. // Function as sole body of either an if statement or a labeled statement
  19802. // works, but not when it is part of a labeled statement that is the sole
  19803. // body of an if statement.
  19804. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  19805. return this.parseFunctionStatement(node, false, !context)
  19806. case types$1._class:
  19807. if (context) { this.unexpected(); }
  19808. return this.parseClass(node, true)
  19809. case types$1._if: return this.parseIfStatement(node)
  19810. case types$1._return: return this.parseReturnStatement(node)
  19811. case types$1._switch: return this.parseSwitchStatement(node)
  19812. case types$1._throw: return this.parseThrowStatement(node)
  19813. case types$1._try: return this.parseTryStatement(node)
  19814. case types$1._const: case types$1._var:
  19815. kind = kind || this.value;
  19816. if (context && kind !== "var") { this.unexpected(); }
  19817. return this.parseVarStatement(node, kind)
  19818. case types$1._while: return this.parseWhileStatement(node)
  19819. case types$1._with: return this.parseWithStatement(node)
  19820. case types$1.braceL: return this.parseBlock(true, node)
  19821. case types$1.semi: return this.parseEmptyStatement(node)
  19822. case types$1._export:
  19823. case types$1._import:
  19824. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  19825. skipWhiteSpace.lastIndex = this.pos;
  19826. var skip = skipWhiteSpace.exec(this.input);
  19827. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  19828. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  19829. { return this.parseExpressionStatement(node, this.parseExpression()) }
  19830. }
  19831. if (!this.options.allowImportExportEverywhere) {
  19832. if (!topLevel)
  19833. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  19834. if (!this.inModule)
  19835. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  19836. }
  19837. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  19838. // If the statement does not start with a statement keyword or a
  19839. // brace, it's an ExpressionStatement or LabeledStatement. We
  19840. // simply start parsing an expression, and afterwards, if the
  19841. // next token is a colon and the expression was a simple
  19842. // Identifier node, we switch to interpreting it as a label.
  19843. default:
  19844. if (this.isAsyncFunction()) {
  19845. if (context) { this.unexpected(); }
  19846. this.next();
  19847. return this.parseFunctionStatement(node, true, !context)
  19848. }
  19849. var maybeName = this.value, expr = this.parseExpression();
  19850. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  19851. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  19852. else { return this.parseExpressionStatement(node, expr) }
  19853. }
  19854. };
  19855. pp$8.parseBreakContinueStatement = function(node, keyword) {
  19856. var isBreak = keyword === "break";
  19857. this.next();
  19858. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  19859. else if (this.type !== types$1.name) { this.unexpected(); }
  19860. else {
  19861. node.label = this.parseIdent();
  19862. this.semicolon();
  19863. }
  19864. // Verify that there is an actual destination to break or
  19865. // continue to.
  19866. var i = 0;
  19867. for (; i < this.labels.length; ++i) {
  19868. var lab = this.labels[i];
  19869. if (node.label == null || lab.name === node.label.name) {
  19870. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  19871. if (node.label && isBreak) { break }
  19872. }
  19873. }
  19874. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  19875. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  19876. };
  19877. pp$8.parseDebuggerStatement = function(node) {
  19878. this.next();
  19879. this.semicolon();
  19880. return this.finishNode(node, "DebuggerStatement")
  19881. };
  19882. pp$8.parseDoStatement = function(node) {
  19883. this.next();
  19884. this.labels.push(loopLabel);
  19885. node.body = this.parseStatement("do");
  19886. this.labels.pop();
  19887. this.expect(types$1._while);
  19888. node.test = this.parseParenExpression();
  19889. if (this.options.ecmaVersion >= 6)
  19890. { this.eat(types$1.semi); }
  19891. else
  19892. { this.semicolon(); }
  19893. return this.finishNode(node, "DoWhileStatement")
  19894. };
  19895. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  19896. // loop is non-trivial. Basically, we have to parse the init `var`
  19897. // statement or expression, disallowing the `in` operator (see
  19898. // the second parameter to `parseExpression`), and then check
  19899. // whether the next token is `in` or `of`. When there is no init
  19900. // part (semicolon immediately after the opening parenthesis), it
  19901. // is a regular `for` loop.
  19902. pp$8.parseForStatement = function(node) {
  19903. this.next();
  19904. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  19905. this.labels.push(loopLabel);
  19906. this.enterScope(0);
  19907. this.expect(types$1.parenL);
  19908. if (this.type === types$1.semi) {
  19909. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19910. return this.parseFor(node, null)
  19911. }
  19912. var isLet = this.isLet();
  19913. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  19914. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  19915. this.next();
  19916. this.parseVar(init$1, true, kind);
  19917. this.finishNode(init$1, "VariableDeclaration");
  19918. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  19919. if (this.options.ecmaVersion >= 9) {
  19920. if (this.type === types$1._in) {
  19921. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19922. } else { node.await = awaitAt > -1; }
  19923. }
  19924. return this.parseForIn(node, init$1)
  19925. }
  19926. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19927. return this.parseFor(node, init$1)
  19928. }
  19929. var startsWithLet = this.isContextual("let"), isForOf = false;
  19930. var refDestructuringErrors = new DestructuringErrors;
  19931. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  19932. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  19933. if (this.options.ecmaVersion >= 9) {
  19934. if (this.type === types$1._in) {
  19935. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19936. } else { node.await = awaitAt > -1; }
  19937. }
  19938. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  19939. this.toAssignable(init, false, refDestructuringErrors);
  19940. this.checkLValPattern(init);
  19941. return this.parseForIn(node, init)
  19942. } else {
  19943. this.checkExpressionErrors(refDestructuringErrors, true);
  19944. }
  19945. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19946. return this.parseFor(node, init)
  19947. };
  19948. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  19949. this.next();
  19950. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  19951. };
  19952. pp$8.parseIfStatement = function(node) {
  19953. this.next();
  19954. node.test = this.parseParenExpression();
  19955. // allow function declarations in branches, but only in non-strict mode
  19956. node.consequent = this.parseStatement("if");
  19957. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  19958. return this.finishNode(node, "IfStatement")
  19959. };
  19960. pp$8.parseReturnStatement = function(node) {
  19961. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  19962. { this.raise(this.start, "'return' outside of function"); }
  19963. this.next();
  19964. // In `return` (and `break`/`continue`), the keywords with
  19965. // optional arguments, we eagerly look for a semicolon or the
  19966. // possibility to insert one.
  19967. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  19968. else { node.argument = this.parseExpression(); this.semicolon(); }
  19969. return this.finishNode(node, "ReturnStatement")
  19970. };
  19971. pp$8.parseSwitchStatement = function(node) {
  19972. this.next();
  19973. node.discriminant = this.parseParenExpression();
  19974. node.cases = [];
  19975. this.expect(types$1.braceL);
  19976. this.labels.push(switchLabel);
  19977. this.enterScope(0);
  19978. // Statements under must be grouped (by label) in SwitchCase
  19979. // nodes. `cur` is used to keep the node that we are currently
  19980. // adding statements to.
  19981. var cur;
  19982. for (var sawDefault = false; this.type !== types$1.braceR;) {
  19983. if (this.type === types$1._case || this.type === types$1._default) {
  19984. var isCase = this.type === types$1._case;
  19985. if (cur) { this.finishNode(cur, "SwitchCase"); }
  19986. node.cases.push(cur = this.startNode());
  19987. cur.consequent = [];
  19988. this.next();
  19989. if (isCase) {
  19990. cur.test = this.parseExpression();
  19991. } else {
  19992. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  19993. sawDefault = true;
  19994. cur.test = null;
  19995. }
  19996. this.expect(types$1.colon);
  19997. } else {
  19998. if (!cur) { this.unexpected(); }
  19999. cur.consequent.push(this.parseStatement(null));
  20000. }
  20001. }
  20002. this.exitScope();
  20003. if (cur) { this.finishNode(cur, "SwitchCase"); }
  20004. this.next(); // Closing brace
  20005. this.labels.pop();
  20006. return this.finishNode(node, "SwitchStatement")
  20007. };
  20008. pp$8.parseThrowStatement = function(node) {
  20009. this.next();
  20010. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  20011. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  20012. node.argument = this.parseExpression();
  20013. this.semicolon();
  20014. return this.finishNode(node, "ThrowStatement")
  20015. };
  20016. // Reused empty array added for node fields that are always empty.
  20017. var empty$1 = [];
  20018. pp$8.parseCatchClauseParam = function() {
  20019. var param = this.parseBindingAtom();
  20020. var simple = param.type === "Identifier";
  20021. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  20022. this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  20023. this.expect(types$1.parenR);
  20024. return param
  20025. };
  20026. pp$8.parseTryStatement = function(node) {
  20027. this.next();
  20028. node.block = this.parseBlock();
  20029. node.handler = null;
  20030. if (this.type === types$1._catch) {
  20031. var clause = this.startNode();
  20032. this.next();
  20033. if (this.eat(types$1.parenL)) {
  20034. clause.param = this.parseCatchClauseParam();
  20035. } else {
  20036. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  20037. clause.param = null;
  20038. this.enterScope(0);
  20039. }
  20040. clause.body = this.parseBlock(false);
  20041. this.exitScope();
  20042. node.handler = this.finishNode(clause, "CatchClause");
  20043. }
  20044. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  20045. if (!node.handler && !node.finalizer)
  20046. { this.raise(node.start, "Missing catch or finally clause"); }
  20047. return this.finishNode(node, "TryStatement")
  20048. };
  20049. pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  20050. this.next();
  20051. this.parseVar(node, false, kind, allowMissingInitializer);
  20052. this.semicolon();
  20053. return this.finishNode(node, "VariableDeclaration")
  20054. };
  20055. pp$8.parseWhileStatement = function(node) {
  20056. this.next();
  20057. node.test = this.parseParenExpression();
  20058. this.labels.push(loopLabel);
  20059. node.body = this.parseStatement("while");
  20060. this.labels.pop();
  20061. return this.finishNode(node, "WhileStatement")
  20062. };
  20063. pp$8.parseWithStatement = function(node) {
  20064. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  20065. this.next();
  20066. node.object = this.parseParenExpression();
  20067. node.body = this.parseStatement("with");
  20068. return this.finishNode(node, "WithStatement")
  20069. };
  20070. pp$8.parseEmptyStatement = function(node) {
  20071. this.next();
  20072. return this.finishNode(node, "EmptyStatement")
  20073. };
  20074. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  20075. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  20076. {
  20077. var label = list[i$1];
  20078. if (label.name === maybeName)
  20079. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  20080. } }
  20081. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  20082. for (var i = this.labels.length - 1; i >= 0; i--) {
  20083. var label$1 = this.labels[i];
  20084. if (label$1.statementStart === node.start) {
  20085. // Update information about previous labels on this node
  20086. label$1.statementStart = this.start;
  20087. label$1.kind = kind;
  20088. } else { break }
  20089. }
  20090. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  20091. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  20092. this.labels.pop();
  20093. node.label = expr;
  20094. return this.finishNode(node, "LabeledStatement")
  20095. };
  20096. pp$8.parseExpressionStatement = function(node, expr) {
  20097. node.expression = expr;
  20098. this.semicolon();
  20099. return this.finishNode(node, "ExpressionStatement")
  20100. };
  20101. // Parse a semicolon-enclosed block of statements, handling `"use
  20102. // strict"` declarations when `allowStrict` is true (used for
  20103. // function bodies).
  20104. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  20105. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  20106. if ( node === void 0 ) node = this.startNode();
  20107. node.body = [];
  20108. this.expect(types$1.braceL);
  20109. if (createNewLexicalScope) { this.enterScope(0); }
  20110. while (this.type !== types$1.braceR) {
  20111. var stmt = this.parseStatement(null);
  20112. node.body.push(stmt);
  20113. }
  20114. if (exitStrict) { this.strict = false; }
  20115. this.next();
  20116. if (createNewLexicalScope) { this.exitScope(); }
  20117. return this.finishNode(node, "BlockStatement")
  20118. };
  20119. // Parse a regular `for` loop. The disambiguation code in
  20120. // `parseStatement` will already have parsed the init statement or
  20121. // expression.
  20122. pp$8.parseFor = function(node, init) {
  20123. node.init = init;
  20124. this.expect(types$1.semi);
  20125. node.test = this.type === types$1.semi ? null : this.parseExpression();
  20126. this.expect(types$1.semi);
  20127. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  20128. this.expect(types$1.parenR);
  20129. node.body = this.parseStatement("for");
  20130. this.exitScope();
  20131. this.labels.pop();
  20132. return this.finishNode(node, "ForStatement")
  20133. };
  20134. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  20135. // same from parser's perspective.
  20136. pp$8.parseForIn = function(node, init) {
  20137. var isForIn = this.type === types$1._in;
  20138. this.next();
  20139. if (
  20140. init.type === "VariableDeclaration" &&
  20141. init.declarations[0].init != null &&
  20142. (
  20143. !isForIn ||
  20144. this.options.ecmaVersion < 8 ||
  20145. this.strict ||
  20146. init.kind !== "var" ||
  20147. init.declarations[0].id.type !== "Identifier"
  20148. )
  20149. ) {
  20150. this.raise(
  20151. init.start,
  20152. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  20153. );
  20154. }
  20155. node.left = init;
  20156. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  20157. this.expect(types$1.parenR);
  20158. node.body = this.parseStatement("for");
  20159. this.exitScope();
  20160. this.labels.pop();
  20161. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  20162. };
  20163. // Parse a list of variable declarations.
  20164. pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  20165. node.declarations = [];
  20166. node.kind = kind;
  20167. for (;;) {
  20168. var decl = this.startNode();
  20169. this.parseVarId(decl, kind);
  20170. if (this.eat(types$1.eq)) {
  20171. decl.init = this.parseMaybeAssign(isFor);
  20172. } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  20173. this.unexpected();
  20174. } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  20175. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  20176. } else {
  20177. decl.init = null;
  20178. }
  20179. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  20180. if (!this.eat(types$1.comma)) { break }
  20181. }
  20182. return node
  20183. };
  20184. pp$8.parseVarId = function(decl, kind) {
  20185. decl.id = this.parseBindingAtom();
  20186. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  20187. };
  20188. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  20189. // Parse a function declaration or literal (depending on the
  20190. // `statement & FUNC_STATEMENT`).
  20191. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  20192. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  20193. this.initFunction(node);
  20194. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  20195. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  20196. { this.unexpected(); }
  20197. node.generator = this.eat(types$1.star);
  20198. }
  20199. if (this.options.ecmaVersion >= 8)
  20200. { node.async = !!isAsync; }
  20201. if (statement & FUNC_STATEMENT) {
  20202. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  20203. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  20204. // If it is a regular function declaration in sloppy mode, then it is
  20205. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  20206. // mode depends on properties of the current scope (see
  20207. // treatFunctionsAsVar).
  20208. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  20209. }
  20210. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20211. this.yieldPos = 0;
  20212. this.awaitPos = 0;
  20213. this.awaitIdentPos = 0;
  20214. this.enterScope(functionFlags(node.async, node.generator));
  20215. if (!(statement & FUNC_STATEMENT))
  20216. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  20217. this.parseFunctionParams(node);
  20218. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  20219. this.yieldPos = oldYieldPos;
  20220. this.awaitPos = oldAwaitPos;
  20221. this.awaitIdentPos = oldAwaitIdentPos;
  20222. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  20223. };
  20224. pp$8.parseFunctionParams = function(node) {
  20225. this.expect(types$1.parenL);
  20226. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  20227. this.checkYieldAwaitInDefaultParams();
  20228. };
  20229. // Parse a class declaration or literal (depending on the
  20230. // `isStatement` parameter).
  20231. pp$8.parseClass = function(node, isStatement) {
  20232. this.next();
  20233. // ecma-262 14.6 Class Definitions
  20234. // A class definition is always strict mode code.
  20235. var oldStrict = this.strict;
  20236. this.strict = true;
  20237. this.parseClassId(node, isStatement);
  20238. this.parseClassSuper(node);
  20239. var privateNameMap = this.enterClassBody();
  20240. var classBody = this.startNode();
  20241. var hadConstructor = false;
  20242. classBody.body = [];
  20243. this.expect(types$1.braceL);
  20244. while (this.type !== types$1.braceR) {
  20245. var element = this.parseClassElement(node.superClass !== null);
  20246. if (element) {
  20247. classBody.body.push(element);
  20248. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  20249. if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
  20250. hadConstructor = true;
  20251. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  20252. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  20253. }
  20254. }
  20255. }
  20256. this.strict = oldStrict;
  20257. this.next();
  20258. node.body = this.finishNode(classBody, "ClassBody");
  20259. this.exitClassBody();
  20260. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  20261. };
  20262. pp$8.parseClassElement = function(constructorAllowsSuper) {
  20263. if (this.eat(types$1.semi)) { return null }
  20264. var ecmaVersion = this.options.ecmaVersion;
  20265. var node = this.startNode();
  20266. var keyName = "";
  20267. var isGenerator = false;
  20268. var isAsync = false;
  20269. var kind = "method";
  20270. var isStatic = false;
  20271. if (this.eatContextual("static")) {
  20272. // Parse static init block
  20273. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  20274. this.parseClassStaticBlock(node);
  20275. return node
  20276. }
  20277. if (this.isClassElementNameStart() || this.type === types$1.star) {
  20278. isStatic = true;
  20279. } else {
  20280. keyName = "static";
  20281. }
  20282. }
  20283. node.static = isStatic;
  20284. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  20285. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  20286. isAsync = true;
  20287. } else {
  20288. keyName = "async";
  20289. }
  20290. }
  20291. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  20292. isGenerator = true;
  20293. }
  20294. if (!keyName && !isAsync && !isGenerator) {
  20295. var lastValue = this.value;
  20296. if (this.eatContextual("get") || this.eatContextual("set")) {
  20297. if (this.isClassElementNameStart()) {
  20298. kind = lastValue;
  20299. } else {
  20300. keyName = lastValue;
  20301. }
  20302. }
  20303. }
  20304. // Parse element name
  20305. if (keyName) {
  20306. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  20307. // The last token is any of those. Make it the element name.
  20308. node.computed = false;
  20309. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  20310. node.key.name = keyName;
  20311. this.finishNode(node.key, "Identifier");
  20312. } else {
  20313. this.parseClassElementName(node);
  20314. }
  20315. // Parse element value
  20316. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  20317. var isConstructor = !node.static && checkKeyName(node, "constructor");
  20318. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  20319. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  20320. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  20321. node.kind = isConstructor ? "constructor" : kind;
  20322. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  20323. } else {
  20324. this.parseClassField(node);
  20325. }
  20326. return node
  20327. };
  20328. pp$8.isClassElementNameStart = function() {
  20329. return (
  20330. this.type === types$1.name ||
  20331. this.type === types$1.privateId ||
  20332. this.type === types$1.num ||
  20333. this.type === types$1.string ||
  20334. this.type === types$1.bracketL ||
  20335. this.type.keyword
  20336. )
  20337. };
  20338. pp$8.parseClassElementName = function(element) {
  20339. if (this.type === types$1.privateId) {
  20340. if (this.value === "constructor") {
  20341. this.raise(this.start, "Classes can't have an element named '#constructor'");
  20342. }
  20343. element.computed = false;
  20344. element.key = this.parsePrivateIdent();
  20345. } else {
  20346. this.parsePropertyName(element);
  20347. }
  20348. };
  20349. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  20350. // Check key and flags
  20351. var key = method.key;
  20352. if (method.kind === "constructor") {
  20353. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  20354. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  20355. } else if (method.static && checkKeyName(method, "prototype")) {
  20356. this.raise(key.start, "Classes may not have a static property named prototype");
  20357. }
  20358. // Parse value
  20359. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  20360. // Check value
  20361. if (method.kind === "get" && value.params.length !== 0)
  20362. { this.raiseRecoverable(value.start, "getter should have no params"); }
  20363. if (method.kind === "set" && value.params.length !== 1)
  20364. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  20365. if (method.kind === "set" && value.params[0].type === "RestElement")
  20366. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  20367. return this.finishNode(method, "MethodDefinition")
  20368. };
  20369. pp$8.parseClassField = function(field) {
  20370. if (checkKeyName(field, "constructor")) {
  20371. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  20372. } else if (field.static && checkKeyName(field, "prototype")) {
  20373. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  20374. }
  20375. if (this.eat(types$1.eq)) {
  20376. // To raise SyntaxError if 'arguments' exists in the initializer.
  20377. var scope = this.currentThisScope();
  20378. var inClassFieldInit = scope.inClassFieldInit;
  20379. scope.inClassFieldInit = true;
  20380. field.value = this.parseMaybeAssign();
  20381. scope.inClassFieldInit = inClassFieldInit;
  20382. } else {
  20383. field.value = null;
  20384. }
  20385. this.semicolon();
  20386. return this.finishNode(field, "PropertyDefinition")
  20387. };
  20388. pp$8.parseClassStaticBlock = function(node) {
  20389. node.body = [];
  20390. var oldLabels = this.labels;
  20391. this.labels = [];
  20392. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  20393. while (this.type !== types$1.braceR) {
  20394. var stmt = this.parseStatement(null);
  20395. node.body.push(stmt);
  20396. }
  20397. this.next();
  20398. this.exitScope();
  20399. this.labels = oldLabels;
  20400. return this.finishNode(node, "StaticBlock")
  20401. };
  20402. pp$8.parseClassId = function(node, isStatement) {
  20403. if (this.type === types$1.name) {
  20404. node.id = this.parseIdent();
  20405. if (isStatement)
  20406. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  20407. } else {
  20408. if (isStatement === true)
  20409. { this.unexpected(); }
  20410. node.id = null;
  20411. }
  20412. };
  20413. pp$8.parseClassSuper = function(node) {
  20414. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
  20415. };
  20416. pp$8.enterClassBody = function() {
  20417. var element = {declared: Object.create(null), used: []};
  20418. this.privateNameStack.push(element);
  20419. return element.declared
  20420. };
  20421. pp$8.exitClassBody = function() {
  20422. var ref = this.privateNameStack.pop();
  20423. var declared = ref.declared;
  20424. var used = ref.used;
  20425. if (!this.options.checkPrivateFields) { return }
  20426. var len = this.privateNameStack.length;
  20427. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  20428. for (var i = 0; i < used.length; ++i) {
  20429. var id = used[i];
  20430. if (!hasOwn(declared, id.name)) {
  20431. if (parent) {
  20432. parent.used.push(id);
  20433. } else {
  20434. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  20435. }
  20436. }
  20437. }
  20438. };
  20439. function isPrivateNameConflicted(privateNameMap, element) {
  20440. var name = element.key.name;
  20441. var curr = privateNameMap[name];
  20442. var next = "true";
  20443. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  20444. next = (element.static ? "s" : "i") + element.kind;
  20445. }
  20446. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  20447. if (
  20448. curr === "iget" && next === "iset" ||
  20449. curr === "iset" && next === "iget" ||
  20450. curr === "sget" && next === "sset" ||
  20451. curr === "sset" && next === "sget"
  20452. ) {
  20453. privateNameMap[name] = "true";
  20454. return false
  20455. } else if (!curr) {
  20456. privateNameMap[name] = next;
  20457. return false
  20458. } else {
  20459. return true
  20460. }
  20461. }
  20462. function checkKeyName(node, name) {
  20463. var computed = node.computed;
  20464. var key = node.key;
  20465. return !computed && (
  20466. key.type === "Identifier" && key.name === name ||
  20467. key.type === "Literal" && key.value === name
  20468. )
  20469. }
  20470. // Parses module export declaration.
  20471. pp$8.parseExportAllDeclaration = function(node, exports) {
  20472. if (this.options.ecmaVersion >= 11) {
  20473. if (this.eatContextual("as")) {
  20474. node.exported = this.parseModuleExportName();
  20475. this.checkExport(exports, node.exported, this.lastTokStart);
  20476. } else {
  20477. node.exported = null;
  20478. }
  20479. }
  20480. this.expectContextual("from");
  20481. if (this.type !== types$1.string) { this.unexpected(); }
  20482. node.source = this.parseExprAtom();
  20483. this.semicolon();
  20484. return this.finishNode(node, "ExportAllDeclaration")
  20485. };
  20486. pp$8.parseExport = function(node, exports) {
  20487. this.next();
  20488. // export * from '...'
  20489. if (this.eat(types$1.star)) {
  20490. return this.parseExportAllDeclaration(node, exports)
  20491. }
  20492. if (this.eat(types$1._default)) { // export default ...
  20493. this.checkExport(exports, "default", this.lastTokStart);
  20494. node.declaration = this.parseExportDefaultDeclaration();
  20495. return this.finishNode(node, "ExportDefaultDeclaration")
  20496. }
  20497. // export var|const|let|function|class ...
  20498. if (this.shouldParseExportStatement()) {
  20499. node.declaration = this.parseExportDeclaration(node);
  20500. if (node.declaration.type === "VariableDeclaration")
  20501. { this.checkVariableExport(exports, node.declaration.declarations); }
  20502. else
  20503. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  20504. node.specifiers = [];
  20505. node.source = null;
  20506. } else { // export { x, y as z } [from '...']
  20507. node.declaration = null;
  20508. node.specifiers = this.parseExportSpecifiers(exports);
  20509. if (this.eatContextual("from")) {
  20510. if (this.type !== types$1.string) { this.unexpected(); }
  20511. node.source = this.parseExprAtom();
  20512. } else {
  20513. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  20514. // check for keywords used as local names
  20515. var spec = list[i];
  20516. this.checkUnreserved(spec.local);
  20517. // check if export is defined
  20518. this.checkLocalExport(spec.local);
  20519. if (spec.local.type === "Literal") {
  20520. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  20521. }
  20522. }
  20523. node.source = null;
  20524. }
  20525. this.semicolon();
  20526. }
  20527. return this.finishNode(node, "ExportNamedDeclaration")
  20528. };
  20529. pp$8.parseExportDeclaration = function(node) {
  20530. return this.parseStatement(null)
  20531. };
  20532. pp$8.parseExportDefaultDeclaration = function() {
  20533. var isAsync;
  20534. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  20535. var fNode = this.startNode();
  20536. this.next();
  20537. if (isAsync) { this.next(); }
  20538. return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)
  20539. } else if (this.type === types$1._class) {
  20540. var cNode = this.startNode();
  20541. return this.parseClass(cNode, "nullableID")
  20542. } else {
  20543. var declaration = this.parseMaybeAssign();
  20544. this.semicolon();
  20545. return declaration
  20546. }
  20547. };
  20548. pp$8.checkExport = function(exports, name, pos) {
  20549. if (!exports) { return }
  20550. if (typeof name !== "string")
  20551. { name = name.type === "Identifier" ? name.name : name.value; }
  20552. if (hasOwn(exports, name))
  20553. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  20554. exports[name] = true;
  20555. };
  20556. pp$8.checkPatternExport = function(exports, pat) {
  20557. var type = pat.type;
  20558. if (type === "Identifier")
  20559. { this.checkExport(exports, pat, pat.start); }
  20560. else if (type === "ObjectPattern")
  20561. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  20562. {
  20563. var prop = list[i];
  20564. this.checkPatternExport(exports, prop);
  20565. } }
  20566. else if (type === "ArrayPattern")
  20567. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  20568. var elt = list$1[i$1];
  20569. if (elt) { this.checkPatternExport(exports, elt); }
  20570. } }
  20571. else if (type === "Property")
  20572. { this.checkPatternExport(exports, pat.value); }
  20573. else if (type === "AssignmentPattern")
  20574. { this.checkPatternExport(exports, pat.left); }
  20575. else if (type === "RestElement")
  20576. { this.checkPatternExport(exports, pat.argument); }
  20577. else if (type === "ParenthesizedExpression")
  20578. { this.checkPatternExport(exports, pat.expression); }
  20579. };
  20580. pp$8.checkVariableExport = function(exports, decls) {
  20581. if (!exports) { return }
  20582. for (var i = 0, list = decls; i < list.length; i += 1)
  20583. {
  20584. var decl = list[i];
  20585. this.checkPatternExport(exports, decl.id);
  20586. }
  20587. };
  20588. pp$8.shouldParseExportStatement = function() {
  20589. return this.type.keyword === "var" ||
  20590. this.type.keyword === "const" ||
  20591. this.type.keyword === "class" ||
  20592. this.type.keyword === "function" ||
  20593. this.isLet() ||
  20594. this.isAsyncFunction()
  20595. };
  20596. // Parses a comma-separated list of module exports.
  20597. pp$8.parseExportSpecifier = function(exports) {
  20598. var node = this.startNode();
  20599. node.local = this.parseModuleExportName();
  20600. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  20601. this.checkExport(
  20602. exports,
  20603. node.exported,
  20604. node.exported.start
  20605. );
  20606. return this.finishNode(node, "ExportSpecifier")
  20607. };
  20608. pp$8.parseExportSpecifiers = function(exports) {
  20609. var nodes = [], first = true;
  20610. // export { x, y as z } [from '...']
  20611. this.expect(types$1.braceL);
  20612. while (!this.eat(types$1.braceR)) {
  20613. if (!first) {
  20614. this.expect(types$1.comma);
  20615. if (this.afterTrailingComma(types$1.braceR)) { break }
  20616. } else { first = false; }
  20617. nodes.push(this.parseExportSpecifier(exports));
  20618. }
  20619. return nodes
  20620. };
  20621. // Parses import declaration.
  20622. pp$8.parseImport = function(node) {
  20623. this.next();
  20624. // import '...'
  20625. if (this.type === types$1.string) {
  20626. node.specifiers = empty$1;
  20627. node.source = this.parseExprAtom();
  20628. } else {
  20629. node.specifiers = this.parseImportSpecifiers();
  20630. this.expectContextual("from");
  20631. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  20632. }
  20633. this.semicolon();
  20634. return this.finishNode(node, "ImportDeclaration")
  20635. };
  20636. // Parses a comma-separated list of module imports.
  20637. pp$8.parseImportSpecifier = function() {
  20638. var node = this.startNode();
  20639. node.imported = this.parseModuleExportName();
  20640. if (this.eatContextual("as")) {
  20641. node.local = this.parseIdent();
  20642. } else {
  20643. this.checkUnreserved(node.imported);
  20644. node.local = node.imported;
  20645. }
  20646. this.checkLValSimple(node.local, BIND_LEXICAL);
  20647. return this.finishNode(node, "ImportSpecifier")
  20648. };
  20649. pp$8.parseImportDefaultSpecifier = function() {
  20650. // import defaultObj, { x, y as z } from '...'
  20651. var node = this.startNode();
  20652. node.local = this.parseIdent();
  20653. this.checkLValSimple(node.local, BIND_LEXICAL);
  20654. return this.finishNode(node, "ImportDefaultSpecifier")
  20655. };
  20656. pp$8.parseImportNamespaceSpecifier = function() {
  20657. var node = this.startNode();
  20658. this.next();
  20659. this.expectContextual("as");
  20660. node.local = this.parseIdent();
  20661. this.checkLValSimple(node.local, BIND_LEXICAL);
  20662. return this.finishNode(node, "ImportNamespaceSpecifier")
  20663. };
  20664. pp$8.parseImportSpecifiers = function() {
  20665. var nodes = [], first = true;
  20666. if (this.type === types$1.name) {
  20667. nodes.push(this.parseImportDefaultSpecifier());
  20668. if (!this.eat(types$1.comma)) { return nodes }
  20669. }
  20670. if (this.type === types$1.star) {
  20671. nodes.push(this.parseImportNamespaceSpecifier());
  20672. return nodes
  20673. }
  20674. this.expect(types$1.braceL);
  20675. while (!this.eat(types$1.braceR)) {
  20676. if (!first) {
  20677. this.expect(types$1.comma);
  20678. if (this.afterTrailingComma(types$1.braceR)) { break }
  20679. } else { first = false; }
  20680. nodes.push(this.parseImportSpecifier());
  20681. }
  20682. return nodes
  20683. };
  20684. pp$8.parseModuleExportName = function() {
  20685. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  20686. var stringLiteral = this.parseLiteral(this.value);
  20687. if (loneSurrogate.test(stringLiteral.value)) {
  20688. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  20689. }
  20690. return stringLiteral
  20691. }
  20692. return this.parseIdent(true)
  20693. };
  20694. // Set `ExpressionStatement#directive` property for directive prologues.
  20695. pp$8.adaptDirectivePrologue = function(statements) {
  20696. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  20697. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  20698. }
  20699. };
  20700. pp$8.isDirectiveCandidate = function(statement) {
  20701. return (
  20702. this.options.ecmaVersion >= 5 &&
  20703. statement.type === "ExpressionStatement" &&
  20704. statement.expression.type === "Literal" &&
  20705. typeof statement.expression.value === "string" &&
  20706. // Reject parenthesized strings.
  20707. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  20708. )
  20709. };
  20710. var pp$7 = Parser$1.prototype;
  20711. // Convert existing expression atom to assignable pattern
  20712. // if possible.
  20713. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  20714. if (this.options.ecmaVersion >= 6 && node) {
  20715. switch (node.type) {
  20716. case "Identifier":
  20717. if (this.inAsync && node.name === "await")
  20718. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  20719. break
  20720. case "ObjectPattern":
  20721. case "ArrayPattern":
  20722. case "AssignmentPattern":
  20723. case "RestElement":
  20724. break
  20725. case "ObjectExpression":
  20726. node.type = "ObjectPattern";
  20727. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20728. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  20729. var prop = list[i];
  20730. this.toAssignable(prop, isBinding);
  20731. // Early error:
  20732. // AssignmentRestProperty[Yield, Await] :
  20733. // `...` DestructuringAssignmentTarget[Yield, Await]
  20734. //
  20735. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  20736. if (
  20737. prop.type === "RestElement" &&
  20738. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  20739. ) {
  20740. this.raise(prop.argument.start, "Unexpected token");
  20741. }
  20742. }
  20743. break
  20744. case "Property":
  20745. // AssignmentProperty has type === "Property"
  20746. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  20747. this.toAssignable(node.value, isBinding);
  20748. break
  20749. case "ArrayExpression":
  20750. node.type = "ArrayPattern";
  20751. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20752. this.toAssignableList(node.elements, isBinding);
  20753. break
  20754. case "SpreadElement":
  20755. node.type = "RestElement";
  20756. this.toAssignable(node.argument, isBinding);
  20757. if (node.argument.type === "AssignmentPattern")
  20758. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  20759. break
  20760. case "AssignmentExpression":
  20761. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  20762. node.type = "AssignmentPattern";
  20763. delete node.operator;
  20764. this.toAssignable(node.left, isBinding);
  20765. break
  20766. case "ParenthesizedExpression":
  20767. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  20768. break
  20769. case "ChainExpression":
  20770. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  20771. break
  20772. case "MemberExpression":
  20773. if (!isBinding) { break }
  20774. default:
  20775. this.raise(node.start, "Assigning to rvalue");
  20776. }
  20777. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20778. return node
  20779. };
  20780. // Convert list of expression atoms to binding list.
  20781. pp$7.toAssignableList = function(exprList, isBinding) {
  20782. var end = exprList.length;
  20783. for (var i = 0; i < end; i++) {
  20784. var elt = exprList[i];
  20785. if (elt) { this.toAssignable(elt, isBinding); }
  20786. }
  20787. if (end) {
  20788. var last = exprList[end - 1];
  20789. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  20790. { this.unexpected(last.argument.start); }
  20791. }
  20792. return exprList
  20793. };
  20794. // Parses spread element.
  20795. pp$7.parseSpread = function(refDestructuringErrors) {
  20796. var node = this.startNode();
  20797. this.next();
  20798. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  20799. return this.finishNode(node, "SpreadElement")
  20800. };
  20801. pp$7.parseRestBinding = function() {
  20802. var node = this.startNode();
  20803. this.next();
  20804. // RestElement inside of a function parameter must be an identifier
  20805. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  20806. { this.unexpected(); }
  20807. node.argument = this.parseBindingAtom();
  20808. return this.finishNode(node, "RestElement")
  20809. };
  20810. // Parses lvalue (assignable) atom.
  20811. pp$7.parseBindingAtom = function() {
  20812. if (this.options.ecmaVersion >= 6) {
  20813. switch (this.type) {
  20814. case types$1.bracketL:
  20815. var node = this.startNode();
  20816. this.next();
  20817. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  20818. return this.finishNode(node, "ArrayPattern")
  20819. case types$1.braceL:
  20820. return this.parseObj(true)
  20821. }
  20822. }
  20823. return this.parseIdent()
  20824. };
  20825. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  20826. var elts = [], first = true;
  20827. while (!this.eat(close)) {
  20828. if (first) { first = false; }
  20829. else { this.expect(types$1.comma); }
  20830. if (allowEmpty && this.type === types$1.comma) {
  20831. elts.push(null);
  20832. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  20833. break
  20834. } else if (this.type === types$1.ellipsis) {
  20835. var rest = this.parseRestBinding();
  20836. this.parseBindingListItem(rest);
  20837. elts.push(rest);
  20838. if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
  20839. this.expect(close);
  20840. break
  20841. } else {
  20842. elts.push(this.parseAssignableListItem(allowModifiers));
  20843. }
  20844. }
  20845. return elts
  20846. };
  20847. pp$7.parseAssignableListItem = function(allowModifiers) {
  20848. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  20849. this.parseBindingListItem(elem);
  20850. return elem
  20851. };
  20852. pp$7.parseBindingListItem = function(param) {
  20853. return param
  20854. };
  20855. // Parses assignment pattern around given atom if possible.
  20856. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  20857. left = left || this.parseBindingAtom();
  20858. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  20859. var node = this.startNodeAt(startPos, startLoc);
  20860. node.left = left;
  20861. node.right = this.parseMaybeAssign();
  20862. return this.finishNode(node, "AssignmentPattern")
  20863. };
  20864. // The following three functions all verify that a node is an lvalue —
  20865. // something that can be bound, or assigned to. In order to do so, they perform
  20866. // a variety of checks:
  20867. //
  20868. // - Check that none of the bound/assigned-to identifiers are reserved words.
  20869. // - Record name declarations for bindings in the appropriate scope.
  20870. // - Check duplicate argument names, if checkClashes is set.
  20871. //
  20872. // If a complex binding pattern is encountered (e.g., object and array
  20873. // destructuring), the entire pattern is recursively checked.
  20874. //
  20875. // There are three versions of checkLVal*() appropriate for different
  20876. // circumstances:
  20877. //
  20878. // - checkLValSimple() shall be used if the syntactic construct supports
  20879. // nothing other than identifiers and member expressions. Parenthesized
  20880. // expressions are also correctly handled. This is generally appropriate for
  20881. // constructs for which the spec says
  20882. //
  20883. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  20884. // > simple.
  20885. //
  20886. // It is also appropriate for checking if an identifier is valid and not
  20887. // defined elsewhere, like import declarations or function/class identifiers.
  20888. //
  20889. // Examples where this is used include:
  20890. // a += …;
  20891. // import a from '…';
  20892. // where a is the node to be checked.
  20893. //
  20894. // - checkLValPattern() shall be used if the syntactic construct supports
  20895. // anything checkLValSimple() supports, as well as object and array
  20896. // destructuring patterns. This is generally appropriate for constructs for
  20897. // which the spec says
  20898. //
  20899. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  20900. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  20901. // > simple.
  20902. //
  20903. // Examples where this is used include:
  20904. // (a = …);
  20905. // const a = …;
  20906. // try { … } catch (a) { … }
  20907. // where a is the node to be checked.
  20908. //
  20909. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  20910. // anything checkLValPattern() supports, as well as default assignment
  20911. // patterns, rest elements, and other constructs that may appear within an
  20912. // object or array destructuring pattern.
  20913. //
  20914. // As a special case, function parameters also use checkLValInnerPattern(),
  20915. // as they also support defaults and rest constructs.
  20916. //
  20917. // These functions deliberately support both assignment and binding constructs,
  20918. // as the logic for both is exceedingly similar. If the node is the target of
  20919. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  20920. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  20921. // BIND_LEXICAL.
  20922. //
  20923. // If the function is called with a non-BIND_NONE bindingType, then
  20924. // additionally a checkClashes object may be specified to allow checking for
  20925. // duplicate argument names. checkClashes is ignored if the provided construct
  20926. // is an assignment (i.e., bindingType is BIND_NONE).
  20927. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  20928. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20929. var isBind = bindingType !== BIND_NONE;
  20930. switch (expr.type) {
  20931. case "Identifier":
  20932. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  20933. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  20934. if (isBind) {
  20935. if (bindingType === BIND_LEXICAL && expr.name === "let")
  20936. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  20937. if (checkClashes) {
  20938. if (hasOwn(checkClashes, expr.name))
  20939. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  20940. checkClashes[expr.name] = true;
  20941. }
  20942. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  20943. }
  20944. break
  20945. case "ChainExpression":
  20946. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  20947. break
  20948. case "MemberExpression":
  20949. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  20950. break
  20951. case "ParenthesizedExpression":
  20952. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  20953. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  20954. default:
  20955. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  20956. }
  20957. };
  20958. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  20959. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20960. switch (expr.type) {
  20961. case "ObjectPattern":
  20962. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  20963. var prop = list[i];
  20964. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  20965. }
  20966. break
  20967. case "ArrayPattern":
  20968. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  20969. var elem = list$1[i$1];
  20970. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  20971. }
  20972. break
  20973. default:
  20974. this.checkLValSimple(expr, bindingType, checkClashes);
  20975. }
  20976. };
  20977. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  20978. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20979. switch (expr.type) {
  20980. case "Property":
  20981. // AssignmentProperty has type === "Property"
  20982. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  20983. break
  20984. case "AssignmentPattern":
  20985. this.checkLValPattern(expr.left, bindingType, checkClashes);
  20986. break
  20987. case "RestElement":
  20988. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  20989. break
  20990. default:
  20991. this.checkLValPattern(expr, bindingType, checkClashes);
  20992. }
  20993. };
  20994. // The algorithm used to determine whether a regexp can appear at a
  20995. // given point in the program is loosely based on sweet.js' approach.
  20996. // See https://github.com/mozilla/sweet.js/wiki/design
  20997. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  20998. this.token = token;
  20999. this.isExpr = !!isExpr;
  21000. this.preserveSpace = !!preserveSpace;
  21001. this.override = override;
  21002. this.generator = !!generator;
  21003. };
  21004. var types$2 = {
  21005. b_stat: new TokContext("{", false),
  21006. b_expr: new TokContext("{", true),
  21007. b_tmpl: new TokContext("${", false),
  21008. p_stat: new TokContext("(", false),
  21009. p_expr: new TokContext("(", true),
  21010. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  21011. f_stat: new TokContext("function", false),
  21012. f_expr: new TokContext("function", true),
  21013. f_expr_gen: new TokContext("function", true, false, null, true),
  21014. f_gen: new TokContext("function", false, false, null, true)
  21015. };
  21016. var pp$6 = Parser$1.prototype;
  21017. pp$6.initialContext = function() {
  21018. return [types$2.b_stat]
  21019. };
  21020. pp$6.curContext = function() {
  21021. return this.context[this.context.length - 1]
  21022. };
  21023. pp$6.braceIsBlock = function(prevType) {
  21024. var parent = this.curContext();
  21025. if (parent === types$2.f_expr || parent === types$2.f_stat)
  21026. { return true }
  21027. if (prevType === types$1.colon && (parent === types$2.b_stat || parent === types$2.b_expr))
  21028. { return !parent.isExpr }
  21029. // The check for `tt.name && exprAllowed` detects whether we are
  21030. // after a `yield` or `of` construct. See the `updateContext` for
  21031. // `tt.name`.
  21032. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  21033. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  21034. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  21035. { return true }
  21036. if (prevType === types$1.braceL)
  21037. { return parent === types$2.b_stat }
  21038. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  21039. { return false }
  21040. return !this.exprAllowed
  21041. };
  21042. pp$6.inGeneratorContext = function() {
  21043. for (var i = this.context.length - 1; i >= 1; i--) {
  21044. var context = this.context[i];
  21045. if (context.token === "function")
  21046. { return context.generator }
  21047. }
  21048. return false
  21049. };
  21050. pp$6.updateContext = function(prevType) {
  21051. var update, type = this.type;
  21052. if (type.keyword && prevType === types$1.dot)
  21053. { this.exprAllowed = false; }
  21054. else if (update = type.updateContext)
  21055. { update.call(this, prevType); }
  21056. else
  21057. { this.exprAllowed = type.beforeExpr; }
  21058. };
  21059. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  21060. pp$6.overrideContext = function(tokenCtx) {
  21061. if (this.curContext() !== tokenCtx) {
  21062. this.context[this.context.length - 1] = tokenCtx;
  21063. }
  21064. };
  21065. // Token-specific context update code
  21066. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  21067. if (this.context.length === 1) {
  21068. this.exprAllowed = true;
  21069. return
  21070. }
  21071. var out = this.context.pop();
  21072. if (out === types$2.b_stat && this.curContext().token === "function") {
  21073. out = this.context.pop();
  21074. }
  21075. this.exprAllowed = !out.isExpr;
  21076. };
  21077. types$1.braceL.updateContext = function(prevType) {
  21078. this.context.push(this.braceIsBlock(prevType) ? types$2.b_stat : types$2.b_expr);
  21079. this.exprAllowed = true;
  21080. };
  21081. types$1.dollarBraceL.updateContext = function() {
  21082. this.context.push(types$2.b_tmpl);
  21083. this.exprAllowed = true;
  21084. };
  21085. types$1.parenL.updateContext = function(prevType) {
  21086. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  21087. this.context.push(statementParens ? types$2.p_stat : types$2.p_expr);
  21088. this.exprAllowed = true;
  21089. };
  21090. types$1.incDec.updateContext = function() {
  21091. // tokExprAllowed stays unchanged
  21092. };
  21093. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  21094. if (prevType.beforeExpr && prevType !== types$1._else &&
  21095. !(prevType === types$1.semi && this.curContext() !== types$2.p_stat) &&
  21096. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  21097. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types$2.b_stat))
  21098. { this.context.push(types$2.f_expr); }
  21099. else
  21100. { this.context.push(types$2.f_stat); }
  21101. this.exprAllowed = false;
  21102. };
  21103. types$1.backQuote.updateContext = function() {
  21104. if (this.curContext() === types$2.q_tmpl)
  21105. { this.context.pop(); }
  21106. else
  21107. { this.context.push(types$2.q_tmpl); }
  21108. this.exprAllowed = false;
  21109. };
  21110. types$1.star.updateContext = function(prevType) {
  21111. if (prevType === types$1._function) {
  21112. var index = this.context.length - 1;
  21113. if (this.context[index] === types$2.f_expr)
  21114. { this.context[index] = types$2.f_expr_gen; }
  21115. else
  21116. { this.context[index] = types$2.f_gen; }
  21117. }
  21118. this.exprAllowed = true;
  21119. };
  21120. types$1.name.updateContext = function(prevType) {
  21121. var allowed = false;
  21122. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  21123. if (this.value === "of" && !this.exprAllowed ||
  21124. this.value === "yield" && this.inGeneratorContext())
  21125. { allowed = true; }
  21126. }
  21127. this.exprAllowed = allowed;
  21128. };
  21129. // A recursive descent parser operates by defining functions for all
  21130. // syntactic elements, and recursively calling those, each function
  21131. // advancing the input stream and returning an AST node. Precedence
  21132. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  21133. // instead of `(!x)[1]` is handled by the fact that the parser
  21134. // function that parses unary prefix operators is called first, and
  21135. // in turn calls the function that parses `[]` subscripts — that
  21136. // way, it'll receive the node for `x[1]` already parsed, and wraps
  21137. // *that* in the unary operator node.
  21138. //
  21139. // Acorn uses an [operator precedence parser][opp] to handle binary
  21140. // operator precedence, because it is much more compact than using
  21141. // the technique outlined above, which uses different, nesting
  21142. // functions to specify precedence, for all of the ten binary
  21143. // precedence levels that JavaScript defines.
  21144. //
  21145. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  21146. var pp$5 = Parser$1.prototype;
  21147. // Check if property name clashes with already added.
  21148. // Object/class getters and setters are not allowed to clash —
  21149. // either with each other or with an init property — and in
  21150. // strict mode, init properties are also not allowed to be repeated.
  21151. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  21152. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  21153. { return }
  21154. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  21155. { return }
  21156. var key = prop.key;
  21157. var name;
  21158. switch (key.type) {
  21159. case "Identifier": name = key.name; break
  21160. case "Literal": name = String(key.value); break
  21161. default: return
  21162. }
  21163. var kind = prop.kind;
  21164. if (this.options.ecmaVersion >= 6) {
  21165. if (name === "__proto__" && kind === "init") {
  21166. if (propHash.proto) {
  21167. if (refDestructuringErrors) {
  21168. if (refDestructuringErrors.doubleProto < 0) {
  21169. refDestructuringErrors.doubleProto = key.start;
  21170. }
  21171. } else {
  21172. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  21173. }
  21174. }
  21175. propHash.proto = true;
  21176. }
  21177. return
  21178. }
  21179. name = "$" + name;
  21180. var other = propHash[name];
  21181. if (other) {
  21182. var redefinition;
  21183. if (kind === "init") {
  21184. redefinition = this.strict && other.init || other.get || other.set;
  21185. } else {
  21186. redefinition = other.init || other[kind];
  21187. }
  21188. if (redefinition)
  21189. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  21190. } else {
  21191. other = propHash[name] = {
  21192. init: false,
  21193. get: false,
  21194. set: false
  21195. };
  21196. }
  21197. other[kind] = true;
  21198. };
  21199. // ### Expression parsing
  21200. // These nest, from the most general expression type at the top to
  21201. // 'atomic', nondivisible expression types at the bottom. Most of
  21202. // the functions will simply let the function(s) below them parse,
  21203. // and, *if* the syntactic construct they handle is present, wrap
  21204. // the AST node that the inner parser gave them in another node.
  21205. // Parse a full expression. The optional arguments are used to
  21206. // forbid the `in` operator (in for loops initalization expressions)
  21207. // and provide reference for storing '=' operator inside shorthand
  21208. // property assignment in contexts where both object expression
  21209. // and object pattern might appear (so it's possible to raise
  21210. // delayed syntax error at correct position).
  21211. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  21212. var startPos = this.start, startLoc = this.startLoc;
  21213. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  21214. if (this.type === types$1.comma) {
  21215. var node = this.startNodeAt(startPos, startLoc);
  21216. node.expressions = [expr];
  21217. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  21218. return this.finishNode(node, "SequenceExpression")
  21219. }
  21220. return expr
  21221. };
  21222. // Parse an assignment expression. This includes applications of
  21223. // operators like `+=`.
  21224. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  21225. if (this.isContextual("yield")) {
  21226. if (this.inGenerator) { return this.parseYield(forInit) }
  21227. // The tokenizer will assume an expression is allowed after
  21228. // `yield`, but this isn't that kind of yield
  21229. else { this.exprAllowed = false; }
  21230. }
  21231. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  21232. if (refDestructuringErrors) {
  21233. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  21234. oldTrailingComma = refDestructuringErrors.trailingComma;
  21235. oldDoubleProto = refDestructuringErrors.doubleProto;
  21236. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  21237. } else {
  21238. refDestructuringErrors = new DestructuringErrors;
  21239. ownDestructuringErrors = true;
  21240. }
  21241. var startPos = this.start, startLoc = this.startLoc;
  21242. if (this.type === types$1.parenL || this.type === types$1.name) {
  21243. this.potentialArrowAt = this.start;
  21244. this.potentialArrowInForAwait = forInit === "await";
  21245. }
  21246. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  21247. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  21248. if (this.type.isAssign) {
  21249. var node = this.startNodeAt(startPos, startLoc);
  21250. node.operator = this.value;
  21251. if (this.type === types$1.eq)
  21252. { left = this.toAssignable(left, false, refDestructuringErrors); }
  21253. if (!ownDestructuringErrors) {
  21254. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  21255. }
  21256. if (refDestructuringErrors.shorthandAssign >= left.start)
  21257. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  21258. if (this.type === types$1.eq)
  21259. { this.checkLValPattern(left); }
  21260. else
  21261. { this.checkLValSimple(left); }
  21262. node.left = left;
  21263. this.next();
  21264. node.right = this.parseMaybeAssign(forInit);
  21265. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  21266. return this.finishNode(node, "AssignmentExpression")
  21267. } else {
  21268. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  21269. }
  21270. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  21271. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  21272. return left
  21273. };
  21274. // Parse a ternary conditional (`?:`) operator.
  21275. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  21276. var startPos = this.start, startLoc = this.startLoc;
  21277. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  21278. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  21279. if (this.eat(types$1.question)) {
  21280. var node = this.startNodeAt(startPos, startLoc);
  21281. node.test = expr;
  21282. node.consequent = this.parseMaybeAssign();
  21283. this.expect(types$1.colon);
  21284. node.alternate = this.parseMaybeAssign(forInit);
  21285. return this.finishNode(node, "ConditionalExpression")
  21286. }
  21287. return expr
  21288. };
  21289. // Start the precedence parser.
  21290. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  21291. var startPos = this.start, startLoc = this.startLoc;
  21292. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  21293. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  21294. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  21295. };
  21296. // Parse binary operators with the operator precedence parsing
  21297. // algorithm. `left` is the left-hand side of the operator.
  21298. // `minPrec` provides context that allows the function to stop and
  21299. // defer further parser to one of its callers when it encounters an
  21300. // operator that has a lower precedence than the set it is parsing.
  21301. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  21302. var prec = this.type.binop;
  21303. if (prec != null && (!forInit || this.type !== types$1._in)) {
  21304. if (prec > minPrec) {
  21305. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  21306. var coalesce = this.type === types$1.coalesce;
  21307. if (coalesce) {
  21308. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  21309. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  21310. prec = types$1.logicalAND.binop;
  21311. }
  21312. var op = this.value;
  21313. this.next();
  21314. var startPos = this.start, startLoc = this.startLoc;
  21315. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  21316. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  21317. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  21318. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  21319. }
  21320. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  21321. }
  21322. }
  21323. return left
  21324. };
  21325. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  21326. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  21327. var node = this.startNodeAt(startPos, startLoc);
  21328. node.left = left;
  21329. node.operator = op;
  21330. node.right = right;
  21331. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  21332. };
  21333. // Parse unary operators, both prefix and postfix.
  21334. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  21335. var startPos = this.start, startLoc = this.startLoc, expr;
  21336. if (this.isContextual("await") && this.canAwait) {
  21337. expr = this.parseAwait(forInit);
  21338. sawUnary = true;
  21339. } else if (this.type.prefix) {
  21340. var node = this.startNode(), update = this.type === types$1.incDec;
  21341. node.operator = this.value;
  21342. node.prefix = true;
  21343. this.next();
  21344. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  21345. this.checkExpressionErrors(refDestructuringErrors, true);
  21346. if (update) { this.checkLValSimple(node.argument); }
  21347. else if (this.strict && node.operator === "delete" &&
  21348. node.argument.type === "Identifier")
  21349. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  21350. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  21351. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  21352. else { sawUnary = true; }
  21353. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  21354. } else if (!sawUnary && this.type === types$1.privateId) {
  21355. if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); }
  21356. expr = this.parsePrivateIdent();
  21357. // only could be private fields in 'in', such as #x in obj
  21358. if (this.type !== types$1._in) { this.unexpected(); }
  21359. } else {
  21360. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  21361. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  21362. while (this.type.postfix && !this.canInsertSemicolon()) {
  21363. var node$1 = this.startNodeAt(startPos, startLoc);
  21364. node$1.operator = this.value;
  21365. node$1.prefix = false;
  21366. node$1.argument = expr;
  21367. this.checkLValSimple(expr);
  21368. this.next();
  21369. expr = this.finishNode(node$1, "UpdateExpression");
  21370. }
  21371. }
  21372. if (!incDec && this.eat(types$1.starstar)) {
  21373. if (sawUnary)
  21374. { this.unexpected(this.lastTokStart); }
  21375. else
  21376. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  21377. } else {
  21378. return expr
  21379. }
  21380. };
  21381. function isPrivateFieldAccess(node) {
  21382. return (
  21383. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  21384. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  21385. )
  21386. }
  21387. // Parse call, dot, and `[]`-subscript expressions.
  21388. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  21389. var startPos = this.start, startLoc = this.startLoc;
  21390. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  21391. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  21392. { return expr }
  21393. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  21394. if (refDestructuringErrors && result.type === "MemberExpression") {
  21395. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  21396. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  21397. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  21398. }
  21399. return result
  21400. };
  21401. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  21402. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  21403. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  21404. this.potentialArrowAt === base.start;
  21405. var optionalChained = false;
  21406. while (true) {
  21407. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  21408. if (element.optional) { optionalChained = true; }
  21409. if (element === base || element.type === "ArrowFunctionExpression") {
  21410. if (optionalChained) {
  21411. var chainNode = this.startNodeAt(startPos, startLoc);
  21412. chainNode.expression = element;
  21413. element = this.finishNode(chainNode, "ChainExpression");
  21414. }
  21415. return element
  21416. }
  21417. base = element;
  21418. }
  21419. };
  21420. pp$5.shouldParseAsyncArrow = function() {
  21421. return !this.canInsertSemicolon() && this.eat(types$1.arrow)
  21422. };
  21423. pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  21424. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  21425. };
  21426. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  21427. var optionalSupported = this.options.ecmaVersion >= 11;
  21428. var optional = optionalSupported && this.eat(types$1.questionDot);
  21429. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  21430. var computed = this.eat(types$1.bracketL);
  21431. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  21432. var node = this.startNodeAt(startPos, startLoc);
  21433. node.object = base;
  21434. if (computed) {
  21435. node.property = this.parseExpression();
  21436. this.expect(types$1.bracketR);
  21437. } else if (this.type === types$1.privateId && base.type !== "Super") {
  21438. node.property = this.parsePrivateIdent();
  21439. } else {
  21440. node.property = this.parseIdent(this.options.allowReserved !== "never");
  21441. }
  21442. node.computed = !!computed;
  21443. if (optionalSupported) {
  21444. node.optional = optional;
  21445. }
  21446. base = this.finishNode(node, "MemberExpression");
  21447. } else if (!noCalls && this.eat(types$1.parenL)) {
  21448. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21449. this.yieldPos = 0;
  21450. this.awaitPos = 0;
  21451. this.awaitIdentPos = 0;
  21452. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  21453. if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
  21454. this.checkPatternErrors(refDestructuringErrors, false);
  21455. this.checkYieldAwaitInDefaultParams();
  21456. if (this.awaitIdentPos > 0)
  21457. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  21458. this.yieldPos = oldYieldPos;
  21459. this.awaitPos = oldAwaitPos;
  21460. this.awaitIdentPos = oldAwaitIdentPos;
  21461. return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
  21462. }
  21463. this.checkExpressionErrors(refDestructuringErrors, true);
  21464. this.yieldPos = oldYieldPos || this.yieldPos;
  21465. this.awaitPos = oldAwaitPos || this.awaitPos;
  21466. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  21467. var node$1 = this.startNodeAt(startPos, startLoc);
  21468. node$1.callee = base;
  21469. node$1.arguments = exprList;
  21470. if (optionalSupported) {
  21471. node$1.optional = optional;
  21472. }
  21473. base = this.finishNode(node$1, "CallExpression");
  21474. } else if (this.type === types$1.backQuote) {
  21475. if (optional || optionalChained) {
  21476. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  21477. }
  21478. var node$2 = this.startNodeAt(startPos, startLoc);
  21479. node$2.tag = base;
  21480. node$2.quasi = this.parseTemplate({isTagged: true});
  21481. base = this.finishNode(node$2, "TaggedTemplateExpression");
  21482. }
  21483. return base
  21484. };
  21485. // Parse an atomic expression — either a single token that is an
  21486. // expression, an expression started by a keyword like `function` or
  21487. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  21488. // or `{}`.
  21489. pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  21490. // If a division operator appears in an expression position, the
  21491. // tokenizer got confused, and we force it to read a regexp instead.
  21492. if (this.type === types$1.slash) { this.readRegexp(); }
  21493. var node, canBeArrow = this.potentialArrowAt === this.start;
  21494. switch (this.type) {
  21495. case types$1._super:
  21496. if (!this.allowSuper)
  21497. { this.raise(this.start, "'super' keyword outside a method"); }
  21498. node = this.startNode();
  21499. this.next();
  21500. if (this.type === types$1.parenL && !this.allowDirectSuper)
  21501. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  21502. // The `super` keyword can appear at below:
  21503. // SuperProperty:
  21504. // super [ Expression ]
  21505. // super . IdentifierName
  21506. // SuperCall:
  21507. // super ( Arguments )
  21508. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  21509. { this.unexpected(); }
  21510. return this.finishNode(node, "Super")
  21511. case types$1._this:
  21512. node = this.startNode();
  21513. this.next();
  21514. return this.finishNode(node, "ThisExpression")
  21515. case types$1.name:
  21516. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  21517. var id = this.parseIdent(false);
  21518. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  21519. this.overrideContext(types$2.f_expr);
  21520. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  21521. }
  21522. if (canBeArrow && !this.canInsertSemicolon()) {
  21523. if (this.eat(types$1.arrow))
  21524. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  21525. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  21526. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  21527. id = this.parseIdent(false);
  21528. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  21529. { this.unexpected(); }
  21530. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  21531. }
  21532. }
  21533. return id
  21534. case types$1.regexp:
  21535. var value = this.value;
  21536. node = this.parseLiteral(value.value);
  21537. node.regex = {pattern: value.pattern, flags: value.flags};
  21538. return node
  21539. case types$1.num: case types$1.string:
  21540. return this.parseLiteral(this.value)
  21541. case types$1._null: case types$1._true: case types$1._false:
  21542. node = this.startNode();
  21543. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  21544. node.raw = this.type.keyword;
  21545. this.next();
  21546. return this.finishNode(node, "Literal")
  21547. case types$1.parenL:
  21548. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  21549. if (refDestructuringErrors) {
  21550. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  21551. { refDestructuringErrors.parenthesizedAssign = start; }
  21552. if (refDestructuringErrors.parenthesizedBind < 0)
  21553. { refDestructuringErrors.parenthesizedBind = start; }
  21554. }
  21555. return expr
  21556. case types$1.bracketL:
  21557. node = this.startNode();
  21558. this.next();
  21559. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  21560. return this.finishNode(node, "ArrayExpression")
  21561. case types$1.braceL:
  21562. this.overrideContext(types$2.b_expr);
  21563. return this.parseObj(false, refDestructuringErrors)
  21564. case types$1._function:
  21565. node = this.startNode();
  21566. this.next();
  21567. return this.parseFunction(node, 0)
  21568. case types$1._class:
  21569. return this.parseClass(this.startNode(), false)
  21570. case types$1._new:
  21571. return this.parseNew()
  21572. case types$1.backQuote:
  21573. return this.parseTemplate()
  21574. case types$1._import:
  21575. if (this.options.ecmaVersion >= 11) {
  21576. return this.parseExprImport(forNew)
  21577. } else {
  21578. return this.unexpected()
  21579. }
  21580. default:
  21581. return this.parseExprAtomDefault()
  21582. }
  21583. };
  21584. pp$5.parseExprAtomDefault = function() {
  21585. this.unexpected();
  21586. };
  21587. pp$5.parseExprImport = function(forNew) {
  21588. var node = this.startNode();
  21589. // Consume `import` as an identifier for `import.meta`.
  21590. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  21591. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  21592. var meta = this.parseIdent(true);
  21593. if (this.type === types$1.parenL && !forNew) {
  21594. return this.parseDynamicImport(node)
  21595. } else if (this.type === types$1.dot) {
  21596. node.meta = meta;
  21597. return this.parseImportMeta(node)
  21598. } else {
  21599. this.unexpected();
  21600. }
  21601. };
  21602. pp$5.parseDynamicImport = function(node) {
  21603. this.next(); // skip `(`
  21604. // Parse node.source.
  21605. node.source = this.parseMaybeAssign();
  21606. // Verify ending.
  21607. if (!this.eat(types$1.parenR)) {
  21608. var errorPos = this.start;
  21609. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  21610. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  21611. } else {
  21612. this.unexpected(errorPos);
  21613. }
  21614. }
  21615. return this.finishNode(node, "ImportExpression")
  21616. };
  21617. pp$5.parseImportMeta = function(node) {
  21618. this.next(); // skip `.`
  21619. var containsEsc = this.containsEsc;
  21620. node.property = this.parseIdent(true);
  21621. if (node.property.name !== "meta")
  21622. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  21623. if (containsEsc)
  21624. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  21625. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  21626. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  21627. return this.finishNode(node, "MetaProperty")
  21628. };
  21629. pp$5.parseLiteral = function(value) {
  21630. var node = this.startNode();
  21631. node.value = value;
  21632. node.raw = this.input.slice(this.start, this.end);
  21633. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  21634. this.next();
  21635. return this.finishNode(node, "Literal")
  21636. };
  21637. pp$5.parseParenExpression = function() {
  21638. this.expect(types$1.parenL);
  21639. var val = this.parseExpression();
  21640. this.expect(types$1.parenR);
  21641. return val
  21642. };
  21643. pp$5.shouldParseArrow = function(exprList) {
  21644. return !this.canInsertSemicolon()
  21645. };
  21646. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  21647. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  21648. if (this.options.ecmaVersion >= 6) {
  21649. this.next();
  21650. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  21651. var exprList = [], first = true, lastIsComma = false;
  21652. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  21653. this.yieldPos = 0;
  21654. this.awaitPos = 0;
  21655. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  21656. while (this.type !== types$1.parenR) {
  21657. first ? first = false : this.expect(types$1.comma);
  21658. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  21659. lastIsComma = true;
  21660. break
  21661. } else if (this.type === types$1.ellipsis) {
  21662. spreadStart = this.start;
  21663. exprList.push(this.parseParenItem(this.parseRestBinding()));
  21664. if (this.type === types$1.comma) {
  21665. this.raiseRecoverable(
  21666. this.start,
  21667. "Comma is not permitted after the rest element"
  21668. );
  21669. }
  21670. break
  21671. } else {
  21672. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  21673. }
  21674. }
  21675. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  21676. this.expect(types$1.parenR);
  21677. if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
  21678. this.checkPatternErrors(refDestructuringErrors, false);
  21679. this.checkYieldAwaitInDefaultParams();
  21680. this.yieldPos = oldYieldPos;
  21681. this.awaitPos = oldAwaitPos;
  21682. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  21683. }
  21684. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  21685. if (spreadStart) { this.unexpected(spreadStart); }
  21686. this.checkExpressionErrors(refDestructuringErrors, true);
  21687. this.yieldPos = oldYieldPos || this.yieldPos;
  21688. this.awaitPos = oldAwaitPos || this.awaitPos;
  21689. if (exprList.length > 1) {
  21690. val = this.startNodeAt(innerStartPos, innerStartLoc);
  21691. val.expressions = exprList;
  21692. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  21693. } else {
  21694. val = exprList[0];
  21695. }
  21696. } else {
  21697. val = this.parseParenExpression();
  21698. }
  21699. if (this.options.preserveParens) {
  21700. var par = this.startNodeAt(startPos, startLoc);
  21701. par.expression = val;
  21702. return this.finishNode(par, "ParenthesizedExpression")
  21703. } else {
  21704. return val
  21705. }
  21706. };
  21707. pp$5.parseParenItem = function(item) {
  21708. return item
  21709. };
  21710. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  21711. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  21712. };
  21713. // New's precedence is slightly tricky. It must allow its argument to
  21714. // be a `[]` or dot subscript expression, but not a call — at least,
  21715. // not without wrapping it in parentheses. Thus, it uses the noCalls
  21716. // argument to parseSubscripts to prevent it from consuming the
  21717. // argument list.
  21718. var empty = [];
  21719. pp$5.parseNew = function() {
  21720. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  21721. var node = this.startNode();
  21722. var meta = this.parseIdent(true);
  21723. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  21724. node.meta = meta;
  21725. var containsEsc = this.containsEsc;
  21726. node.property = this.parseIdent(true);
  21727. if (node.property.name !== "target")
  21728. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  21729. if (containsEsc)
  21730. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  21731. if (!this.allowNewDotTarget)
  21732. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  21733. return this.finishNode(node, "MetaProperty")
  21734. }
  21735. var startPos = this.start, startLoc = this.startLoc;
  21736. node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  21737. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  21738. else { node.arguments = empty; }
  21739. return this.finishNode(node, "NewExpression")
  21740. };
  21741. // Parse template expression.
  21742. pp$5.parseTemplateElement = function(ref) {
  21743. var isTagged = ref.isTagged;
  21744. var elem = this.startNode();
  21745. if (this.type === types$1.invalidTemplate) {
  21746. if (!isTagged) {
  21747. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  21748. }
  21749. elem.value = {
  21750. raw: this.value,
  21751. cooked: null
  21752. };
  21753. } else {
  21754. elem.value = {
  21755. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  21756. cooked: this.value
  21757. };
  21758. }
  21759. this.next();
  21760. elem.tail = this.type === types$1.backQuote;
  21761. return this.finishNode(elem, "TemplateElement")
  21762. };
  21763. pp$5.parseTemplate = function(ref) {
  21764. if ( ref === void 0 ) ref = {};
  21765. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  21766. var node = this.startNode();
  21767. this.next();
  21768. node.expressions = [];
  21769. var curElt = this.parseTemplateElement({isTagged: isTagged});
  21770. node.quasis = [curElt];
  21771. while (!curElt.tail) {
  21772. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  21773. this.expect(types$1.dollarBraceL);
  21774. node.expressions.push(this.parseExpression());
  21775. this.expect(types$1.braceR);
  21776. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  21777. }
  21778. this.next();
  21779. return this.finishNode(node, "TemplateLiteral")
  21780. };
  21781. pp$5.isAsyncProp = function(prop) {
  21782. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  21783. (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
  21784. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  21785. };
  21786. // Parse an object literal or binding pattern.
  21787. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  21788. var node = this.startNode(), first = true, propHash = {};
  21789. node.properties = [];
  21790. this.next();
  21791. while (!this.eat(types$1.braceR)) {
  21792. if (!first) {
  21793. this.expect(types$1.comma);
  21794. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  21795. } else { first = false; }
  21796. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  21797. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  21798. node.properties.push(prop);
  21799. }
  21800. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  21801. };
  21802. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  21803. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  21804. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  21805. if (isPattern) {
  21806. prop.argument = this.parseIdent(false);
  21807. if (this.type === types$1.comma) {
  21808. this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
  21809. }
  21810. return this.finishNode(prop, "RestElement")
  21811. }
  21812. // Parse argument.
  21813. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  21814. // To disallow trailing comma via `this.toAssignable()`.
  21815. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  21816. refDestructuringErrors.trailingComma = this.start;
  21817. }
  21818. // Finish
  21819. return this.finishNode(prop, "SpreadElement")
  21820. }
  21821. if (this.options.ecmaVersion >= 6) {
  21822. prop.method = false;
  21823. prop.shorthand = false;
  21824. if (isPattern || refDestructuringErrors) {
  21825. startPos = this.start;
  21826. startLoc = this.startLoc;
  21827. }
  21828. if (!isPattern)
  21829. { isGenerator = this.eat(types$1.star); }
  21830. }
  21831. var containsEsc = this.containsEsc;
  21832. this.parsePropertyName(prop);
  21833. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  21834. isAsync = true;
  21835. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  21836. this.parsePropertyName(prop);
  21837. } else {
  21838. isAsync = false;
  21839. }
  21840. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  21841. return this.finishNode(prop, "Property")
  21842. };
  21843. pp$5.parseGetterSetter = function(prop) {
  21844. prop.kind = prop.key.name;
  21845. this.parsePropertyName(prop);
  21846. prop.value = this.parseMethod(false);
  21847. var paramCount = prop.kind === "get" ? 0 : 1;
  21848. if (prop.value.params.length !== paramCount) {
  21849. var start = prop.value.start;
  21850. if (prop.kind === "get")
  21851. { this.raiseRecoverable(start, "getter should have no params"); }
  21852. else
  21853. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  21854. } else {
  21855. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  21856. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  21857. }
  21858. };
  21859. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  21860. if ((isGenerator || isAsync) && this.type === types$1.colon)
  21861. { this.unexpected(); }
  21862. if (this.eat(types$1.colon)) {
  21863. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  21864. prop.kind = "init";
  21865. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  21866. if (isPattern) { this.unexpected(); }
  21867. prop.kind = "init";
  21868. prop.method = true;
  21869. prop.value = this.parseMethod(isGenerator, isAsync);
  21870. } else if (!isPattern && !containsEsc &&
  21871. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  21872. (prop.key.name === "get" || prop.key.name === "set") &&
  21873. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  21874. if (isGenerator || isAsync) { this.unexpected(); }
  21875. this.parseGetterSetter(prop);
  21876. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  21877. if (isGenerator || isAsync) { this.unexpected(); }
  21878. this.checkUnreserved(prop.key);
  21879. if (prop.key.name === "await" && !this.awaitIdentPos)
  21880. { this.awaitIdentPos = startPos; }
  21881. prop.kind = "init";
  21882. if (isPattern) {
  21883. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  21884. } else if (this.type === types$1.eq && refDestructuringErrors) {
  21885. if (refDestructuringErrors.shorthandAssign < 0)
  21886. { refDestructuringErrors.shorthandAssign = this.start; }
  21887. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  21888. } else {
  21889. prop.value = this.copyNode(prop.key);
  21890. }
  21891. prop.shorthand = true;
  21892. } else { this.unexpected(); }
  21893. };
  21894. pp$5.parsePropertyName = function(prop) {
  21895. if (this.options.ecmaVersion >= 6) {
  21896. if (this.eat(types$1.bracketL)) {
  21897. prop.computed = true;
  21898. prop.key = this.parseMaybeAssign();
  21899. this.expect(types$1.bracketR);
  21900. return prop.key
  21901. } else {
  21902. prop.computed = false;
  21903. }
  21904. }
  21905. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  21906. };
  21907. // Initialize empty function node.
  21908. pp$5.initFunction = function(node) {
  21909. node.id = null;
  21910. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  21911. if (this.options.ecmaVersion >= 8) { node.async = false; }
  21912. };
  21913. // Parse object or class method.
  21914. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  21915. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21916. this.initFunction(node);
  21917. if (this.options.ecmaVersion >= 6)
  21918. { node.generator = isGenerator; }
  21919. if (this.options.ecmaVersion >= 8)
  21920. { node.async = !!isAsync; }
  21921. this.yieldPos = 0;
  21922. this.awaitPos = 0;
  21923. this.awaitIdentPos = 0;
  21924. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  21925. this.expect(types$1.parenL);
  21926. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  21927. this.checkYieldAwaitInDefaultParams();
  21928. this.parseFunctionBody(node, false, true, false);
  21929. this.yieldPos = oldYieldPos;
  21930. this.awaitPos = oldAwaitPos;
  21931. this.awaitIdentPos = oldAwaitIdentPos;
  21932. return this.finishNode(node, "FunctionExpression")
  21933. };
  21934. // Parse arrow function expression with given parameters.
  21935. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  21936. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21937. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  21938. this.initFunction(node);
  21939. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  21940. this.yieldPos = 0;
  21941. this.awaitPos = 0;
  21942. this.awaitIdentPos = 0;
  21943. node.params = this.toAssignableList(params, true);
  21944. this.parseFunctionBody(node, true, false, forInit);
  21945. this.yieldPos = oldYieldPos;
  21946. this.awaitPos = oldAwaitPos;
  21947. this.awaitIdentPos = oldAwaitIdentPos;
  21948. return this.finishNode(node, "ArrowFunctionExpression")
  21949. };
  21950. // Parse function body and check parameters.
  21951. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  21952. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  21953. var oldStrict = this.strict, useStrict = false;
  21954. if (isExpression) {
  21955. node.body = this.parseMaybeAssign(forInit);
  21956. node.expression = true;
  21957. this.checkParams(node, false);
  21958. } else {
  21959. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  21960. if (!oldStrict || nonSimple) {
  21961. useStrict = this.strictDirective(this.end);
  21962. // If this is a strict mode function, verify that argument names
  21963. // are not repeated, and it does not try to bind the words `eval`
  21964. // or `arguments`.
  21965. if (useStrict && nonSimple)
  21966. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  21967. }
  21968. // Start a new scope with regard to labels and the `inFunction`
  21969. // flag (restore them to their old value afterwards).
  21970. var oldLabels = this.labels;
  21971. this.labels = [];
  21972. if (useStrict) { this.strict = true; }
  21973. // Add the params to varDeclaredNames to ensure that an error is thrown
  21974. // if a let/const declaration in the function clashes with one of the params.
  21975. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  21976. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  21977. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  21978. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  21979. node.expression = false;
  21980. this.adaptDirectivePrologue(node.body.body);
  21981. this.labels = oldLabels;
  21982. }
  21983. this.exitScope();
  21984. };
  21985. pp$5.isSimpleParamList = function(params) {
  21986. for (var i = 0, list = params; i < list.length; i += 1)
  21987. {
  21988. var param = list[i];
  21989. if (param.type !== "Identifier") { return false
  21990. } }
  21991. return true
  21992. };
  21993. // Checks function params for various disallowed patterns such as using "eval"
  21994. // or "arguments" and duplicate parameters.
  21995. pp$5.checkParams = function(node, allowDuplicates) {
  21996. var nameHash = Object.create(null);
  21997. for (var i = 0, list = node.params; i < list.length; i += 1)
  21998. {
  21999. var param = list[i];
  22000. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  22001. }
  22002. };
  22003. // Parses a comma-separated list of expressions, and returns them as
  22004. // an array. `close` is the token type that ends the list, and
  22005. // `allowEmpty` can be turned on to allow subsequent commas with
  22006. // nothing in between them to be parsed as `null` (which is needed
  22007. // for array literals).
  22008. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  22009. var elts = [], first = true;
  22010. while (!this.eat(close)) {
  22011. if (!first) {
  22012. this.expect(types$1.comma);
  22013. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  22014. } else { first = false; }
  22015. var elt = (void 0);
  22016. if (allowEmpty && this.type === types$1.comma)
  22017. { elt = null; }
  22018. else if (this.type === types$1.ellipsis) {
  22019. elt = this.parseSpread(refDestructuringErrors);
  22020. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  22021. { refDestructuringErrors.trailingComma = this.start; }
  22022. } else {
  22023. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  22024. }
  22025. elts.push(elt);
  22026. }
  22027. return elts
  22028. };
  22029. pp$5.checkUnreserved = function(ref) {
  22030. var start = ref.start;
  22031. var end = ref.end;
  22032. var name = ref.name;
  22033. if (this.inGenerator && name === "yield")
  22034. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  22035. if (this.inAsync && name === "await")
  22036. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  22037. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  22038. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  22039. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  22040. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  22041. if (this.keywords.test(name))
  22042. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  22043. if (this.options.ecmaVersion < 6 &&
  22044. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  22045. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  22046. if (re.test(name)) {
  22047. if (!this.inAsync && name === "await")
  22048. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  22049. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  22050. }
  22051. };
  22052. // Parse the next token as an identifier. If `liberal` is true (used
  22053. // when parsing properties), it will also convert keywords into
  22054. // identifiers.
  22055. pp$5.parseIdent = function(liberal) {
  22056. var node = this.parseIdentNode();
  22057. this.next(!!liberal);
  22058. this.finishNode(node, "Identifier");
  22059. if (!liberal) {
  22060. this.checkUnreserved(node);
  22061. if (node.name === "await" && !this.awaitIdentPos)
  22062. { this.awaitIdentPos = node.start; }
  22063. }
  22064. return node
  22065. };
  22066. pp$5.parseIdentNode = function() {
  22067. var node = this.startNode();
  22068. if (this.type === types$1.name) {
  22069. node.name = this.value;
  22070. } else if (this.type.keyword) {
  22071. node.name = this.type.keyword;
  22072. // To fix https://github.com/acornjs/acorn/issues/575
  22073. // `class` and `function` keywords push new context into this.context.
  22074. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  22075. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  22076. if ((node.name === "class" || node.name === "function") &&
  22077. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  22078. this.context.pop();
  22079. }
  22080. } else {
  22081. this.unexpected();
  22082. }
  22083. return node
  22084. };
  22085. pp$5.parsePrivateIdent = function() {
  22086. var node = this.startNode();
  22087. if (this.type === types$1.privateId) {
  22088. node.name = this.value;
  22089. } else {
  22090. this.unexpected();
  22091. }
  22092. this.next();
  22093. this.finishNode(node, "PrivateIdentifier");
  22094. // For validating existence
  22095. if (this.options.checkPrivateFields) {
  22096. if (this.privateNameStack.length === 0) {
  22097. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  22098. } else {
  22099. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  22100. }
  22101. }
  22102. return node
  22103. };
  22104. // Parses yield expression inside generator.
  22105. pp$5.parseYield = function(forInit) {
  22106. if (!this.yieldPos) { this.yieldPos = this.start; }
  22107. var node = this.startNode();
  22108. this.next();
  22109. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  22110. node.delegate = false;
  22111. node.argument = null;
  22112. } else {
  22113. node.delegate = this.eat(types$1.star);
  22114. node.argument = this.parseMaybeAssign(forInit);
  22115. }
  22116. return this.finishNode(node, "YieldExpression")
  22117. };
  22118. pp$5.parseAwait = function(forInit) {
  22119. if (!this.awaitPos) { this.awaitPos = this.start; }
  22120. var node = this.startNode();
  22121. this.next();
  22122. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  22123. return this.finishNode(node, "AwaitExpression")
  22124. };
  22125. var pp$4 = Parser$1.prototype;
  22126. // This function is used to raise exceptions on parse errors. It
  22127. // takes an offset integer (into the current `input`) to indicate
  22128. // the location of the error, attaches the position to the end
  22129. // of the error message, and then raises a `SyntaxError` with that
  22130. // message.
  22131. pp$4.raise = function(pos, message) {
  22132. var loc = getLineInfo(this.input, pos);
  22133. message += " (" + loc.line + ":" + loc.column + ")";
  22134. var err = new SyntaxError(message);
  22135. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  22136. throw err
  22137. };
  22138. pp$4.raiseRecoverable = pp$4.raise;
  22139. pp$4.curPosition = function() {
  22140. if (this.options.locations) {
  22141. return new Position(this.curLine, this.pos - this.lineStart)
  22142. }
  22143. };
  22144. var pp$3 = Parser$1.prototype;
  22145. var Scope = function Scope(flags) {
  22146. this.flags = flags;
  22147. // A list of var-declared names in the current lexical scope
  22148. this.var = [];
  22149. // A list of lexically-declared names in the current lexical scope
  22150. this.lexical = [];
  22151. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  22152. this.functions = [];
  22153. // A switch to disallow the identifier reference 'arguments'
  22154. this.inClassFieldInit = false;
  22155. };
  22156. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  22157. pp$3.enterScope = function(flags) {
  22158. this.scopeStack.push(new Scope(flags));
  22159. };
  22160. pp$3.exitScope = function() {
  22161. this.scopeStack.pop();
  22162. };
  22163. // The spec says:
  22164. // > At the top level of a function, or script, function declarations are
  22165. // > treated like var declarations rather than like lexical declarations.
  22166. pp$3.treatFunctionsAsVarInScope = function(scope) {
  22167. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  22168. };
  22169. pp$3.declareName = function(name, bindingType, pos) {
  22170. var redeclared = false;
  22171. if (bindingType === BIND_LEXICAL) {
  22172. var scope = this.currentScope();
  22173. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  22174. scope.lexical.push(name);
  22175. if (this.inModule && (scope.flags & SCOPE_TOP))
  22176. { delete this.undefinedExports[name]; }
  22177. } else if (bindingType === BIND_SIMPLE_CATCH) {
  22178. var scope$1 = this.currentScope();
  22179. scope$1.lexical.push(name);
  22180. } else if (bindingType === BIND_FUNCTION) {
  22181. var scope$2 = this.currentScope();
  22182. if (this.treatFunctionsAsVar)
  22183. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  22184. else
  22185. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  22186. scope$2.functions.push(name);
  22187. } else {
  22188. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  22189. var scope$3 = this.scopeStack[i];
  22190. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  22191. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  22192. redeclared = true;
  22193. break
  22194. }
  22195. scope$3.var.push(name);
  22196. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  22197. { delete this.undefinedExports[name]; }
  22198. if (scope$3.flags & SCOPE_VAR) { break }
  22199. }
  22200. }
  22201. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  22202. };
  22203. pp$3.checkLocalExport = function(id) {
  22204. // scope.functions must be empty as Module code is always strict.
  22205. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  22206. this.scopeStack[0].var.indexOf(id.name) === -1) {
  22207. this.undefinedExports[id.name] = id;
  22208. }
  22209. };
  22210. pp$3.currentScope = function() {
  22211. return this.scopeStack[this.scopeStack.length - 1]
  22212. };
  22213. pp$3.currentVarScope = function() {
  22214. for (var i = this.scopeStack.length - 1;; i--) {
  22215. var scope = this.scopeStack[i];
  22216. if (scope.flags & SCOPE_VAR) { return scope }
  22217. }
  22218. };
  22219. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  22220. pp$3.currentThisScope = function() {
  22221. for (var i = this.scopeStack.length - 1;; i--) {
  22222. var scope = this.scopeStack[i];
  22223. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  22224. }
  22225. };
  22226. var Node = function Node(parser, pos, loc) {
  22227. this.type = "";
  22228. this.start = pos;
  22229. this.end = 0;
  22230. if (parser.options.locations)
  22231. { this.loc = new SourceLocation(parser, loc); }
  22232. if (parser.options.directSourceFile)
  22233. { this.sourceFile = parser.options.directSourceFile; }
  22234. if (parser.options.ranges)
  22235. { this.range = [pos, 0]; }
  22236. };
  22237. // Start an AST node, attaching a start offset.
  22238. var pp$2 = Parser$1.prototype;
  22239. pp$2.startNode = function() {
  22240. return new Node(this, this.start, this.startLoc)
  22241. };
  22242. pp$2.startNodeAt = function(pos, loc) {
  22243. return new Node(this, pos, loc)
  22244. };
  22245. // Finish an AST node, adding `type` and `end` properties.
  22246. function finishNodeAt(node, type, pos, loc) {
  22247. node.type = type;
  22248. node.end = pos;
  22249. if (this.options.locations)
  22250. { node.loc.end = loc; }
  22251. if (this.options.ranges)
  22252. { node.range[1] = pos; }
  22253. return node
  22254. }
  22255. pp$2.finishNode = function(node, type) {
  22256. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  22257. };
  22258. // Finish node at given position
  22259. pp$2.finishNodeAt = function(node, type, pos, loc) {
  22260. return finishNodeAt.call(this, node, type, pos, loc)
  22261. };
  22262. pp$2.copyNode = function(node) {
  22263. var newNode = new Node(this, node.start, this.startLoc);
  22264. for (var prop in node) { newNode[prop] = node[prop]; }
  22265. return newNode
  22266. };
  22267. // This file contains Unicode properties extracted from the ECMAScript specification.
  22268. // The lists are extracted like so:
  22269. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  22270. // #table-binary-unicode-properties
  22271. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  22272. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  22273. var ecma11BinaryProperties = ecma10BinaryProperties;
  22274. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  22275. var ecma13BinaryProperties = ecma12BinaryProperties;
  22276. var ecma14BinaryProperties = ecma13BinaryProperties;
  22277. var unicodeBinaryProperties = {
  22278. 9: ecma9BinaryProperties,
  22279. 10: ecma10BinaryProperties,
  22280. 11: ecma11BinaryProperties,
  22281. 12: ecma12BinaryProperties,
  22282. 13: ecma13BinaryProperties,
  22283. 14: ecma14BinaryProperties
  22284. };
  22285. // #table-binary-unicode-properties-of-strings
  22286. var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
  22287. var unicodeBinaryPropertiesOfStrings = {
  22288. 9: "",
  22289. 10: "",
  22290. 11: "",
  22291. 12: "",
  22292. 13: "",
  22293. 14: ecma14BinaryPropertiesOfStrings
  22294. };
  22295. // #table-unicode-general-category-values
  22296. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  22297. // #table-unicode-script-values
  22298. var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  22299. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  22300. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  22301. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  22302. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  22303. var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz";
  22304. var unicodeScriptValues = {
  22305. 9: ecma9ScriptValues,
  22306. 10: ecma10ScriptValues,
  22307. 11: ecma11ScriptValues,
  22308. 12: ecma12ScriptValues,
  22309. 13: ecma13ScriptValues,
  22310. 14: ecma14ScriptValues
  22311. };
  22312. var data = {};
  22313. function buildUnicodeData(ecmaVersion) {
  22314. var d = data[ecmaVersion] = {
  22315. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  22316. binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
  22317. nonBinary: {
  22318. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  22319. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  22320. }
  22321. };
  22322. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  22323. d.nonBinary.gc = d.nonBinary.General_Category;
  22324. d.nonBinary.sc = d.nonBinary.Script;
  22325. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  22326. }
  22327. for (var i$1 = 0, list = [9, 10, 11, 12, 13, 14]; i$1 < list.length; i$1 += 1) {
  22328. var ecmaVersion = list[i$1];
  22329. buildUnicodeData(ecmaVersion);
  22330. }
  22331. var pp$1 = Parser$1.prototype;
  22332. var RegExpValidationState = function RegExpValidationState(parser) {
  22333. this.parser = parser;
  22334. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  22335. this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  22336. this.source = "";
  22337. this.flags = "";
  22338. this.start = 0;
  22339. this.switchU = false;
  22340. this.switchV = false;
  22341. this.switchN = false;
  22342. this.pos = 0;
  22343. this.lastIntValue = 0;
  22344. this.lastStringValue = "";
  22345. this.lastAssertionIsQuantifiable = false;
  22346. this.numCapturingParens = 0;
  22347. this.maxBackReference = 0;
  22348. this.groupNames = [];
  22349. this.backReferenceNames = [];
  22350. };
  22351. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  22352. var unicodeSets = flags.indexOf("v") !== -1;
  22353. var unicode = flags.indexOf("u") !== -1;
  22354. this.start = start | 0;
  22355. this.source = pattern + "";
  22356. this.flags = flags;
  22357. if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
  22358. this.switchU = true;
  22359. this.switchV = true;
  22360. this.switchN = true;
  22361. } else {
  22362. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  22363. this.switchV = false;
  22364. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  22365. }
  22366. };
  22367. RegExpValidationState.prototype.raise = function raise (message) {
  22368. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  22369. };
  22370. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  22371. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  22372. RegExpValidationState.prototype.at = function at (i, forceU) {
  22373. if ( forceU === void 0 ) forceU = false;
  22374. var s = this.source;
  22375. var l = s.length;
  22376. if (i >= l) {
  22377. return -1
  22378. }
  22379. var c = s.charCodeAt(i);
  22380. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  22381. return c
  22382. }
  22383. var next = s.charCodeAt(i + 1);
  22384. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  22385. };
  22386. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  22387. if ( forceU === void 0 ) forceU = false;
  22388. var s = this.source;
  22389. var l = s.length;
  22390. if (i >= l) {
  22391. return l
  22392. }
  22393. var c = s.charCodeAt(i), next;
  22394. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  22395. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  22396. return i + 1
  22397. }
  22398. return i + 2
  22399. };
  22400. RegExpValidationState.prototype.current = function current (forceU) {
  22401. if ( forceU === void 0 ) forceU = false;
  22402. return this.at(this.pos, forceU)
  22403. };
  22404. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  22405. if ( forceU === void 0 ) forceU = false;
  22406. return this.at(this.nextIndex(this.pos, forceU), forceU)
  22407. };
  22408. RegExpValidationState.prototype.advance = function advance (forceU) {
  22409. if ( forceU === void 0 ) forceU = false;
  22410. this.pos = this.nextIndex(this.pos, forceU);
  22411. };
  22412. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  22413. if ( forceU === void 0 ) forceU = false;
  22414. if (this.current(forceU) === ch) {
  22415. this.advance(forceU);
  22416. return true
  22417. }
  22418. return false
  22419. };
  22420. RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
  22421. if ( forceU === void 0 ) forceU = false;
  22422. var pos = this.pos;
  22423. for (var i = 0, list = chs; i < list.length; i += 1) {
  22424. var ch = list[i];
  22425. var current = this.at(pos, forceU);
  22426. if (current === -1 || current !== ch) {
  22427. return false
  22428. }
  22429. pos = this.nextIndex(pos, forceU);
  22430. }
  22431. this.pos = pos;
  22432. return true
  22433. };
  22434. /**
  22435. * Validate the flags part of a given RegExpLiteral.
  22436. *
  22437. * @param {RegExpValidationState} state The state to validate RegExp.
  22438. * @returns {void}
  22439. */
  22440. pp$1.validateRegExpFlags = function(state) {
  22441. var validFlags = state.validFlags;
  22442. var flags = state.flags;
  22443. var u = false;
  22444. var v = false;
  22445. for (var i = 0; i < flags.length; i++) {
  22446. var flag = flags.charAt(i);
  22447. if (validFlags.indexOf(flag) === -1) {
  22448. this.raise(state.start, "Invalid regular expression flag");
  22449. }
  22450. if (flags.indexOf(flag, i + 1) > -1) {
  22451. this.raise(state.start, "Duplicate regular expression flag");
  22452. }
  22453. if (flag === "u") { u = true; }
  22454. if (flag === "v") { v = true; }
  22455. }
  22456. if (this.options.ecmaVersion >= 15 && u && v) {
  22457. this.raise(state.start, "Invalid regular expression flag");
  22458. }
  22459. };
  22460. /**
  22461. * Validate the pattern part of a given RegExpLiteral.
  22462. *
  22463. * @param {RegExpValidationState} state The state to validate RegExp.
  22464. * @returns {void}
  22465. */
  22466. pp$1.validateRegExpPattern = function(state) {
  22467. this.regexp_pattern(state);
  22468. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  22469. // parsing contains a |GroupName|, reparse with the goal symbol
  22470. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  22471. // exception if _P_ did not conform to the grammar, if any elements of _P_
  22472. // were not matched by the parse, or if any Early Error conditions exist.
  22473. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  22474. state.switchN = true;
  22475. this.regexp_pattern(state);
  22476. }
  22477. };
  22478. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  22479. pp$1.regexp_pattern = function(state) {
  22480. state.pos = 0;
  22481. state.lastIntValue = 0;
  22482. state.lastStringValue = "";
  22483. state.lastAssertionIsQuantifiable = false;
  22484. state.numCapturingParens = 0;
  22485. state.maxBackReference = 0;
  22486. state.groupNames.length = 0;
  22487. state.backReferenceNames.length = 0;
  22488. this.regexp_disjunction(state);
  22489. if (state.pos !== state.source.length) {
  22490. // Make the same messages as V8.
  22491. if (state.eat(0x29 /* ) */)) {
  22492. state.raise("Unmatched ')'");
  22493. }
  22494. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  22495. state.raise("Lone quantifier brackets");
  22496. }
  22497. }
  22498. if (state.maxBackReference > state.numCapturingParens) {
  22499. state.raise("Invalid escape");
  22500. }
  22501. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  22502. var name = list[i];
  22503. if (state.groupNames.indexOf(name) === -1) {
  22504. state.raise("Invalid named capture referenced");
  22505. }
  22506. }
  22507. };
  22508. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  22509. pp$1.regexp_disjunction = function(state) {
  22510. this.regexp_alternative(state);
  22511. while (state.eat(0x7C /* | */)) {
  22512. this.regexp_alternative(state);
  22513. }
  22514. // Make the same message as V8.
  22515. if (this.regexp_eatQuantifier(state, true)) {
  22516. state.raise("Nothing to repeat");
  22517. }
  22518. if (state.eat(0x7B /* { */)) {
  22519. state.raise("Lone quantifier brackets");
  22520. }
  22521. };
  22522. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  22523. pp$1.regexp_alternative = function(state) {
  22524. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  22525. { }
  22526. };
  22527. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  22528. pp$1.regexp_eatTerm = function(state) {
  22529. if (this.regexp_eatAssertion(state)) {
  22530. // Handle `QuantifiableAssertion Quantifier` alternative.
  22531. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  22532. // is a QuantifiableAssertion.
  22533. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  22534. // Make the same message as V8.
  22535. if (state.switchU) {
  22536. state.raise("Invalid quantifier");
  22537. }
  22538. }
  22539. return true
  22540. }
  22541. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  22542. this.regexp_eatQuantifier(state);
  22543. return true
  22544. }
  22545. return false
  22546. };
  22547. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  22548. pp$1.regexp_eatAssertion = function(state) {
  22549. var start = state.pos;
  22550. state.lastAssertionIsQuantifiable = false;
  22551. // ^, $
  22552. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  22553. return true
  22554. }
  22555. // \b \B
  22556. if (state.eat(0x5C /* \ */)) {
  22557. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  22558. return true
  22559. }
  22560. state.pos = start;
  22561. }
  22562. // Lookahead / Lookbehind
  22563. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  22564. var lookbehind = false;
  22565. if (this.options.ecmaVersion >= 9) {
  22566. lookbehind = state.eat(0x3C /* < */);
  22567. }
  22568. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  22569. this.regexp_disjunction(state);
  22570. if (!state.eat(0x29 /* ) */)) {
  22571. state.raise("Unterminated group");
  22572. }
  22573. state.lastAssertionIsQuantifiable = !lookbehind;
  22574. return true
  22575. }
  22576. }
  22577. state.pos = start;
  22578. return false
  22579. };
  22580. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  22581. pp$1.regexp_eatQuantifier = function(state, noError) {
  22582. if ( noError === void 0 ) noError = false;
  22583. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  22584. state.eat(0x3F /* ? */);
  22585. return true
  22586. }
  22587. return false
  22588. };
  22589. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  22590. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  22591. return (
  22592. state.eat(0x2A /* * */) ||
  22593. state.eat(0x2B /* + */) ||
  22594. state.eat(0x3F /* ? */) ||
  22595. this.regexp_eatBracedQuantifier(state, noError)
  22596. )
  22597. };
  22598. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  22599. var start = state.pos;
  22600. if (state.eat(0x7B /* { */)) {
  22601. var min = 0, max = -1;
  22602. if (this.regexp_eatDecimalDigits(state)) {
  22603. min = state.lastIntValue;
  22604. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  22605. max = state.lastIntValue;
  22606. }
  22607. if (state.eat(0x7D /* } */)) {
  22608. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  22609. if (max !== -1 && max < min && !noError) {
  22610. state.raise("numbers out of order in {} quantifier");
  22611. }
  22612. return true
  22613. }
  22614. }
  22615. if (state.switchU && !noError) {
  22616. state.raise("Incomplete quantifier");
  22617. }
  22618. state.pos = start;
  22619. }
  22620. return false
  22621. };
  22622. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  22623. pp$1.regexp_eatAtom = function(state) {
  22624. return (
  22625. this.regexp_eatPatternCharacters(state) ||
  22626. state.eat(0x2E /* . */) ||
  22627. this.regexp_eatReverseSolidusAtomEscape(state) ||
  22628. this.regexp_eatCharacterClass(state) ||
  22629. this.regexp_eatUncapturingGroup(state) ||
  22630. this.regexp_eatCapturingGroup(state)
  22631. )
  22632. };
  22633. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  22634. var start = state.pos;
  22635. if (state.eat(0x5C /* \ */)) {
  22636. if (this.regexp_eatAtomEscape(state)) {
  22637. return true
  22638. }
  22639. state.pos = start;
  22640. }
  22641. return false
  22642. };
  22643. pp$1.regexp_eatUncapturingGroup = function(state) {
  22644. var start = state.pos;
  22645. if (state.eat(0x28 /* ( */)) {
  22646. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  22647. this.regexp_disjunction(state);
  22648. if (state.eat(0x29 /* ) */)) {
  22649. return true
  22650. }
  22651. state.raise("Unterminated group");
  22652. }
  22653. state.pos = start;
  22654. }
  22655. return false
  22656. };
  22657. pp$1.regexp_eatCapturingGroup = function(state) {
  22658. if (state.eat(0x28 /* ( */)) {
  22659. if (this.options.ecmaVersion >= 9) {
  22660. this.regexp_groupSpecifier(state);
  22661. } else if (state.current() === 0x3F /* ? */) {
  22662. state.raise("Invalid group");
  22663. }
  22664. this.regexp_disjunction(state);
  22665. if (state.eat(0x29 /* ) */)) {
  22666. state.numCapturingParens += 1;
  22667. return true
  22668. }
  22669. state.raise("Unterminated group");
  22670. }
  22671. return false
  22672. };
  22673. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  22674. pp$1.regexp_eatExtendedAtom = function(state) {
  22675. return (
  22676. state.eat(0x2E /* . */) ||
  22677. this.regexp_eatReverseSolidusAtomEscape(state) ||
  22678. this.regexp_eatCharacterClass(state) ||
  22679. this.regexp_eatUncapturingGroup(state) ||
  22680. this.regexp_eatCapturingGroup(state) ||
  22681. this.regexp_eatInvalidBracedQuantifier(state) ||
  22682. this.regexp_eatExtendedPatternCharacter(state)
  22683. )
  22684. };
  22685. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  22686. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  22687. if (this.regexp_eatBracedQuantifier(state, true)) {
  22688. state.raise("Nothing to repeat");
  22689. }
  22690. return false
  22691. };
  22692. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  22693. pp$1.regexp_eatSyntaxCharacter = function(state) {
  22694. var ch = state.current();
  22695. if (isSyntaxCharacter(ch)) {
  22696. state.lastIntValue = ch;
  22697. state.advance();
  22698. return true
  22699. }
  22700. return false
  22701. };
  22702. function isSyntaxCharacter(ch) {
  22703. return (
  22704. ch === 0x24 /* $ */ ||
  22705. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  22706. ch === 0x2E /* . */ ||
  22707. ch === 0x3F /* ? */ ||
  22708. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  22709. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  22710. )
  22711. }
  22712. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  22713. // But eat eager.
  22714. pp$1.regexp_eatPatternCharacters = function(state) {
  22715. var start = state.pos;
  22716. var ch = 0;
  22717. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  22718. state.advance();
  22719. }
  22720. return state.pos !== start
  22721. };
  22722. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  22723. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  22724. var ch = state.current();
  22725. if (
  22726. ch !== -1 &&
  22727. ch !== 0x24 /* $ */ &&
  22728. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  22729. ch !== 0x2E /* . */ &&
  22730. ch !== 0x3F /* ? */ &&
  22731. ch !== 0x5B /* [ */ &&
  22732. ch !== 0x5E /* ^ */ &&
  22733. ch !== 0x7C /* | */
  22734. ) {
  22735. state.advance();
  22736. return true
  22737. }
  22738. return false
  22739. };
  22740. // GroupSpecifier ::
  22741. // [empty]
  22742. // `?` GroupName
  22743. pp$1.regexp_groupSpecifier = function(state) {
  22744. if (state.eat(0x3F /* ? */)) {
  22745. if (this.regexp_eatGroupName(state)) {
  22746. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  22747. state.raise("Duplicate capture group name");
  22748. }
  22749. state.groupNames.push(state.lastStringValue);
  22750. return
  22751. }
  22752. state.raise("Invalid group");
  22753. }
  22754. };
  22755. // GroupName ::
  22756. // `<` RegExpIdentifierName `>`
  22757. // Note: this updates `state.lastStringValue` property with the eaten name.
  22758. pp$1.regexp_eatGroupName = function(state) {
  22759. state.lastStringValue = "";
  22760. if (state.eat(0x3C /* < */)) {
  22761. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  22762. return true
  22763. }
  22764. state.raise("Invalid capture group name");
  22765. }
  22766. return false
  22767. };
  22768. // RegExpIdentifierName ::
  22769. // RegExpIdentifierStart
  22770. // RegExpIdentifierName RegExpIdentifierPart
  22771. // Note: this updates `state.lastStringValue` property with the eaten name.
  22772. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  22773. state.lastStringValue = "";
  22774. if (this.regexp_eatRegExpIdentifierStart(state)) {
  22775. state.lastStringValue += codePointToString(state.lastIntValue);
  22776. while (this.regexp_eatRegExpIdentifierPart(state)) {
  22777. state.lastStringValue += codePointToString(state.lastIntValue);
  22778. }
  22779. return true
  22780. }
  22781. return false
  22782. };
  22783. // RegExpIdentifierStart ::
  22784. // UnicodeIDStart
  22785. // `$`
  22786. // `_`
  22787. // `\` RegExpUnicodeEscapeSequence[+U]
  22788. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  22789. var start = state.pos;
  22790. var forceU = this.options.ecmaVersion >= 11;
  22791. var ch = state.current(forceU);
  22792. state.advance(forceU);
  22793. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  22794. ch = state.lastIntValue;
  22795. }
  22796. if (isRegExpIdentifierStart(ch)) {
  22797. state.lastIntValue = ch;
  22798. return true
  22799. }
  22800. state.pos = start;
  22801. return false
  22802. };
  22803. function isRegExpIdentifierStart(ch) {
  22804. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  22805. }
  22806. // RegExpIdentifierPart ::
  22807. // UnicodeIDContinue
  22808. // `$`
  22809. // `_`
  22810. // `\` RegExpUnicodeEscapeSequence[+U]
  22811. // <ZWNJ>
  22812. // <ZWJ>
  22813. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  22814. var start = state.pos;
  22815. var forceU = this.options.ecmaVersion >= 11;
  22816. var ch = state.current(forceU);
  22817. state.advance(forceU);
  22818. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  22819. ch = state.lastIntValue;
  22820. }
  22821. if (isRegExpIdentifierPart(ch)) {
  22822. state.lastIntValue = ch;
  22823. return true
  22824. }
  22825. state.pos = start;
  22826. return false
  22827. };
  22828. function isRegExpIdentifierPart(ch) {
  22829. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  22830. }
  22831. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  22832. pp$1.regexp_eatAtomEscape = function(state) {
  22833. if (
  22834. this.regexp_eatBackReference(state) ||
  22835. this.regexp_eatCharacterClassEscape(state) ||
  22836. this.regexp_eatCharacterEscape(state) ||
  22837. (state.switchN && this.regexp_eatKGroupName(state))
  22838. ) {
  22839. return true
  22840. }
  22841. if (state.switchU) {
  22842. // Make the same message as V8.
  22843. if (state.current() === 0x63 /* c */) {
  22844. state.raise("Invalid unicode escape");
  22845. }
  22846. state.raise("Invalid escape");
  22847. }
  22848. return false
  22849. };
  22850. pp$1.regexp_eatBackReference = function(state) {
  22851. var start = state.pos;
  22852. if (this.regexp_eatDecimalEscape(state)) {
  22853. var n = state.lastIntValue;
  22854. if (state.switchU) {
  22855. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  22856. if (n > state.maxBackReference) {
  22857. state.maxBackReference = n;
  22858. }
  22859. return true
  22860. }
  22861. if (n <= state.numCapturingParens) {
  22862. return true
  22863. }
  22864. state.pos = start;
  22865. }
  22866. return false
  22867. };
  22868. pp$1.regexp_eatKGroupName = function(state) {
  22869. if (state.eat(0x6B /* k */)) {
  22870. if (this.regexp_eatGroupName(state)) {
  22871. state.backReferenceNames.push(state.lastStringValue);
  22872. return true
  22873. }
  22874. state.raise("Invalid named reference");
  22875. }
  22876. return false
  22877. };
  22878. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  22879. pp$1.regexp_eatCharacterEscape = function(state) {
  22880. return (
  22881. this.regexp_eatControlEscape(state) ||
  22882. this.regexp_eatCControlLetter(state) ||
  22883. this.regexp_eatZero(state) ||
  22884. this.regexp_eatHexEscapeSequence(state) ||
  22885. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  22886. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  22887. this.regexp_eatIdentityEscape(state)
  22888. )
  22889. };
  22890. pp$1.regexp_eatCControlLetter = function(state) {
  22891. var start = state.pos;
  22892. if (state.eat(0x63 /* c */)) {
  22893. if (this.regexp_eatControlLetter(state)) {
  22894. return true
  22895. }
  22896. state.pos = start;
  22897. }
  22898. return false
  22899. };
  22900. pp$1.regexp_eatZero = function(state) {
  22901. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  22902. state.lastIntValue = 0;
  22903. state.advance();
  22904. return true
  22905. }
  22906. return false
  22907. };
  22908. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  22909. pp$1.regexp_eatControlEscape = function(state) {
  22910. var ch = state.current();
  22911. if (ch === 0x74 /* t */) {
  22912. state.lastIntValue = 0x09; /* \t */
  22913. state.advance();
  22914. return true
  22915. }
  22916. if (ch === 0x6E /* n */) {
  22917. state.lastIntValue = 0x0A; /* \n */
  22918. state.advance();
  22919. return true
  22920. }
  22921. if (ch === 0x76 /* v */) {
  22922. state.lastIntValue = 0x0B; /* \v */
  22923. state.advance();
  22924. return true
  22925. }
  22926. if (ch === 0x66 /* f */) {
  22927. state.lastIntValue = 0x0C; /* \f */
  22928. state.advance();
  22929. return true
  22930. }
  22931. if (ch === 0x72 /* r */) {
  22932. state.lastIntValue = 0x0D; /* \r */
  22933. state.advance();
  22934. return true
  22935. }
  22936. return false
  22937. };
  22938. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  22939. pp$1.regexp_eatControlLetter = function(state) {
  22940. var ch = state.current();
  22941. if (isControlLetter(ch)) {
  22942. state.lastIntValue = ch % 0x20;
  22943. state.advance();
  22944. return true
  22945. }
  22946. return false
  22947. };
  22948. function isControlLetter(ch) {
  22949. return (
  22950. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  22951. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  22952. )
  22953. }
  22954. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  22955. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  22956. if ( forceU === void 0 ) forceU = false;
  22957. var start = state.pos;
  22958. var switchU = forceU || state.switchU;
  22959. if (state.eat(0x75 /* u */)) {
  22960. if (this.regexp_eatFixedHexDigits(state, 4)) {
  22961. var lead = state.lastIntValue;
  22962. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  22963. var leadSurrogateEnd = state.pos;
  22964. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  22965. var trail = state.lastIntValue;
  22966. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  22967. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  22968. return true
  22969. }
  22970. }
  22971. state.pos = leadSurrogateEnd;
  22972. state.lastIntValue = lead;
  22973. }
  22974. return true
  22975. }
  22976. if (
  22977. switchU &&
  22978. state.eat(0x7B /* { */) &&
  22979. this.regexp_eatHexDigits(state) &&
  22980. state.eat(0x7D /* } */) &&
  22981. isValidUnicode(state.lastIntValue)
  22982. ) {
  22983. return true
  22984. }
  22985. if (switchU) {
  22986. state.raise("Invalid unicode escape");
  22987. }
  22988. state.pos = start;
  22989. }
  22990. return false
  22991. };
  22992. function isValidUnicode(ch) {
  22993. return ch >= 0 && ch <= 0x10FFFF
  22994. }
  22995. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  22996. pp$1.regexp_eatIdentityEscape = function(state) {
  22997. if (state.switchU) {
  22998. if (this.regexp_eatSyntaxCharacter(state)) {
  22999. return true
  23000. }
  23001. if (state.eat(0x2F /* / */)) {
  23002. state.lastIntValue = 0x2F; /* / */
  23003. return true
  23004. }
  23005. return false
  23006. }
  23007. var ch = state.current();
  23008. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  23009. state.lastIntValue = ch;
  23010. state.advance();
  23011. return true
  23012. }
  23013. return false
  23014. };
  23015. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  23016. pp$1.regexp_eatDecimalEscape = function(state) {
  23017. state.lastIntValue = 0;
  23018. var ch = state.current();
  23019. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  23020. do {
  23021. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  23022. state.advance();
  23023. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  23024. return true
  23025. }
  23026. return false
  23027. };
  23028. // Return values used by character set parsing methods, needed to
  23029. // forbid negation of sets that can match strings.
  23030. var CharSetNone = 0; // Nothing parsed
  23031. var CharSetOk = 1; // Construct parsed, cannot contain strings
  23032. var CharSetString = 2; // Construct parsed, can contain strings
  23033. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  23034. pp$1.regexp_eatCharacterClassEscape = function(state) {
  23035. var ch = state.current();
  23036. if (isCharacterClassEscape(ch)) {
  23037. state.lastIntValue = -1;
  23038. state.advance();
  23039. return CharSetOk
  23040. }
  23041. var negate = false;
  23042. if (
  23043. state.switchU &&
  23044. this.options.ecmaVersion >= 9 &&
  23045. ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
  23046. ) {
  23047. state.lastIntValue = -1;
  23048. state.advance();
  23049. var result;
  23050. if (
  23051. state.eat(0x7B /* { */) &&
  23052. (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
  23053. state.eat(0x7D /* } */)
  23054. ) {
  23055. if (negate && result === CharSetString) { state.raise("Invalid property name"); }
  23056. return result
  23057. }
  23058. state.raise("Invalid property name");
  23059. }
  23060. return CharSetNone
  23061. };
  23062. function isCharacterClassEscape(ch) {
  23063. return (
  23064. ch === 0x64 /* d */ ||
  23065. ch === 0x44 /* D */ ||
  23066. ch === 0x73 /* s */ ||
  23067. ch === 0x53 /* S */ ||
  23068. ch === 0x77 /* w */ ||
  23069. ch === 0x57 /* W */
  23070. )
  23071. }
  23072. // UnicodePropertyValueExpression ::
  23073. // UnicodePropertyName `=` UnicodePropertyValue
  23074. // LoneUnicodePropertyNameOrValue
  23075. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  23076. var start = state.pos;
  23077. // UnicodePropertyName `=` UnicodePropertyValue
  23078. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  23079. var name = state.lastStringValue;
  23080. if (this.regexp_eatUnicodePropertyValue(state)) {
  23081. var value = state.lastStringValue;
  23082. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  23083. return CharSetOk
  23084. }
  23085. }
  23086. state.pos = start;
  23087. // LoneUnicodePropertyNameOrValue
  23088. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  23089. var nameOrValue = state.lastStringValue;
  23090. return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  23091. }
  23092. return CharSetNone
  23093. };
  23094. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  23095. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  23096. { state.raise("Invalid property name"); }
  23097. if (!state.unicodeProperties.nonBinary[name].test(value))
  23098. { state.raise("Invalid property value"); }
  23099. };
  23100. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  23101. if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }
  23102. if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }
  23103. state.raise("Invalid property name");
  23104. };
  23105. // UnicodePropertyName ::
  23106. // UnicodePropertyNameCharacters
  23107. pp$1.regexp_eatUnicodePropertyName = function(state) {
  23108. var ch = 0;
  23109. state.lastStringValue = "";
  23110. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  23111. state.lastStringValue += codePointToString(ch);
  23112. state.advance();
  23113. }
  23114. return state.lastStringValue !== ""
  23115. };
  23116. function isUnicodePropertyNameCharacter(ch) {
  23117. return isControlLetter(ch) || ch === 0x5F /* _ */
  23118. }
  23119. // UnicodePropertyValue ::
  23120. // UnicodePropertyValueCharacters
  23121. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  23122. var ch = 0;
  23123. state.lastStringValue = "";
  23124. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  23125. state.lastStringValue += codePointToString(ch);
  23126. state.advance();
  23127. }
  23128. return state.lastStringValue !== ""
  23129. };
  23130. function isUnicodePropertyValueCharacter(ch) {
  23131. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  23132. }
  23133. // LoneUnicodePropertyNameOrValue ::
  23134. // UnicodePropertyValueCharacters
  23135. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  23136. return this.regexp_eatUnicodePropertyValue(state)
  23137. };
  23138. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  23139. pp$1.regexp_eatCharacterClass = function(state) {
  23140. if (state.eat(0x5B /* [ */)) {
  23141. var negate = state.eat(0x5E /* ^ */);
  23142. var result = this.regexp_classContents(state);
  23143. if (!state.eat(0x5D /* ] */))
  23144. { state.raise("Unterminated character class"); }
  23145. if (negate && result === CharSetString)
  23146. { state.raise("Negated character class may contain strings"); }
  23147. return true
  23148. }
  23149. return false
  23150. };
  23151. // https://tc39.es/ecma262/#prod-ClassContents
  23152. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  23153. pp$1.regexp_classContents = function(state) {
  23154. if (state.current() === 0x5D /* ] */) { return CharSetOk }
  23155. if (state.switchV) { return this.regexp_classSetExpression(state) }
  23156. this.regexp_nonEmptyClassRanges(state);
  23157. return CharSetOk
  23158. };
  23159. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  23160. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  23161. pp$1.regexp_nonEmptyClassRanges = function(state) {
  23162. while (this.regexp_eatClassAtom(state)) {
  23163. var left = state.lastIntValue;
  23164. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  23165. var right = state.lastIntValue;
  23166. if (state.switchU && (left === -1 || right === -1)) {
  23167. state.raise("Invalid character class");
  23168. }
  23169. if (left !== -1 && right !== -1 && left > right) {
  23170. state.raise("Range out of order in character class");
  23171. }
  23172. }
  23173. }
  23174. };
  23175. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  23176. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  23177. pp$1.regexp_eatClassAtom = function(state) {
  23178. var start = state.pos;
  23179. if (state.eat(0x5C /* \ */)) {
  23180. if (this.regexp_eatClassEscape(state)) {
  23181. return true
  23182. }
  23183. if (state.switchU) {
  23184. // Make the same message as V8.
  23185. var ch$1 = state.current();
  23186. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  23187. state.raise("Invalid class escape");
  23188. }
  23189. state.raise("Invalid escape");
  23190. }
  23191. state.pos = start;
  23192. }
  23193. var ch = state.current();
  23194. if (ch !== 0x5D /* ] */) {
  23195. state.lastIntValue = ch;
  23196. state.advance();
  23197. return true
  23198. }
  23199. return false
  23200. };
  23201. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  23202. pp$1.regexp_eatClassEscape = function(state) {
  23203. var start = state.pos;
  23204. if (state.eat(0x62 /* b */)) {
  23205. state.lastIntValue = 0x08; /* <BS> */
  23206. return true
  23207. }
  23208. if (state.switchU && state.eat(0x2D /* - */)) {
  23209. state.lastIntValue = 0x2D; /* - */
  23210. return true
  23211. }
  23212. if (!state.switchU && state.eat(0x63 /* c */)) {
  23213. if (this.regexp_eatClassControlLetter(state)) {
  23214. return true
  23215. }
  23216. state.pos = start;
  23217. }
  23218. return (
  23219. this.regexp_eatCharacterClassEscape(state) ||
  23220. this.regexp_eatCharacterEscape(state)
  23221. )
  23222. };
  23223. // https://tc39.es/ecma262/#prod-ClassSetExpression
  23224. // https://tc39.es/ecma262/#prod-ClassUnion
  23225. // https://tc39.es/ecma262/#prod-ClassIntersection
  23226. // https://tc39.es/ecma262/#prod-ClassSubtraction
  23227. pp$1.regexp_classSetExpression = function(state) {
  23228. var result = CharSetOk, subResult;
  23229. if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
  23230. if (subResult === CharSetString) { result = CharSetString; }
  23231. // https://tc39.es/ecma262/#prod-ClassIntersection
  23232. var start = state.pos;
  23233. while (state.eatChars([0x26, 0x26] /* && */)) {
  23234. if (
  23235. state.current() !== 0x26 /* & */ &&
  23236. (subResult = this.regexp_eatClassSetOperand(state))
  23237. ) {
  23238. if (subResult !== CharSetString) { result = CharSetOk; }
  23239. continue
  23240. }
  23241. state.raise("Invalid character in character class");
  23242. }
  23243. if (start !== state.pos) { return result }
  23244. // https://tc39.es/ecma262/#prod-ClassSubtraction
  23245. while (state.eatChars([0x2D, 0x2D] /* -- */)) {
  23246. if (this.regexp_eatClassSetOperand(state)) { continue }
  23247. state.raise("Invalid character in character class");
  23248. }
  23249. if (start !== state.pos) { return result }
  23250. } else {
  23251. state.raise("Invalid character in character class");
  23252. }
  23253. // https://tc39.es/ecma262/#prod-ClassUnion
  23254. for (;;) {
  23255. if (this.regexp_eatClassSetRange(state)) { continue }
  23256. subResult = this.regexp_eatClassSetOperand(state);
  23257. if (!subResult) { return result }
  23258. if (subResult === CharSetString) { result = CharSetString; }
  23259. }
  23260. };
  23261. // https://tc39.es/ecma262/#prod-ClassSetRange
  23262. pp$1.regexp_eatClassSetRange = function(state) {
  23263. var start = state.pos;
  23264. if (this.regexp_eatClassSetCharacter(state)) {
  23265. var left = state.lastIntValue;
  23266. if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
  23267. var right = state.lastIntValue;
  23268. if (left !== -1 && right !== -1 && left > right) {
  23269. state.raise("Range out of order in character class");
  23270. }
  23271. return true
  23272. }
  23273. state.pos = start;
  23274. }
  23275. return false
  23276. };
  23277. // https://tc39.es/ecma262/#prod-ClassSetOperand
  23278. pp$1.regexp_eatClassSetOperand = function(state) {
  23279. if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }
  23280. return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
  23281. };
  23282. // https://tc39.es/ecma262/#prod-NestedClass
  23283. pp$1.regexp_eatNestedClass = function(state) {
  23284. var start = state.pos;
  23285. if (state.eat(0x5B /* [ */)) {
  23286. var negate = state.eat(0x5E /* ^ */);
  23287. var result = this.regexp_classContents(state);
  23288. if (state.eat(0x5D /* ] */)) {
  23289. if (negate && result === CharSetString) {
  23290. state.raise("Negated character class may contain strings");
  23291. }
  23292. return result
  23293. }
  23294. state.pos = start;
  23295. }
  23296. if (state.eat(0x5C /* \ */)) {
  23297. var result$1 = this.regexp_eatCharacterClassEscape(state);
  23298. if (result$1) {
  23299. return result$1
  23300. }
  23301. state.pos = start;
  23302. }
  23303. return null
  23304. };
  23305. // https://tc39.es/ecma262/#prod-ClassStringDisjunction
  23306. pp$1.regexp_eatClassStringDisjunction = function(state) {
  23307. var start = state.pos;
  23308. if (state.eatChars([0x5C, 0x71] /* \q */)) {
  23309. if (state.eat(0x7B /* { */)) {
  23310. var result = this.regexp_classStringDisjunctionContents(state);
  23311. if (state.eat(0x7D /* } */)) {
  23312. return result
  23313. }
  23314. } else {
  23315. // Make the same message as V8.
  23316. state.raise("Invalid escape");
  23317. }
  23318. state.pos = start;
  23319. }
  23320. return null
  23321. };
  23322. // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
  23323. pp$1.regexp_classStringDisjunctionContents = function(state) {
  23324. var result = this.regexp_classString(state);
  23325. while (state.eat(0x7C /* | */)) {
  23326. if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }
  23327. }
  23328. return result
  23329. };
  23330. // https://tc39.es/ecma262/#prod-ClassString
  23331. // https://tc39.es/ecma262/#prod-NonEmptyClassString
  23332. pp$1.regexp_classString = function(state) {
  23333. var count = 0;
  23334. while (this.regexp_eatClassSetCharacter(state)) { count++; }
  23335. return count === 1 ? CharSetOk : CharSetString
  23336. };
  23337. // https://tc39.es/ecma262/#prod-ClassSetCharacter
  23338. pp$1.regexp_eatClassSetCharacter = function(state) {
  23339. var start = state.pos;
  23340. if (state.eat(0x5C /* \ */)) {
  23341. if (
  23342. this.regexp_eatCharacterEscape(state) ||
  23343. this.regexp_eatClassSetReservedPunctuator(state)
  23344. ) {
  23345. return true
  23346. }
  23347. if (state.eat(0x62 /* b */)) {
  23348. state.lastIntValue = 0x08; /* <BS> */
  23349. return true
  23350. }
  23351. state.pos = start;
  23352. return false
  23353. }
  23354. var ch = state.current();
  23355. if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  23356. if (isClassSetSyntaxCharacter(ch)) { return false }
  23357. state.advance();
  23358. state.lastIntValue = ch;
  23359. return true
  23360. };
  23361. // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
  23362. function isClassSetReservedDoublePunctuatorCharacter(ch) {
  23363. return (
  23364. ch === 0x21 /* ! */ ||
  23365. ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
  23366. ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
  23367. ch === 0x2E /* . */ ||
  23368. ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
  23369. ch === 0x5E /* ^ */ ||
  23370. ch === 0x60 /* ` */ ||
  23371. ch === 0x7E /* ~ */
  23372. )
  23373. }
  23374. // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
  23375. function isClassSetSyntaxCharacter(ch) {
  23376. return (
  23377. ch === 0x28 /* ( */ ||
  23378. ch === 0x29 /* ) */ ||
  23379. ch === 0x2D /* - */ ||
  23380. ch === 0x2F /* / */ ||
  23381. ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
  23382. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  23383. )
  23384. }
  23385. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  23386. pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  23387. var ch = state.current();
  23388. if (isClassSetReservedPunctuator(ch)) {
  23389. state.lastIntValue = ch;
  23390. state.advance();
  23391. return true
  23392. }
  23393. return false
  23394. };
  23395. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  23396. function isClassSetReservedPunctuator(ch) {
  23397. return (
  23398. ch === 0x21 /* ! */ ||
  23399. ch === 0x23 /* # */ ||
  23400. ch === 0x25 /* % */ ||
  23401. ch === 0x26 /* & */ ||
  23402. ch === 0x2C /* , */ ||
  23403. ch === 0x2D /* - */ ||
  23404. ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
  23405. ch === 0x40 /* @ */ ||
  23406. ch === 0x60 /* ` */ ||
  23407. ch === 0x7E /* ~ */
  23408. )
  23409. }
  23410. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  23411. pp$1.regexp_eatClassControlLetter = function(state) {
  23412. var ch = state.current();
  23413. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  23414. state.lastIntValue = ch % 0x20;
  23415. state.advance();
  23416. return true
  23417. }
  23418. return false
  23419. };
  23420. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  23421. pp$1.regexp_eatHexEscapeSequence = function(state) {
  23422. var start = state.pos;
  23423. if (state.eat(0x78 /* x */)) {
  23424. if (this.regexp_eatFixedHexDigits(state, 2)) {
  23425. return true
  23426. }
  23427. if (state.switchU) {
  23428. state.raise("Invalid escape");
  23429. }
  23430. state.pos = start;
  23431. }
  23432. return false
  23433. };
  23434. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  23435. pp$1.regexp_eatDecimalDigits = function(state) {
  23436. var start = state.pos;
  23437. var ch = 0;
  23438. state.lastIntValue = 0;
  23439. while (isDecimalDigit(ch = state.current())) {
  23440. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  23441. state.advance();
  23442. }
  23443. return state.pos !== start
  23444. };
  23445. function isDecimalDigit(ch) {
  23446. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  23447. }
  23448. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  23449. pp$1.regexp_eatHexDigits = function(state) {
  23450. var start = state.pos;
  23451. var ch = 0;
  23452. state.lastIntValue = 0;
  23453. while (isHexDigit(ch = state.current())) {
  23454. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  23455. state.advance();
  23456. }
  23457. return state.pos !== start
  23458. };
  23459. function isHexDigit(ch) {
  23460. return (
  23461. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  23462. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  23463. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  23464. )
  23465. }
  23466. function hexToInt(ch) {
  23467. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  23468. return 10 + (ch - 0x41 /* A */)
  23469. }
  23470. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  23471. return 10 + (ch - 0x61 /* a */)
  23472. }
  23473. return ch - 0x30 /* 0 */
  23474. }
  23475. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  23476. // Allows only 0-377(octal) i.e. 0-255(decimal).
  23477. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  23478. if (this.regexp_eatOctalDigit(state)) {
  23479. var n1 = state.lastIntValue;
  23480. if (this.regexp_eatOctalDigit(state)) {
  23481. var n2 = state.lastIntValue;
  23482. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  23483. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  23484. } else {
  23485. state.lastIntValue = n1 * 8 + n2;
  23486. }
  23487. } else {
  23488. state.lastIntValue = n1;
  23489. }
  23490. return true
  23491. }
  23492. return false
  23493. };
  23494. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  23495. pp$1.regexp_eatOctalDigit = function(state) {
  23496. var ch = state.current();
  23497. if (isOctalDigit(ch)) {
  23498. state.lastIntValue = ch - 0x30; /* 0 */
  23499. state.advance();
  23500. return true
  23501. }
  23502. state.lastIntValue = 0;
  23503. return false
  23504. };
  23505. function isOctalDigit(ch) {
  23506. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  23507. }
  23508. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  23509. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  23510. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  23511. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  23512. var start = state.pos;
  23513. state.lastIntValue = 0;
  23514. for (var i = 0; i < length; ++i) {
  23515. var ch = state.current();
  23516. if (!isHexDigit(ch)) {
  23517. state.pos = start;
  23518. return false
  23519. }
  23520. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  23521. state.advance();
  23522. }
  23523. return true
  23524. };
  23525. // Object type used to represent tokens. Note that normally, tokens
  23526. // simply exist as properties on the parser object. This is only
  23527. // used for the onToken callback and the external tokenizer.
  23528. var Token = function Token(p) {
  23529. this.type = p.type;
  23530. this.value = p.value;
  23531. this.start = p.start;
  23532. this.end = p.end;
  23533. if (p.options.locations)
  23534. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  23535. if (p.options.ranges)
  23536. { this.range = [p.start, p.end]; }
  23537. };
  23538. // ## Tokenizer
  23539. var pp = Parser$1.prototype;
  23540. // Move to the next token
  23541. pp.next = function(ignoreEscapeSequenceInKeyword) {
  23542. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  23543. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  23544. if (this.options.onToken)
  23545. { this.options.onToken(new Token(this)); }
  23546. this.lastTokEnd = this.end;
  23547. this.lastTokStart = this.start;
  23548. this.lastTokEndLoc = this.endLoc;
  23549. this.lastTokStartLoc = this.startLoc;
  23550. this.nextToken();
  23551. };
  23552. pp.getToken = function() {
  23553. this.next();
  23554. return new Token(this)
  23555. };
  23556. // If we're in an ES6 environment, make parsers iterable
  23557. if (typeof Symbol !== "undefined")
  23558. { pp[Symbol.iterator] = function() {
  23559. var this$1$1 = this;
  23560. return {
  23561. next: function () {
  23562. var token = this$1$1.getToken();
  23563. return {
  23564. done: token.type === types$1.eof,
  23565. value: token
  23566. }
  23567. }
  23568. }
  23569. }; }
  23570. // Toggle strict mode. Re-reads the next number or string to please
  23571. // pedantic tests (`"use strict"; 010;` should fail).
  23572. // Read a single token, updating the parser object's token-related
  23573. // properties.
  23574. pp.nextToken = function() {
  23575. var curContext = this.curContext();
  23576. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  23577. this.start = this.pos;
  23578. if (this.options.locations) { this.startLoc = this.curPosition(); }
  23579. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  23580. if (curContext.override) { return curContext.override(this) }
  23581. else { this.readToken(this.fullCharCodeAtPos()); }
  23582. };
  23583. pp.readToken = function(code) {
  23584. // Identifier or keyword. '\uXXXX' sequences are allowed in
  23585. // identifiers, so '\' also dispatches to that.
  23586. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  23587. { return this.readWord() }
  23588. return this.getTokenFromCode(code)
  23589. };
  23590. pp.fullCharCodeAtPos = function() {
  23591. var code = this.input.charCodeAt(this.pos);
  23592. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  23593. var next = this.input.charCodeAt(this.pos + 1);
  23594. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  23595. };
  23596. pp.skipBlockComment = function() {
  23597. var startLoc = this.options.onComment && this.curPosition();
  23598. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  23599. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  23600. this.pos = end + 2;
  23601. if (this.options.locations) {
  23602. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  23603. ++this.curLine;
  23604. pos = this.lineStart = nextBreak;
  23605. }
  23606. }
  23607. if (this.options.onComment)
  23608. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  23609. startLoc, this.curPosition()); }
  23610. };
  23611. pp.skipLineComment = function(startSkip) {
  23612. var start = this.pos;
  23613. var startLoc = this.options.onComment && this.curPosition();
  23614. var ch = this.input.charCodeAt(this.pos += startSkip);
  23615. while (this.pos < this.input.length && !isNewLine(ch)) {
  23616. ch = this.input.charCodeAt(++this.pos);
  23617. }
  23618. if (this.options.onComment)
  23619. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  23620. startLoc, this.curPosition()); }
  23621. };
  23622. // Called at the start of the parse and after every token. Skips
  23623. // whitespace and comments, and.
  23624. pp.skipSpace = function() {
  23625. loop: while (this.pos < this.input.length) {
  23626. var ch = this.input.charCodeAt(this.pos);
  23627. switch (ch) {
  23628. case 32: case 160: // ' '
  23629. ++this.pos;
  23630. break
  23631. case 13:
  23632. if (this.input.charCodeAt(this.pos + 1) === 10) {
  23633. ++this.pos;
  23634. }
  23635. case 10: case 8232: case 8233:
  23636. ++this.pos;
  23637. if (this.options.locations) {
  23638. ++this.curLine;
  23639. this.lineStart = this.pos;
  23640. }
  23641. break
  23642. case 47: // '/'
  23643. switch (this.input.charCodeAt(this.pos + 1)) {
  23644. case 42: // '*'
  23645. this.skipBlockComment();
  23646. break
  23647. case 47:
  23648. this.skipLineComment(2);
  23649. break
  23650. default:
  23651. break loop
  23652. }
  23653. break
  23654. default:
  23655. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  23656. ++this.pos;
  23657. } else {
  23658. break loop
  23659. }
  23660. }
  23661. }
  23662. };
  23663. // Called at the end of every token. Sets `end`, `val`, and
  23664. // maintains `context` and `exprAllowed`, and skips the space after
  23665. // the token, so that the next one's `start` will point at the
  23666. // right position.
  23667. pp.finishToken = function(type, val) {
  23668. this.end = this.pos;
  23669. if (this.options.locations) { this.endLoc = this.curPosition(); }
  23670. var prevType = this.type;
  23671. this.type = type;
  23672. this.value = val;
  23673. this.updateContext(prevType);
  23674. };
  23675. // ### Token reading
  23676. // This is the function that is called to fetch the next token. It
  23677. // is somewhat obscure, because it works in character codes rather
  23678. // than characters, and because operator parsing has been inlined
  23679. // into it.
  23680. //
  23681. // All in the name of speed.
  23682. //
  23683. pp.readToken_dot = function() {
  23684. var next = this.input.charCodeAt(this.pos + 1);
  23685. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  23686. var next2 = this.input.charCodeAt(this.pos + 2);
  23687. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  23688. this.pos += 3;
  23689. return this.finishToken(types$1.ellipsis)
  23690. } else {
  23691. ++this.pos;
  23692. return this.finishToken(types$1.dot)
  23693. }
  23694. };
  23695. pp.readToken_slash = function() { // '/'
  23696. var next = this.input.charCodeAt(this.pos + 1);
  23697. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  23698. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23699. return this.finishOp(types$1.slash, 1)
  23700. };
  23701. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  23702. var next = this.input.charCodeAt(this.pos + 1);
  23703. var size = 1;
  23704. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  23705. // exponentiation operator ** and **=
  23706. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  23707. ++size;
  23708. tokentype = types$1.starstar;
  23709. next = this.input.charCodeAt(this.pos + 2);
  23710. }
  23711. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  23712. return this.finishOp(tokentype, size)
  23713. };
  23714. pp.readToken_pipe_amp = function(code) { // '|&'
  23715. var next = this.input.charCodeAt(this.pos + 1);
  23716. if (next === code) {
  23717. if (this.options.ecmaVersion >= 12) {
  23718. var next2 = this.input.charCodeAt(this.pos + 2);
  23719. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  23720. }
  23721. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  23722. }
  23723. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23724. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  23725. };
  23726. pp.readToken_caret = function() { // '^'
  23727. var next = this.input.charCodeAt(this.pos + 1);
  23728. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23729. return this.finishOp(types$1.bitwiseXOR, 1)
  23730. };
  23731. pp.readToken_plus_min = function(code) { // '+-'
  23732. var next = this.input.charCodeAt(this.pos + 1);
  23733. if (next === code) {
  23734. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  23735. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  23736. // A `-->` line comment
  23737. this.skipLineComment(3);
  23738. this.skipSpace();
  23739. return this.nextToken()
  23740. }
  23741. return this.finishOp(types$1.incDec, 2)
  23742. }
  23743. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23744. return this.finishOp(types$1.plusMin, 1)
  23745. };
  23746. pp.readToken_lt_gt = function(code) { // '<>'
  23747. var next = this.input.charCodeAt(this.pos + 1);
  23748. var size = 1;
  23749. if (next === code) {
  23750. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  23751. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  23752. return this.finishOp(types$1.bitShift, size)
  23753. }
  23754. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  23755. this.input.charCodeAt(this.pos + 3) === 45) {
  23756. // `<!--`, an XML-style comment that should be interpreted as a line comment
  23757. this.skipLineComment(4);
  23758. this.skipSpace();
  23759. return this.nextToken()
  23760. }
  23761. if (next === 61) { size = 2; }
  23762. return this.finishOp(types$1.relational, size)
  23763. };
  23764. pp.readToken_eq_excl = function(code) { // '=!'
  23765. var next = this.input.charCodeAt(this.pos + 1);
  23766. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  23767. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  23768. this.pos += 2;
  23769. return this.finishToken(types$1.arrow)
  23770. }
  23771. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  23772. };
  23773. pp.readToken_question = function() { // '?'
  23774. var ecmaVersion = this.options.ecmaVersion;
  23775. if (ecmaVersion >= 11) {
  23776. var next = this.input.charCodeAt(this.pos + 1);
  23777. if (next === 46) {
  23778. var next2 = this.input.charCodeAt(this.pos + 2);
  23779. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  23780. }
  23781. if (next === 63) {
  23782. if (ecmaVersion >= 12) {
  23783. var next2$1 = this.input.charCodeAt(this.pos + 2);
  23784. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  23785. }
  23786. return this.finishOp(types$1.coalesce, 2)
  23787. }
  23788. }
  23789. return this.finishOp(types$1.question, 1)
  23790. };
  23791. pp.readToken_numberSign = function() { // '#'
  23792. var ecmaVersion = this.options.ecmaVersion;
  23793. var code = 35; // '#'
  23794. if (ecmaVersion >= 13) {
  23795. ++this.pos;
  23796. code = this.fullCharCodeAtPos();
  23797. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  23798. return this.finishToken(types$1.privateId, this.readWord1())
  23799. }
  23800. }
  23801. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  23802. };
  23803. pp.getTokenFromCode = function(code) {
  23804. switch (code) {
  23805. // The interpretation of a dot depends on whether it is followed
  23806. // by a digit or another two dots.
  23807. case 46: // '.'
  23808. return this.readToken_dot()
  23809. // Punctuation tokens.
  23810. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  23811. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  23812. case 59: ++this.pos; return this.finishToken(types$1.semi)
  23813. case 44: ++this.pos; return this.finishToken(types$1.comma)
  23814. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  23815. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  23816. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  23817. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  23818. case 58: ++this.pos; return this.finishToken(types$1.colon)
  23819. case 96: // '`'
  23820. if (this.options.ecmaVersion < 6) { break }
  23821. ++this.pos;
  23822. return this.finishToken(types$1.backQuote)
  23823. case 48: // '0'
  23824. var next = this.input.charCodeAt(this.pos + 1);
  23825. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  23826. if (this.options.ecmaVersion >= 6) {
  23827. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  23828. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  23829. }
  23830. // Anything else beginning with a digit is an integer, octal
  23831. // number, or float.
  23832. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  23833. return this.readNumber(false)
  23834. // Quotes produce strings.
  23835. case 34: case 39: // '"', "'"
  23836. return this.readString(code)
  23837. // Operators are parsed inline in tiny state machines. '=' (61) is
  23838. // often referred to. `finishOp` simply skips the amount of
  23839. // characters it is given as second argument, and returns a token
  23840. // of the type given by its first argument.
  23841. case 47: // '/'
  23842. return this.readToken_slash()
  23843. case 37: case 42: // '%*'
  23844. return this.readToken_mult_modulo_exp(code)
  23845. case 124: case 38: // '|&'
  23846. return this.readToken_pipe_amp(code)
  23847. case 94: // '^'
  23848. return this.readToken_caret()
  23849. case 43: case 45: // '+-'
  23850. return this.readToken_plus_min(code)
  23851. case 60: case 62: // '<>'
  23852. return this.readToken_lt_gt(code)
  23853. case 61: case 33: // '=!'
  23854. return this.readToken_eq_excl(code)
  23855. case 63: // '?'
  23856. return this.readToken_question()
  23857. case 126: // '~'
  23858. return this.finishOp(types$1.prefix, 1)
  23859. case 35: // '#'
  23860. return this.readToken_numberSign()
  23861. }
  23862. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  23863. };
  23864. pp.finishOp = function(type, size) {
  23865. var str = this.input.slice(this.pos, this.pos + size);
  23866. this.pos += size;
  23867. return this.finishToken(type, str)
  23868. };
  23869. pp.readRegexp = function() {
  23870. var escaped, inClass, start = this.pos;
  23871. for (;;) {
  23872. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  23873. var ch = this.input.charAt(this.pos);
  23874. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  23875. if (!escaped) {
  23876. if (ch === "[") { inClass = true; }
  23877. else if (ch === "]" && inClass) { inClass = false; }
  23878. else if (ch === "/" && !inClass) { break }
  23879. escaped = ch === "\\";
  23880. } else { escaped = false; }
  23881. ++this.pos;
  23882. }
  23883. var pattern = this.input.slice(start, this.pos);
  23884. ++this.pos;
  23885. var flagsStart = this.pos;
  23886. var flags = this.readWord1();
  23887. if (this.containsEsc) { this.unexpected(flagsStart); }
  23888. // Validate pattern
  23889. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  23890. state.reset(start, pattern, flags);
  23891. this.validateRegExpFlags(state);
  23892. this.validateRegExpPattern(state);
  23893. // Create Literal#value property value.
  23894. var value = null;
  23895. try {
  23896. value = new RegExp(pattern, flags);
  23897. } catch (e) {
  23898. // ESTree requires null if it failed to instantiate RegExp object.
  23899. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  23900. }
  23901. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  23902. };
  23903. // Read an integer in the given radix. Return null if zero digits
  23904. // were read, the integer value otherwise. When `len` is given, this
  23905. // will return `null` unless the integer has exactly `len` digits.
  23906. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  23907. // `len` is used for character escape sequences. In that case, disallow separators.
  23908. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  23909. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  23910. // and isn't fraction part nor exponent part. In that case, if the first digit
  23911. // is zero then disallow separators.
  23912. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  23913. var start = this.pos, total = 0, lastCode = 0;
  23914. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  23915. var code = this.input.charCodeAt(this.pos), val = (void 0);
  23916. if (allowSeparators && code === 95) {
  23917. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  23918. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  23919. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  23920. lastCode = code;
  23921. continue
  23922. }
  23923. if (code >= 97) { val = code - 97 + 10; } // a
  23924. else if (code >= 65) { val = code - 65 + 10; } // A
  23925. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  23926. else { val = Infinity; }
  23927. if (val >= radix) { break }
  23928. lastCode = code;
  23929. total = total * radix + val;
  23930. }
  23931. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  23932. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  23933. return total
  23934. };
  23935. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  23936. if (isLegacyOctalNumericLiteral) {
  23937. return parseInt(str, 8)
  23938. }
  23939. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  23940. return parseFloat(str.replace(/_/g, ""))
  23941. }
  23942. function stringToBigInt(str) {
  23943. if (typeof BigInt !== "function") {
  23944. return null
  23945. }
  23946. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  23947. return BigInt(str.replace(/_/g, ""))
  23948. }
  23949. pp.readRadixNumber = function(radix) {
  23950. var start = this.pos;
  23951. this.pos += 2; // 0x
  23952. var val = this.readInt(radix);
  23953. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  23954. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  23955. val = stringToBigInt(this.input.slice(start, this.pos));
  23956. ++this.pos;
  23957. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23958. return this.finishToken(types$1.num, val)
  23959. };
  23960. // Read an integer, octal integer, or floating-point number.
  23961. pp.readNumber = function(startsWithDot) {
  23962. var start = this.pos;
  23963. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  23964. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  23965. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  23966. var next = this.input.charCodeAt(this.pos);
  23967. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  23968. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  23969. ++this.pos;
  23970. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23971. return this.finishToken(types$1.num, val$1)
  23972. }
  23973. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  23974. if (next === 46 && !octal) { // '.'
  23975. ++this.pos;
  23976. this.readInt(10);
  23977. next = this.input.charCodeAt(this.pos);
  23978. }
  23979. if ((next === 69 || next === 101) && !octal) { // 'eE'
  23980. next = this.input.charCodeAt(++this.pos);
  23981. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  23982. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  23983. }
  23984. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23985. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  23986. return this.finishToken(types$1.num, val)
  23987. };
  23988. // Read a string value, interpreting backslash-escapes.
  23989. pp.readCodePoint = function() {
  23990. var ch = this.input.charCodeAt(this.pos), code;
  23991. if (ch === 123) { // '{'
  23992. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  23993. var codePos = ++this.pos;
  23994. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  23995. ++this.pos;
  23996. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  23997. } else {
  23998. code = this.readHexChar(4);
  23999. }
  24000. return code
  24001. };
  24002. pp.readString = function(quote) {
  24003. var out = "", chunkStart = ++this.pos;
  24004. for (;;) {
  24005. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  24006. var ch = this.input.charCodeAt(this.pos);
  24007. if (ch === quote) { break }
  24008. if (ch === 92) { // '\'
  24009. out += this.input.slice(chunkStart, this.pos);
  24010. out += this.readEscapedChar(false);
  24011. chunkStart = this.pos;
  24012. } else if (ch === 0x2028 || ch === 0x2029) {
  24013. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  24014. ++this.pos;
  24015. if (this.options.locations) {
  24016. this.curLine++;
  24017. this.lineStart = this.pos;
  24018. }
  24019. } else {
  24020. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  24021. ++this.pos;
  24022. }
  24023. }
  24024. out += this.input.slice(chunkStart, this.pos++);
  24025. return this.finishToken(types$1.string, out)
  24026. };
  24027. // Reads template string tokens.
  24028. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  24029. pp.tryReadTemplateToken = function() {
  24030. this.inTemplateElement = true;
  24031. try {
  24032. this.readTmplToken();
  24033. } catch (err) {
  24034. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  24035. this.readInvalidTemplateToken();
  24036. } else {
  24037. throw err
  24038. }
  24039. }
  24040. this.inTemplateElement = false;
  24041. };
  24042. pp.invalidStringToken = function(position, message) {
  24043. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  24044. throw INVALID_TEMPLATE_ESCAPE_ERROR
  24045. } else {
  24046. this.raise(position, message);
  24047. }
  24048. };
  24049. pp.readTmplToken = function() {
  24050. var out = "", chunkStart = this.pos;
  24051. for (;;) {
  24052. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  24053. var ch = this.input.charCodeAt(this.pos);
  24054. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  24055. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  24056. if (ch === 36) {
  24057. this.pos += 2;
  24058. return this.finishToken(types$1.dollarBraceL)
  24059. } else {
  24060. ++this.pos;
  24061. return this.finishToken(types$1.backQuote)
  24062. }
  24063. }
  24064. out += this.input.slice(chunkStart, this.pos);
  24065. return this.finishToken(types$1.template, out)
  24066. }
  24067. if (ch === 92) { // '\'
  24068. out += this.input.slice(chunkStart, this.pos);
  24069. out += this.readEscapedChar(true);
  24070. chunkStart = this.pos;
  24071. } else if (isNewLine(ch)) {
  24072. out += this.input.slice(chunkStart, this.pos);
  24073. ++this.pos;
  24074. switch (ch) {
  24075. case 13:
  24076. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  24077. case 10:
  24078. out += "\n";
  24079. break
  24080. default:
  24081. out += String.fromCharCode(ch);
  24082. break
  24083. }
  24084. if (this.options.locations) {
  24085. ++this.curLine;
  24086. this.lineStart = this.pos;
  24087. }
  24088. chunkStart = this.pos;
  24089. } else {
  24090. ++this.pos;
  24091. }
  24092. }
  24093. };
  24094. // Reads a template token to search for the end, without validating any escape sequences
  24095. pp.readInvalidTemplateToken = function() {
  24096. for (; this.pos < this.input.length; this.pos++) {
  24097. switch (this.input[this.pos]) {
  24098. case "\\":
  24099. ++this.pos;
  24100. break
  24101. case "$":
  24102. if (this.input[this.pos + 1] !== "{") {
  24103. break
  24104. }
  24105. // falls through
  24106. case "`":
  24107. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  24108. // no default
  24109. }
  24110. }
  24111. this.raise(this.start, "Unterminated template");
  24112. };
  24113. // Used to read escaped characters
  24114. pp.readEscapedChar = function(inTemplate) {
  24115. var ch = this.input.charCodeAt(++this.pos);
  24116. ++this.pos;
  24117. switch (ch) {
  24118. case 110: return "\n" // 'n' -> '\n'
  24119. case 114: return "\r" // 'r' -> '\r'
  24120. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  24121. case 117: return codePointToString(this.readCodePoint()) // 'u'
  24122. case 116: return "\t" // 't' -> '\t'
  24123. case 98: return "\b" // 'b' -> '\b'
  24124. case 118: return "\u000b" // 'v' -> '\u000b'
  24125. case 102: return "\f" // 'f' -> '\f'
  24126. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  24127. case 10: // ' \n'
  24128. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  24129. return ""
  24130. case 56:
  24131. case 57:
  24132. if (this.strict) {
  24133. this.invalidStringToken(
  24134. this.pos - 1,
  24135. "Invalid escape sequence"
  24136. );
  24137. }
  24138. if (inTemplate) {
  24139. var codePos = this.pos - 1;
  24140. this.invalidStringToken(
  24141. codePos,
  24142. "Invalid escape sequence in template string"
  24143. );
  24144. }
  24145. default:
  24146. if (ch >= 48 && ch <= 55) {
  24147. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  24148. var octal = parseInt(octalStr, 8);
  24149. if (octal > 255) {
  24150. octalStr = octalStr.slice(0, -1);
  24151. octal = parseInt(octalStr, 8);
  24152. }
  24153. this.pos += octalStr.length - 1;
  24154. ch = this.input.charCodeAt(this.pos);
  24155. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  24156. this.invalidStringToken(
  24157. this.pos - 1 - octalStr.length,
  24158. inTemplate
  24159. ? "Octal literal in template string"
  24160. : "Octal literal in strict mode"
  24161. );
  24162. }
  24163. return String.fromCharCode(octal)
  24164. }
  24165. if (isNewLine(ch)) {
  24166. // Unicode new line characters after \ get removed from output in both
  24167. // template literals and strings
  24168. return ""
  24169. }
  24170. return String.fromCharCode(ch)
  24171. }
  24172. };
  24173. // Used to read character escape sequences ('\x', '\u', '\U').
  24174. pp.readHexChar = function(len) {
  24175. var codePos = this.pos;
  24176. var n = this.readInt(16, len);
  24177. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  24178. return n
  24179. };
  24180. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  24181. // to whether the word contained a '\u' escape.
  24182. //
  24183. // Incrementally adds only escaped chars, adding other chunks as-is
  24184. // as a micro-optimization.
  24185. pp.readWord1 = function() {
  24186. this.containsEsc = false;
  24187. var word = "", first = true, chunkStart = this.pos;
  24188. var astral = this.options.ecmaVersion >= 6;
  24189. while (this.pos < this.input.length) {
  24190. var ch = this.fullCharCodeAtPos();
  24191. if (isIdentifierChar(ch, astral)) {
  24192. this.pos += ch <= 0xffff ? 1 : 2;
  24193. } else if (ch === 92) { // "\"
  24194. this.containsEsc = true;
  24195. word += this.input.slice(chunkStart, this.pos);
  24196. var escStart = this.pos;
  24197. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  24198. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  24199. ++this.pos;
  24200. var esc = this.readCodePoint();
  24201. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  24202. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  24203. word += codePointToString(esc);
  24204. chunkStart = this.pos;
  24205. } else {
  24206. break
  24207. }
  24208. first = false;
  24209. }
  24210. return word + this.input.slice(chunkStart, this.pos)
  24211. };
  24212. // Read an identifier or keyword token. Will check for reserved
  24213. // words when necessary.
  24214. pp.readWord = function() {
  24215. var word = this.readWord1();
  24216. var type = types$1.name;
  24217. if (this.keywords.test(word)) {
  24218. type = keywords$2[word];
  24219. }
  24220. return this.finishToken(type, word)
  24221. };
  24222. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  24223. //
  24224. // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
  24225. // various contributors and released under an MIT license.
  24226. //
  24227. // Git repositories for Acorn are available at
  24228. //
  24229. // http://marijnhaverbeke.nl/git/acorn
  24230. // https://github.com/acornjs/acorn.git
  24231. //
  24232. // Please use the [github bug tracker][ghbt] to report issues.
  24233. //
  24234. // [ghbt]: https://github.com/acornjs/acorn/issues
  24235. //
  24236. // [walk]: util/walk.js
  24237. var version$2 = "8.10.0";
  24238. Parser$1.acorn = {
  24239. Parser: Parser$1,
  24240. version: version$2,
  24241. defaultOptions: defaultOptions,
  24242. Position: Position,
  24243. SourceLocation: SourceLocation,
  24244. getLineInfo: getLineInfo,
  24245. Node: Node,
  24246. TokenType: TokenType,
  24247. tokTypes: types$1,
  24248. keywordTypes: keywords$2,
  24249. TokContext: TokContext,
  24250. tokContexts: types$2,
  24251. isIdentifierChar: isIdentifierChar,
  24252. isIdentifierStart: isIdentifierStart,
  24253. Token: Token,
  24254. isNewLine: isNewLine,
  24255. lineBreak: lineBreak,
  24256. lineBreakG: lineBreakG,
  24257. nonASCIIwhitespace: nonASCIIwhitespace
  24258. };
  24259. // The main exported interface (under `self.acorn` when in the
  24260. // browser) is a `parse` function that takes a code string and
  24261. // returns an abstract syntax tree as specified by [Mozilla parser
  24262. // API][api].
  24263. //
  24264. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  24265. function parse$b(input, options) {
  24266. return Parser$1.parse(input, options)
  24267. }
  24268. // This function tries to parse a single expression at a given
  24269. // offset in a string. Useful for parsing mixed-language formats
  24270. // that embed JavaScript expressions.
  24271. function parseExpressionAt(input, pos, options) {
  24272. return Parser$1.parseExpressionAt(input, pos, options)
  24273. }
  24274. // Acorn is organized as a tokenizer and a recursive-descent parser.
  24275. // The `tokenizer` export provides an interface to the tokenizer.
  24276. function tokenizer(input, options) {
  24277. return Parser$1.tokenizer(input, options)
  24278. }
  24279. var acorn = {
  24280. __proto__: null,
  24281. Node: Node,
  24282. Parser: Parser$1,
  24283. Position: Position,
  24284. SourceLocation: SourceLocation,
  24285. TokContext: TokContext,
  24286. Token: Token,
  24287. TokenType: TokenType,
  24288. defaultOptions: defaultOptions,
  24289. getLineInfo: getLineInfo,
  24290. isIdentifierChar: isIdentifierChar,
  24291. isIdentifierStart: isIdentifierStart,
  24292. isNewLine: isNewLine,
  24293. keywordTypes: keywords$2,
  24294. lineBreak: lineBreak,
  24295. lineBreakG: lineBreakG,
  24296. nonASCIIwhitespace: nonASCIIwhitespace,
  24297. parse: parse$b,
  24298. parseExpressionAt: parseExpressionAt,
  24299. tokContexts: types$2,
  24300. tokTypes: types$1,
  24301. tokenizer: tokenizer,
  24302. version: version$2
  24303. };
  24304. const HASH_RE = /#/g;
  24305. const AMPERSAND_RE = /&/g;
  24306. const EQUAL_RE = /=/g;
  24307. const PLUS_RE = /\+/g;
  24308. const ENC_CARET_RE = /%5e/gi;
  24309. const ENC_BACKTICK_RE = /%60/gi;
  24310. const ENC_PIPE_RE = /%7c/gi;
  24311. const ENC_SPACE_RE = /%20/gi;
  24312. function encode(text) {
  24313. return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
  24314. }
  24315. function encodeQueryValue(input) {
  24316. return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^");
  24317. }
  24318. function encodeQueryKey(text) {
  24319. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  24320. }
  24321. function encodeQueryItem(key, value) {
  24322. if (typeof value === "number" || typeof value === "boolean") {
  24323. value = String(value);
  24324. }
  24325. if (!value) {
  24326. return encodeQueryKey(key);
  24327. }
  24328. if (Array.isArray(value)) {
  24329. return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
  24330. }
  24331. return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
  24332. }
  24333. function stringifyQuery(query) {
  24334. return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
  24335. }
  24336. new Set(builtinModules);
  24337. function matchAll(regex, string, addition) {
  24338. const matches = [];
  24339. for (const match of string.matchAll(regex)) {
  24340. matches.push({
  24341. ...addition,
  24342. ...match.groups,
  24343. code: match[0],
  24344. start: match.index,
  24345. end: match.index + match[0].length
  24346. });
  24347. }
  24348. return matches;
  24349. }
  24350. function clearImports(imports) {
  24351. return (imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " ");
  24352. }
  24353. function getImportNames(cleanedImports) {
  24354. const topLevelImports = cleanedImports.replace(/{([^}]*)}/, "");
  24355. const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1];
  24356. const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0;
  24357. return {
  24358. namespacedImport,
  24359. defaultImport
  24360. };
  24361. }
  24362. /**
  24363. * @typedef ErrnoExceptionFields
  24364. * @property {number | undefined} [errnode]
  24365. * @property {string | undefined} [code]
  24366. * @property {string | undefined} [path]
  24367. * @property {string | undefined} [syscall]
  24368. * @property {string | undefined} [url]
  24369. *
  24370. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  24371. */
  24372. const isWindows$3 = process$1.platform === 'win32';
  24373. const own$1 = {}.hasOwnProperty;
  24374. const classRegExp = /^([A-Z][a-z\d]*)+$/;
  24375. // Sorted by a rough estimate on most frequently used entries.
  24376. const kTypes = new Set([
  24377. 'string',
  24378. 'function',
  24379. 'number',
  24380. 'object',
  24381. // Accept 'Function' and 'Object' as alternative to the lower cased version.
  24382. 'Function',
  24383. 'Object',
  24384. 'boolean',
  24385. 'bigint',
  24386. 'symbol'
  24387. ]);
  24388. /**
  24389. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  24390. * We cannot use Intl.ListFormat because it's not available in
  24391. * --without-intl builds.
  24392. *
  24393. * @param {Array<string>} array
  24394. * An array of strings.
  24395. * @param {string} [type]
  24396. * The list type to be inserted before the last element.
  24397. * @returns {string}
  24398. */
  24399. function formatList(array, type = 'and') {
  24400. return array.length < 3
  24401. ? array.join(` ${type} `)
  24402. : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
  24403. }
  24404. /** @type {Map<string, MessageFunction | string>} */
  24405. const messages = new Map();
  24406. const nodeInternalPrefix = '__node_internal_';
  24407. /** @type {number} */
  24408. let userStackTraceLimit;
  24409. createError(
  24410. 'ERR_INVALID_ARG_TYPE',
  24411. /**
  24412. * @param {string} name
  24413. * @param {Array<string> | string} expected
  24414. * @param {unknown} actual
  24415. */
  24416. (name, expected, actual) => {
  24417. assert$1(typeof name === 'string', "'name' must be a string");
  24418. if (!Array.isArray(expected)) {
  24419. expected = [expected];
  24420. }
  24421. let message = 'The ';
  24422. if (name.endsWith(' argument')) {
  24423. // For cases like 'first argument'
  24424. message += `${name} `;
  24425. } else {
  24426. const type = name.includes('.') ? 'property' : 'argument';
  24427. message += `"${name}" ${type} `;
  24428. }
  24429. message += 'must be ';
  24430. /** @type {Array<string>} */
  24431. const types = [];
  24432. /** @type {Array<string>} */
  24433. const instances = [];
  24434. /** @type {Array<string>} */
  24435. const other = [];
  24436. for (const value of expected) {
  24437. assert$1(
  24438. typeof value === 'string',
  24439. 'All expected entries have to be of type string'
  24440. );
  24441. if (kTypes.has(value)) {
  24442. types.push(value.toLowerCase());
  24443. } else if (classRegExp.exec(value) === null) {
  24444. assert$1(
  24445. value !== 'object',
  24446. 'The value "object" should be written as "Object"'
  24447. );
  24448. other.push(value);
  24449. } else {
  24450. instances.push(value);
  24451. }
  24452. }
  24453. // Special handle `object` in case other instances are allowed to outline
  24454. // the differences between each other.
  24455. if (instances.length > 0) {
  24456. const pos = types.indexOf('object');
  24457. if (pos !== -1) {
  24458. types.slice(pos, 1);
  24459. instances.push('Object');
  24460. }
  24461. }
  24462. if (types.length > 0) {
  24463. message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
  24464. types,
  24465. 'or'
  24466. )}`;
  24467. if (instances.length > 0 || other.length > 0) message += ' or ';
  24468. }
  24469. if (instances.length > 0) {
  24470. message += `an instance of ${formatList(instances, 'or')}`;
  24471. if (other.length > 0) message += ' or ';
  24472. }
  24473. if (other.length > 0) {
  24474. if (other.length > 1) {
  24475. message += `one of ${formatList(other, 'or')}`;
  24476. } else {
  24477. if (other[0].toLowerCase() !== other[0]) message += 'an ';
  24478. message += `${other[0]}`;
  24479. }
  24480. }
  24481. message += `. Received ${determineSpecificType(actual)}`;
  24482. return message
  24483. },
  24484. TypeError
  24485. );
  24486. createError(
  24487. 'ERR_INVALID_MODULE_SPECIFIER',
  24488. /**
  24489. * @param {string} request
  24490. * @param {string} reason
  24491. * @param {string} [base]
  24492. */
  24493. (request, reason, base = undefined) => {
  24494. return `Invalid module "${request}" ${reason}${
  24495. base ? ` imported from ${base}` : ''
  24496. }`
  24497. },
  24498. TypeError
  24499. );
  24500. createError(
  24501. 'ERR_INVALID_PACKAGE_CONFIG',
  24502. /**
  24503. * @param {string} path
  24504. * @param {string} [base]
  24505. * @param {string} [message]
  24506. */
  24507. (path, base, message) => {
  24508. return `Invalid package config ${path}${
  24509. base ? ` while importing ${base}` : ''
  24510. }${message ? `. ${message}` : ''}`
  24511. },
  24512. Error
  24513. );
  24514. createError(
  24515. 'ERR_INVALID_PACKAGE_TARGET',
  24516. /**
  24517. * @param {string} pkgPath
  24518. * @param {string} key
  24519. * @param {unknown} target
  24520. * @param {boolean} [isImport=false]
  24521. * @param {string} [base]
  24522. */
  24523. (pkgPath, key, target, isImport = false, base = undefined) => {
  24524. const relError =
  24525. typeof target === 'string' &&
  24526. !isImport &&
  24527. target.length > 0 &&
  24528. !target.startsWith('./');
  24529. if (key === '.') {
  24530. assert$1(isImport === false);
  24531. return (
  24532. `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
  24533. `in the package config ${pkgPath}package.json${
  24534. base ? ` imported from ${base}` : ''
  24535. }${relError ? '; targets must start with "./"' : ''}`
  24536. )
  24537. }
  24538. return `Invalid "${
  24539. isImport ? 'imports' : 'exports'
  24540. }" target ${JSON.stringify(
  24541. target
  24542. )} defined for '${key}' in the package config ${pkgPath}package.json${
  24543. base ? ` imported from ${base}` : ''
  24544. }${relError ? '; targets must start with "./"' : ''}`
  24545. },
  24546. Error
  24547. );
  24548. createError(
  24549. 'ERR_MODULE_NOT_FOUND',
  24550. /**
  24551. * @param {string} path
  24552. * @param {string} base
  24553. * @param {string} [type]
  24554. */
  24555. (path, base, type = 'package') => {
  24556. return `Cannot find ${type} '${path}' imported from ${base}`
  24557. },
  24558. Error
  24559. );
  24560. createError(
  24561. 'ERR_NETWORK_IMPORT_DISALLOWED',
  24562. "import of '%s' by %s is not supported: %s",
  24563. Error
  24564. );
  24565. createError(
  24566. 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
  24567. /**
  24568. * @param {string} specifier
  24569. * @param {string} packagePath
  24570. * @param {string} base
  24571. */
  24572. (specifier, packagePath, base) => {
  24573. return `Package import specifier "${specifier}" is not defined${
  24574. packagePath ? ` in package ${packagePath}package.json` : ''
  24575. } imported from ${base}`
  24576. },
  24577. TypeError
  24578. );
  24579. createError(
  24580. 'ERR_PACKAGE_PATH_NOT_EXPORTED',
  24581. /**
  24582. * @param {string} pkgPath
  24583. * @param {string} subpath
  24584. * @param {string} [base]
  24585. */
  24586. (pkgPath, subpath, base = undefined) => {
  24587. if (subpath === '.')
  24588. return `No "exports" main defined in ${pkgPath}package.json${
  24589. base ? ` imported from ${base}` : ''
  24590. }`
  24591. return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${
  24592. base ? ` imported from ${base}` : ''
  24593. }`
  24594. },
  24595. Error
  24596. );
  24597. createError(
  24598. 'ERR_UNSUPPORTED_DIR_IMPORT',
  24599. "Directory import '%s' is not supported " +
  24600. 'resolving ES modules imported from %s',
  24601. Error
  24602. );
  24603. createError(
  24604. 'ERR_UNKNOWN_FILE_EXTENSION',
  24605. /**
  24606. * @param {string} ext
  24607. * @param {string} path
  24608. */
  24609. (ext, path) => {
  24610. return `Unknown file extension "${ext}" for ${path}`
  24611. },
  24612. TypeError
  24613. );
  24614. createError(
  24615. 'ERR_INVALID_ARG_VALUE',
  24616. /**
  24617. * @param {string} name
  24618. * @param {unknown} value
  24619. * @param {string} [reason='is invalid']
  24620. */
  24621. (name, value, reason = 'is invalid') => {
  24622. let inspected = inspect(value);
  24623. if (inspected.length > 128) {
  24624. inspected = `${inspected.slice(0, 128)}...`;
  24625. }
  24626. const type = name.includes('.') ? 'property' : 'argument';
  24627. return `The ${type} '${name}' ${reason}. Received ${inspected}`
  24628. },
  24629. TypeError
  24630. // Note: extra classes have been shaken out.
  24631. // , RangeError
  24632. );
  24633. createError(
  24634. 'ERR_UNSUPPORTED_ESM_URL_SCHEME',
  24635. /**
  24636. * @param {URL} url
  24637. * @param {Array<string>} supported
  24638. */
  24639. (url, supported) => {
  24640. let message = `Only URLs with a scheme in: ${formatList(
  24641. supported
  24642. )} are supported by the default ESM loader`;
  24643. if (isWindows$3 && url.protocol.length === 2) {
  24644. message += '. On Windows, absolute paths must be valid file:// URLs';
  24645. }
  24646. message += `. Received protocol '${url.protocol}'`;
  24647. return message
  24648. },
  24649. Error
  24650. );
  24651. /**
  24652. * Utility function for registering the error codes. Only used here. Exported
  24653. * *only* to allow for testing.
  24654. * @param {string} sym
  24655. * @param {MessageFunction | string} value
  24656. * @param {ErrorConstructor} def
  24657. * @returns {new (...args: Array<any>) => Error}
  24658. */
  24659. function createError(sym, value, def) {
  24660. // Special case for SystemError that formats the error message differently
  24661. // The SystemErrors only have SystemError as their base classes.
  24662. messages.set(sym, value);
  24663. return makeNodeErrorWithCode(def, sym)
  24664. }
  24665. /**
  24666. * @param {ErrorConstructor} Base
  24667. * @param {string} key
  24668. * @returns {ErrorConstructor}
  24669. */
  24670. function makeNodeErrorWithCode(Base, key) {
  24671. // @ts-expect-error It’s a Node error.
  24672. return NodeError
  24673. /**
  24674. * @param {Array<unknown>} args
  24675. */
  24676. function NodeError(...args) {
  24677. const limit = Error.stackTraceLimit;
  24678. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  24679. const error = new Base();
  24680. // Reset the limit and setting the name property.
  24681. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  24682. const message = getMessage(key, args, error);
  24683. Object.defineProperties(error, {
  24684. // Note: no need to implement `kIsNodeError` symbol, would be hard,
  24685. // probably.
  24686. message: {
  24687. value: message,
  24688. enumerable: false,
  24689. writable: true,
  24690. configurable: true
  24691. },
  24692. toString: {
  24693. /** @this {Error} */
  24694. value() {
  24695. return `${this.name} [${key}]: ${this.message}`
  24696. },
  24697. enumerable: false,
  24698. writable: true,
  24699. configurable: true
  24700. }
  24701. });
  24702. captureLargerStackTrace(error);
  24703. // @ts-expect-error It’s a Node error.
  24704. error.code = key;
  24705. return error
  24706. }
  24707. }
  24708. /**
  24709. * @returns {boolean}
  24710. */
  24711. function isErrorStackTraceLimitWritable() {
  24712. // Do no touch Error.stackTraceLimit as V8 would attempt to install
  24713. // it again during deserialization.
  24714. try {
  24715. // @ts-expect-error: not in types?
  24716. if (v8.startupSnapshot.isBuildingSnapshot()) {
  24717. return false
  24718. }
  24719. } catch {}
  24720. const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
  24721. if (desc === undefined) {
  24722. return Object.isExtensible(Error)
  24723. }
  24724. return own$1.call(desc, 'writable') && desc.writable !== undefined
  24725. ? desc.writable
  24726. : desc.set !== undefined
  24727. }
  24728. /**
  24729. * This function removes unnecessary frames from Node.js core errors.
  24730. * @template {(...args: unknown[]) => unknown} T
  24731. * @param {T} fn
  24732. * @returns {T}
  24733. */
  24734. function hideStackFrames(fn) {
  24735. // We rename the functions that will be hidden to cut off the stacktrace
  24736. // at the outermost one
  24737. const hidden = nodeInternalPrefix + fn.name;
  24738. Object.defineProperty(fn, 'name', {value: hidden});
  24739. return fn
  24740. }
  24741. const captureLargerStackTrace = hideStackFrames(
  24742. /**
  24743. * @param {Error} error
  24744. * @returns {Error}
  24745. */
  24746. // @ts-expect-error: fine
  24747. function (error) {
  24748. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  24749. if (stackTraceLimitIsWritable) {
  24750. userStackTraceLimit = Error.stackTraceLimit;
  24751. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  24752. }
  24753. Error.captureStackTrace(error);
  24754. // Reset the limit
  24755. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  24756. return error
  24757. }
  24758. );
  24759. /**
  24760. * @param {string} key
  24761. * @param {Array<unknown>} args
  24762. * @param {Error} self
  24763. * @returns {string}
  24764. */
  24765. function getMessage(key, args, self) {
  24766. const message = messages.get(key);
  24767. assert$1(message !== undefined, 'expected `message` to be found');
  24768. if (typeof message === 'function') {
  24769. assert$1(
  24770. message.length <= args.length, // Default options do not count.
  24771. `Code: ${key}; The provided arguments length (${args.length}) does not ` +
  24772. `match the required ones (${message.length}).`
  24773. );
  24774. return Reflect.apply(message, self, args)
  24775. }
  24776. const regex = /%[dfijoOs]/g;
  24777. let expectedLength = 0;
  24778. while (regex.exec(message) !== null) expectedLength++;
  24779. assert$1(
  24780. expectedLength === args.length,
  24781. `Code: ${key}; The provided arguments length (${args.length}) does not ` +
  24782. `match the required ones (${expectedLength}).`
  24783. );
  24784. if (args.length === 0) return message
  24785. args.unshift(message);
  24786. return Reflect.apply(format$2, null, args)
  24787. }
  24788. /**
  24789. * Determine the specific type of a value for type-mismatch errors.
  24790. * @param {unknown} value
  24791. * @returns {string}
  24792. */
  24793. function determineSpecificType(value) {
  24794. if (value === null || value === undefined) {
  24795. return String(value)
  24796. }
  24797. if (typeof value === 'function' && value.name) {
  24798. return `function ${value.name}`
  24799. }
  24800. if (typeof value === 'object') {
  24801. if (value.constructor && value.constructor.name) {
  24802. return `an instance of ${value.constructor.name}`
  24803. }
  24804. return `${inspect(value, {depth: -1})}`
  24805. }
  24806. let inspected = inspect(value, {colors: false});
  24807. if (inspected.length > 28) {
  24808. inspected = `${inspected.slice(0, 25)}...`;
  24809. }
  24810. return `type ${typeof value} (${inspected})`
  24811. }
  24812. pathToFileURL(process.cwd());
  24813. const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;)import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
  24814. const TYPE_RE = /^\s*?type\s/;
  24815. function findStaticImports(code) {
  24816. return matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" });
  24817. }
  24818. function parseStaticImport(matched) {
  24819. const cleanedImports = clearImports(matched.imports);
  24820. const namedImports = {};
  24821. for (const namedImport of cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []) {
  24822. const [, source = namedImport.trim(), importName = source] = namedImport.match(/^\s*(\S*) as (\S*)\s*$/) || [];
  24823. if (source && !TYPE_RE.test(source)) {
  24824. namedImports[source] = importName;
  24825. }
  24826. }
  24827. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  24828. return {
  24829. ...matched,
  24830. defaultImport,
  24831. namespacedImport,
  24832. namedImports
  24833. };
  24834. }
  24835. const ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
  24836. function hasESMSyntax(code) {
  24837. return ESM_RE.test(code);
  24838. }
  24839. const normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
  24840. const normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
  24841. // special id for paths marked with browser: false
  24842. // https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
  24843. const browserExternalId = '__vite-browser-external';
  24844. // special id for packages that are optional peer deps
  24845. const optionalPeerDepId = '__vite-optional-peer-dep';
  24846. const subpathImportsPrefix = '#';
  24847. const startsWithWordCharRE = /^\w/;
  24848. const debug$d = createDebugger('vite:resolve-details', {
  24849. onlyWhenFocused: true,
  24850. });
  24851. function resolvePlugin(resolveOptions) {
  24852. const { root, isProduction, asSrc, ssrConfig, preferRelative = false, } = resolveOptions;
  24853. const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {};
  24854. // In unix systems, absolute paths inside root first needs to be checked as an
  24855. // absolute URL (/root/root/path-to-file) resulting in failed checks before falling
  24856. // back to checking the path as absolute. If /root/root isn't a valid path, we can
  24857. // avoid these checks. Absolute paths inside root are common in user code as many
  24858. // paths are resolved by the user. For example for an alias.
  24859. const rootInRoot = tryStatSync(path$o.join(root, root))?.isDirectory() ?? false;
  24860. return {
  24861. name: 'vite:resolve',
  24862. async resolveId(id, importer, resolveOpts) {
  24863. if (id[0] === '\0' ||
  24864. id.startsWith('virtual:') ||
  24865. // When injected directly in html/client code
  24866. id.startsWith('/virtual:')) {
  24867. return;
  24868. }
  24869. const ssr = resolveOpts?.ssr === true;
  24870. // We need to delay depsOptimizer until here instead of passing it as an option
  24871. // the resolvePlugin because the optimizer is created on server listen during dev
  24872. const depsOptimizer = resolveOptions.getDepsOptimizer?.(ssr);
  24873. if (id.startsWith(browserExternalId)) {
  24874. return id;
  24875. }
  24876. const targetWeb = !ssr || ssrTarget === 'webworker';
  24877. // this is passed by @rollup/plugin-commonjs
  24878. const isRequire = resolveOpts?.custom?.['node-resolve']?.isRequire ?? false;
  24879. // end user can configure different conditions for ssr and client.
  24880. // falls back to client conditions if no ssr conditions supplied
  24881. const ssrConditions = resolveOptions.ssrConfig?.resolve?.conditions ||
  24882. resolveOptions.conditions;
  24883. const options = {
  24884. isRequire,
  24885. ...resolveOptions,
  24886. scan: resolveOpts?.scan ?? resolveOptions.scan,
  24887. conditions: ssr ? ssrConditions : resolveOptions.conditions,
  24888. };
  24889. const resolvedImports = resolveSubpathImports(id, importer, options, targetWeb);
  24890. if (resolvedImports) {
  24891. id = resolvedImports;
  24892. if (resolveOpts.custom?.['vite:import-glob']?.isSubImportsPattern) {
  24893. return id;
  24894. }
  24895. }
  24896. if (importer) {
  24897. if (isTsRequest(importer) ||
  24898. resolveOpts.custom?.depScan?.loader?.startsWith('ts')) {
  24899. options.isFromTsImporter = true;
  24900. }
  24901. else {
  24902. const moduleLang = this.getModuleInfo(importer)?.meta?.vite?.lang;
  24903. options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
  24904. }
  24905. }
  24906. let res;
  24907. // resolve pre-bundled deps requests, these could be resolved by
  24908. // tryFileResolve or /fs/ resolution but these files may not yet
  24909. // exists if we are in the middle of a deps re-processing
  24910. if (asSrc && depsOptimizer?.isOptimizedDepUrl(id)) {
  24911. const optimizedPath = id.startsWith(FS_PREFIX)
  24912. ? fsPathFromId(id)
  24913. : normalizePath$3(path$o.resolve(root, id.slice(1)));
  24914. return optimizedPath;
  24915. }
  24916. // explicit fs paths that starts with /@fs/*
  24917. if (asSrc && id.startsWith(FS_PREFIX)) {
  24918. res = fsPathFromId(id);
  24919. // We don't need to resolve these paths since they are already resolved
  24920. // always return here even if res doesn't exist since /@fs/ is explicit
  24921. // if the file doesn't exist it should be a 404.
  24922. debug$d?.(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  24923. return ensureVersionQuery(res, id, options, depsOptimizer);
  24924. }
  24925. // URL
  24926. // /foo -> /fs-root/foo
  24927. if (asSrc &&
  24928. id[0] === '/' &&
  24929. (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
  24930. const fsPath = path$o.resolve(root, id.slice(1));
  24931. if ((res = tryFsResolve(fsPath, options))) {
  24932. debug$d?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  24933. return ensureVersionQuery(res, id, options, depsOptimizer);
  24934. }
  24935. }
  24936. // relative
  24937. if (id[0] === '.' ||
  24938. ((preferRelative || importer?.endsWith('.html')) &&
  24939. startsWithWordCharRE.test(id))) {
  24940. const basedir = importer ? path$o.dirname(importer) : process.cwd();
  24941. const fsPath = path$o.resolve(basedir, id);
  24942. // handle browser field mapping for relative imports
  24943. const normalizedFsPath = normalizePath$3(fsPath);
  24944. if (depsOptimizer?.isOptimizedDepFile(normalizedFsPath)) {
  24945. // Optimized files could not yet exist in disk, resolve to the full path
  24946. // Inject the current browserHash version if the path doesn't have one
  24947. if (!resolveOptions.isBuild &&
  24948. !normalizedFsPath.match(DEP_VERSION_RE)) {
  24949. const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
  24950. if (browserHash) {
  24951. return injectQuery(normalizedFsPath, `v=${browserHash}`);
  24952. }
  24953. }
  24954. return normalizedFsPath;
  24955. }
  24956. if (targetWeb &&
  24957. options.browserField &&
  24958. (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
  24959. return res;
  24960. }
  24961. if ((res = tryFsResolve(fsPath, options))) {
  24962. res = ensureVersionQuery(res, id, options, depsOptimizer);
  24963. debug$d?.(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  24964. // If this isn't a script imported from a .html file, include side effects
  24965. // hints so the non-used code is properly tree-shaken during build time.
  24966. if (!options.idOnly &&
  24967. !options.scan &&
  24968. options.isBuild &&
  24969. !importer?.endsWith('.html')) {
  24970. const resPkg = findNearestPackageData(path$o.dirname(res), options.packageCache);
  24971. if (resPkg) {
  24972. return {
  24973. id: res,
  24974. moduleSideEffects: resPkg.hasSideEffects(res),
  24975. };
  24976. }
  24977. }
  24978. return res;
  24979. }
  24980. }
  24981. // drive relative fs paths (only windows)
  24982. if (isWindows$4 && id[0] === '/') {
  24983. const basedir = importer ? path$o.dirname(importer) : process.cwd();
  24984. const fsPath = path$o.resolve(basedir, id);
  24985. if ((res = tryFsResolve(fsPath, options))) {
  24986. debug$d?.(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  24987. return ensureVersionQuery(res, id, options, depsOptimizer);
  24988. }
  24989. }
  24990. // absolute fs paths
  24991. if (isNonDriveRelativeAbsolutePath(id) &&
  24992. (res = tryFsResolve(id, options))) {
  24993. debug$d?.(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  24994. return ensureVersionQuery(res, id, options, depsOptimizer);
  24995. }
  24996. // external
  24997. if (isExternalUrl(id)) {
  24998. return options.idOnly ? id : { id, external: true };
  24999. }
  25000. // data uri: pass through (this only happens during build and will be
  25001. // handled by dedicated plugin)
  25002. if (isDataUrl(id)) {
  25003. return null;
  25004. }
  25005. // bare package imports, perform node resolve
  25006. if (bareImportRE.test(id)) {
  25007. const external = options.shouldExternalize?.(id, importer);
  25008. if (!external &&
  25009. asSrc &&
  25010. depsOptimizer &&
  25011. !options.scan &&
  25012. (res = await tryOptimizedResolve(depsOptimizer, id, importer, options.preserveSymlinks, options.packageCache))) {
  25013. return res;
  25014. }
  25015. if (targetWeb &&
  25016. options.browserField &&
  25017. (res = tryResolveBrowserMapping(id, importer, options, false, external))) {
  25018. return res;
  25019. }
  25020. if ((res = tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, external))) {
  25021. return res;
  25022. }
  25023. // node built-ins.
  25024. // externalize if building for SSR, otherwise redirect to empty module
  25025. if (isBuiltin(id)) {
  25026. if (ssr) {
  25027. if (ssrNoExternal === true) {
  25028. let message = `Cannot bundle Node.js built-in "${id}"`;
  25029. if (importer) {
  25030. message += ` imported from "${path$o.relative(process.cwd(), importer)}"`;
  25031. }
  25032. message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`;
  25033. this.error(message);
  25034. }
  25035. return options.idOnly ? id : { id, external: true };
  25036. }
  25037. else {
  25038. if (!asSrc) {
  25039. debug$d?.(`externalized node built-in "${id}" to empty module. ` +
  25040. `(imported by: ${colors$1.white(colors$1.dim(importer))})`);
  25041. }
  25042. else if (isProduction) {
  25043. this.warn(`Module "${id}" has been externalized for browser compatibility, imported by "${importer}". ` +
  25044. `See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  25045. }
  25046. return isProduction
  25047. ? browserExternalId
  25048. : `${browserExternalId}:${id}`;
  25049. }
  25050. }
  25051. }
  25052. debug$d?.(`[fallthrough] ${colors$1.dim(id)}`);
  25053. },
  25054. load(id) {
  25055. if (id.startsWith(browserExternalId)) {
  25056. if (isProduction) {
  25057. return `export default {}`;
  25058. }
  25059. else {
  25060. id = id.slice(browserExternalId.length + 1);
  25061. return `\
  25062. export default new Proxy({}, {
  25063. get(_, key) {
  25064. throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  25065. }
  25066. })`;
  25067. }
  25068. }
  25069. if (id.startsWith(optionalPeerDepId)) {
  25070. if (isProduction) {
  25071. return `export default {}`;
  25072. }
  25073. else {
  25074. const [, peerDep, parentDep] = id.split(':');
  25075. return `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`;
  25076. }
  25077. }
  25078. },
  25079. };
  25080. }
  25081. function resolveSubpathImports(id, importer, options, targetWeb) {
  25082. if (!importer || !id.startsWith(subpathImportsPrefix))
  25083. return;
  25084. const basedir = path$o.dirname(importer);
  25085. const pkgData = findNearestPackageData(basedir, options.packageCache);
  25086. if (!pkgData)
  25087. return;
  25088. let importsPath = resolveExportsOrImports(pkgData.data, id, options, targetWeb, 'imports');
  25089. if (importsPath?.[0] === '.') {
  25090. importsPath = path$o.relative(basedir, path$o.join(pkgData.dir, importsPath));
  25091. if (importsPath[0] !== '.') {
  25092. importsPath = `./${importsPath}`;
  25093. }
  25094. }
  25095. return importsPath;
  25096. }
  25097. function ensureVersionQuery(resolved, id, options, depsOptimizer) {
  25098. if (!options.isBuild &&
  25099. !options.scan &&
  25100. depsOptimizer &&
  25101. !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
  25102. // Ensure that direct imports of node_modules have the same version query
  25103. // as if they would have been imported through a bare import
  25104. // Use the original id to do the check as the resolved id may be the real
  25105. // file path after symlinks resolution
  25106. const isNodeModule = isInNodeModules(id) || isInNodeModules(resolved);
  25107. if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
  25108. const versionHash = depsOptimizer.metadata.browserHash;
  25109. if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
  25110. resolved = injectQuery(resolved, `v=${versionHash}`);
  25111. }
  25112. }
  25113. }
  25114. return resolved;
  25115. }
  25116. function splitFileAndPostfix(path) {
  25117. const file = cleanUrl(path);
  25118. return { file, postfix: path.slice(file.length) };
  25119. }
  25120. function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
  25121. // Dependencies like es5-ext use `#` in their paths. We don't support `#` in user
  25122. // source code so we only need to perform the check for dependencies.
  25123. // We don't support `?` in node_modules paths, so we only need to check in this branch.
  25124. const hashIndex = fsPath.indexOf('#');
  25125. if (hashIndex >= 0 && isInNodeModules(fsPath)) {
  25126. const queryIndex = fsPath.indexOf('?');
  25127. // We only need to check foo#bar?baz and foo#bar, ignore foo?bar#baz
  25128. if (queryIndex < 0 || queryIndex > hashIndex) {
  25129. const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
  25130. const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
  25131. if (res)
  25132. return res + fsPath.slice(file.length);
  25133. }
  25134. }
  25135. const { file, postfix } = splitFileAndPostfix(fsPath);
  25136. const res = tryCleanFsResolve(file, options, tryIndex, targetWeb, skipPackageJson);
  25137. if (res)
  25138. return res + postfix;
  25139. }
  25140. const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
  25141. const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
  25142. function tryCleanFsResolve(file, options, tryIndex = true, targetWeb = true, skipPackageJson = false) {
  25143. const { tryPrefix, extensions, preserveSymlinks } = options;
  25144. const fileStat = tryStatSync(file);
  25145. // Try direct match first
  25146. if (fileStat?.isFile())
  25147. return getRealPath(file, options.preserveSymlinks);
  25148. let res;
  25149. // If path.dirname is a valid directory, try extensions and ts resolution logic
  25150. const possibleJsToTs = options.isFromTsImporter && isPossibleTsOutput(file);
  25151. if (possibleJsToTs || extensions.length || tryPrefix) {
  25152. const dirPath = path$o.dirname(file);
  25153. const dirStat = tryStatSync(dirPath);
  25154. if (dirStat?.isDirectory()) {
  25155. if (possibleJsToTs) {
  25156. // try resolve .js, .mjs, .cjs or .jsx import to typescript file
  25157. const fileExt = path$o.extname(file);
  25158. const fileName = file.slice(0, -fileExt.length);
  25159. if ((res = tryResolveRealFile(fileName + fileExt.replace('js', 'ts'), preserveSymlinks)))
  25160. return res;
  25161. // for .js, also try .tsx
  25162. if (fileExt === '.js' &&
  25163. (res = tryResolveRealFile(fileName + '.tsx', preserveSymlinks)))
  25164. return res;
  25165. }
  25166. if ((res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)))
  25167. return res;
  25168. if (tryPrefix) {
  25169. const prefixed = `${dirPath}/${options.tryPrefix}${path$o.basename(file)}`;
  25170. if ((res = tryResolveRealFile(prefixed, preserveSymlinks)))
  25171. return res;
  25172. if ((res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)))
  25173. return res;
  25174. }
  25175. }
  25176. }
  25177. if (tryIndex && fileStat) {
  25178. // Path points to a directory, check for package.json and entry and /index file
  25179. const dirPath = file;
  25180. if (!skipPackageJson) {
  25181. let pkgPath = `${dirPath}/package.json`;
  25182. try {
  25183. if (fs$l.existsSync(pkgPath)) {
  25184. if (!options.preserveSymlinks) {
  25185. pkgPath = safeRealpathSync(pkgPath);
  25186. }
  25187. // path points to a node package
  25188. const pkg = loadPackageData(pkgPath);
  25189. return resolvePackageEntry(dirPath, pkg, targetWeb, options);
  25190. }
  25191. }
  25192. catch (e) {
  25193. if (e.code !== 'ENOENT')
  25194. throw e;
  25195. }
  25196. }
  25197. if ((res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)))
  25198. return res;
  25199. if (tryPrefix) {
  25200. if ((res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)))
  25201. return res;
  25202. }
  25203. }
  25204. }
  25205. function tryResolveRealFile(file, preserveSymlinks) {
  25206. const stat = tryStatSync(file);
  25207. if (stat?.isFile())
  25208. return getRealPath(file, preserveSymlinks);
  25209. }
  25210. function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
  25211. for (const ext of extensions) {
  25212. const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
  25213. if (res)
  25214. return res;
  25215. }
  25216. }
  25217. function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
  25218. const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
  25219. // check for deep import, e.g. "my-lib/foo"
  25220. const deepMatch = id.match(deepImportRE);
  25221. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id;
  25222. let basedir;
  25223. if (dedupe?.includes(pkgId)) {
  25224. basedir = root;
  25225. }
  25226. else if (importer &&
  25227. path$o.isAbsolute(importer) &&
  25228. // css processing appends `*` for importer
  25229. (importer[importer.length - 1] === '*' || fs$l.existsSync(cleanUrl(importer)))) {
  25230. basedir = path$o.dirname(importer);
  25231. }
  25232. else {
  25233. basedir = root;
  25234. }
  25235. const pkg = resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
  25236. if (!pkg) {
  25237. // if import can't be found, check if it's an optional peer dep.
  25238. // if so, we can resolve to a special id that errors only when imported.
  25239. if (basedir !== root && // root has no peer dep
  25240. !isBuiltin(id) &&
  25241. !id.includes('\0') &&
  25242. bareImportRE.test(id)) {
  25243. const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
  25244. if (mainPkg) {
  25245. const pkgName = getNpmPackageName(id);
  25246. if (pkgName != null &&
  25247. mainPkg.peerDependencies?.[pkgName] &&
  25248. mainPkg.peerDependenciesMeta?.[pkgName]?.optional) {
  25249. return {
  25250. id: `${optionalPeerDepId}:${id}:${mainPkg.name}`,
  25251. };
  25252. }
  25253. }
  25254. }
  25255. return;
  25256. }
  25257. const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
  25258. const unresolvedId = deepMatch ? '.' + id.slice(pkgId.length) : pkgId;
  25259. let resolved;
  25260. try {
  25261. resolved = resolveId(unresolvedId, pkg, targetWeb, options);
  25262. }
  25263. catch (err) {
  25264. if (!options.tryEsmOnly) {
  25265. throw err;
  25266. }
  25267. }
  25268. if (!resolved && options.tryEsmOnly) {
  25269. resolved = resolveId(unresolvedId, pkg, targetWeb, {
  25270. ...options,
  25271. isRequire: false,
  25272. mainFields: DEFAULT_MAIN_FIELDS,
  25273. extensions: DEFAULT_EXTENSIONS$1,
  25274. });
  25275. }
  25276. if (!resolved) {
  25277. return;
  25278. }
  25279. const processResult = (resolved) => {
  25280. if (!externalize) {
  25281. return resolved;
  25282. }
  25283. // don't external symlink packages
  25284. if (!allowLinkedExternal && !isInNodeModules(resolved.id)) {
  25285. return resolved;
  25286. }
  25287. const resolvedExt = path$o.extname(resolved.id);
  25288. // don't external non-js imports
  25289. if (resolvedExt &&
  25290. resolvedExt !== '.js' &&
  25291. resolvedExt !== '.mjs' &&
  25292. resolvedExt !== '.cjs') {
  25293. return resolved;
  25294. }
  25295. let resolvedId = id;
  25296. if (deepMatch && !pkg?.data.exports && path$o.extname(id) !== resolvedExt) {
  25297. // id date-fns/locale
  25298. // resolve.id ...date-fns/esm/locale/index.js
  25299. const index = resolved.id.indexOf(id);
  25300. if (index > -1) {
  25301. resolvedId = resolved.id.slice(index);
  25302. debug$d?.(`[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}`);
  25303. }
  25304. }
  25305. return { ...resolved, id: resolvedId, external: true };
  25306. };
  25307. if (!options.idOnly &&
  25308. ((!options.scan && isBuild && !depsOptimizer) || externalize)) {
  25309. // Resolve package side effects for build so that rollup can better
  25310. // perform tree-shaking
  25311. return processResult({
  25312. id: resolved,
  25313. moduleSideEffects: pkg.hasSideEffects(resolved),
  25314. });
  25315. }
  25316. const ext = path$o.extname(resolved);
  25317. if (!options.ssrOptimizeCheck &&
  25318. (!isInNodeModules(resolved) || // linked
  25319. !depsOptimizer || // resolving before listening to the server
  25320. options.scan) // initial esbuild scan phase
  25321. ) {
  25322. return { id: resolved };
  25323. }
  25324. // if we reach here, it's a valid dep import that hasn't been optimized.
  25325. const isJsType = depsOptimizer
  25326. ? isOptimizable(resolved, depsOptimizer.options)
  25327. : OPTIMIZABLE_ENTRY_RE.test(resolved);
  25328. let exclude = depsOptimizer?.options.exclude;
  25329. let include = depsOptimizer?.options.include;
  25330. if (options.ssrOptimizeCheck) {
  25331. // we don't have the depsOptimizer
  25332. exclude = options.ssrConfig?.optimizeDeps?.exclude;
  25333. include = options.ssrConfig?.optimizeDeps?.include;
  25334. }
  25335. const skipOptimization = depsOptimizer?.options.noDiscovery ||
  25336. !isJsType ||
  25337. (importer && isInNodeModules(importer)) ||
  25338. exclude?.includes(pkgId) ||
  25339. exclude?.includes(id) ||
  25340. SPECIAL_QUERY_RE.test(resolved) ||
  25341. // During dev SSR, we don't have a way to reload the module graph if
  25342. // a non-optimized dep is found. So we need to skip optimization here.
  25343. // The only optimized deps are the ones explicitly listed in the config.
  25344. (!options.ssrOptimizeCheck && !isBuild && ssr) ||
  25345. // Only optimize non-external CJS deps during SSR by default
  25346. (ssr &&
  25347. !(ext === '.cjs' ||
  25348. (ext === '.js' &&
  25349. findNearestPackageData(path$o.dirname(resolved), options.packageCache)
  25350. ?.data.type !== 'module')) &&
  25351. !(include?.includes(pkgId) || include?.includes(id)));
  25352. if (options.ssrOptimizeCheck) {
  25353. return {
  25354. id: skipOptimization
  25355. ? injectQuery(resolved, `__vite_skip_optimization`)
  25356. : resolved,
  25357. };
  25358. }
  25359. if (skipOptimization) {
  25360. // excluded from optimization
  25361. // Inject a version query to npm deps so that the browser
  25362. // can cache it without re-validation, but only do so for known js types.
  25363. // otherwise we may introduce duplicated modules for externalized files
  25364. // from pre-bundled deps.
  25365. if (!isBuild) {
  25366. const versionHash = depsOptimizer.metadata.browserHash;
  25367. if (versionHash && isJsType) {
  25368. resolved = injectQuery(resolved, `v=${versionHash}`);
  25369. }
  25370. }
  25371. }
  25372. else {
  25373. // this is a missing import, queue optimize-deps re-run and
  25374. // get a resolved its optimized info
  25375. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
  25376. resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
  25377. }
  25378. if (!options.idOnly && !options.scan && isBuild) {
  25379. // Resolve package side effects for build so that rollup can better
  25380. // perform tree-shaking
  25381. return {
  25382. id: resolved,
  25383. moduleSideEffects: pkg.hasSideEffects(resolved),
  25384. };
  25385. }
  25386. else {
  25387. return { id: resolved };
  25388. }
  25389. }
  25390. async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
  25391. // TODO: we need to wait until scanning is done here as this function
  25392. // is used in the preAliasPlugin to decide if an aliased dep is optimized,
  25393. // and avoid replacing the bare import with the resolved path.
  25394. // We should be able to remove this in the future
  25395. await depsOptimizer.scanProcessing;
  25396. const metadata = depsOptimizer.metadata;
  25397. const depInfo = optimizedDepInfoFromId(metadata, id);
  25398. if (depInfo) {
  25399. return depsOptimizer.getOptimizedDepId(depInfo);
  25400. }
  25401. if (!importer)
  25402. return;
  25403. // further check if id is imported by nested dependency
  25404. let idPkgDir;
  25405. const nestedIdMatch = `> ${id}`;
  25406. for (const optimizedData of metadata.depInfoList) {
  25407. if (!optimizedData.src)
  25408. continue; // Ignore chunks
  25409. // check where "foo" is nested in "my-lib > foo"
  25410. if (!optimizedData.id.endsWith(nestedIdMatch))
  25411. continue;
  25412. // lazily initialize idPkgDir
  25413. if (idPkgDir == null) {
  25414. const pkgName = getNpmPackageName(id);
  25415. if (!pkgName)
  25416. break;
  25417. idPkgDir = resolvePackageData(pkgName, importer, preserveSymlinks, packageCache)?.dir;
  25418. // if still null, it likely means that this id isn't a dep for importer.
  25419. // break to bail early
  25420. if (idPkgDir == null)
  25421. break;
  25422. idPkgDir = normalizePath$3(idPkgDir);
  25423. }
  25424. // match by src to correctly identify if id belongs to nested dependency
  25425. if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) {
  25426. return depsOptimizer.getOptimizedDepId(optimizedData);
  25427. }
  25428. }
  25429. }
  25430. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, targetWeb, options) {
  25431. const cached = getResolvedCache('.', targetWeb);
  25432. if (cached) {
  25433. return cached;
  25434. }
  25435. try {
  25436. let entryPoint;
  25437. // resolve exports field with highest priority
  25438. // using https://github.com/lukeed/resolve.exports
  25439. if (data.exports) {
  25440. entryPoint = resolveExportsOrImports(data, '.', options, targetWeb, 'exports');
  25441. }
  25442. const resolvedFromExports = !!entryPoint;
  25443. // if exports resolved to .mjs, still resolve other fields.
  25444. // This is because .mjs files can technically import .cjs files which would
  25445. // make them invalid for pure ESM environments - so if other module/browser
  25446. // fields are present, prioritize those instead.
  25447. if (targetWeb &&
  25448. options.browserField &&
  25449. (!entryPoint || entryPoint.endsWith('.mjs'))) {
  25450. // check browser field
  25451. // https://github.com/defunctzombie/package-browser-field-spec
  25452. const browserEntry = typeof data.browser === 'string'
  25453. ? data.browser
  25454. : isObject$2(data.browser) && data.browser['.'];
  25455. if (browserEntry) {
  25456. // check if the package also has a "module" field.
  25457. if (!options.isRequire &&
  25458. options.mainFields.includes('module') &&
  25459. typeof data.module === 'string' &&
  25460. data.module !== browserEntry) {
  25461. // if both are present, we may have a problem: some package points both
  25462. // to ESM, with "module" targeting Node.js, while some packages points
  25463. // "module" to browser ESM and "browser" to UMD/IIFE.
  25464. // the heuristics here is to actually read the browser entry when
  25465. // possible and check for hints of ESM. If it is not ESM, prefer "module"
  25466. // instead; Otherwise, assume it's ESM and use it.
  25467. const resolvedBrowserEntry = tryFsResolve(path$o.join(dir, browserEntry), options);
  25468. if (resolvedBrowserEntry) {
  25469. const content = fs$l.readFileSync(resolvedBrowserEntry, 'utf-8');
  25470. if (hasESMSyntax(content)) {
  25471. // likely ESM, prefer browser
  25472. entryPoint = browserEntry;
  25473. }
  25474. else {
  25475. // non-ESM, UMD or IIFE or CJS(!!! e.g. firebase 7.x), prefer module
  25476. entryPoint = data.module;
  25477. }
  25478. }
  25479. }
  25480. else {
  25481. entryPoint = browserEntry;
  25482. }
  25483. }
  25484. }
  25485. // fallback to mainFields if still not resolved
  25486. // TODO: review if `.mjs` check is still needed
  25487. if (!resolvedFromExports && (!entryPoint || entryPoint.endsWith('.mjs'))) {
  25488. for (const field of options.mainFields) {
  25489. if (field === 'browser')
  25490. continue; // already checked above
  25491. if (typeof data[field] === 'string') {
  25492. entryPoint = data[field];
  25493. break;
  25494. }
  25495. }
  25496. }
  25497. entryPoint || (entryPoint = data.main);
  25498. // try default entry when entry is not define
  25499. // https://nodejs.org/api/modules.html#all-together
  25500. const entryPoints = entryPoint
  25501. ? [entryPoint]
  25502. : ['index.js', 'index.json', 'index.node'];
  25503. for (let entry of entryPoints) {
  25504. // make sure we don't get scripts when looking for sass
  25505. let skipPackageJson = false;
  25506. if (options.mainFields[0] === 'sass' &&
  25507. !options.extensions.includes(path$o.extname(entry))) {
  25508. entry = '';
  25509. skipPackageJson = true;
  25510. }
  25511. else {
  25512. // resolve object browser field in package.json
  25513. const { browser: browserField } = data;
  25514. if (targetWeb && options.browserField && isObject$2(browserField)) {
  25515. entry = mapWithBrowserField(entry, browserField) || entry;
  25516. }
  25517. }
  25518. const entryPointPath = path$o.join(dir, entry);
  25519. const resolvedEntryPoint = tryFsResolve(entryPointPath, options, true, true, skipPackageJson);
  25520. if (resolvedEntryPoint) {
  25521. debug$d?.(`[package entry] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedEntryPoint)}`);
  25522. setResolvedCache('.', resolvedEntryPoint, targetWeb);
  25523. return resolvedEntryPoint;
  25524. }
  25525. }
  25526. }
  25527. catch (e) {
  25528. packageEntryFailure(id, e.message);
  25529. }
  25530. packageEntryFailure(id);
  25531. }
  25532. function packageEntryFailure(id, details) {
  25533. throw new Error(`Failed to resolve entry for package "${id}". ` +
  25534. `The package may have incorrect main/module/exports specified in its package.json` +
  25535. (details ? ': ' + details : '.'));
  25536. }
  25537. function resolveExportsOrImports(pkg, key, options, targetWeb, type) {
  25538. const additionalConditions = new Set(options.overrideConditions || [
  25539. 'production',
  25540. 'development',
  25541. 'module',
  25542. ...options.conditions,
  25543. ]);
  25544. const conditions = [...additionalConditions].filter((condition) => {
  25545. switch (condition) {
  25546. case 'production':
  25547. return options.isProduction;
  25548. case 'development':
  25549. return !options.isProduction;
  25550. }
  25551. return true;
  25552. });
  25553. const fn = type === 'imports' ? f : o;
  25554. const result = fn(pkg, key, {
  25555. browser: targetWeb && !additionalConditions.has('node'),
  25556. require: options.isRequire && !additionalConditions.has('import'),
  25557. conditions,
  25558. });
  25559. return result ? result[0] : undefined;
  25560. }
  25561. function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolvedCache, dir, data, }, targetWeb, options) {
  25562. const cache = getResolvedCache(id, targetWeb);
  25563. if (cache) {
  25564. return cache;
  25565. }
  25566. let relativeId = id;
  25567. const { exports: exportsField, browser: browserField } = data;
  25568. // map relative based on exports data
  25569. if (exportsField) {
  25570. if (isObject$2(exportsField) && !Array.isArray(exportsField)) {
  25571. // resolve without postfix (see #7098)
  25572. const { file, postfix } = splitFileAndPostfix(relativeId);
  25573. const exportsId = resolveExportsOrImports(data, file, options, targetWeb, 'exports');
  25574. if (exportsId !== undefined) {
  25575. relativeId = exportsId + postfix;
  25576. }
  25577. else {
  25578. relativeId = undefined;
  25579. }
  25580. }
  25581. else {
  25582. // not exposed
  25583. relativeId = undefined;
  25584. }
  25585. if (!relativeId) {
  25586. throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` +
  25587. `${path$o.join(dir, 'package.json')}.`);
  25588. }
  25589. }
  25590. else if (targetWeb && options.browserField && isObject$2(browserField)) {
  25591. // resolve without postfix (see #7098)
  25592. const { file, postfix } = splitFileAndPostfix(relativeId);
  25593. const mapped = mapWithBrowserField(file, browserField);
  25594. if (mapped) {
  25595. relativeId = mapped + postfix;
  25596. }
  25597. else if (mapped === false) {
  25598. return (webResolvedImports[id] = browserExternalId);
  25599. }
  25600. }
  25601. if (relativeId) {
  25602. const resolved = tryFsResolve(path$o.join(dir, relativeId), options, !exportsField, // try index only if no exports field
  25603. targetWeb);
  25604. if (resolved) {
  25605. debug$d?.(`[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`);
  25606. setResolvedCache(id, resolved, targetWeb);
  25607. return resolved;
  25608. }
  25609. }
  25610. }
  25611. function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
  25612. let res;
  25613. const pkg = importer &&
  25614. findNearestPackageData(path$o.dirname(importer), options.packageCache);
  25615. if (pkg && isObject$2(pkg.data.browser)) {
  25616. const mapId = isFilePath ? './' + slash$1(path$o.relative(pkg.dir, id)) : id;
  25617. const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
  25618. if (browserMappedPath) {
  25619. if ((res = bareImportRE.test(browserMappedPath)
  25620. ? tryNodeResolve(browserMappedPath, importer, options, true)?.id
  25621. : tryFsResolve(path$o.join(pkg.dir, browserMappedPath), options))) {
  25622. debug$d?.(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  25623. let result = { id: res };
  25624. if (options.idOnly) {
  25625. return result;
  25626. }
  25627. if (!options.scan && options.isBuild) {
  25628. const resPkg = findNearestPackageData(path$o.dirname(res), options.packageCache);
  25629. if (resPkg) {
  25630. result = {
  25631. id: res,
  25632. moduleSideEffects: resPkg.hasSideEffects(res),
  25633. };
  25634. }
  25635. }
  25636. return externalize ? { ...result, external: true } : result;
  25637. }
  25638. }
  25639. else if (browserMappedPath === false) {
  25640. return browserExternalId;
  25641. }
  25642. }
  25643. }
  25644. /**
  25645. * given a relative path in pkg dir,
  25646. * return a relative path in pkg dir,
  25647. * mapped with the "map" object
  25648. *
  25649. * - Returning `undefined` means there is no browser mapping for this id
  25650. * - Returning `false` means this id is explicitly externalized for browser
  25651. */
  25652. function mapWithBrowserField(relativePathInPkgDir, map) {
  25653. const normalizedPath = path$o.posix.normalize(relativePathInPkgDir);
  25654. for (const key in map) {
  25655. const normalizedKey = path$o.posix.normalize(key);
  25656. if (normalizedPath === normalizedKey ||
  25657. equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||
  25658. equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) {
  25659. return map[key];
  25660. }
  25661. }
  25662. }
  25663. function equalWithoutSuffix(path, key, suffix) {
  25664. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
  25665. }
  25666. function getRealPath(resolved, preserveSymlinks) {
  25667. if (!preserveSymlinks && browserExternalId !== resolved) {
  25668. resolved = safeRealpathSync(resolved);
  25669. }
  25670. return normalizePath$3(resolved);
  25671. }
  25672. var dist = {};
  25673. (function (exports) {
  25674. Object.defineProperty(exports, "__esModule", { value: true });
  25675. exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0;
  25676. const path = require$$0$4;
  25677. const fs = require$$0__default;
  25678. const os = require$$2;
  25679. const fsReadFileAsync = fs.promises.readFile;
  25680. function getDefaultSearchPlaces(name) {
  25681. return [
  25682. 'package.json',
  25683. `.${name}rc.json`,
  25684. `.${name}rc.js`,
  25685. `${name}.config.js`,
  25686. `.${name}rc.cjs`,
  25687. `${name}.config.cjs`,
  25688. ];
  25689. }
  25690. function getSearchPaths(startDir, stopDir) {
  25691. return startDir
  25692. .split(path.sep)
  25693. .reduceRight((acc, _, ind, arr) => {
  25694. const currentPath = arr.slice(0, ind + 1).join(path.sep);
  25695. if (!acc.passedStopDir)
  25696. acc.searchPlaces.push(currentPath || path.sep);
  25697. if (currentPath === stopDir)
  25698. acc.passedStopDir = true;
  25699. return acc;
  25700. }, { searchPlaces: [], passedStopDir: false }).searchPlaces;
  25701. }
  25702. exports.defaultLoaders = Object.freeze({
  25703. '.js': __require,
  25704. '.json': __require,
  25705. '.cjs': __require,
  25706. noExt(_, content) {
  25707. return JSON.parse(content);
  25708. },
  25709. });
  25710. function getExtDesc(ext) {
  25711. return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`;
  25712. }
  25713. function getOptions(name, options = {}) {
  25714. const conf = {
  25715. stopDir: os.homedir(),
  25716. searchPlaces: getDefaultSearchPlaces(name),
  25717. ignoreEmptySearchPlaces: true,
  25718. transform: (x) => x,
  25719. packageProp: [name],
  25720. ...options,
  25721. loaders: { ...exports.defaultLoaders, ...options.loaders },
  25722. };
  25723. conf.searchPlaces.forEach(place => {
  25724. const key = path.extname(place) || 'noExt';
  25725. const loader = conf.loaders[key];
  25726. if (!loader) {
  25727. throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`);
  25728. }
  25729. if (typeof loader !== 'function') {
  25730. throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
  25731. }
  25732. });
  25733. return conf;
  25734. }
  25735. function getPackageProp(props, obj) {
  25736. if (typeof props === 'string' && props in obj)
  25737. return obj[props];
  25738. return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null);
  25739. }
  25740. function getSearchItems(searchPlaces, searchPaths) {
  25741. return searchPaths.reduce((acc, searchPath) => {
  25742. searchPlaces.forEach(fileName => acc.push({
  25743. fileName,
  25744. filepath: path.join(searchPath, fileName),
  25745. loaderKey: path.extname(fileName) || 'noExt',
  25746. }));
  25747. return acc;
  25748. }, []);
  25749. }
  25750. function validateFilePath(filepath) {
  25751. if (!filepath)
  25752. throw new Error('load must pass a non-empty string');
  25753. }
  25754. function validateLoader(loader, ext) {
  25755. if (!loader)
  25756. throw new Error(`No loader specified for extension "${ext}"`);
  25757. if (typeof loader !== 'function')
  25758. throw new Error('loader is not a function');
  25759. }
  25760. function lilconfig(name, options) {
  25761. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  25762. return {
  25763. async search(searchFrom = process.cwd()) {
  25764. const searchPaths = getSearchPaths(searchFrom, stopDir);
  25765. const result = {
  25766. config: null,
  25767. filepath: '',
  25768. };
  25769. const searchItems = getSearchItems(searchPlaces, searchPaths);
  25770. for (const { fileName, filepath, loaderKey } of searchItems) {
  25771. try {
  25772. await fs.promises.access(filepath);
  25773. }
  25774. catch (_a) {
  25775. continue;
  25776. }
  25777. const content = String(await fsReadFileAsync(filepath));
  25778. const loader = loaders[loaderKey];
  25779. if (fileName === 'package.json') {
  25780. const pkg = await loader(filepath, content);
  25781. const maybeConfig = getPackageProp(packageProp, pkg);
  25782. if (maybeConfig != null) {
  25783. result.config = maybeConfig;
  25784. result.filepath = filepath;
  25785. break;
  25786. }
  25787. continue;
  25788. }
  25789. const isEmpty = content.trim() === '';
  25790. if (isEmpty && ignoreEmptySearchPlaces)
  25791. continue;
  25792. if (isEmpty) {
  25793. result.isEmpty = true;
  25794. result.config = undefined;
  25795. }
  25796. else {
  25797. validateLoader(loader, loaderKey);
  25798. result.config = await loader(filepath, content);
  25799. }
  25800. result.filepath = filepath;
  25801. break;
  25802. }
  25803. if (result.filepath === '' && result.config === null)
  25804. return transform(null);
  25805. return transform(result);
  25806. },
  25807. async load(filepath) {
  25808. validateFilePath(filepath);
  25809. const absPath = path.resolve(process.cwd(), filepath);
  25810. const { base, ext } = path.parse(absPath);
  25811. const loaderKey = ext || 'noExt';
  25812. const loader = loaders[loaderKey];
  25813. validateLoader(loader, loaderKey);
  25814. const content = String(await fsReadFileAsync(absPath));
  25815. if (base === 'package.json') {
  25816. const pkg = await loader(absPath, content);
  25817. return transform({
  25818. config: getPackageProp(packageProp, pkg),
  25819. filepath: absPath,
  25820. });
  25821. }
  25822. const result = {
  25823. config: null,
  25824. filepath: absPath,
  25825. };
  25826. const isEmpty = content.trim() === '';
  25827. if (isEmpty && ignoreEmptySearchPlaces)
  25828. return transform({
  25829. config: undefined,
  25830. filepath: absPath,
  25831. isEmpty: true,
  25832. });
  25833. result.config = isEmpty
  25834. ? undefined
  25835. : await loader(absPath, content);
  25836. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  25837. },
  25838. };
  25839. }
  25840. exports.lilconfig = lilconfig;
  25841. function lilconfigSync(name, options) {
  25842. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  25843. return {
  25844. search(searchFrom = process.cwd()) {
  25845. const searchPaths = getSearchPaths(searchFrom, stopDir);
  25846. const result = {
  25847. config: null,
  25848. filepath: '',
  25849. };
  25850. const searchItems = getSearchItems(searchPlaces, searchPaths);
  25851. for (const { fileName, filepath, loaderKey } of searchItems) {
  25852. try {
  25853. fs.accessSync(filepath);
  25854. }
  25855. catch (_a) {
  25856. continue;
  25857. }
  25858. const loader = loaders[loaderKey];
  25859. const content = String(fs.readFileSync(filepath));
  25860. if (fileName === 'package.json') {
  25861. const pkg = loader(filepath, content);
  25862. const maybeConfig = getPackageProp(packageProp, pkg);
  25863. if (maybeConfig != null) {
  25864. result.config = maybeConfig;
  25865. result.filepath = filepath;
  25866. break;
  25867. }
  25868. continue;
  25869. }
  25870. const isEmpty = content.trim() === '';
  25871. if (isEmpty && ignoreEmptySearchPlaces)
  25872. continue;
  25873. if (isEmpty) {
  25874. result.isEmpty = true;
  25875. result.config = undefined;
  25876. }
  25877. else {
  25878. validateLoader(loader, loaderKey);
  25879. result.config = loader(filepath, content);
  25880. }
  25881. result.filepath = filepath;
  25882. break;
  25883. }
  25884. if (result.filepath === '' && result.config === null)
  25885. return transform(null);
  25886. return transform(result);
  25887. },
  25888. load(filepath) {
  25889. validateFilePath(filepath);
  25890. const absPath = path.resolve(process.cwd(), filepath);
  25891. const { base, ext } = path.parse(absPath);
  25892. const loaderKey = ext || 'noExt';
  25893. const loader = loaders[loaderKey];
  25894. validateLoader(loader, loaderKey);
  25895. const content = String(fs.readFileSync(absPath));
  25896. if (base === 'package.json') {
  25897. const pkg = loader(absPath, content);
  25898. return transform({
  25899. config: getPackageProp(packageProp, pkg),
  25900. filepath: absPath,
  25901. });
  25902. }
  25903. const result = {
  25904. config: null,
  25905. filepath: absPath,
  25906. };
  25907. const isEmpty = content.trim() === '';
  25908. if (isEmpty && ignoreEmptySearchPlaces)
  25909. return transform({
  25910. filepath: absPath,
  25911. config: undefined,
  25912. isEmpty: true,
  25913. });
  25914. result.config = isEmpty ? undefined : loader(absPath, content);
  25915. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  25916. },
  25917. };
  25918. }
  25919. exports.lilconfigSync = lilconfigSync;
  25920. } (dist));
  25921. const ALIAS = Symbol.for('yaml.alias');
  25922. const DOC = Symbol.for('yaml.document');
  25923. const MAP = Symbol.for('yaml.map');
  25924. const PAIR = Symbol.for('yaml.pair');
  25925. const SCALAR$1 = Symbol.for('yaml.scalar');
  25926. const SEQ = Symbol.for('yaml.seq');
  25927. const NODE_TYPE = Symbol.for('yaml.node.type');
  25928. const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
  25929. const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
  25930. const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
  25931. const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
  25932. const isScalar$1 = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR$1;
  25933. const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
  25934. function isCollection$1(node) {
  25935. if (node && typeof node === 'object')
  25936. switch (node[NODE_TYPE]) {
  25937. case MAP:
  25938. case SEQ:
  25939. return true;
  25940. }
  25941. return false;
  25942. }
  25943. function isNode$1(node) {
  25944. if (node && typeof node === 'object')
  25945. switch (node[NODE_TYPE]) {
  25946. case ALIAS:
  25947. case MAP:
  25948. case SCALAR$1:
  25949. case SEQ:
  25950. return true;
  25951. }
  25952. return false;
  25953. }
  25954. const hasAnchor = (node) => (isScalar$1(node) || isCollection$1(node)) && !!node.anchor;
  25955. class NodeBase {
  25956. constructor(type) {
  25957. Object.defineProperty(this, NODE_TYPE, { value: type });
  25958. }
  25959. /** Create a copy of this node. */
  25960. clone() {
  25961. const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
  25962. if (this.range)
  25963. copy.range = this.range.slice();
  25964. return copy;
  25965. }
  25966. }
  25967. const BREAK$1 = Symbol('break visit');
  25968. const SKIP$1 = Symbol('skip children');
  25969. const REMOVE$1 = Symbol('remove node');
  25970. /**
  25971. * Apply a visitor to an AST node or document.
  25972. *
  25973. * Walks through the tree (depth-first) starting from `node`, calling a
  25974. * `visitor` function with three arguments:
  25975. * - `key`: For sequence values and map `Pair`, the node's index in the
  25976. * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
  25977. * `null` for the root node.
  25978. * - `node`: The current node.
  25979. * - `path`: The ancestry of the current node.
  25980. *
  25981. * The return value of the visitor may be used to control the traversal:
  25982. * - `undefined` (default): Do nothing and continue
  25983. * - `visit.SKIP`: Do not visit the children of this node, continue with next
  25984. * sibling
  25985. * - `visit.BREAK`: Terminate traversal completely
  25986. * - `visit.REMOVE`: Remove the current node, then continue with the next one
  25987. * - `Node`: Replace the current node, then continue by visiting it
  25988. * - `number`: While iterating the items of a sequence or map, set the index
  25989. * of the next step. This is useful especially if the index of the current
  25990. * node has changed.
  25991. *
  25992. * If `visitor` is a single function, it will be called with all values
  25993. * encountered in the tree, including e.g. `null` values. Alternatively,
  25994. * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
  25995. * `Alias` and `Scalar` node. To define the same visitor function for more than
  25996. * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
  25997. * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
  25998. * specific defined one will be used for each node.
  25999. */
  26000. function visit$1(node, visitor) {
  26001. const visitor_ = initVisitor(visitor);
  26002. if (isDocument(node)) {
  26003. const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
  26004. if (cd === REMOVE$1)
  26005. node.contents = null;
  26006. }
  26007. else
  26008. visit_(null, node, visitor_, Object.freeze([]));
  26009. }
  26010. // Without the `as symbol` casts, TS declares these in the `visit`
  26011. // namespace using `var`, but then complains about that because
  26012. // `unique symbol` must be `const`.
  26013. /** Terminate visit traversal completely */
  26014. visit$1.BREAK = BREAK$1;
  26015. /** Do not visit the children of the current node */
  26016. visit$1.SKIP = SKIP$1;
  26017. /** Remove the current node */
  26018. visit$1.REMOVE = REMOVE$1;
  26019. function visit_(key, node, visitor, path) {
  26020. const ctrl = callVisitor(key, node, visitor, path);
  26021. if (isNode$1(ctrl) || isPair(ctrl)) {
  26022. replaceNode(key, path, ctrl);
  26023. return visit_(key, ctrl, visitor, path);
  26024. }
  26025. if (typeof ctrl !== 'symbol') {
  26026. if (isCollection$1(node)) {
  26027. path = Object.freeze(path.concat(node));
  26028. for (let i = 0; i < node.items.length; ++i) {
  26029. const ci = visit_(i, node.items[i], visitor, path);
  26030. if (typeof ci === 'number')
  26031. i = ci - 1;
  26032. else if (ci === BREAK$1)
  26033. return BREAK$1;
  26034. else if (ci === REMOVE$1) {
  26035. node.items.splice(i, 1);
  26036. i -= 1;
  26037. }
  26038. }
  26039. }
  26040. else if (isPair(node)) {
  26041. path = Object.freeze(path.concat(node));
  26042. const ck = visit_('key', node.key, visitor, path);
  26043. if (ck === BREAK$1)
  26044. return BREAK$1;
  26045. else if (ck === REMOVE$1)
  26046. node.key = null;
  26047. const cv = visit_('value', node.value, visitor, path);
  26048. if (cv === BREAK$1)
  26049. return BREAK$1;
  26050. else if (cv === REMOVE$1)
  26051. node.value = null;
  26052. }
  26053. }
  26054. return ctrl;
  26055. }
  26056. /**
  26057. * Apply an async visitor to an AST node or document.
  26058. *
  26059. * Walks through the tree (depth-first) starting from `node`, calling a
  26060. * `visitor` function with three arguments:
  26061. * - `key`: For sequence values and map `Pair`, the node's index in the
  26062. * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
  26063. * `null` for the root node.
  26064. * - `node`: The current node.
  26065. * - `path`: The ancestry of the current node.
  26066. *
  26067. * The return value of the visitor may be used to control the traversal:
  26068. * - `Promise`: Must resolve to one of the following values
  26069. * - `undefined` (default): Do nothing and continue
  26070. * - `visit.SKIP`: Do not visit the children of this node, continue with next
  26071. * sibling
  26072. * - `visit.BREAK`: Terminate traversal completely
  26073. * - `visit.REMOVE`: Remove the current node, then continue with the next one
  26074. * - `Node`: Replace the current node, then continue by visiting it
  26075. * - `number`: While iterating the items of a sequence or map, set the index
  26076. * of the next step. This is useful especially if the index of the current
  26077. * node has changed.
  26078. *
  26079. * If `visitor` is a single function, it will be called with all values
  26080. * encountered in the tree, including e.g. `null` values. Alternatively,
  26081. * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
  26082. * `Alias` and `Scalar` node. To define the same visitor function for more than
  26083. * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
  26084. * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
  26085. * specific defined one will be used for each node.
  26086. */
  26087. async function visitAsync(node, visitor) {
  26088. const visitor_ = initVisitor(visitor);
  26089. if (isDocument(node)) {
  26090. const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
  26091. if (cd === REMOVE$1)
  26092. node.contents = null;
  26093. }
  26094. else
  26095. await visitAsync_(null, node, visitor_, Object.freeze([]));
  26096. }
  26097. // Without the `as symbol` casts, TS declares these in the `visit`
  26098. // namespace using `var`, but then complains about that because
  26099. // `unique symbol` must be `const`.
  26100. /** Terminate visit traversal completely */
  26101. visitAsync.BREAK = BREAK$1;
  26102. /** Do not visit the children of the current node */
  26103. visitAsync.SKIP = SKIP$1;
  26104. /** Remove the current node */
  26105. visitAsync.REMOVE = REMOVE$1;
  26106. async function visitAsync_(key, node, visitor, path) {
  26107. const ctrl = await callVisitor(key, node, visitor, path);
  26108. if (isNode$1(ctrl) || isPair(ctrl)) {
  26109. replaceNode(key, path, ctrl);
  26110. return visitAsync_(key, ctrl, visitor, path);
  26111. }
  26112. if (typeof ctrl !== 'symbol') {
  26113. if (isCollection$1(node)) {
  26114. path = Object.freeze(path.concat(node));
  26115. for (let i = 0; i < node.items.length; ++i) {
  26116. const ci = await visitAsync_(i, node.items[i], visitor, path);
  26117. if (typeof ci === 'number')
  26118. i = ci - 1;
  26119. else if (ci === BREAK$1)
  26120. return BREAK$1;
  26121. else if (ci === REMOVE$1) {
  26122. node.items.splice(i, 1);
  26123. i -= 1;
  26124. }
  26125. }
  26126. }
  26127. else if (isPair(node)) {
  26128. path = Object.freeze(path.concat(node));
  26129. const ck = await visitAsync_('key', node.key, visitor, path);
  26130. if (ck === BREAK$1)
  26131. return BREAK$1;
  26132. else if (ck === REMOVE$1)
  26133. node.key = null;
  26134. const cv = await visitAsync_('value', node.value, visitor, path);
  26135. if (cv === BREAK$1)
  26136. return BREAK$1;
  26137. else if (cv === REMOVE$1)
  26138. node.value = null;
  26139. }
  26140. }
  26141. return ctrl;
  26142. }
  26143. function initVisitor(visitor) {
  26144. if (typeof visitor === 'object' &&
  26145. (visitor.Collection || visitor.Node || visitor.Value)) {
  26146. return Object.assign({
  26147. Alias: visitor.Node,
  26148. Map: visitor.Node,
  26149. Scalar: visitor.Node,
  26150. Seq: visitor.Node
  26151. }, visitor.Value && {
  26152. Map: visitor.Value,
  26153. Scalar: visitor.Value,
  26154. Seq: visitor.Value
  26155. }, visitor.Collection && {
  26156. Map: visitor.Collection,
  26157. Seq: visitor.Collection
  26158. }, visitor);
  26159. }
  26160. return visitor;
  26161. }
  26162. function callVisitor(key, node, visitor, path) {
  26163. if (typeof visitor === 'function')
  26164. return visitor(key, node, path);
  26165. if (isMap(node))
  26166. return visitor.Map?.(key, node, path);
  26167. if (isSeq(node))
  26168. return visitor.Seq?.(key, node, path);
  26169. if (isPair(node))
  26170. return visitor.Pair?.(key, node, path);
  26171. if (isScalar$1(node))
  26172. return visitor.Scalar?.(key, node, path);
  26173. if (isAlias(node))
  26174. return visitor.Alias?.(key, node, path);
  26175. return undefined;
  26176. }
  26177. function replaceNode(key, path, node) {
  26178. const parent = path[path.length - 1];
  26179. if (isCollection$1(parent)) {
  26180. parent.items[key] = node;
  26181. }
  26182. else if (isPair(parent)) {
  26183. if (key === 'key')
  26184. parent.key = node;
  26185. else
  26186. parent.value = node;
  26187. }
  26188. else if (isDocument(parent)) {
  26189. parent.contents = node;
  26190. }
  26191. else {
  26192. const pt = isAlias(parent) ? 'alias' : 'scalar';
  26193. throw new Error(`Cannot replace node with ${pt} parent`);
  26194. }
  26195. }
  26196. const escapeChars = {
  26197. '!': '%21',
  26198. ',': '%2C',
  26199. '[': '%5B',
  26200. ']': '%5D',
  26201. '{': '%7B',
  26202. '}': '%7D'
  26203. };
  26204. const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]);
  26205. class Directives {
  26206. constructor(yaml, tags) {
  26207. /**
  26208. * The directives-end/doc-start marker `---`. If `null`, a marker may still be
  26209. * included in the document's stringified representation.
  26210. */
  26211. this.docStart = null;
  26212. /** The doc-end marker `...`. */
  26213. this.docEnd = false;
  26214. this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
  26215. this.tags = Object.assign({}, Directives.defaultTags, tags);
  26216. }
  26217. clone() {
  26218. const copy = new Directives(this.yaml, this.tags);
  26219. copy.docStart = this.docStart;
  26220. return copy;
  26221. }
  26222. /**
  26223. * During parsing, get a Directives instance for the current document and
  26224. * update the stream state according to the current version's spec.
  26225. */
  26226. atDocument() {
  26227. const res = new Directives(this.yaml, this.tags);
  26228. switch (this.yaml.version) {
  26229. case '1.1':
  26230. this.atNextDocument = true;
  26231. break;
  26232. case '1.2':
  26233. this.atNextDocument = false;
  26234. this.yaml = {
  26235. explicit: Directives.defaultYaml.explicit,
  26236. version: '1.2'
  26237. };
  26238. this.tags = Object.assign({}, Directives.defaultTags);
  26239. break;
  26240. }
  26241. return res;
  26242. }
  26243. /**
  26244. * @param onError - May be called even if the action was successful
  26245. * @returns `true` on success
  26246. */
  26247. add(line, onError) {
  26248. if (this.atNextDocument) {
  26249. this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };
  26250. this.tags = Object.assign({}, Directives.defaultTags);
  26251. this.atNextDocument = false;
  26252. }
  26253. const parts = line.trim().split(/[ \t]+/);
  26254. const name = parts.shift();
  26255. switch (name) {
  26256. case '%TAG': {
  26257. if (parts.length !== 2) {
  26258. onError(0, '%TAG directive should contain exactly two parts');
  26259. if (parts.length < 2)
  26260. return false;
  26261. }
  26262. const [handle, prefix] = parts;
  26263. this.tags[handle] = prefix;
  26264. return true;
  26265. }
  26266. case '%YAML': {
  26267. this.yaml.explicit = true;
  26268. if (parts.length !== 1) {
  26269. onError(0, '%YAML directive should contain exactly one part');
  26270. return false;
  26271. }
  26272. const [version] = parts;
  26273. if (version === '1.1' || version === '1.2') {
  26274. this.yaml.version = version;
  26275. return true;
  26276. }
  26277. else {
  26278. const isValid = /^\d+\.\d+$/.test(version);
  26279. onError(6, `Unsupported YAML version ${version}`, isValid);
  26280. return false;
  26281. }
  26282. }
  26283. default:
  26284. onError(0, `Unknown directive ${name}`, true);
  26285. return false;
  26286. }
  26287. }
  26288. /**
  26289. * Resolves a tag, matching handles to those defined in %TAG directives.
  26290. *
  26291. * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
  26292. * `'!local'` tag, or `null` if unresolvable.
  26293. */
  26294. tagName(source, onError) {
  26295. if (source === '!')
  26296. return '!'; // non-specific tag
  26297. if (source[0] !== '!') {
  26298. onError(`Not a valid tag: ${source}`);
  26299. return null;
  26300. }
  26301. if (source[1] === '<') {
  26302. const verbatim = source.slice(2, -1);
  26303. if (verbatim === '!' || verbatim === '!!') {
  26304. onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
  26305. return null;
  26306. }
  26307. if (source[source.length - 1] !== '>')
  26308. onError('Verbatim tags must end with a >');
  26309. return verbatim;
  26310. }
  26311. const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/);
  26312. if (!suffix)
  26313. onError(`The ${source} tag has no suffix`);
  26314. const prefix = this.tags[handle];
  26315. if (prefix)
  26316. return prefix + decodeURIComponent(suffix);
  26317. if (handle === '!')
  26318. return source; // local tag
  26319. onError(`Could not resolve tag: ${source}`);
  26320. return null;
  26321. }
  26322. /**
  26323. * Given a fully resolved tag, returns its printable string form,
  26324. * taking into account current tag prefixes and defaults.
  26325. */
  26326. tagString(tag) {
  26327. for (const [handle, prefix] of Object.entries(this.tags)) {
  26328. if (tag.startsWith(prefix))
  26329. return handle + escapeTagName(tag.substring(prefix.length));
  26330. }
  26331. return tag[0] === '!' ? tag : `!<${tag}>`;
  26332. }
  26333. toString(doc) {
  26334. const lines = this.yaml.explicit
  26335. ? [`%YAML ${this.yaml.version || '1.2'}`]
  26336. : [];
  26337. const tagEntries = Object.entries(this.tags);
  26338. let tagNames;
  26339. if (doc && tagEntries.length > 0 && isNode$1(doc.contents)) {
  26340. const tags = {};
  26341. visit$1(doc.contents, (_key, node) => {
  26342. if (isNode$1(node) && node.tag)
  26343. tags[node.tag] = true;
  26344. });
  26345. tagNames = Object.keys(tags);
  26346. }
  26347. else
  26348. tagNames = [];
  26349. for (const [handle, prefix] of tagEntries) {
  26350. if (handle === '!!' && prefix === 'tag:yaml.org,2002:')
  26351. continue;
  26352. if (!doc || tagNames.some(tn => tn.startsWith(prefix)))
  26353. lines.push(`%TAG ${handle} ${prefix}`);
  26354. }
  26355. return lines.join('\n');
  26356. }
  26357. }
  26358. Directives.defaultYaml = { explicit: false, version: '1.2' };
  26359. Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' };
  26360. /**
  26361. * Verify that the input string is a valid anchor.
  26362. *
  26363. * Will throw on errors.
  26364. */
  26365. function anchorIsValid(anchor) {
  26366. if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
  26367. const sa = JSON.stringify(anchor);
  26368. const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
  26369. throw new Error(msg);
  26370. }
  26371. return true;
  26372. }
  26373. function anchorNames(root) {
  26374. const anchors = new Set();
  26375. visit$1(root, {
  26376. Value(_key, node) {
  26377. if (node.anchor)
  26378. anchors.add(node.anchor);
  26379. }
  26380. });
  26381. return anchors;
  26382. }
  26383. /** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
  26384. function findNewAnchor(prefix, exclude) {
  26385. for (let i = 1; true; ++i) {
  26386. const name = `${prefix}${i}`;
  26387. if (!exclude.has(name))
  26388. return name;
  26389. }
  26390. }
  26391. function createNodeAnchors(doc, prefix) {
  26392. const aliasObjects = [];
  26393. const sourceObjects = new Map();
  26394. let prevAnchors = null;
  26395. return {
  26396. onAnchor: (source) => {
  26397. aliasObjects.push(source);
  26398. if (!prevAnchors)
  26399. prevAnchors = anchorNames(doc);
  26400. const anchor = findNewAnchor(prefix, prevAnchors);
  26401. prevAnchors.add(anchor);
  26402. return anchor;
  26403. },
  26404. /**
  26405. * With circular references, the source node is only resolved after all
  26406. * of its child nodes are. This is why anchors are set only after all of
  26407. * the nodes have been created.
  26408. */
  26409. setAnchors: () => {
  26410. for (const source of aliasObjects) {
  26411. const ref = sourceObjects.get(source);
  26412. if (typeof ref === 'object' &&
  26413. ref.anchor &&
  26414. (isScalar$1(ref.node) || isCollection$1(ref.node))) {
  26415. ref.node.anchor = ref.anchor;
  26416. }
  26417. else {
  26418. const error = new Error('Failed to resolve repeated object (this should not happen)');
  26419. error.source = source;
  26420. throw error;
  26421. }
  26422. }
  26423. },
  26424. sourceObjects
  26425. };
  26426. }
  26427. class Alias extends NodeBase {
  26428. constructor(source) {
  26429. super(ALIAS);
  26430. this.source = source;
  26431. Object.defineProperty(this, 'tag', {
  26432. set() {
  26433. throw new Error('Alias nodes cannot have tags');
  26434. }
  26435. });
  26436. }
  26437. /**
  26438. * Resolve the value of this alias within `doc`, finding the last
  26439. * instance of the `source` anchor before this node.
  26440. */
  26441. resolve(doc) {
  26442. let found = undefined;
  26443. visit$1(doc, {
  26444. Node: (_key, node) => {
  26445. if (node === this)
  26446. return visit$1.BREAK;
  26447. if (node.anchor === this.source)
  26448. found = node;
  26449. }
  26450. });
  26451. return found;
  26452. }
  26453. toJSON(_arg, ctx) {
  26454. if (!ctx)
  26455. return { source: this.source };
  26456. const { anchors, doc, maxAliasCount } = ctx;
  26457. const source = this.resolve(doc);
  26458. if (!source) {
  26459. const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
  26460. throw new ReferenceError(msg);
  26461. }
  26462. const data = anchors.get(source);
  26463. /* istanbul ignore if */
  26464. if (!data || data.res === undefined) {
  26465. const msg = 'This should not happen: Alias anchor was not resolved?';
  26466. throw new ReferenceError(msg);
  26467. }
  26468. if (maxAliasCount >= 0) {
  26469. data.count += 1;
  26470. if (data.aliasCount === 0)
  26471. data.aliasCount = getAliasCount(doc, source, anchors);
  26472. if (data.count * data.aliasCount > maxAliasCount) {
  26473. const msg = 'Excessive alias count indicates a resource exhaustion attack';
  26474. throw new ReferenceError(msg);
  26475. }
  26476. }
  26477. return data.res;
  26478. }
  26479. toString(ctx, _onComment, _onChompKeep) {
  26480. const src = `*${this.source}`;
  26481. if (ctx) {
  26482. anchorIsValid(this.source);
  26483. if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
  26484. const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
  26485. throw new Error(msg);
  26486. }
  26487. if (ctx.implicitKey)
  26488. return `${src} `;
  26489. }
  26490. return src;
  26491. }
  26492. }
  26493. function getAliasCount(doc, node, anchors) {
  26494. if (isAlias(node)) {
  26495. const source = node.resolve(doc);
  26496. const anchor = anchors && source && anchors.get(source);
  26497. return anchor ? anchor.count * anchor.aliasCount : 0;
  26498. }
  26499. else if (isCollection$1(node)) {
  26500. let count = 0;
  26501. for (const item of node.items) {
  26502. const c = getAliasCount(doc, item, anchors);
  26503. if (c > count)
  26504. count = c;
  26505. }
  26506. return count;
  26507. }
  26508. else if (isPair(node)) {
  26509. const kc = getAliasCount(doc, node.key, anchors);
  26510. const vc = getAliasCount(doc, node.value, anchors);
  26511. return Math.max(kc, vc);
  26512. }
  26513. return 1;
  26514. }
  26515. /**
  26516. * Recursively convert any node or its contents to native JavaScript
  26517. *
  26518. * @param value - The input value
  26519. * @param arg - If `value` defines a `toJSON()` method, use this
  26520. * as its first argument
  26521. * @param ctx - Conversion context, originally set in Document#toJS(). If
  26522. * `{ keep: true }` is not set, output should be suitable for JSON
  26523. * stringification.
  26524. */
  26525. function toJS(value, arg, ctx) {
  26526. // eslint-disable-next-line @typescript-eslint/no-unsafe-return
  26527. if (Array.isArray(value))
  26528. return value.map((v, i) => toJS(v, String(i), ctx));
  26529. if (value && typeof value.toJSON === 'function') {
  26530. // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  26531. if (!ctx || !hasAnchor(value))
  26532. return value.toJSON(arg, ctx);
  26533. const data = { aliasCount: 0, count: 1, res: undefined };
  26534. ctx.anchors.set(value, data);
  26535. ctx.onCreate = res => {
  26536. data.res = res;
  26537. delete ctx.onCreate;
  26538. };
  26539. const res = value.toJSON(arg, ctx);
  26540. if (ctx.onCreate)
  26541. ctx.onCreate(res);
  26542. return res;
  26543. }
  26544. if (typeof value === 'bigint' && !ctx?.keep)
  26545. return Number(value);
  26546. return value;
  26547. }
  26548. const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
  26549. class Scalar extends NodeBase {
  26550. constructor(value) {
  26551. super(SCALAR$1);
  26552. this.value = value;
  26553. }
  26554. toJSON(arg, ctx) {
  26555. return ctx?.keep ? this.value : toJS(this.value, arg, ctx);
  26556. }
  26557. toString() {
  26558. return String(this.value);
  26559. }
  26560. }
  26561. Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED';
  26562. Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL';
  26563. Scalar.PLAIN = 'PLAIN';
  26564. Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
  26565. Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';
  26566. const defaultTagPrefix = 'tag:yaml.org,2002:';
  26567. function findTagObject(value, tagName, tags) {
  26568. if (tagName) {
  26569. const match = tags.filter(t => t.tag === tagName);
  26570. const tagObj = match.find(t => !t.format) ?? match[0];
  26571. if (!tagObj)
  26572. throw new Error(`Tag ${tagName} not found`);
  26573. return tagObj;
  26574. }
  26575. return tags.find(t => t.identify?.(value) && !t.format);
  26576. }
  26577. function createNode(value, tagName, ctx) {
  26578. if (isDocument(value))
  26579. value = value.contents;
  26580. if (isNode$1(value))
  26581. return value;
  26582. if (isPair(value)) {
  26583. const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
  26584. map.items.push(value);
  26585. return map;
  26586. }
  26587. if (value instanceof String ||
  26588. value instanceof Number ||
  26589. value instanceof Boolean ||
  26590. (typeof BigInt === 'function' && value instanceof BigInt) // not supported everywhere
  26591. ) {
  26592. // https://tc39.es/ecma262/#sec-serializejsonproperty
  26593. value = value.valueOf();
  26594. }
  26595. const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
  26596. // Detect duplicate references to the same object & use Alias nodes for all
  26597. // after first. The `ref` wrapper allows for circular references to resolve.
  26598. let ref = undefined;
  26599. if (aliasDuplicateObjects && value && typeof value === 'object') {
  26600. ref = sourceObjects.get(value);
  26601. if (ref) {
  26602. if (!ref.anchor)
  26603. ref.anchor = onAnchor(value);
  26604. return new Alias(ref.anchor);
  26605. }
  26606. else {
  26607. ref = { anchor: null, node: null };
  26608. sourceObjects.set(value, ref);
  26609. }
  26610. }
  26611. if (tagName?.startsWith('!!'))
  26612. tagName = defaultTagPrefix + tagName.slice(2);
  26613. let tagObj = findTagObject(value, tagName, schema.tags);
  26614. if (!tagObj) {
  26615. if (value && typeof value.toJSON === 'function') {
  26616. // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  26617. value = value.toJSON();
  26618. }
  26619. if (!value || typeof value !== 'object') {
  26620. const node = new Scalar(value);
  26621. if (ref)
  26622. ref.node = node;
  26623. return node;
  26624. }
  26625. tagObj =
  26626. value instanceof Map
  26627. ? schema[MAP]
  26628. : Symbol.iterator in Object(value)
  26629. ? schema[SEQ]
  26630. : schema[MAP];
  26631. }
  26632. if (onTagObj) {
  26633. onTagObj(tagObj);
  26634. delete ctx.onTagObj;
  26635. }
  26636. const node = tagObj?.createNode
  26637. ? tagObj.createNode(ctx.schema, value, ctx)
  26638. : new Scalar(value);
  26639. if (tagName)
  26640. node.tag = tagName;
  26641. if (ref)
  26642. ref.node = node;
  26643. return node;
  26644. }
  26645. function collectionFromPath(schema, path, value) {
  26646. let v = value;
  26647. for (let i = path.length - 1; i >= 0; --i) {
  26648. const k = path[i];
  26649. if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
  26650. const a = [];
  26651. a[k] = v;
  26652. v = a;
  26653. }
  26654. else {
  26655. v = new Map([[k, v]]);
  26656. }
  26657. }
  26658. return createNode(v, undefined, {
  26659. aliasDuplicateObjects: false,
  26660. keepUndefined: false,
  26661. onAnchor: () => {
  26662. throw new Error('This should not happen, please report a bug.');
  26663. },
  26664. schema,
  26665. sourceObjects: new Map()
  26666. });
  26667. }
  26668. // Type guard is intentionally a little wrong so as to be more useful,
  26669. // as it does not cover untypable empty non-string iterables (e.g. []).
  26670. const isEmptyPath = (path) => path == null ||
  26671. (typeof path === 'object' && !!path[Symbol.iterator]().next().done);
  26672. class Collection extends NodeBase {
  26673. constructor(type, schema) {
  26674. super(type);
  26675. Object.defineProperty(this, 'schema', {
  26676. value: schema,
  26677. configurable: true,
  26678. enumerable: false,
  26679. writable: true
  26680. });
  26681. }
  26682. /**
  26683. * Create a copy of this collection.
  26684. *
  26685. * @param schema - If defined, overwrites the original's schema
  26686. */
  26687. clone(schema) {
  26688. const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
  26689. if (schema)
  26690. copy.schema = schema;
  26691. copy.items = copy.items.map(it => isNode$1(it) || isPair(it) ? it.clone(schema) : it);
  26692. if (this.range)
  26693. copy.range = this.range.slice();
  26694. return copy;
  26695. }
  26696. /**
  26697. * Adds a value to the collection. For `!!map` and `!!omap` the value must
  26698. * be a Pair instance or a `{ key, value }` object, which may not have a key
  26699. * that already exists in the map.
  26700. */
  26701. addIn(path, value) {
  26702. if (isEmptyPath(path))
  26703. this.add(value);
  26704. else {
  26705. const [key, ...rest] = path;
  26706. const node = this.get(key, true);
  26707. if (isCollection$1(node))
  26708. node.addIn(rest, value);
  26709. else if (node === undefined && this.schema)
  26710. this.set(key, collectionFromPath(this.schema, rest, value));
  26711. else
  26712. throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  26713. }
  26714. }
  26715. /**
  26716. * Removes a value from the collection.
  26717. * @returns `true` if the item was found and removed.
  26718. */
  26719. deleteIn(path) {
  26720. const [key, ...rest] = path;
  26721. if (rest.length === 0)
  26722. return this.delete(key);
  26723. const node = this.get(key, true);
  26724. if (isCollection$1(node))
  26725. return node.deleteIn(rest);
  26726. else
  26727. throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  26728. }
  26729. /**
  26730. * Returns item at `key`, or `undefined` if not found. By default unwraps
  26731. * scalar values from their surrounding node; to disable set `keepScalar` to
  26732. * `true` (collections are always returned intact).
  26733. */
  26734. getIn(path, keepScalar) {
  26735. const [key, ...rest] = path;
  26736. const node = this.get(key, true);
  26737. if (rest.length === 0)
  26738. return !keepScalar && isScalar$1(node) ? node.value : node;
  26739. else
  26740. return isCollection$1(node) ? node.getIn(rest, keepScalar) : undefined;
  26741. }
  26742. hasAllNullValues(allowScalar) {
  26743. return this.items.every(node => {
  26744. if (!isPair(node))
  26745. return false;
  26746. const n = node.value;
  26747. return (n == null ||
  26748. (allowScalar &&
  26749. isScalar$1(n) &&
  26750. n.value == null &&
  26751. !n.commentBefore &&
  26752. !n.comment &&
  26753. !n.tag));
  26754. });
  26755. }
  26756. /**
  26757. * Checks if the collection includes a value with the key `key`.
  26758. */
  26759. hasIn(path) {
  26760. const [key, ...rest] = path;
  26761. if (rest.length === 0)
  26762. return this.has(key);
  26763. const node = this.get(key, true);
  26764. return isCollection$1(node) ? node.hasIn(rest) : false;
  26765. }
  26766. /**
  26767. * Sets a value in this collection. For `!!set`, `value` needs to be a
  26768. * boolean to add/remove the item from the set.
  26769. */
  26770. setIn(path, value) {
  26771. const [key, ...rest] = path;
  26772. if (rest.length === 0) {
  26773. this.set(key, value);
  26774. }
  26775. else {
  26776. const node = this.get(key, true);
  26777. if (isCollection$1(node))
  26778. node.setIn(rest, value);
  26779. else if (node === undefined && this.schema)
  26780. this.set(key, collectionFromPath(this.schema, rest, value));
  26781. else
  26782. throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  26783. }
  26784. }
  26785. }
  26786. Collection.maxFlowStringSingleLineLength = 60;
  26787. /**
  26788. * Stringifies a comment.
  26789. *
  26790. * Empty comment lines are left empty,
  26791. * lines consisting of a single space are replaced by `#`,
  26792. * and all other lines are prefixed with a `#`.
  26793. */
  26794. const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
  26795. function indentComment(comment, indent) {
  26796. if (/^\n+$/.test(comment))
  26797. return comment.substring(1);
  26798. return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
  26799. }
  26800. const lineComment = (str, indent, comment) => str.endsWith('\n')
  26801. ? indentComment(comment, indent)
  26802. : comment.includes('\n')
  26803. ? '\n' + indentComment(comment, indent)
  26804. : (str.endsWith(' ') ? '' : ' ') + comment;
  26805. const FOLD_FLOW = 'flow';
  26806. const FOLD_BLOCK = 'block';
  26807. const FOLD_QUOTED = 'quoted';
  26808. /**
  26809. * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
  26810. * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
  26811. * terminated with `\n` and started with `indent`.
  26812. */
  26813. function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
  26814. if (!lineWidth || lineWidth < 0)
  26815. return text;
  26816. const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  26817. if (text.length <= endStep)
  26818. return text;
  26819. const folds = [];
  26820. const escapedFolds = {};
  26821. let end = lineWidth - indent.length;
  26822. if (typeof indentAtStart === 'number') {
  26823. if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
  26824. folds.push(0);
  26825. else
  26826. end = lineWidth - indentAtStart;
  26827. }
  26828. let split = undefined;
  26829. let prev = undefined;
  26830. let overflow = false;
  26831. let i = -1;
  26832. let escStart = -1;
  26833. let escEnd = -1;
  26834. if (mode === FOLD_BLOCK) {
  26835. i = consumeMoreIndentedLines(text, i);
  26836. if (i !== -1)
  26837. end = i + endStep;
  26838. }
  26839. for (let ch; (ch = text[(i += 1)]);) {
  26840. if (mode === FOLD_QUOTED && ch === '\\') {
  26841. escStart = i;
  26842. switch (text[i + 1]) {
  26843. case 'x':
  26844. i += 3;
  26845. break;
  26846. case 'u':
  26847. i += 5;
  26848. break;
  26849. case 'U':
  26850. i += 9;
  26851. break;
  26852. default:
  26853. i += 1;
  26854. }
  26855. escEnd = i;
  26856. }
  26857. if (ch === '\n') {
  26858. if (mode === FOLD_BLOCK)
  26859. i = consumeMoreIndentedLines(text, i);
  26860. end = i + endStep;
  26861. split = undefined;
  26862. }
  26863. else {
  26864. if (ch === ' ' &&
  26865. prev &&
  26866. prev !== ' ' &&
  26867. prev !== '\n' &&
  26868. prev !== '\t') {
  26869. // space surrounded by non-space can be replaced with newline + indent
  26870. const next = text[i + 1];
  26871. if (next && next !== ' ' && next !== '\n' && next !== '\t')
  26872. split = i;
  26873. }
  26874. if (i >= end) {
  26875. if (split) {
  26876. folds.push(split);
  26877. end = split + endStep;
  26878. split = undefined;
  26879. }
  26880. else if (mode === FOLD_QUOTED) {
  26881. // white-space collected at end may stretch past lineWidth
  26882. while (prev === ' ' || prev === '\t') {
  26883. prev = ch;
  26884. ch = text[(i += 1)];
  26885. overflow = true;
  26886. }
  26887. // Account for newline escape, but don't break preceding escape
  26888. const j = i > escEnd + 1 ? i - 2 : escStart - 1;
  26889. // Bail out if lineWidth & minContentWidth are shorter than an escape string
  26890. if (escapedFolds[j])
  26891. return text;
  26892. folds.push(j);
  26893. escapedFolds[j] = true;
  26894. end = j + endStep;
  26895. split = undefined;
  26896. }
  26897. else {
  26898. overflow = true;
  26899. }
  26900. }
  26901. }
  26902. prev = ch;
  26903. }
  26904. if (overflow && onOverflow)
  26905. onOverflow();
  26906. if (folds.length === 0)
  26907. return text;
  26908. if (onFold)
  26909. onFold();
  26910. let res = text.slice(0, folds[0]);
  26911. for (let i = 0; i < folds.length; ++i) {
  26912. const fold = folds[i];
  26913. const end = folds[i + 1] || text.length;
  26914. if (fold === 0)
  26915. res = `\n${indent}${text.slice(0, end)}`;
  26916. else {
  26917. if (mode === FOLD_QUOTED && escapedFolds[fold])
  26918. res += `${text[fold]}\\`;
  26919. res += `\n${indent}${text.slice(fold + 1, end)}`;
  26920. }
  26921. }
  26922. return res;
  26923. }
  26924. /**
  26925. * Presumes `i + 1` is at the start of a line
  26926. * @returns index of last newline in more-indented block
  26927. */
  26928. function consumeMoreIndentedLines(text, i) {
  26929. let ch = text[i + 1];
  26930. while (ch === ' ' || ch === '\t') {
  26931. do {
  26932. ch = text[(i += 1)];
  26933. } while (ch && ch !== '\n');
  26934. ch = text[i + 1];
  26935. }
  26936. return i;
  26937. }
  26938. const getFoldOptions = (ctx) => ({
  26939. indentAtStart: ctx.indentAtStart,
  26940. lineWidth: ctx.options.lineWidth,
  26941. minContentWidth: ctx.options.minContentWidth
  26942. });
  26943. // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
  26944. // presume that's starting a new document.
  26945. const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
  26946. function lineLengthOverLimit(str, lineWidth, indentLength) {
  26947. if (!lineWidth || lineWidth < 0)
  26948. return false;
  26949. const limit = lineWidth - indentLength;
  26950. const strLen = str.length;
  26951. if (strLen <= limit)
  26952. return false;
  26953. for (let i = 0, start = 0; i < strLen; ++i) {
  26954. if (str[i] === '\n') {
  26955. if (i - start > limit)
  26956. return true;
  26957. start = i + 1;
  26958. if (strLen - start <= limit)
  26959. return false;
  26960. }
  26961. }
  26962. return true;
  26963. }
  26964. function doubleQuotedString(value, ctx) {
  26965. const json = JSON.stringify(value);
  26966. if (ctx.options.doubleQuotedAsJSON)
  26967. return json;
  26968. const { implicitKey } = ctx;
  26969. const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
  26970. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  26971. let str = '';
  26972. let start = 0;
  26973. for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
  26974. if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
  26975. // space before newline needs to be escaped to not be folded
  26976. str += json.slice(start, i) + '\\ ';
  26977. i += 1;
  26978. start = i;
  26979. ch = '\\';
  26980. }
  26981. if (ch === '\\')
  26982. switch (json[i + 1]) {
  26983. case 'u':
  26984. {
  26985. str += json.slice(start, i);
  26986. const code = json.substr(i + 2, 4);
  26987. switch (code) {
  26988. case '0000':
  26989. str += '\\0';
  26990. break;
  26991. case '0007':
  26992. str += '\\a';
  26993. break;
  26994. case '000b':
  26995. str += '\\v';
  26996. break;
  26997. case '001b':
  26998. str += '\\e';
  26999. break;
  27000. case '0085':
  27001. str += '\\N';
  27002. break;
  27003. case '00a0':
  27004. str += '\\_';
  27005. break;
  27006. case '2028':
  27007. str += '\\L';
  27008. break;
  27009. case '2029':
  27010. str += '\\P';
  27011. break;
  27012. default:
  27013. if (code.substr(0, 2) === '00')
  27014. str += '\\x' + code.substr(2);
  27015. else
  27016. str += json.substr(i, 6);
  27017. }
  27018. i += 5;
  27019. start = i + 1;
  27020. }
  27021. break;
  27022. case 'n':
  27023. if (implicitKey ||
  27024. json[i + 2] === '"' ||
  27025. json.length < minMultiLineLength) {
  27026. i += 1;
  27027. }
  27028. else {
  27029. // folding will eat first newline
  27030. str += json.slice(start, i) + '\n\n';
  27031. while (json[i + 2] === '\\' &&
  27032. json[i + 3] === 'n' &&
  27033. json[i + 4] !== '"') {
  27034. str += '\n';
  27035. i += 2;
  27036. }
  27037. str += indent;
  27038. // space after newline needs to be escaped to not be folded
  27039. if (json[i + 2] === ' ')
  27040. str += '\\';
  27041. i += 1;
  27042. start = i + 1;
  27043. }
  27044. break;
  27045. default:
  27046. i += 1;
  27047. }
  27048. }
  27049. str = start ? str + json.slice(start) : json;
  27050. return implicitKey
  27051. ? str
  27052. : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
  27053. }
  27054. function singleQuotedString(value, ctx) {
  27055. if (ctx.options.singleQuote === false ||
  27056. (ctx.implicitKey && value.includes('\n')) ||
  27057. /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline
  27058. )
  27059. return doubleQuotedString(value, ctx);
  27060. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  27061. const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
  27062. return ctx.implicitKey
  27063. ? res
  27064. : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
  27065. }
  27066. function quotedString(value, ctx) {
  27067. const { singleQuote } = ctx.options;
  27068. let qs;
  27069. if (singleQuote === false)
  27070. qs = doubleQuotedString;
  27071. else {
  27072. const hasDouble = value.includes('"');
  27073. const hasSingle = value.includes("'");
  27074. if (hasDouble && !hasSingle)
  27075. qs = singleQuotedString;
  27076. else if (hasSingle && !hasDouble)
  27077. qs = doubleQuotedString;
  27078. else
  27079. qs = singleQuote ? singleQuotedString : doubleQuotedString;
  27080. }
  27081. return qs(value, ctx);
  27082. }
  27083. function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
  27084. const { blockQuote, commentString, lineWidth } = ctx.options;
  27085. // 1. Block can't end in whitespace unless the last line is non-empty.
  27086. // 2. Strings consisting of only whitespace are best rendered explicitly.
  27087. if (!blockQuote || /\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
  27088. return quotedString(value, ctx);
  27089. }
  27090. const indent = ctx.indent ||
  27091. (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
  27092. const literal = blockQuote === 'literal'
  27093. ? true
  27094. : blockQuote === 'folded' || type === Scalar.BLOCK_FOLDED
  27095. ? false
  27096. : type === Scalar.BLOCK_LITERAL
  27097. ? true
  27098. : !lineLengthOverLimit(value, lineWidth, indent.length);
  27099. if (!value)
  27100. return literal ? '|\n' : '>\n';
  27101. // determine chomping from whitespace at value end
  27102. let chomp;
  27103. let endStart;
  27104. for (endStart = value.length; endStart > 0; --endStart) {
  27105. const ch = value[endStart - 1];
  27106. if (ch !== '\n' && ch !== '\t' && ch !== ' ')
  27107. break;
  27108. }
  27109. let end = value.substring(endStart);
  27110. const endNlPos = end.indexOf('\n');
  27111. if (endNlPos === -1) {
  27112. chomp = '-'; // strip
  27113. }
  27114. else if (value === end || endNlPos !== end.length - 1) {
  27115. chomp = '+'; // keep
  27116. if (onChompKeep)
  27117. onChompKeep();
  27118. }
  27119. else {
  27120. chomp = ''; // clip
  27121. }
  27122. if (end) {
  27123. value = value.slice(0, -end.length);
  27124. if (end[end.length - 1] === '\n')
  27125. end = end.slice(0, -1);
  27126. end = end.replace(/\n+(?!\n|$)/g, `$&${indent}`);
  27127. }
  27128. // determine indent indicator from whitespace at value start
  27129. let startWithSpace = false;
  27130. let startEnd;
  27131. let startNlPos = -1;
  27132. for (startEnd = 0; startEnd < value.length; ++startEnd) {
  27133. const ch = value[startEnd];
  27134. if (ch === ' ')
  27135. startWithSpace = true;
  27136. else if (ch === '\n')
  27137. startNlPos = startEnd;
  27138. else
  27139. break;
  27140. }
  27141. let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
  27142. if (start) {
  27143. value = value.substring(start.length);
  27144. start = start.replace(/\n+/g, `$&${indent}`);
  27145. }
  27146. const indentSize = indent ? '2' : '1'; // root is at -1
  27147. let header = (literal ? '|' : '>') + (startWithSpace ? indentSize : '') + chomp;
  27148. if (comment) {
  27149. header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '));
  27150. if (onComment)
  27151. onComment();
  27152. }
  27153. if (literal) {
  27154. value = value.replace(/\n+/g, `$&${indent}`);
  27155. return `${header}\n${indent}${start}${value}${end}`;
  27156. }
  27157. value = value
  27158. .replace(/\n+/g, '\n$&')
  27159. .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
  27160. // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
  27161. .replace(/\n+/g, `$&${indent}`);
  27162. const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx));
  27163. return `${header}\n${indent}${body}`;
  27164. }
  27165. function plainString(item, ctx, onComment, onChompKeep) {
  27166. const { type, value } = item;
  27167. const { actualString, implicitKey, indent, inFlow } = ctx;
  27168. if ((implicitKey && /[\n[\]{},]/.test(value)) ||
  27169. (inFlow && /[[\]{},]/.test(value))) {
  27170. return quotedString(value, ctx);
  27171. }
  27172. if (!value ||
  27173. /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
  27174. // not allowed:
  27175. // - empty string, '-' or '?'
  27176. // - start with an indicator character (except [?:-]) or /[?-] /
  27177. // - '\n ', ': ' or ' \n' anywhere
  27178. // - '#' not preceded by a non-space char
  27179. // - end with ' ' or ':'
  27180. return implicitKey || inFlow || !value.includes('\n')
  27181. ? quotedString(value, ctx)
  27182. : blockString(item, ctx, onComment, onChompKeep);
  27183. }
  27184. if (!implicitKey &&
  27185. !inFlow &&
  27186. type !== Scalar.PLAIN &&
  27187. value.includes('\n')) {
  27188. // Where allowed & type not set explicitly, prefer block style for multiline strings
  27189. return blockString(item, ctx, onComment, onChompKeep);
  27190. }
  27191. if (indent === '' && containsDocumentMarker(value)) {
  27192. ctx.forceBlockIndent = true;
  27193. return blockString(item, ctx, onComment, onChompKeep);
  27194. }
  27195. const str = value.replace(/\n+/g, `$&\n${indent}`);
  27196. // Verify that output will be parsed as a string, as e.g. plain numbers and
  27197. // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
  27198. // and others in v1.1.
  27199. if (actualString) {
  27200. const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);
  27201. const { compat, tags } = ctx.doc.schema;
  27202. if (tags.some(test) || compat?.some(test))
  27203. return quotedString(value, ctx);
  27204. }
  27205. return implicitKey
  27206. ? str
  27207. : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
  27208. }
  27209. function stringifyString(item, ctx, onComment, onChompKeep) {
  27210. const { implicitKey, inFlow } = ctx;
  27211. const ss = typeof item.value === 'string'
  27212. ? item
  27213. : Object.assign({}, item, { value: String(item.value) });
  27214. let { type } = item;
  27215. if (type !== Scalar.QUOTE_DOUBLE) {
  27216. // force double quotes on control characters & unpaired surrogates
  27217. if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
  27218. type = Scalar.QUOTE_DOUBLE;
  27219. }
  27220. const _stringify = (_type) => {
  27221. switch (_type) {
  27222. case Scalar.BLOCK_FOLDED:
  27223. case Scalar.BLOCK_LITERAL:
  27224. return implicitKey || inFlow
  27225. ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers
  27226. : blockString(ss, ctx, onComment, onChompKeep);
  27227. case Scalar.QUOTE_DOUBLE:
  27228. return doubleQuotedString(ss.value, ctx);
  27229. case Scalar.QUOTE_SINGLE:
  27230. return singleQuotedString(ss.value, ctx);
  27231. case Scalar.PLAIN:
  27232. return plainString(ss, ctx, onComment, onChompKeep);
  27233. default:
  27234. return null;
  27235. }
  27236. };
  27237. let res = _stringify(type);
  27238. if (res === null) {
  27239. const { defaultKeyType, defaultStringType } = ctx.options;
  27240. const t = (implicitKey && defaultKeyType) || defaultStringType;
  27241. res = _stringify(t);
  27242. if (res === null)
  27243. throw new Error(`Unsupported default string type ${t}`);
  27244. }
  27245. return res;
  27246. }
  27247. function createStringifyContext(doc, options) {
  27248. const opt = Object.assign({
  27249. blockQuote: true,
  27250. commentString: stringifyComment,
  27251. defaultKeyType: null,
  27252. defaultStringType: 'PLAIN',
  27253. directives: null,
  27254. doubleQuotedAsJSON: false,
  27255. doubleQuotedMinMultiLineLength: 40,
  27256. falseStr: 'false',
  27257. indentSeq: true,
  27258. lineWidth: 80,
  27259. minContentWidth: 20,
  27260. nullStr: 'null',
  27261. simpleKeys: false,
  27262. singleQuote: null,
  27263. trueStr: 'true',
  27264. verifyAliasOrder: true
  27265. }, doc.schema.toStringOptions, options);
  27266. let inFlow;
  27267. switch (opt.collectionStyle) {
  27268. case 'block':
  27269. inFlow = false;
  27270. break;
  27271. case 'flow':
  27272. inFlow = true;
  27273. break;
  27274. default:
  27275. inFlow = null;
  27276. }
  27277. return {
  27278. anchors: new Set(),
  27279. doc,
  27280. indent: '',
  27281. indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
  27282. inFlow,
  27283. options: opt
  27284. };
  27285. }
  27286. function getTagObject(tags, item) {
  27287. if (item.tag) {
  27288. const match = tags.filter(t => t.tag === item.tag);
  27289. if (match.length > 0)
  27290. return match.find(t => t.format === item.format) ?? match[0];
  27291. }
  27292. let tagObj = undefined;
  27293. let obj;
  27294. if (isScalar$1(item)) {
  27295. obj = item.value;
  27296. const match = tags.filter(t => t.identify?.(obj));
  27297. tagObj =
  27298. match.find(t => t.format === item.format) ?? match.find(t => !t.format);
  27299. }
  27300. else {
  27301. obj = item;
  27302. tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
  27303. }
  27304. if (!tagObj) {
  27305. const name = obj?.constructor?.name ?? typeof obj;
  27306. throw new Error(`Tag not resolved for ${name} value`);
  27307. }
  27308. return tagObj;
  27309. }
  27310. // needs to be called before value stringifier to allow for circular anchor refs
  27311. function stringifyProps(node, tagObj, { anchors, doc }) {
  27312. if (!doc.directives)
  27313. return '';
  27314. const props = [];
  27315. const anchor = (isScalar$1(node) || isCollection$1(node)) && node.anchor;
  27316. if (anchor && anchorIsValid(anchor)) {
  27317. anchors.add(anchor);
  27318. props.push(`&${anchor}`);
  27319. }
  27320. const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag;
  27321. if (tag)
  27322. props.push(doc.directives.tagString(tag));
  27323. return props.join(' ');
  27324. }
  27325. function stringify$2(item, ctx, onComment, onChompKeep) {
  27326. if (isPair(item))
  27327. return item.toString(ctx, onComment, onChompKeep);
  27328. if (isAlias(item)) {
  27329. if (ctx.doc.directives)
  27330. return item.toString(ctx);
  27331. if (ctx.resolvedAliases?.has(item)) {
  27332. throw new TypeError(`Cannot stringify circular structure without alias nodes`);
  27333. }
  27334. else {
  27335. if (ctx.resolvedAliases)
  27336. ctx.resolvedAliases.add(item);
  27337. else
  27338. ctx.resolvedAliases = new Set([item]);
  27339. item = item.resolve(ctx.doc);
  27340. }
  27341. }
  27342. let tagObj = undefined;
  27343. const node = isNode$1(item)
  27344. ? item
  27345. : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
  27346. if (!tagObj)
  27347. tagObj = getTagObject(ctx.doc.schema.tags, node);
  27348. const props = stringifyProps(node, tagObj, ctx);
  27349. if (props.length > 0)
  27350. ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
  27351. const str = typeof tagObj.stringify === 'function'
  27352. ? tagObj.stringify(node, ctx, onComment, onChompKeep)
  27353. : isScalar$1(node)
  27354. ? stringifyString(node, ctx, onComment, onChompKeep)
  27355. : node.toString(ctx, onComment, onChompKeep);
  27356. if (!props)
  27357. return str;
  27358. return isScalar$1(node) || str[0] === '{' || str[0] === '['
  27359. ? `${props} ${str}`
  27360. : `${props}\n${ctx.indent}${str}`;
  27361. }
  27362. function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
  27363. const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
  27364. let keyComment = (isNode$1(key) && key.comment) || null;
  27365. if (simpleKeys) {
  27366. if (keyComment) {
  27367. throw new Error('With simple keys, key nodes cannot have comments');
  27368. }
  27369. if (isCollection$1(key)) {
  27370. const msg = 'With simple keys, collection cannot be used as a key value';
  27371. throw new Error(msg);
  27372. }
  27373. }
  27374. let explicitKey = !simpleKeys &&
  27375. (!key ||
  27376. (keyComment && value == null && !ctx.inFlow) ||
  27377. isCollection$1(key) ||
  27378. (isScalar$1(key)
  27379. ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL
  27380. : typeof key === 'object'));
  27381. ctx = Object.assign({}, ctx, {
  27382. allNullValues: false,
  27383. implicitKey: !explicitKey && (simpleKeys || !allNullValues),
  27384. indent: indent + indentStep
  27385. });
  27386. let keyCommentDone = false;
  27387. let chompKeep = false;
  27388. let str = stringify$2(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));
  27389. if (!explicitKey && !ctx.inFlow && str.length > 1024) {
  27390. if (simpleKeys)
  27391. throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
  27392. explicitKey = true;
  27393. }
  27394. if (ctx.inFlow) {
  27395. if (allNullValues || value == null) {
  27396. if (keyCommentDone && onComment)
  27397. onComment();
  27398. return str === '' ? '?' : explicitKey ? `? ${str}` : str;
  27399. }
  27400. }
  27401. else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {
  27402. str = `? ${str}`;
  27403. if (keyComment && !keyCommentDone) {
  27404. str += lineComment(str, ctx.indent, commentString(keyComment));
  27405. }
  27406. else if (chompKeep && onChompKeep)
  27407. onChompKeep();
  27408. return str;
  27409. }
  27410. if (keyCommentDone)
  27411. keyComment = null;
  27412. if (explicitKey) {
  27413. if (keyComment)
  27414. str += lineComment(str, ctx.indent, commentString(keyComment));
  27415. str = `? ${str}\n${indent}:`;
  27416. }
  27417. else {
  27418. str = `${str}:`;
  27419. if (keyComment)
  27420. str += lineComment(str, ctx.indent, commentString(keyComment));
  27421. }
  27422. let vcb = '';
  27423. let valueComment = null;
  27424. if (isNode$1(value)) {
  27425. if (value.spaceBefore)
  27426. vcb = '\n';
  27427. if (value.commentBefore) {
  27428. const cs = commentString(value.commentBefore);
  27429. vcb += `\n${indentComment(cs, ctx.indent)}`;
  27430. }
  27431. valueComment = value.comment;
  27432. }
  27433. else if (value && typeof value === 'object') {
  27434. value = doc.createNode(value);
  27435. }
  27436. ctx.implicitKey = false;
  27437. if (!explicitKey && !keyComment && isScalar$1(value))
  27438. ctx.indentAtStart = str.length + 1;
  27439. chompKeep = false;
  27440. if (!indentSeq &&
  27441. indentStep.length >= 2 &&
  27442. !ctx.inFlow &&
  27443. !explicitKey &&
  27444. isSeq(value) &&
  27445. !value.flow &&
  27446. !value.tag &&
  27447. !value.anchor) {
  27448. // If indentSeq === false, consider '- ' as part of indentation where possible
  27449. ctx.indent = ctx.indent.substr(2);
  27450. }
  27451. let valueCommentDone = false;
  27452. const valueStr = stringify$2(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
  27453. let ws = ' ';
  27454. if (vcb || keyComment) {
  27455. if (valueStr === '' && !ctx.inFlow)
  27456. ws = vcb === '\n' ? '\n\n' : vcb;
  27457. else
  27458. ws = `${vcb}\n${ctx.indent}`;
  27459. }
  27460. else if (!explicitKey && isCollection$1(value)) {
  27461. const flow = valueStr[0] === '[' || valueStr[0] === '{';
  27462. if (!flow || valueStr.includes('\n'))
  27463. ws = `\n${ctx.indent}`;
  27464. }
  27465. else if (valueStr === '' || valueStr[0] === '\n')
  27466. ws = '';
  27467. str += ws + valueStr;
  27468. if (ctx.inFlow) {
  27469. if (valueCommentDone && onComment)
  27470. onComment();
  27471. }
  27472. else if (valueComment && !valueCommentDone) {
  27473. str += lineComment(str, ctx.indent, commentString(valueComment));
  27474. }
  27475. else if (chompKeep && onChompKeep) {
  27476. onChompKeep();
  27477. }
  27478. return str;
  27479. }
  27480. function warn(logLevel, warning) {
  27481. if (logLevel === 'debug' || logLevel === 'warn') {
  27482. if (typeof process !== 'undefined' && process.emitWarning)
  27483. process.emitWarning(warning);
  27484. else
  27485. console.warn(warning);
  27486. }
  27487. }
  27488. const MERGE_KEY = '<<';
  27489. function addPairToJSMap(ctx, map, { key, value }) {
  27490. if (ctx?.doc.schema.merge && isMergeKey(key)) {
  27491. value = isAlias(value) ? value.resolve(ctx.doc) : value;
  27492. if (isSeq(value))
  27493. for (const it of value.items)
  27494. mergeToJSMap(ctx, map, it);
  27495. else if (Array.isArray(value))
  27496. for (const it of value)
  27497. mergeToJSMap(ctx, map, it);
  27498. else
  27499. mergeToJSMap(ctx, map, value);
  27500. }
  27501. else {
  27502. const jsKey = toJS(key, '', ctx);
  27503. if (map instanceof Map) {
  27504. map.set(jsKey, toJS(value, jsKey, ctx));
  27505. }
  27506. else if (map instanceof Set) {
  27507. map.add(jsKey);
  27508. }
  27509. else {
  27510. const stringKey = stringifyKey(key, jsKey, ctx);
  27511. const jsValue = toJS(value, stringKey, ctx);
  27512. if (stringKey in map)
  27513. Object.defineProperty(map, stringKey, {
  27514. value: jsValue,
  27515. writable: true,
  27516. enumerable: true,
  27517. configurable: true
  27518. });
  27519. else
  27520. map[stringKey] = jsValue;
  27521. }
  27522. }
  27523. return map;
  27524. }
  27525. const isMergeKey = (key) => key === MERGE_KEY ||
  27526. (isScalar$1(key) &&
  27527. key.value === MERGE_KEY &&
  27528. (!key.type || key.type === Scalar.PLAIN));
  27529. // If the value associated with a merge key is a single mapping node, each of
  27530. // its key/value pairs is inserted into the current mapping, unless the key
  27531. // already exists in it. If the value associated with the merge key is a
  27532. // sequence, then this sequence is expected to contain mapping nodes and each
  27533. // of these nodes is merged in turn according to its order in the sequence.
  27534. // Keys in mapping nodes earlier in the sequence override keys specified in
  27535. // later mapping nodes. -- http://yaml.org/type/merge.html
  27536. function mergeToJSMap(ctx, map, value) {
  27537. const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
  27538. if (!isMap(source))
  27539. throw new Error('Merge sources must be maps or map aliases');
  27540. const srcMap = source.toJSON(null, ctx, Map);
  27541. for (const [key, value] of srcMap) {
  27542. if (map instanceof Map) {
  27543. if (!map.has(key))
  27544. map.set(key, value);
  27545. }
  27546. else if (map instanceof Set) {
  27547. map.add(key);
  27548. }
  27549. else if (!Object.prototype.hasOwnProperty.call(map, key)) {
  27550. Object.defineProperty(map, key, {
  27551. value,
  27552. writable: true,
  27553. enumerable: true,
  27554. configurable: true
  27555. });
  27556. }
  27557. }
  27558. return map;
  27559. }
  27560. function stringifyKey(key, jsKey, ctx) {
  27561. if (jsKey === null)
  27562. return '';
  27563. if (typeof jsKey !== 'object')
  27564. return String(jsKey);
  27565. if (isNode$1(key) && ctx && ctx.doc) {
  27566. const strCtx = createStringifyContext(ctx.doc, {});
  27567. strCtx.anchors = new Set();
  27568. for (const node of ctx.anchors.keys())
  27569. strCtx.anchors.add(node.anchor);
  27570. strCtx.inFlow = true;
  27571. strCtx.inStringifyKey = true;
  27572. const strKey = key.toString(strCtx);
  27573. if (!ctx.mapKeyWarned) {
  27574. let jsonStr = JSON.stringify(strKey);
  27575. if (jsonStr.length > 40)
  27576. jsonStr = jsonStr.substring(0, 36) + '..."';
  27577. warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
  27578. ctx.mapKeyWarned = true;
  27579. }
  27580. return strKey;
  27581. }
  27582. return JSON.stringify(jsKey);
  27583. }
  27584. function createPair(key, value, ctx) {
  27585. const k = createNode(key, undefined, ctx);
  27586. const v = createNode(value, undefined, ctx);
  27587. return new Pair(k, v);
  27588. }
  27589. class Pair {
  27590. constructor(key, value = null) {
  27591. Object.defineProperty(this, NODE_TYPE, { value: PAIR });
  27592. this.key = key;
  27593. this.value = value;
  27594. }
  27595. clone(schema) {
  27596. let { key, value } = this;
  27597. if (isNode$1(key))
  27598. key = key.clone(schema);
  27599. if (isNode$1(value))
  27600. value = value.clone(schema);
  27601. return new Pair(key, value);
  27602. }
  27603. toJSON(_, ctx) {
  27604. const pair = ctx?.mapAsMap ? new Map() : {};
  27605. return addPairToJSMap(ctx, pair, this);
  27606. }
  27607. toString(ctx, onComment, onChompKeep) {
  27608. return ctx?.doc
  27609. ? stringifyPair(this, ctx, onComment, onChompKeep)
  27610. : JSON.stringify(this);
  27611. }
  27612. }
  27613. function stringifyCollection(collection, ctx, options) {
  27614. const flow = ctx.inFlow ?? collection.flow;
  27615. const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
  27616. return stringify(collection, ctx, options);
  27617. }
  27618. function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
  27619. const { indent, options: { commentString } } = ctx;
  27620. const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
  27621. let chompKeep = false; // flag for the preceding node's status
  27622. const lines = [];
  27623. for (let i = 0; i < items.length; ++i) {
  27624. const item = items[i];
  27625. let comment = null;
  27626. if (isNode$1(item)) {
  27627. if (!chompKeep && item.spaceBefore)
  27628. lines.push('');
  27629. addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
  27630. if (item.comment)
  27631. comment = item.comment;
  27632. }
  27633. else if (isPair(item)) {
  27634. const ik = isNode$1(item.key) ? item.key : null;
  27635. if (ik) {
  27636. if (!chompKeep && ik.spaceBefore)
  27637. lines.push('');
  27638. addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
  27639. }
  27640. }
  27641. chompKeep = false;
  27642. let str = stringify$2(item, itemCtx, () => (comment = null), () => (chompKeep = true));
  27643. if (comment)
  27644. str += lineComment(str, itemIndent, commentString(comment));
  27645. if (chompKeep && comment)
  27646. chompKeep = false;
  27647. lines.push(blockItemPrefix + str);
  27648. }
  27649. let str;
  27650. if (lines.length === 0) {
  27651. str = flowChars.start + flowChars.end;
  27652. }
  27653. else {
  27654. str = lines[0];
  27655. for (let i = 1; i < lines.length; ++i) {
  27656. const line = lines[i];
  27657. str += line ? `\n${indent}${line}` : '\n';
  27658. }
  27659. }
  27660. if (comment) {
  27661. str += '\n' + indentComment(commentString(comment), indent);
  27662. if (onComment)
  27663. onComment();
  27664. }
  27665. else if (chompKeep && onChompKeep)
  27666. onChompKeep();
  27667. return str;
  27668. }
  27669. function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) {
  27670. const { indent, indentStep, options: { commentString } } = ctx;
  27671. itemIndent += indentStep;
  27672. const itemCtx = Object.assign({}, ctx, {
  27673. indent: itemIndent,
  27674. inFlow: true,
  27675. type: null
  27676. });
  27677. let reqNewline = false;
  27678. let linesAtValue = 0;
  27679. const lines = [];
  27680. for (let i = 0; i < items.length; ++i) {
  27681. const item = items[i];
  27682. let comment = null;
  27683. if (isNode$1(item)) {
  27684. if (item.spaceBefore)
  27685. lines.push('');
  27686. addCommentBefore(ctx, lines, item.commentBefore, false);
  27687. if (item.comment)
  27688. comment = item.comment;
  27689. }
  27690. else if (isPair(item)) {
  27691. const ik = isNode$1(item.key) ? item.key : null;
  27692. if (ik) {
  27693. if (ik.spaceBefore)
  27694. lines.push('');
  27695. addCommentBefore(ctx, lines, ik.commentBefore, false);
  27696. if (ik.comment)
  27697. reqNewline = true;
  27698. }
  27699. const iv = isNode$1(item.value) ? item.value : null;
  27700. if (iv) {
  27701. if (iv.comment)
  27702. comment = iv.comment;
  27703. if (iv.commentBefore)
  27704. reqNewline = true;
  27705. }
  27706. else if (item.value == null && ik && ik.comment) {
  27707. comment = ik.comment;
  27708. }
  27709. }
  27710. if (comment)
  27711. reqNewline = true;
  27712. let str = stringify$2(item, itemCtx, () => (comment = null));
  27713. if (i < items.length - 1)
  27714. str += ',';
  27715. if (comment)
  27716. str += lineComment(str, itemIndent, commentString(comment));
  27717. if (!reqNewline && (lines.length > linesAtValue || str.includes('\n')))
  27718. reqNewline = true;
  27719. lines.push(str);
  27720. linesAtValue = lines.length;
  27721. }
  27722. let str;
  27723. const { start, end } = flowChars;
  27724. if (lines.length === 0) {
  27725. str = start + end;
  27726. }
  27727. else {
  27728. if (!reqNewline) {
  27729. const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
  27730. reqNewline = len > Collection.maxFlowStringSingleLineLength;
  27731. }
  27732. if (reqNewline) {
  27733. str = start;
  27734. for (const line of lines)
  27735. str += line ? `\n${indentStep}${indent}${line}` : '\n';
  27736. str += `\n${indent}${end}`;
  27737. }
  27738. else {
  27739. str = `${start} ${lines.join(' ')} ${end}`;
  27740. }
  27741. }
  27742. if (comment) {
  27743. str += lineComment(str, commentString(comment), indent);
  27744. if (onComment)
  27745. onComment();
  27746. }
  27747. return str;
  27748. }
  27749. function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
  27750. if (comment && chompKeep)
  27751. comment = comment.replace(/^\n+/, '');
  27752. if (comment) {
  27753. const ic = indentComment(commentString(comment), indent);
  27754. lines.push(ic.trimStart()); // Avoid double indent on first line
  27755. }
  27756. }
  27757. function findPair(items, key) {
  27758. const k = isScalar$1(key) ? key.value : key;
  27759. for (const it of items) {
  27760. if (isPair(it)) {
  27761. if (it.key === key || it.key === k)
  27762. return it;
  27763. if (isScalar$1(it.key) && it.key.value === k)
  27764. return it;
  27765. }
  27766. }
  27767. return undefined;
  27768. }
  27769. class YAMLMap extends Collection {
  27770. constructor(schema) {
  27771. super(MAP, schema);
  27772. this.items = [];
  27773. }
  27774. static get tagName() {
  27775. return 'tag:yaml.org,2002:map';
  27776. }
  27777. /**
  27778. * Adds a value to the collection.
  27779. *
  27780. * @param overwrite - If not set `true`, using a key that is already in the
  27781. * collection will throw. Otherwise, overwrites the previous value.
  27782. */
  27783. add(pair, overwrite) {
  27784. let _pair;
  27785. if (isPair(pair))
  27786. _pair = pair;
  27787. else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
  27788. // In TypeScript, this never happens.
  27789. _pair = new Pair(pair, pair?.value);
  27790. }
  27791. else
  27792. _pair = new Pair(pair.key, pair.value);
  27793. const prev = findPair(this.items, _pair.key);
  27794. const sortEntries = this.schema?.sortMapEntries;
  27795. if (prev) {
  27796. if (!overwrite)
  27797. throw new Error(`Key ${_pair.key} already set`);
  27798. // For scalars, keep the old node & its comments and anchors
  27799. if (isScalar$1(prev.value) && isScalarValue(_pair.value))
  27800. prev.value.value = _pair.value;
  27801. else
  27802. prev.value = _pair.value;
  27803. }
  27804. else if (sortEntries) {
  27805. const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);
  27806. if (i === -1)
  27807. this.items.push(_pair);
  27808. else
  27809. this.items.splice(i, 0, _pair);
  27810. }
  27811. else {
  27812. this.items.push(_pair);
  27813. }
  27814. }
  27815. delete(key) {
  27816. const it = findPair(this.items, key);
  27817. if (!it)
  27818. return false;
  27819. const del = this.items.splice(this.items.indexOf(it), 1);
  27820. return del.length > 0;
  27821. }
  27822. get(key, keepScalar) {
  27823. const it = findPair(this.items, key);
  27824. const node = it?.value;
  27825. return (!keepScalar && isScalar$1(node) ? node.value : node) ?? undefined;
  27826. }
  27827. has(key) {
  27828. return !!findPair(this.items, key);
  27829. }
  27830. set(key, value) {
  27831. this.add(new Pair(key, value), true);
  27832. }
  27833. /**
  27834. * @param ctx - Conversion context, originally set in Document#toJS()
  27835. * @param {Class} Type - If set, forces the returned collection type
  27836. * @returns Instance of Type, Map, or Object
  27837. */
  27838. toJSON(_, ctx, Type) {
  27839. const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};
  27840. if (ctx?.onCreate)
  27841. ctx.onCreate(map);
  27842. for (const item of this.items)
  27843. addPairToJSMap(ctx, map, item);
  27844. return map;
  27845. }
  27846. toString(ctx, onComment, onChompKeep) {
  27847. if (!ctx)
  27848. return JSON.stringify(this);
  27849. for (const item of this.items) {
  27850. if (!isPair(item))
  27851. throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
  27852. }
  27853. if (!ctx.allNullValues && this.hasAllNullValues(false))
  27854. ctx = Object.assign({}, ctx, { allNullValues: true });
  27855. return stringifyCollection(this, ctx, {
  27856. blockItemPrefix: '',
  27857. flowChars: { start: '{', end: '}' },
  27858. itemIndent: ctx.indent || '',
  27859. onChompKeep,
  27860. onComment
  27861. });
  27862. }
  27863. }
  27864. function createMap(schema, obj, ctx) {
  27865. const { keepUndefined, replacer } = ctx;
  27866. const map = new YAMLMap(schema);
  27867. const add = (key, value) => {
  27868. if (typeof replacer === 'function')
  27869. value = replacer.call(obj, key, value);
  27870. else if (Array.isArray(replacer) && !replacer.includes(key))
  27871. return;
  27872. if (value !== undefined || keepUndefined)
  27873. map.items.push(createPair(key, value, ctx));
  27874. };
  27875. if (obj instanceof Map) {
  27876. for (const [key, value] of obj)
  27877. add(key, value);
  27878. }
  27879. else if (obj && typeof obj === 'object') {
  27880. for (const key of Object.keys(obj))
  27881. add(key, obj[key]);
  27882. }
  27883. if (typeof schema.sortMapEntries === 'function') {
  27884. map.items.sort(schema.sortMapEntries);
  27885. }
  27886. return map;
  27887. }
  27888. const map$1 = {
  27889. collection: 'map',
  27890. createNode: createMap,
  27891. default: true,
  27892. nodeClass: YAMLMap,
  27893. tag: 'tag:yaml.org,2002:map',
  27894. resolve(map, onError) {
  27895. if (!isMap(map))
  27896. onError('Expected a mapping for this tag');
  27897. return map;
  27898. }
  27899. };
  27900. class YAMLSeq extends Collection {
  27901. constructor(schema) {
  27902. super(SEQ, schema);
  27903. this.items = [];
  27904. }
  27905. static get tagName() {
  27906. return 'tag:yaml.org,2002:seq';
  27907. }
  27908. add(value) {
  27909. this.items.push(value);
  27910. }
  27911. /**
  27912. * Removes a value from the collection.
  27913. *
  27914. * `key` must contain a representation of an integer for this to succeed.
  27915. * It may be wrapped in a `Scalar`.
  27916. *
  27917. * @returns `true` if the item was found and removed.
  27918. */
  27919. delete(key) {
  27920. const idx = asItemIndex(key);
  27921. if (typeof idx !== 'number')
  27922. return false;
  27923. const del = this.items.splice(idx, 1);
  27924. return del.length > 0;
  27925. }
  27926. get(key, keepScalar) {
  27927. const idx = asItemIndex(key);
  27928. if (typeof idx !== 'number')
  27929. return undefined;
  27930. const it = this.items[idx];
  27931. return !keepScalar && isScalar$1(it) ? it.value : it;
  27932. }
  27933. /**
  27934. * Checks if the collection includes a value with the key `key`.
  27935. *
  27936. * `key` must contain a representation of an integer for this to succeed.
  27937. * It may be wrapped in a `Scalar`.
  27938. */
  27939. has(key) {
  27940. const idx = asItemIndex(key);
  27941. return typeof idx === 'number' && idx < this.items.length;
  27942. }
  27943. /**
  27944. * Sets a value in this collection. For `!!set`, `value` needs to be a
  27945. * boolean to add/remove the item from the set.
  27946. *
  27947. * If `key` does not contain a representation of an integer, this will throw.
  27948. * It may be wrapped in a `Scalar`.
  27949. */
  27950. set(key, value) {
  27951. const idx = asItemIndex(key);
  27952. if (typeof idx !== 'number')
  27953. throw new Error(`Expected a valid index, not ${key}.`);
  27954. const prev = this.items[idx];
  27955. if (isScalar$1(prev) && isScalarValue(value))
  27956. prev.value = value;
  27957. else
  27958. this.items[idx] = value;
  27959. }
  27960. toJSON(_, ctx) {
  27961. const seq = [];
  27962. if (ctx?.onCreate)
  27963. ctx.onCreate(seq);
  27964. let i = 0;
  27965. for (const item of this.items)
  27966. seq.push(toJS(item, String(i++), ctx));
  27967. return seq;
  27968. }
  27969. toString(ctx, onComment, onChompKeep) {
  27970. if (!ctx)
  27971. return JSON.stringify(this);
  27972. return stringifyCollection(this, ctx, {
  27973. blockItemPrefix: '- ',
  27974. flowChars: { start: '[', end: ']' },
  27975. itemIndent: (ctx.indent || '') + ' ',
  27976. onChompKeep,
  27977. onComment
  27978. });
  27979. }
  27980. }
  27981. function asItemIndex(key) {
  27982. let idx = isScalar$1(key) ? key.value : key;
  27983. if (idx && typeof idx === 'string')
  27984. idx = Number(idx);
  27985. return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0
  27986. ? idx
  27987. : null;
  27988. }
  27989. function createSeq(schema, obj, ctx) {
  27990. const { replacer } = ctx;
  27991. const seq = new YAMLSeq(schema);
  27992. if (obj && Symbol.iterator in Object(obj)) {
  27993. let i = 0;
  27994. for (let it of obj) {
  27995. if (typeof replacer === 'function') {
  27996. const key = obj instanceof Set ? it : String(i++);
  27997. it = replacer.call(obj, key, it);
  27998. }
  27999. seq.items.push(createNode(it, undefined, ctx));
  28000. }
  28001. }
  28002. return seq;
  28003. }
  28004. const seq = {
  28005. collection: 'seq',
  28006. createNode: createSeq,
  28007. default: true,
  28008. nodeClass: YAMLSeq,
  28009. tag: 'tag:yaml.org,2002:seq',
  28010. resolve(seq, onError) {
  28011. if (!isSeq(seq))
  28012. onError('Expected a sequence for this tag');
  28013. return seq;
  28014. }
  28015. };
  28016. const string = {
  28017. identify: value => typeof value === 'string',
  28018. default: true,
  28019. tag: 'tag:yaml.org,2002:str',
  28020. resolve: str => str,
  28021. stringify(item, ctx, onComment, onChompKeep) {
  28022. ctx = Object.assign({ actualString: true }, ctx);
  28023. return stringifyString(item, ctx, onComment, onChompKeep);
  28024. }
  28025. };
  28026. const nullTag = {
  28027. identify: value => value == null,
  28028. createNode: () => new Scalar(null),
  28029. default: true,
  28030. tag: 'tag:yaml.org,2002:null',
  28031. test: /^(?:~|[Nn]ull|NULL)?$/,
  28032. resolve: () => new Scalar(null),
  28033. stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
  28034. ? source
  28035. : ctx.options.nullStr
  28036. };
  28037. const boolTag = {
  28038. identify: value => typeof value === 'boolean',
  28039. default: true,
  28040. tag: 'tag:yaml.org,2002:bool',
  28041. test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  28042. resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),
  28043. stringify({ source, value }, ctx) {
  28044. if (source && boolTag.test.test(source)) {
  28045. const sv = source[0] === 't' || source[0] === 'T';
  28046. if (value === sv)
  28047. return source;
  28048. }
  28049. return value ? ctx.options.trueStr : ctx.options.falseStr;
  28050. }
  28051. };
  28052. function stringifyNumber({ format, minFractionDigits, tag, value }) {
  28053. if (typeof value === 'bigint')
  28054. return String(value);
  28055. const num = typeof value === 'number' ? value : Number(value);
  28056. if (!isFinite(num))
  28057. return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
  28058. let n = JSON.stringify(value);
  28059. if (!format &&
  28060. minFractionDigits &&
  28061. (!tag || tag === 'tag:yaml.org,2002:float') &&
  28062. /^\d/.test(n)) {
  28063. let i = n.indexOf('.');
  28064. if (i < 0) {
  28065. i = n.length;
  28066. n += '.';
  28067. }
  28068. let d = minFractionDigits - (n.length - i - 1);
  28069. while (d-- > 0)
  28070. n += '0';
  28071. }
  28072. return n;
  28073. }
  28074. const floatNaN$1 = {
  28075. identify: value => typeof value === 'number',
  28076. default: true,
  28077. tag: 'tag:yaml.org,2002:float',
  28078. test: /^(?:[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN))$/,
  28079. resolve: str => str.slice(-3).toLowerCase() === 'nan'
  28080. ? NaN
  28081. : str[0] === '-'
  28082. ? Number.NEGATIVE_INFINITY
  28083. : Number.POSITIVE_INFINITY,
  28084. stringify: stringifyNumber
  28085. };
  28086. const floatExp$1 = {
  28087. identify: value => typeof value === 'number',
  28088. default: true,
  28089. tag: 'tag:yaml.org,2002:float',
  28090. format: 'EXP',
  28091. test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  28092. resolve: str => parseFloat(str),
  28093. stringify(node) {
  28094. const num = Number(node.value);
  28095. return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  28096. }
  28097. };
  28098. const float$1 = {
  28099. identify: value => typeof value === 'number',
  28100. default: true,
  28101. tag: 'tag:yaml.org,2002:float',
  28102. test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
  28103. resolve(str) {
  28104. const node = new Scalar(parseFloat(str));
  28105. const dot = str.indexOf('.');
  28106. if (dot !== -1 && str[str.length - 1] === '0')
  28107. node.minFractionDigits = str.length - dot - 1;
  28108. return node;
  28109. },
  28110. stringify: stringifyNumber
  28111. };
  28112. const intIdentify$2 = (value) => typeof value === 'bigint' || Number.isInteger(value);
  28113. const intResolve$1 = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
  28114. function intStringify$1(node, radix, prefix) {
  28115. const { value } = node;
  28116. if (intIdentify$2(value) && value >= 0)
  28117. return prefix + value.toString(radix);
  28118. return stringifyNumber(node);
  28119. }
  28120. const intOct$1 = {
  28121. identify: value => intIdentify$2(value) && value >= 0,
  28122. default: true,
  28123. tag: 'tag:yaml.org,2002:int',
  28124. format: 'OCT',
  28125. test: /^0o[0-7]+$/,
  28126. resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt),
  28127. stringify: node => intStringify$1(node, 8, '0o')
  28128. };
  28129. const int$1 = {
  28130. identify: intIdentify$2,
  28131. default: true,
  28132. tag: 'tag:yaml.org,2002:int',
  28133. test: /^[-+]?[0-9]+$/,
  28134. resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt),
  28135. stringify: stringifyNumber
  28136. };
  28137. const intHex$1 = {
  28138. identify: value => intIdentify$2(value) && value >= 0,
  28139. default: true,
  28140. tag: 'tag:yaml.org,2002:int',
  28141. format: 'HEX',
  28142. test: /^0x[0-9a-fA-F]+$/,
  28143. resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt),
  28144. stringify: node => intStringify$1(node, 16, '0x')
  28145. };
  28146. const schema$2 = [
  28147. map$1,
  28148. seq,
  28149. string,
  28150. nullTag,
  28151. boolTag,
  28152. intOct$1,
  28153. int$1,
  28154. intHex$1,
  28155. floatNaN$1,
  28156. floatExp$1,
  28157. float$1
  28158. ];
  28159. function intIdentify$1(value) {
  28160. return typeof value === 'bigint' || Number.isInteger(value);
  28161. }
  28162. const stringifyJSON = ({ value }) => JSON.stringify(value);
  28163. const jsonScalars = [
  28164. {
  28165. identify: value => typeof value === 'string',
  28166. default: true,
  28167. tag: 'tag:yaml.org,2002:str',
  28168. resolve: str => str,
  28169. stringify: stringifyJSON
  28170. },
  28171. {
  28172. identify: value => value == null,
  28173. createNode: () => new Scalar(null),
  28174. default: true,
  28175. tag: 'tag:yaml.org,2002:null',
  28176. test: /^null$/,
  28177. resolve: () => null,
  28178. stringify: stringifyJSON
  28179. },
  28180. {
  28181. identify: value => typeof value === 'boolean',
  28182. default: true,
  28183. tag: 'tag:yaml.org,2002:bool',
  28184. test: /^true|false$/,
  28185. resolve: str => str === 'true',
  28186. stringify: stringifyJSON
  28187. },
  28188. {
  28189. identify: intIdentify$1,
  28190. default: true,
  28191. tag: 'tag:yaml.org,2002:int',
  28192. test: /^-?(?:0|[1-9][0-9]*)$/,
  28193. resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
  28194. stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
  28195. },
  28196. {
  28197. identify: value => typeof value === 'number',
  28198. default: true,
  28199. tag: 'tag:yaml.org,2002:float',
  28200. test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
  28201. resolve: str => parseFloat(str),
  28202. stringify: stringifyJSON
  28203. }
  28204. ];
  28205. const jsonError = {
  28206. default: true,
  28207. tag: '',
  28208. test: /^/,
  28209. resolve(str, onError) {
  28210. onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
  28211. return str;
  28212. }
  28213. };
  28214. const schema$1 = [map$1, seq].concat(jsonScalars, jsonError);
  28215. const binary = {
  28216. identify: value => value instanceof Uint8Array,
  28217. default: false,
  28218. tag: 'tag:yaml.org,2002:binary',
  28219. /**
  28220. * Returns a Buffer in node and an Uint8Array in browsers
  28221. *
  28222. * To use the resulting buffer as an image, you'll want to do something like:
  28223. *
  28224. * const blob = new Blob([buffer], { type: 'image/jpeg' })
  28225. * document.querySelector('#photo').src = URL.createObjectURL(blob)
  28226. */
  28227. resolve(src, onError) {
  28228. if (typeof Buffer === 'function') {
  28229. return Buffer.from(src, 'base64');
  28230. }
  28231. else if (typeof atob === 'function') {
  28232. // On IE 11, atob() can't handle newlines
  28233. const str = atob(src.replace(/[\n\r]/g, ''));
  28234. const buffer = new Uint8Array(str.length);
  28235. for (let i = 0; i < str.length; ++i)
  28236. buffer[i] = str.charCodeAt(i);
  28237. return buffer;
  28238. }
  28239. else {
  28240. onError('This environment does not support reading binary tags; either Buffer or atob is required');
  28241. return src;
  28242. }
  28243. },
  28244. stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
  28245. const buf = value; // checked earlier by binary.identify()
  28246. let str;
  28247. if (typeof Buffer === 'function') {
  28248. str =
  28249. buf instanceof Buffer
  28250. ? buf.toString('base64')
  28251. : Buffer.from(buf.buffer).toString('base64');
  28252. }
  28253. else if (typeof btoa === 'function') {
  28254. let s = '';
  28255. for (let i = 0; i < buf.length; ++i)
  28256. s += String.fromCharCode(buf[i]);
  28257. str = btoa(s);
  28258. }
  28259. else {
  28260. throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
  28261. }
  28262. if (!type)
  28263. type = Scalar.BLOCK_LITERAL;
  28264. if (type !== Scalar.QUOTE_DOUBLE) {
  28265. const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
  28266. const n = Math.ceil(str.length / lineWidth);
  28267. const lines = new Array(n);
  28268. for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
  28269. lines[i] = str.substr(o, lineWidth);
  28270. }
  28271. str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' ');
  28272. }
  28273. return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
  28274. }
  28275. };
  28276. function resolvePairs(seq, onError) {
  28277. if (isSeq(seq)) {
  28278. for (let i = 0; i < seq.items.length; ++i) {
  28279. let item = seq.items[i];
  28280. if (isPair(item))
  28281. continue;
  28282. else if (isMap(item)) {
  28283. if (item.items.length > 1)
  28284. onError('Each pair must have its own sequence indicator');
  28285. const pair = item.items[0] || new Pair(new Scalar(null));
  28286. if (item.commentBefore)
  28287. pair.key.commentBefore = pair.key.commentBefore
  28288. ? `${item.commentBefore}\n${pair.key.commentBefore}`
  28289. : item.commentBefore;
  28290. if (item.comment) {
  28291. const cn = pair.value ?? pair.key;
  28292. cn.comment = cn.comment
  28293. ? `${item.comment}\n${cn.comment}`
  28294. : item.comment;
  28295. }
  28296. item = pair;
  28297. }
  28298. seq.items[i] = isPair(item) ? item : new Pair(item);
  28299. }
  28300. }
  28301. else
  28302. onError('Expected a sequence for this tag');
  28303. return seq;
  28304. }
  28305. function createPairs(schema, iterable, ctx) {
  28306. const { replacer } = ctx;
  28307. const pairs = new YAMLSeq(schema);
  28308. pairs.tag = 'tag:yaml.org,2002:pairs';
  28309. let i = 0;
  28310. if (iterable && Symbol.iterator in Object(iterable))
  28311. for (let it of iterable) {
  28312. if (typeof replacer === 'function')
  28313. it = replacer.call(iterable, String(i++), it);
  28314. let key, value;
  28315. if (Array.isArray(it)) {
  28316. if (it.length === 2) {
  28317. key = it[0];
  28318. value = it[1];
  28319. }
  28320. else
  28321. throw new TypeError(`Expected [key, value] tuple: ${it}`);
  28322. }
  28323. else if (it && it instanceof Object) {
  28324. const keys = Object.keys(it);
  28325. if (keys.length === 1) {
  28326. key = keys[0];
  28327. value = it[key];
  28328. }
  28329. else
  28330. throw new TypeError(`Expected { key: value } tuple: ${it}`);
  28331. }
  28332. else {
  28333. key = it;
  28334. }
  28335. pairs.items.push(createPair(key, value, ctx));
  28336. }
  28337. return pairs;
  28338. }
  28339. const pairs = {
  28340. collection: 'seq',
  28341. default: false,
  28342. tag: 'tag:yaml.org,2002:pairs',
  28343. resolve: resolvePairs,
  28344. createNode: createPairs
  28345. };
  28346. class YAMLOMap extends YAMLSeq {
  28347. constructor() {
  28348. super();
  28349. this.add = YAMLMap.prototype.add.bind(this);
  28350. this.delete = YAMLMap.prototype.delete.bind(this);
  28351. this.get = YAMLMap.prototype.get.bind(this);
  28352. this.has = YAMLMap.prototype.has.bind(this);
  28353. this.set = YAMLMap.prototype.set.bind(this);
  28354. this.tag = YAMLOMap.tag;
  28355. }
  28356. /**
  28357. * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
  28358. * but TypeScript won't allow widening the signature of a child method.
  28359. */
  28360. toJSON(_, ctx) {
  28361. if (!ctx)
  28362. return super.toJSON(_);
  28363. const map = new Map();
  28364. if (ctx?.onCreate)
  28365. ctx.onCreate(map);
  28366. for (const pair of this.items) {
  28367. let key, value;
  28368. if (isPair(pair)) {
  28369. key = toJS(pair.key, '', ctx);
  28370. value = toJS(pair.value, key, ctx);
  28371. }
  28372. else {
  28373. key = toJS(pair, '', ctx);
  28374. }
  28375. if (map.has(key))
  28376. throw new Error('Ordered maps must not include duplicate keys');
  28377. map.set(key, value);
  28378. }
  28379. return map;
  28380. }
  28381. }
  28382. YAMLOMap.tag = 'tag:yaml.org,2002:omap';
  28383. const omap = {
  28384. collection: 'seq',
  28385. identify: value => value instanceof Map,
  28386. nodeClass: YAMLOMap,
  28387. default: false,
  28388. tag: 'tag:yaml.org,2002:omap',
  28389. resolve(seq, onError) {
  28390. const pairs = resolvePairs(seq, onError);
  28391. const seenKeys = [];
  28392. for (const { key } of pairs.items) {
  28393. if (isScalar$1(key)) {
  28394. if (seenKeys.includes(key.value)) {
  28395. onError(`Ordered maps must not include duplicate keys: ${key.value}`);
  28396. }
  28397. else {
  28398. seenKeys.push(key.value);
  28399. }
  28400. }
  28401. }
  28402. return Object.assign(new YAMLOMap(), pairs);
  28403. },
  28404. createNode(schema, iterable, ctx) {
  28405. const pairs = createPairs(schema, iterable, ctx);
  28406. const omap = new YAMLOMap();
  28407. omap.items = pairs.items;
  28408. return omap;
  28409. }
  28410. };
  28411. function boolStringify({ value, source }, ctx) {
  28412. const boolObj = value ? trueTag : falseTag;
  28413. if (source && boolObj.test.test(source))
  28414. return source;
  28415. return value ? ctx.options.trueStr : ctx.options.falseStr;
  28416. }
  28417. const trueTag = {
  28418. identify: value => value === true,
  28419. default: true,
  28420. tag: 'tag:yaml.org,2002:bool',
  28421. test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  28422. resolve: () => new Scalar(true),
  28423. stringify: boolStringify
  28424. };
  28425. const falseTag = {
  28426. identify: value => value === false,
  28427. default: true,
  28428. tag: 'tag:yaml.org,2002:bool',
  28429. test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
  28430. resolve: () => new Scalar(false),
  28431. stringify: boolStringify
  28432. };
  28433. const floatNaN = {
  28434. identify: value => typeof value === 'number',
  28435. default: true,
  28436. tag: 'tag:yaml.org,2002:float',
  28437. test: /^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/,
  28438. resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
  28439. ? NaN
  28440. : str[0] === '-'
  28441. ? Number.NEGATIVE_INFINITY
  28442. : Number.POSITIVE_INFINITY,
  28443. stringify: stringifyNumber
  28444. };
  28445. const floatExp = {
  28446. identify: value => typeof value === 'number',
  28447. default: true,
  28448. tag: 'tag:yaml.org,2002:float',
  28449. format: 'EXP',
  28450. test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  28451. resolve: (str) => parseFloat(str.replace(/_/g, '')),
  28452. stringify(node) {
  28453. const num = Number(node.value);
  28454. return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  28455. }
  28456. };
  28457. const float = {
  28458. identify: value => typeof value === 'number',
  28459. default: true,
  28460. tag: 'tag:yaml.org,2002:float',
  28461. test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
  28462. resolve(str) {
  28463. const node = new Scalar(parseFloat(str.replace(/_/g, '')));
  28464. const dot = str.indexOf('.');
  28465. if (dot !== -1) {
  28466. const f = str.substring(dot + 1).replace(/_/g, '');
  28467. if (f[f.length - 1] === '0')
  28468. node.minFractionDigits = f.length;
  28469. }
  28470. return node;
  28471. },
  28472. stringify: stringifyNumber
  28473. };
  28474. const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
  28475. function intResolve(str, offset, radix, { intAsBigInt }) {
  28476. const sign = str[0];
  28477. if (sign === '-' || sign === '+')
  28478. offset += 1;
  28479. str = str.substring(offset).replace(/_/g, '');
  28480. if (intAsBigInt) {
  28481. switch (radix) {
  28482. case 2:
  28483. str = `0b${str}`;
  28484. break;
  28485. case 8:
  28486. str = `0o${str}`;
  28487. break;
  28488. case 16:
  28489. str = `0x${str}`;
  28490. break;
  28491. }
  28492. const n = BigInt(str);
  28493. return sign === '-' ? BigInt(-1) * n : n;
  28494. }
  28495. const n = parseInt(str, radix);
  28496. return sign === '-' ? -1 * n : n;
  28497. }
  28498. function intStringify(node, radix, prefix) {
  28499. const { value } = node;
  28500. if (intIdentify(value)) {
  28501. const str = value.toString(radix);
  28502. return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
  28503. }
  28504. return stringifyNumber(node);
  28505. }
  28506. const intBin = {
  28507. identify: intIdentify,
  28508. default: true,
  28509. tag: 'tag:yaml.org,2002:int',
  28510. format: 'BIN',
  28511. test: /^[-+]?0b[0-1_]+$/,
  28512. resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
  28513. stringify: node => intStringify(node, 2, '0b')
  28514. };
  28515. const intOct = {
  28516. identify: intIdentify,
  28517. default: true,
  28518. tag: 'tag:yaml.org,2002:int',
  28519. format: 'OCT',
  28520. test: /^[-+]?0[0-7_]+$/,
  28521. resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
  28522. stringify: node => intStringify(node, 8, '0')
  28523. };
  28524. const int = {
  28525. identify: intIdentify,
  28526. default: true,
  28527. tag: 'tag:yaml.org,2002:int',
  28528. test: /^[-+]?[0-9][0-9_]*$/,
  28529. resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  28530. stringify: stringifyNumber
  28531. };
  28532. const intHex = {
  28533. identify: intIdentify,
  28534. default: true,
  28535. tag: 'tag:yaml.org,2002:int',
  28536. format: 'HEX',
  28537. test: /^[-+]?0x[0-9a-fA-F_]+$/,
  28538. resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  28539. stringify: node => intStringify(node, 16, '0x')
  28540. };
  28541. class YAMLSet extends YAMLMap {
  28542. constructor(schema) {
  28543. super(schema);
  28544. this.tag = YAMLSet.tag;
  28545. }
  28546. add(key) {
  28547. let pair;
  28548. if (isPair(key))
  28549. pair = key;
  28550. else if (typeof key === 'object' &&
  28551. 'key' in key &&
  28552. 'value' in key &&
  28553. key.value === null)
  28554. pair = new Pair(key.key, null);
  28555. else
  28556. pair = new Pair(key, null);
  28557. const prev = findPair(this.items, pair.key);
  28558. if (!prev)
  28559. this.items.push(pair);
  28560. }
  28561. /**
  28562. * If `keepPair` is `true`, returns the Pair matching `key`.
  28563. * Otherwise, returns the value of that Pair's key.
  28564. */
  28565. get(key, keepPair) {
  28566. const pair = findPair(this.items, key);
  28567. return !keepPair && isPair(pair)
  28568. ? isScalar$1(pair.key)
  28569. ? pair.key.value
  28570. : pair.key
  28571. : pair;
  28572. }
  28573. set(key, value) {
  28574. if (typeof value !== 'boolean')
  28575. throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
  28576. const prev = findPair(this.items, key);
  28577. if (prev && !value) {
  28578. this.items.splice(this.items.indexOf(prev), 1);
  28579. }
  28580. else if (!prev && value) {
  28581. this.items.push(new Pair(key));
  28582. }
  28583. }
  28584. toJSON(_, ctx) {
  28585. return super.toJSON(_, ctx, Set);
  28586. }
  28587. toString(ctx, onComment, onChompKeep) {
  28588. if (!ctx)
  28589. return JSON.stringify(this);
  28590. if (this.hasAllNullValues(true))
  28591. return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
  28592. else
  28593. throw new Error('Set items must all have null values');
  28594. }
  28595. }
  28596. YAMLSet.tag = 'tag:yaml.org,2002:set';
  28597. const set = {
  28598. collection: 'map',
  28599. identify: value => value instanceof Set,
  28600. nodeClass: YAMLSet,
  28601. default: false,
  28602. tag: 'tag:yaml.org,2002:set',
  28603. resolve(map, onError) {
  28604. if (isMap(map)) {
  28605. if (map.hasAllNullValues(true))
  28606. return Object.assign(new YAMLSet(), map);
  28607. else
  28608. onError('Set items must all have null values');
  28609. }
  28610. else
  28611. onError('Expected a mapping for this tag');
  28612. return map;
  28613. },
  28614. createNode(schema, iterable, ctx) {
  28615. const { replacer } = ctx;
  28616. const set = new YAMLSet(schema);
  28617. if (iterable && Symbol.iterator in Object(iterable))
  28618. for (let value of iterable) {
  28619. if (typeof replacer === 'function')
  28620. value = replacer.call(iterable, value, value);
  28621. set.items.push(createPair(value, null, ctx));
  28622. }
  28623. return set;
  28624. }
  28625. };
  28626. /** Internal types handle bigint as number, because TS can't figure it out. */
  28627. function parseSexagesimal(str, asBigInt) {
  28628. const sign = str[0];
  28629. const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
  28630. const num = (n) => asBigInt ? BigInt(n) : Number(n);
  28631. const res = parts
  28632. .replace(/_/g, '')
  28633. .split(':')
  28634. .reduce((res, p) => res * num(60) + num(p), num(0));
  28635. return (sign === '-' ? num(-1) * res : res);
  28636. }
  28637. /**
  28638. * hhhh:mm:ss.sss
  28639. *
  28640. * Internal types handle bigint as number, because TS can't figure it out.
  28641. */
  28642. function stringifySexagesimal(node) {
  28643. let { value } = node;
  28644. let num = (n) => n;
  28645. if (typeof value === 'bigint')
  28646. num = n => BigInt(n);
  28647. else if (isNaN(value) || !isFinite(value))
  28648. return stringifyNumber(node);
  28649. let sign = '';
  28650. if (value < 0) {
  28651. sign = '-';
  28652. value *= num(-1);
  28653. }
  28654. const _60 = num(60);
  28655. const parts = [value % _60]; // seconds, including ms
  28656. if (value < 60) {
  28657. parts.unshift(0); // at least one : is required
  28658. }
  28659. else {
  28660. value = (value - parts[0]) / _60;
  28661. parts.unshift(value % _60); // minutes
  28662. if (value >= 60) {
  28663. value = (value - parts[0]) / _60;
  28664. parts.unshift(value); // hours
  28665. }
  28666. }
  28667. return (sign +
  28668. parts
  28669. .map(n => (n < 10 ? '0' + String(n) : String(n)))
  28670. .join(':')
  28671. .replace(/000000\d*$/, '') // % 60 may introduce error
  28672. );
  28673. }
  28674. const intTime = {
  28675. identify: value => typeof value === 'bigint' || Number.isInteger(value),
  28676. default: true,
  28677. tag: 'tag:yaml.org,2002:int',
  28678. format: 'TIME',
  28679. test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
  28680. resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
  28681. stringify: stringifySexagesimal
  28682. };
  28683. const floatTime = {
  28684. identify: value => typeof value === 'number',
  28685. default: true,
  28686. tag: 'tag:yaml.org,2002:float',
  28687. format: 'TIME',
  28688. test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
  28689. resolve: str => parseSexagesimal(str, false),
  28690. stringify: stringifySexagesimal
  28691. };
  28692. const timestamp = {
  28693. identify: value => value instanceof Date,
  28694. default: true,
  28695. tag: 'tag:yaml.org,2002:timestamp',
  28696. // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  28697. // may be omitted altogether, resulting in a date format. In such a case, the time part is
  28698. // assumed to be 00:00:00Z (start of day, UTC).
  28699. test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
  28700. '(?:' + // time is optional
  28701. '(?:t|T|[ \\t]+)' + // t | T | whitespace
  28702. '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
  28703. '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
  28704. ')?$'),
  28705. resolve(str) {
  28706. const match = str.match(timestamp.test);
  28707. if (!match)
  28708. throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
  28709. const [, year, month, day, hour, minute, second] = match.map(Number);
  28710. const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
  28711. let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
  28712. const tz = match[8];
  28713. if (tz && tz !== 'Z') {
  28714. let d = parseSexagesimal(tz, false);
  28715. if (Math.abs(d) < 30)
  28716. d *= 60;
  28717. date -= 60000 * d;
  28718. }
  28719. return new Date(date);
  28720. },
  28721. stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
  28722. };
  28723. const schema = [
  28724. map$1,
  28725. seq,
  28726. string,
  28727. nullTag,
  28728. trueTag,
  28729. falseTag,
  28730. intBin,
  28731. intOct,
  28732. int,
  28733. intHex,
  28734. floatNaN,
  28735. floatExp,
  28736. float,
  28737. binary,
  28738. omap,
  28739. pairs,
  28740. set,
  28741. intTime,
  28742. floatTime,
  28743. timestamp
  28744. ];
  28745. const schemas = new Map([
  28746. ['core', schema$2],
  28747. ['failsafe', [map$1, seq, string]],
  28748. ['json', schema$1],
  28749. ['yaml11', schema],
  28750. ['yaml-1.1', schema]
  28751. ]);
  28752. const tagsByName = {
  28753. binary,
  28754. bool: boolTag,
  28755. float: float$1,
  28756. floatExp: floatExp$1,
  28757. floatNaN: floatNaN$1,
  28758. floatTime,
  28759. int: int$1,
  28760. intHex: intHex$1,
  28761. intOct: intOct$1,
  28762. intTime,
  28763. map: map$1,
  28764. null: nullTag,
  28765. omap,
  28766. pairs,
  28767. seq,
  28768. set,
  28769. timestamp
  28770. };
  28771. const coreKnownTags = {
  28772. 'tag:yaml.org,2002:binary': binary,
  28773. 'tag:yaml.org,2002:omap': omap,
  28774. 'tag:yaml.org,2002:pairs': pairs,
  28775. 'tag:yaml.org,2002:set': set,
  28776. 'tag:yaml.org,2002:timestamp': timestamp
  28777. };
  28778. function getTags(customTags, schemaName) {
  28779. let tags = schemas.get(schemaName);
  28780. if (!tags) {
  28781. if (Array.isArray(customTags))
  28782. tags = [];
  28783. else {
  28784. const keys = Array.from(schemas.keys())
  28785. .filter(key => key !== 'yaml11')
  28786. .map(key => JSON.stringify(key))
  28787. .join(', ');
  28788. throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
  28789. }
  28790. }
  28791. if (Array.isArray(customTags)) {
  28792. for (const tag of customTags)
  28793. tags = tags.concat(tag);
  28794. }
  28795. else if (typeof customTags === 'function') {
  28796. tags = customTags(tags.slice());
  28797. }
  28798. return tags.map(tag => {
  28799. if (typeof tag !== 'string')
  28800. return tag;
  28801. const tagObj = tagsByName[tag];
  28802. if (tagObj)
  28803. return tagObj;
  28804. const keys = Object.keys(tagsByName)
  28805. .map(key => JSON.stringify(key))
  28806. .join(', ');
  28807. throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
  28808. });
  28809. }
  28810. const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
  28811. class Schema {
  28812. constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
  28813. this.compat = Array.isArray(compat)
  28814. ? getTags(compat, 'compat')
  28815. : compat
  28816. ? getTags(null, compat)
  28817. : null;
  28818. this.merge = !!merge;
  28819. this.name = (typeof schema === 'string' && schema) || 'core';
  28820. this.knownTags = resolveKnownTags ? coreKnownTags : {};
  28821. this.tags = getTags(customTags, this.name);
  28822. this.toStringOptions = toStringDefaults ?? null;
  28823. Object.defineProperty(this, MAP, { value: map$1 });
  28824. Object.defineProperty(this, SCALAR$1, { value: string });
  28825. Object.defineProperty(this, SEQ, { value: seq });
  28826. // Used by createMap()
  28827. this.sortMapEntries =
  28828. typeof sortMapEntries === 'function'
  28829. ? sortMapEntries
  28830. : sortMapEntries === true
  28831. ? sortMapEntriesByKey
  28832. : null;
  28833. }
  28834. clone() {
  28835. const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
  28836. copy.tags = this.tags.slice();
  28837. return copy;
  28838. }
  28839. }
  28840. function stringifyDocument(doc, options) {
  28841. const lines = [];
  28842. let hasDirectives = options.directives === true;
  28843. if (options.directives !== false && doc.directives) {
  28844. const dir = doc.directives.toString(doc);
  28845. if (dir) {
  28846. lines.push(dir);
  28847. hasDirectives = true;
  28848. }
  28849. else if (doc.directives.docStart)
  28850. hasDirectives = true;
  28851. }
  28852. if (hasDirectives)
  28853. lines.push('---');
  28854. const ctx = createStringifyContext(doc, options);
  28855. const { commentString } = ctx.options;
  28856. if (doc.commentBefore) {
  28857. if (lines.length !== 1)
  28858. lines.unshift('');
  28859. const cs = commentString(doc.commentBefore);
  28860. lines.unshift(indentComment(cs, ''));
  28861. }
  28862. let chompKeep = false;
  28863. let contentComment = null;
  28864. if (doc.contents) {
  28865. if (isNode$1(doc.contents)) {
  28866. if (doc.contents.spaceBefore && hasDirectives)
  28867. lines.push('');
  28868. if (doc.contents.commentBefore) {
  28869. const cs = commentString(doc.contents.commentBefore);
  28870. lines.push(indentComment(cs, ''));
  28871. }
  28872. // top-level block scalars need to be indented if followed by a comment
  28873. ctx.forceBlockIndent = !!doc.comment;
  28874. contentComment = doc.contents.comment;
  28875. }
  28876. const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
  28877. let body = stringify$2(doc.contents, ctx, () => (contentComment = null), onChompKeep);
  28878. if (contentComment)
  28879. body += lineComment(body, '', commentString(contentComment));
  28880. if ((body[0] === '|' || body[0] === '>') &&
  28881. lines[lines.length - 1] === '---') {
  28882. // Top-level block scalars with a preceding doc marker ought to use the
  28883. // same line for their header.
  28884. lines[lines.length - 1] = `--- ${body}`;
  28885. }
  28886. else
  28887. lines.push(body);
  28888. }
  28889. else {
  28890. lines.push(stringify$2(doc.contents, ctx));
  28891. }
  28892. if (doc.directives?.docEnd) {
  28893. if (doc.comment) {
  28894. const cs = commentString(doc.comment);
  28895. if (cs.includes('\n')) {
  28896. lines.push('...');
  28897. lines.push(indentComment(cs, ''));
  28898. }
  28899. else {
  28900. lines.push(`... ${cs}`);
  28901. }
  28902. }
  28903. else {
  28904. lines.push('...');
  28905. }
  28906. }
  28907. else {
  28908. let dc = doc.comment;
  28909. if (dc && chompKeep)
  28910. dc = dc.replace(/^\n+/, '');
  28911. if (dc) {
  28912. if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
  28913. lines.push('');
  28914. lines.push(indentComment(commentString(dc), ''));
  28915. }
  28916. }
  28917. return lines.join('\n') + '\n';
  28918. }
  28919. /**
  28920. * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
  28921. * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
  28922. * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
  28923. *
  28924. * Includes extensions for handling Map and Set objects.
  28925. */
  28926. function applyReviver(reviver, obj, key, val) {
  28927. if (val && typeof val === 'object') {
  28928. if (Array.isArray(val)) {
  28929. for (let i = 0, len = val.length; i < len; ++i) {
  28930. const v0 = val[i];
  28931. const v1 = applyReviver(reviver, val, String(i), v0);
  28932. if (v1 === undefined)
  28933. delete val[i];
  28934. else if (v1 !== v0)
  28935. val[i] = v1;
  28936. }
  28937. }
  28938. else if (val instanceof Map) {
  28939. for (const k of Array.from(val.keys())) {
  28940. const v0 = val.get(k);
  28941. const v1 = applyReviver(reviver, val, k, v0);
  28942. if (v1 === undefined)
  28943. val.delete(k);
  28944. else if (v1 !== v0)
  28945. val.set(k, v1);
  28946. }
  28947. }
  28948. else if (val instanceof Set) {
  28949. for (const v0 of Array.from(val)) {
  28950. const v1 = applyReviver(reviver, val, v0, v0);
  28951. if (v1 === undefined)
  28952. val.delete(v0);
  28953. else if (v1 !== v0) {
  28954. val.delete(v0);
  28955. val.add(v1);
  28956. }
  28957. }
  28958. }
  28959. else {
  28960. for (const [k, v0] of Object.entries(val)) {
  28961. const v1 = applyReviver(reviver, val, k, v0);
  28962. if (v1 === undefined)
  28963. delete val[k];
  28964. else if (v1 !== v0)
  28965. val[k] = v1;
  28966. }
  28967. }
  28968. }
  28969. return reviver.call(obj, key, val);
  28970. }
  28971. class Document {
  28972. constructor(value, replacer, options) {
  28973. /** A comment before this Document */
  28974. this.commentBefore = null;
  28975. /** A comment immediately after this Document */
  28976. this.comment = null;
  28977. /** Errors encountered during parsing. */
  28978. this.errors = [];
  28979. /** Warnings encountered during parsing. */
  28980. this.warnings = [];
  28981. Object.defineProperty(this, NODE_TYPE, { value: DOC });
  28982. let _replacer = null;
  28983. if (typeof replacer === 'function' || Array.isArray(replacer)) {
  28984. _replacer = replacer;
  28985. }
  28986. else if (options === undefined && replacer) {
  28987. options = replacer;
  28988. replacer = undefined;
  28989. }
  28990. const opt = Object.assign({
  28991. intAsBigInt: false,
  28992. keepSourceTokens: false,
  28993. logLevel: 'warn',
  28994. prettyErrors: true,
  28995. strict: true,
  28996. uniqueKeys: true,
  28997. version: '1.2'
  28998. }, options);
  28999. this.options = opt;
  29000. let { version } = opt;
  29001. if (options?._directives) {
  29002. this.directives = options._directives.atDocument();
  29003. if (this.directives.yaml.explicit)
  29004. version = this.directives.yaml.version;
  29005. }
  29006. else
  29007. this.directives = new Directives({ version });
  29008. this.setSchema(version, options);
  29009. if (value === undefined)
  29010. this.contents = null;
  29011. else {
  29012. this.contents = this.createNode(value, _replacer, options);
  29013. }
  29014. }
  29015. /**
  29016. * Create a deep copy of this Document and its contents.
  29017. *
  29018. * Custom Node values that inherit from `Object` still refer to their original instances.
  29019. */
  29020. clone() {
  29021. const copy = Object.create(Document.prototype, {
  29022. [NODE_TYPE]: { value: DOC }
  29023. });
  29024. copy.commentBefore = this.commentBefore;
  29025. copy.comment = this.comment;
  29026. copy.errors = this.errors.slice();
  29027. copy.warnings = this.warnings.slice();
  29028. copy.options = Object.assign({}, this.options);
  29029. if (this.directives)
  29030. copy.directives = this.directives.clone();
  29031. copy.schema = this.schema.clone();
  29032. copy.contents = isNode$1(this.contents)
  29033. ? this.contents.clone(copy.schema)
  29034. : this.contents;
  29035. if (this.range)
  29036. copy.range = this.range.slice();
  29037. return copy;
  29038. }
  29039. /** Adds a value to the document. */
  29040. add(value) {
  29041. if (assertCollection(this.contents))
  29042. this.contents.add(value);
  29043. }
  29044. /** Adds a value to the document. */
  29045. addIn(path, value) {
  29046. if (assertCollection(this.contents))
  29047. this.contents.addIn(path, value);
  29048. }
  29049. /**
  29050. * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
  29051. *
  29052. * If `node` already has an anchor, `name` is ignored.
  29053. * Otherwise, the `node.anchor` value will be set to `name`,
  29054. * or if an anchor with that name is already present in the document,
  29055. * `name` will be used as a prefix for a new unique anchor.
  29056. * If `name` is undefined, the generated anchor will use 'a' as a prefix.
  29057. */
  29058. createAlias(node, name) {
  29059. if (!node.anchor) {
  29060. const prev = anchorNames(this);
  29061. node.anchor =
  29062. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  29063. !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;
  29064. }
  29065. return new Alias(node.anchor);
  29066. }
  29067. createNode(value, replacer, options) {
  29068. let _replacer = undefined;
  29069. if (typeof replacer === 'function') {
  29070. value = replacer.call({ '': value }, '', value);
  29071. _replacer = replacer;
  29072. }
  29073. else if (Array.isArray(replacer)) {
  29074. const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
  29075. const asStr = replacer.filter(keyToStr).map(String);
  29076. if (asStr.length > 0)
  29077. replacer = replacer.concat(asStr);
  29078. _replacer = replacer;
  29079. }
  29080. else if (options === undefined && replacer) {
  29081. options = replacer;
  29082. replacer = undefined;
  29083. }
  29084. const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
  29085. const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this,
  29086. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  29087. anchorPrefix || 'a');
  29088. const ctx = {
  29089. aliasDuplicateObjects: aliasDuplicateObjects ?? true,
  29090. keepUndefined: keepUndefined ?? false,
  29091. onAnchor,
  29092. onTagObj,
  29093. replacer: _replacer,
  29094. schema: this.schema,
  29095. sourceObjects
  29096. };
  29097. const node = createNode(value, tag, ctx);
  29098. if (flow && isCollection$1(node))
  29099. node.flow = true;
  29100. setAnchors();
  29101. return node;
  29102. }
  29103. /**
  29104. * Convert a key and a value into a `Pair` using the current schema,
  29105. * recursively wrapping all values as `Scalar` or `Collection` nodes.
  29106. */
  29107. createPair(key, value, options = {}) {
  29108. const k = this.createNode(key, null, options);
  29109. const v = this.createNode(value, null, options);
  29110. return new Pair(k, v);
  29111. }
  29112. /**
  29113. * Removes a value from the document.
  29114. * @returns `true` if the item was found and removed.
  29115. */
  29116. delete(key) {
  29117. return assertCollection(this.contents) ? this.contents.delete(key) : false;
  29118. }
  29119. /**
  29120. * Removes a value from the document.
  29121. * @returns `true` if the item was found and removed.
  29122. */
  29123. deleteIn(path) {
  29124. if (isEmptyPath(path)) {
  29125. if (this.contents == null)
  29126. return false;
  29127. this.contents = null;
  29128. return true;
  29129. }
  29130. return assertCollection(this.contents)
  29131. ? this.contents.deleteIn(path)
  29132. : false;
  29133. }
  29134. /**
  29135. * Returns item at `key`, or `undefined` if not found. By default unwraps
  29136. * scalar values from their surrounding node; to disable set `keepScalar` to
  29137. * `true` (collections are always returned intact).
  29138. */
  29139. get(key, keepScalar) {
  29140. return isCollection$1(this.contents)
  29141. ? this.contents.get(key, keepScalar)
  29142. : undefined;
  29143. }
  29144. /**
  29145. * Returns item at `path`, or `undefined` if not found. By default unwraps
  29146. * scalar values from their surrounding node; to disable set `keepScalar` to
  29147. * `true` (collections are always returned intact).
  29148. */
  29149. getIn(path, keepScalar) {
  29150. if (isEmptyPath(path))
  29151. return !keepScalar && isScalar$1(this.contents)
  29152. ? this.contents.value
  29153. : this.contents;
  29154. return isCollection$1(this.contents)
  29155. ? this.contents.getIn(path, keepScalar)
  29156. : undefined;
  29157. }
  29158. /**
  29159. * Checks if the document includes a value with the key `key`.
  29160. */
  29161. has(key) {
  29162. return isCollection$1(this.contents) ? this.contents.has(key) : false;
  29163. }
  29164. /**
  29165. * Checks if the document includes a value at `path`.
  29166. */
  29167. hasIn(path) {
  29168. if (isEmptyPath(path))
  29169. return this.contents !== undefined;
  29170. return isCollection$1(this.contents) ? this.contents.hasIn(path) : false;
  29171. }
  29172. /**
  29173. * Sets a value in this document. For `!!set`, `value` needs to be a
  29174. * boolean to add/remove the item from the set.
  29175. */
  29176. set(key, value) {
  29177. if (this.contents == null) {
  29178. this.contents = collectionFromPath(this.schema, [key], value);
  29179. }
  29180. else if (assertCollection(this.contents)) {
  29181. this.contents.set(key, value);
  29182. }
  29183. }
  29184. /**
  29185. * Sets a value in this document. For `!!set`, `value` needs to be a
  29186. * boolean to add/remove the item from the set.
  29187. */
  29188. setIn(path, value) {
  29189. if (isEmptyPath(path))
  29190. this.contents = value;
  29191. else if (this.contents == null) {
  29192. this.contents = collectionFromPath(this.schema, Array.from(path), value);
  29193. }
  29194. else if (assertCollection(this.contents)) {
  29195. this.contents.setIn(path, value);
  29196. }
  29197. }
  29198. /**
  29199. * Change the YAML version and schema used by the document.
  29200. * A `null` version disables support for directives, explicit tags, anchors, and aliases.
  29201. * It also requires the `schema` option to be given as a `Schema` instance value.
  29202. *
  29203. * Overrides all previously set schema options.
  29204. */
  29205. setSchema(version, options = {}) {
  29206. if (typeof version === 'number')
  29207. version = String(version);
  29208. let opt;
  29209. switch (version) {
  29210. case '1.1':
  29211. if (this.directives)
  29212. this.directives.yaml.version = '1.1';
  29213. else
  29214. this.directives = new Directives({ version: '1.1' });
  29215. opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' };
  29216. break;
  29217. case '1.2':
  29218. case 'next':
  29219. if (this.directives)
  29220. this.directives.yaml.version = version;
  29221. else
  29222. this.directives = new Directives({ version });
  29223. opt = { merge: false, resolveKnownTags: true, schema: 'core' };
  29224. break;
  29225. case null:
  29226. if (this.directives)
  29227. delete this.directives;
  29228. opt = null;
  29229. break;
  29230. default: {
  29231. const sv = JSON.stringify(version);
  29232. throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
  29233. }
  29234. }
  29235. // Not using `instanceof Schema` to allow for duck typing
  29236. if (options.schema instanceof Object)
  29237. this.schema = options.schema;
  29238. else if (opt)
  29239. this.schema = new Schema(Object.assign(opt, options));
  29240. else
  29241. throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  29242. }
  29243. // json & jsonArg are only used from toJSON()
  29244. toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
  29245. const ctx = {
  29246. anchors: new Map(),
  29247. doc: this,
  29248. keep: !json,
  29249. mapAsMap: mapAsMap === true,
  29250. mapKeyWarned: false,
  29251. maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
  29252. stringify: stringify$2
  29253. };
  29254. const res = toJS(this.contents, jsonArg ?? '', ctx);
  29255. if (typeof onAnchor === 'function')
  29256. for (const { count, res } of ctx.anchors.values())
  29257. onAnchor(res, count);
  29258. return typeof reviver === 'function'
  29259. ? applyReviver(reviver, { '': res }, '', res)
  29260. : res;
  29261. }
  29262. /**
  29263. * A JSON representation of the document `contents`.
  29264. *
  29265. * @param jsonArg Used by `JSON.stringify` to indicate the array index or
  29266. * property name.
  29267. */
  29268. toJSON(jsonArg, onAnchor) {
  29269. return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  29270. }
  29271. /** A YAML representation of the document. */
  29272. toString(options = {}) {
  29273. if (this.errors.length > 0)
  29274. throw new Error('Document with errors cannot be stringified');
  29275. if ('indent' in options &&
  29276. (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
  29277. const s = JSON.stringify(options.indent);
  29278. throw new Error(`"indent" option must be a positive integer, not ${s}`);
  29279. }
  29280. return stringifyDocument(this, options);
  29281. }
  29282. }
  29283. function assertCollection(contents) {
  29284. if (isCollection$1(contents))
  29285. return true;
  29286. throw new Error('Expected a YAML collection as document contents');
  29287. }
  29288. class YAMLError extends Error {
  29289. constructor(name, pos, code, message) {
  29290. super();
  29291. this.name = name;
  29292. this.code = code;
  29293. this.message = message;
  29294. this.pos = pos;
  29295. }
  29296. }
  29297. class YAMLParseError extends YAMLError {
  29298. constructor(pos, code, message) {
  29299. super('YAMLParseError', pos, code, message);
  29300. }
  29301. }
  29302. class YAMLWarning extends YAMLError {
  29303. constructor(pos, code, message) {
  29304. super('YAMLWarning', pos, code, message);
  29305. }
  29306. }
  29307. const prettifyError = (src, lc) => (error) => {
  29308. if (error.pos[0] === -1)
  29309. return;
  29310. error.linePos = error.pos.map(pos => lc.linePos(pos));
  29311. const { line, col } = error.linePos[0];
  29312. error.message += ` at line ${line}, column ${col}`;
  29313. let ci = col - 1;
  29314. let lineStr = src
  29315. .substring(lc.lineStarts[line - 1], lc.lineStarts[line])
  29316. .replace(/[\n\r]+$/, '');
  29317. // Trim to max 80 chars, keeping col position near the middle
  29318. if (ci >= 60 && lineStr.length > 80) {
  29319. const trimStart = Math.min(ci - 39, lineStr.length - 79);
  29320. lineStr = '…' + lineStr.substring(trimStart);
  29321. ci -= trimStart - 1;
  29322. }
  29323. if (lineStr.length > 80)
  29324. lineStr = lineStr.substring(0, 79) + '…';
  29325. // Include previous line in context if pointing at line start
  29326. if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
  29327. // Regexp won't match if start is trimmed
  29328. let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
  29329. if (prev.length > 80)
  29330. prev = prev.substring(0, 79) + '…\n';
  29331. lineStr = prev + lineStr;
  29332. }
  29333. if (/[^ ]/.test(lineStr)) {
  29334. let count = 1;
  29335. const end = error.linePos[1];
  29336. if (end && end.line === line && end.col > col) {
  29337. count = Math.min(end.col - col, 80 - ci);
  29338. }
  29339. const pointer = ' '.repeat(ci) + '^'.repeat(count);
  29340. error.message += `:\n\n${lineStr}\n${pointer}\n`;
  29341. }
  29342. };
  29343. function resolveProps(tokens, { flow, indicator, next, offset, onError, startOnNewline }) {
  29344. let spaceBefore = false;
  29345. let atNewline = startOnNewline;
  29346. let hasSpace = startOnNewline;
  29347. let comment = '';
  29348. let commentSep = '';
  29349. let hasNewline = false;
  29350. let hasNewlineAfterProp = false;
  29351. let reqSpace = false;
  29352. let anchor = null;
  29353. let tag = null;
  29354. let comma = null;
  29355. let found = null;
  29356. let start = null;
  29357. for (const token of tokens) {
  29358. if (reqSpace) {
  29359. if (token.type !== 'space' &&
  29360. token.type !== 'newline' &&
  29361. token.type !== 'comma')
  29362. onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
  29363. reqSpace = false;
  29364. }
  29365. switch (token.type) {
  29366. case 'space':
  29367. // At the doc level, tabs at line start may be parsed
  29368. // as leading white space rather than indentation.
  29369. // In a flow collection, only the parser handles indent.
  29370. if (!flow &&
  29371. atNewline &&
  29372. indicator !== 'doc-start' &&
  29373. token.source[0] === '\t')
  29374. onError(token, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
  29375. hasSpace = true;
  29376. break;
  29377. case 'comment': {
  29378. if (!hasSpace)
  29379. onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
  29380. const cb = token.source.substring(1) || ' ';
  29381. if (!comment)
  29382. comment = cb;
  29383. else
  29384. comment += commentSep + cb;
  29385. commentSep = '';
  29386. atNewline = false;
  29387. break;
  29388. }
  29389. case 'newline':
  29390. if (atNewline) {
  29391. if (comment)
  29392. comment += token.source;
  29393. else
  29394. spaceBefore = true;
  29395. }
  29396. else
  29397. commentSep += token.source;
  29398. atNewline = true;
  29399. hasNewline = true;
  29400. if (anchor || tag)
  29401. hasNewlineAfterProp = true;
  29402. hasSpace = true;
  29403. break;
  29404. case 'anchor':
  29405. if (anchor)
  29406. onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');
  29407. if (token.source.endsWith(':'))
  29408. onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);
  29409. anchor = token;
  29410. if (start === null)
  29411. start = token.offset;
  29412. atNewline = false;
  29413. hasSpace = false;
  29414. reqSpace = true;
  29415. break;
  29416. case 'tag': {
  29417. if (tag)
  29418. onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');
  29419. tag = token;
  29420. if (start === null)
  29421. start = token.offset;
  29422. atNewline = false;
  29423. hasSpace = false;
  29424. reqSpace = true;
  29425. break;
  29426. }
  29427. case indicator:
  29428. // Could here handle preceding comments differently
  29429. if (anchor || tag)
  29430. onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);
  29431. if (found)
  29432. onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);
  29433. found = token;
  29434. atNewline = false;
  29435. hasSpace = false;
  29436. break;
  29437. case 'comma':
  29438. if (flow) {
  29439. if (comma)
  29440. onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);
  29441. comma = token;
  29442. atNewline = false;
  29443. hasSpace = false;
  29444. break;
  29445. }
  29446. // else fallthrough
  29447. default:
  29448. onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);
  29449. atNewline = false;
  29450. hasSpace = false;
  29451. }
  29452. }
  29453. const last = tokens[tokens.length - 1];
  29454. const end = last ? last.offset + last.source.length : offset;
  29455. if (reqSpace &&
  29456. next &&
  29457. next.type !== 'space' &&
  29458. next.type !== 'newline' &&
  29459. next.type !== 'comma' &&
  29460. (next.type !== 'scalar' || next.source !== ''))
  29461. onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
  29462. return {
  29463. comma,
  29464. found,
  29465. spaceBefore,
  29466. comment,
  29467. hasNewline,
  29468. hasNewlineAfterProp,
  29469. anchor,
  29470. tag,
  29471. end,
  29472. start: start ?? end
  29473. };
  29474. }
  29475. function containsNewline(key) {
  29476. if (!key)
  29477. return null;
  29478. switch (key.type) {
  29479. case 'alias':
  29480. case 'scalar':
  29481. case 'double-quoted-scalar':
  29482. case 'single-quoted-scalar':
  29483. if (key.source.includes('\n'))
  29484. return true;
  29485. if (key.end)
  29486. for (const st of key.end)
  29487. if (st.type === 'newline')
  29488. return true;
  29489. return false;
  29490. case 'flow-collection':
  29491. for (const it of key.items) {
  29492. for (const st of it.start)
  29493. if (st.type === 'newline')
  29494. return true;
  29495. if (it.sep)
  29496. for (const st of it.sep)
  29497. if (st.type === 'newline')
  29498. return true;
  29499. if (containsNewline(it.key) || containsNewline(it.value))
  29500. return true;
  29501. }
  29502. return false;
  29503. default:
  29504. return true;
  29505. }
  29506. }
  29507. function flowIndentCheck(indent, fc, onError) {
  29508. if (fc?.type === 'flow-collection') {
  29509. const end = fc.end[0];
  29510. if (end.indent === indent &&
  29511. (end.source === ']' || end.source === '}') &&
  29512. containsNewline(fc)) {
  29513. const msg = 'Flow end indicator should be more indented than parent';
  29514. onError(end, 'BAD_INDENT', msg, true);
  29515. }
  29516. }
  29517. }
  29518. function mapIncludes(ctx, items, search) {
  29519. const { uniqueKeys } = ctx.options;
  29520. if (uniqueKeys === false)
  29521. return false;
  29522. const isEqual = typeof uniqueKeys === 'function'
  29523. ? uniqueKeys
  29524. : (a, b) => a === b ||
  29525. (isScalar$1(a) &&
  29526. isScalar$1(b) &&
  29527. a.value === b.value &&
  29528. !(a.value === '<<' && ctx.schema.merge));
  29529. return items.some(pair => isEqual(pair.key, search));
  29530. }
  29531. const startColMsg = 'All mapping items must start at the same column';
  29532. function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError) {
  29533. const map = new YAMLMap(ctx.schema);
  29534. if (ctx.atRoot)
  29535. ctx.atRoot = false;
  29536. let offset = bm.offset;
  29537. for (const collItem of bm.items) {
  29538. const { start, key, sep, value } = collItem;
  29539. // key properties
  29540. const keyProps = resolveProps(start, {
  29541. indicator: 'explicit-key-ind',
  29542. next: key ?? sep?.[0],
  29543. offset,
  29544. onError,
  29545. startOnNewline: true
  29546. });
  29547. const implicitKey = !keyProps.found;
  29548. if (implicitKey) {
  29549. if (key) {
  29550. if (key.type === 'block-seq')
  29551. onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');
  29552. else if ('indent' in key && key.indent !== bm.indent)
  29553. onError(offset, 'BAD_INDENT', startColMsg);
  29554. }
  29555. if (!keyProps.anchor && !keyProps.tag && !sep) {
  29556. // TODO: assert being at last item?
  29557. if (keyProps.comment) {
  29558. if (map.comment)
  29559. map.comment += '\n' + keyProps.comment;
  29560. else
  29561. map.comment = keyProps.comment;
  29562. }
  29563. continue;
  29564. }
  29565. if (keyProps.hasNewlineAfterProp || containsNewline(key)) {
  29566. onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');
  29567. }
  29568. }
  29569. else if (keyProps.found?.indent !== bm.indent) {
  29570. onError(offset, 'BAD_INDENT', startColMsg);
  29571. }
  29572. // key value
  29573. const keyStart = keyProps.end;
  29574. const keyNode = key
  29575. ? composeNode(ctx, key, keyProps, onError)
  29576. : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
  29577. if (ctx.schema.compat)
  29578. flowIndentCheck(bm.indent, key, onError);
  29579. if (mapIncludes(ctx, map.items, keyNode))
  29580. onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
  29581. // value properties
  29582. const valueProps = resolveProps(sep ?? [], {
  29583. indicator: 'map-value-ind',
  29584. next: value,
  29585. offset: keyNode.range[2],
  29586. onError,
  29587. startOnNewline: !key || key.type === 'block-scalar'
  29588. });
  29589. offset = valueProps.end;
  29590. if (valueProps.found) {
  29591. if (implicitKey) {
  29592. if (value?.type === 'block-map' && !valueProps.hasNewline)
  29593. onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');
  29594. if (ctx.options.strict &&
  29595. keyProps.start < valueProps.found.offset - 1024)
  29596. onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');
  29597. }
  29598. // value value
  29599. const valueNode = value
  29600. ? composeNode(ctx, value, valueProps, onError)
  29601. : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
  29602. if (ctx.schema.compat)
  29603. flowIndentCheck(bm.indent, value, onError);
  29604. offset = valueNode.range[2];
  29605. const pair = new Pair(keyNode, valueNode);
  29606. if (ctx.options.keepSourceTokens)
  29607. pair.srcToken = collItem;
  29608. map.items.push(pair);
  29609. }
  29610. else {
  29611. // key with no value
  29612. if (implicitKey)
  29613. onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');
  29614. if (valueProps.comment) {
  29615. if (keyNode.comment)
  29616. keyNode.comment += '\n' + valueProps.comment;
  29617. else
  29618. keyNode.comment = valueProps.comment;
  29619. }
  29620. const pair = new Pair(keyNode);
  29621. if (ctx.options.keepSourceTokens)
  29622. pair.srcToken = collItem;
  29623. map.items.push(pair);
  29624. }
  29625. }
  29626. map.range = [bm.offset, offset, offset];
  29627. return map;
  29628. }
  29629. function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError) {
  29630. const seq = new YAMLSeq(ctx.schema);
  29631. if (ctx.atRoot)
  29632. ctx.atRoot = false;
  29633. let offset = bs.offset;
  29634. for (const { start, value } of bs.items) {
  29635. const props = resolveProps(start, {
  29636. indicator: 'seq-item-ind',
  29637. next: value,
  29638. offset,
  29639. onError,
  29640. startOnNewline: true
  29641. });
  29642. offset = props.end;
  29643. if (!props.found) {
  29644. if (props.anchor || props.tag || value) {
  29645. if (value && value.type === 'block-seq')
  29646. onError(offset, 'BAD_INDENT', 'All sequence items must start at the same column');
  29647. else
  29648. onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
  29649. }
  29650. else {
  29651. // TODO: assert being at last item?
  29652. if (props.comment)
  29653. seq.comment = props.comment;
  29654. continue;
  29655. }
  29656. }
  29657. const node = value
  29658. ? composeNode(ctx, value, props, onError)
  29659. : composeEmptyNode(ctx, offset, start, null, props, onError);
  29660. if (ctx.schema.compat)
  29661. flowIndentCheck(bs.indent, value, onError);
  29662. offset = node.range[2];
  29663. seq.items.push(node);
  29664. }
  29665. seq.range = [bs.offset, offset, offset];
  29666. return seq;
  29667. }
  29668. function resolveEnd(end, offset, reqSpace, onError) {
  29669. let comment = '';
  29670. if (end) {
  29671. let hasSpace = false;
  29672. let sep = '';
  29673. for (const token of end) {
  29674. const { source, type } = token;
  29675. switch (type) {
  29676. case 'space':
  29677. hasSpace = true;
  29678. break;
  29679. case 'comment': {
  29680. if (reqSpace && !hasSpace)
  29681. onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
  29682. const cb = source.substring(1) || ' ';
  29683. if (!comment)
  29684. comment = cb;
  29685. else
  29686. comment += sep + cb;
  29687. sep = '';
  29688. break;
  29689. }
  29690. case 'newline':
  29691. if (comment)
  29692. sep += source;
  29693. hasSpace = true;
  29694. break;
  29695. default:
  29696. onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);
  29697. }
  29698. offset += source.length;
  29699. }
  29700. }
  29701. return { comment, offset };
  29702. }
  29703. const blockMsg = 'Block collections are not allowed within flow collections';
  29704. const isBlock$1 = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
  29705. function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError) {
  29706. const isMap = fc.start.source === '{';
  29707. const fcName = isMap ? 'flow map' : 'flow sequence';
  29708. const coll = isMap
  29709. ? new YAMLMap(ctx.schema)
  29710. : new YAMLSeq(ctx.schema);
  29711. coll.flow = true;
  29712. const atRoot = ctx.atRoot;
  29713. if (atRoot)
  29714. ctx.atRoot = false;
  29715. let offset = fc.offset + fc.start.source.length;
  29716. for (let i = 0; i < fc.items.length; ++i) {
  29717. const collItem = fc.items[i];
  29718. const { start, key, sep, value } = collItem;
  29719. const props = resolveProps(start, {
  29720. flow: fcName,
  29721. indicator: 'explicit-key-ind',
  29722. next: key ?? sep?.[0],
  29723. offset,
  29724. onError,
  29725. startOnNewline: false
  29726. });
  29727. if (!props.found) {
  29728. if (!props.anchor && !props.tag && !sep && !value) {
  29729. if (i === 0 && props.comma)
  29730. onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
  29731. else if (i < fc.items.length - 1)
  29732. onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);
  29733. if (props.comment) {
  29734. if (coll.comment)
  29735. coll.comment += '\n' + props.comment;
  29736. else
  29737. coll.comment = props.comment;
  29738. }
  29739. offset = props.end;
  29740. continue;
  29741. }
  29742. if (!isMap && ctx.options.strict && containsNewline(key))
  29743. onError(key, // checked by containsNewline()
  29744. 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
  29745. }
  29746. if (i === 0) {
  29747. if (props.comma)
  29748. onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
  29749. }
  29750. else {
  29751. if (!props.comma)
  29752. onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);
  29753. if (props.comment) {
  29754. let prevItemComment = '';
  29755. loop: for (const st of start) {
  29756. switch (st.type) {
  29757. case 'comma':
  29758. case 'space':
  29759. break;
  29760. case 'comment':
  29761. prevItemComment = st.source.substring(1);
  29762. break loop;
  29763. default:
  29764. break loop;
  29765. }
  29766. }
  29767. if (prevItemComment) {
  29768. let prev = coll.items[coll.items.length - 1];
  29769. if (isPair(prev))
  29770. prev = prev.value ?? prev.key;
  29771. if (prev.comment)
  29772. prev.comment += '\n' + prevItemComment;
  29773. else
  29774. prev.comment = prevItemComment;
  29775. props.comment = props.comment.substring(prevItemComment.length + 1);
  29776. }
  29777. }
  29778. }
  29779. if (!isMap && !sep && !props.found) {
  29780. // item is a value in a seq
  29781. // → key & sep are empty, start does not include ? or :
  29782. const valueNode = value
  29783. ? composeNode(ctx, value, props, onError)
  29784. : composeEmptyNode(ctx, props.end, sep, null, props, onError);
  29785. coll.items.push(valueNode);
  29786. offset = valueNode.range[2];
  29787. if (isBlock$1(value))
  29788. onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
  29789. }
  29790. else {
  29791. // item is a key+value pair
  29792. // key value
  29793. const keyStart = props.end;
  29794. const keyNode = key
  29795. ? composeNode(ctx, key, props, onError)
  29796. : composeEmptyNode(ctx, keyStart, start, null, props, onError);
  29797. if (isBlock$1(key))
  29798. onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);
  29799. // value properties
  29800. const valueProps = resolveProps(sep ?? [], {
  29801. flow: fcName,
  29802. indicator: 'map-value-ind',
  29803. next: value,
  29804. offset: keyNode.range[2],
  29805. onError,
  29806. startOnNewline: false
  29807. });
  29808. if (valueProps.found) {
  29809. if (!isMap && !props.found && ctx.options.strict) {
  29810. if (sep)
  29811. for (const st of sep) {
  29812. if (st === valueProps.found)
  29813. break;
  29814. if (st.type === 'newline') {
  29815. onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
  29816. break;
  29817. }
  29818. }
  29819. if (props.start < valueProps.found.offset - 1024)
  29820. onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');
  29821. }
  29822. }
  29823. else if (value) {
  29824. if ('source' in value && value.source && value.source[0] === ':')
  29825. onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
  29826. else
  29827. onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
  29828. }
  29829. // value value
  29830. const valueNode = value
  29831. ? composeNode(ctx, value, valueProps, onError)
  29832. : valueProps.found
  29833. ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)
  29834. : null;
  29835. if (valueNode) {
  29836. if (isBlock$1(value))
  29837. onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
  29838. }
  29839. else if (valueProps.comment) {
  29840. if (keyNode.comment)
  29841. keyNode.comment += '\n' + valueProps.comment;
  29842. else
  29843. keyNode.comment = valueProps.comment;
  29844. }
  29845. const pair = new Pair(keyNode, valueNode);
  29846. if (ctx.options.keepSourceTokens)
  29847. pair.srcToken = collItem;
  29848. if (isMap) {
  29849. const map = coll;
  29850. if (mapIncludes(ctx, map.items, keyNode))
  29851. onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
  29852. map.items.push(pair);
  29853. }
  29854. else {
  29855. const map = new YAMLMap(ctx.schema);
  29856. map.flow = true;
  29857. map.items.push(pair);
  29858. coll.items.push(map);
  29859. }
  29860. offset = valueNode ? valueNode.range[2] : valueProps.end;
  29861. }
  29862. }
  29863. const expectedEnd = isMap ? '}' : ']';
  29864. const [ce, ...ee] = fc.end;
  29865. let cePos = offset;
  29866. if (ce && ce.source === expectedEnd)
  29867. cePos = ce.offset + ce.source.length;
  29868. else {
  29869. const name = fcName[0].toUpperCase() + fcName.substring(1);
  29870. const msg = atRoot
  29871. ? `${name} must end with a ${expectedEnd}`
  29872. : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
  29873. onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);
  29874. if (ce && ce.source.length !== 1)
  29875. ee.unshift(ce);
  29876. }
  29877. if (ee.length > 0) {
  29878. const end = resolveEnd(ee, cePos, ctx.options.strict, onError);
  29879. if (end.comment) {
  29880. if (coll.comment)
  29881. coll.comment += '\n' + end.comment;
  29882. else
  29883. coll.comment = end.comment;
  29884. }
  29885. coll.range = [fc.offset, cePos, end.offset];
  29886. }
  29887. else {
  29888. coll.range = [fc.offset, cePos, cePos];
  29889. }
  29890. return coll;
  29891. }
  29892. function composeCollection(CN, ctx, token, tagToken, onError) {
  29893. let coll;
  29894. switch (token.type) {
  29895. case 'block-map': {
  29896. coll = resolveBlockMap(CN, ctx, token, onError);
  29897. break;
  29898. }
  29899. case 'block-seq': {
  29900. coll = resolveBlockSeq(CN, ctx, token, onError);
  29901. break;
  29902. }
  29903. case 'flow-collection': {
  29904. coll = resolveFlowCollection(CN, ctx, token, onError);
  29905. break;
  29906. }
  29907. }
  29908. if (!tagToken)
  29909. return coll;
  29910. const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
  29911. if (!tagName)
  29912. return coll;
  29913. // Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841
  29914. const Coll = coll.constructor;
  29915. if (tagName === '!' || tagName === Coll.tagName) {
  29916. coll.tag = Coll.tagName;
  29917. return coll;
  29918. }
  29919. const expType = isMap(coll) ? 'map' : 'seq';
  29920. let tag = ctx.schema.tags.find(t => t.collection === expType && t.tag === tagName);
  29921. if (!tag) {
  29922. const kt = ctx.schema.knownTags[tagName];
  29923. if (kt && kt.collection === expType) {
  29924. ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
  29925. tag = kt;
  29926. }
  29927. else {
  29928. onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
  29929. coll.tag = tagName;
  29930. return coll;
  29931. }
  29932. }
  29933. const res = tag.resolve(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options);
  29934. const node = isNode$1(res)
  29935. ? res
  29936. : new Scalar(res);
  29937. node.range = coll.range;
  29938. node.tag = tagName;
  29939. if (tag?.format)
  29940. node.format = tag.format;
  29941. return node;
  29942. }
  29943. function resolveBlockScalar(scalar, strict, onError) {
  29944. const start = scalar.offset;
  29945. const header = parseBlockScalarHeader(scalar, strict, onError);
  29946. if (!header)
  29947. return { value: '', type: null, comment: '', range: [start, start, start] };
  29948. const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
  29949. const lines = scalar.source ? splitLines(scalar.source) : [];
  29950. // determine the end of content & start of chomping
  29951. let chompStart = lines.length;
  29952. for (let i = lines.length - 1; i >= 0; --i) {
  29953. const content = lines[i][1];
  29954. if (content === '' || content === '\r')
  29955. chompStart = i;
  29956. else
  29957. break;
  29958. }
  29959. // shortcut for empty contents
  29960. if (chompStart === 0) {
  29961. const value = header.chomp === '+' && lines.length > 0
  29962. ? '\n'.repeat(Math.max(1, lines.length - 1))
  29963. : '';
  29964. let end = start + header.length;
  29965. if (scalar.source)
  29966. end += scalar.source.length;
  29967. return { value, type, comment: header.comment, range: [start, end, end] };
  29968. }
  29969. // find the indentation level to trim from start
  29970. let trimIndent = scalar.indent + header.indent;
  29971. let offset = scalar.offset + header.length;
  29972. let contentStart = 0;
  29973. for (let i = 0; i < chompStart; ++i) {
  29974. const [indent, content] = lines[i];
  29975. if (content === '' || content === '\r') {
  29976. if (header.indent === 0 && indent.length > trimIndent)
  29977. trimIndent = indent.length;
  29978. }
  29979. else {
  29980. if (indent.length < trimIndent) {
  29981. const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
  29982. onError(offset + indent.length, 'MISSING_CHAR', message);
  29983. }
  29984. if (header.indent === 0)
  29985. trimIndent = indent.length;
  29986. contentStart = i;
  29987. break;
  29988. }
  29989. offset += indent.length + content.length + 1;
  29990. }
  29991. // include trailing more-indented empty lines in content
  29992. for (let i = lines.length - 1; i >= chompStart; --i) {
  29993. if (lines[i][0].length > trimIndent)
  29994. chompStart = i + 1;
  29995. }
  29996. let value = '';
  29997. let sep = '';
  29998. let prevMoreIndented = false;
  29999. // leading whitespace is kept intact
  30000. for (let i = 0; i < contentStart; ++i)
  30001. value += lines[i][0].slice(trimIndent) + '\n';
  30002. for (let i = contentStart; i < chompStart; ++i) {
  30003. let [indent, content] = lines[i];
  30004. offset += indent.length + content.length + 1;
  30005. const crlf = content[content.length - 1] === '\r';
  30006. if (crlf)
  30007. content = content.slice(0, -1);
  30008. /* istanbul ignore if already caught in lexer */
  30009. if (content && indent.length < trimIndent) {
  30010. const src = header.indent
  30011. ? 'explicit indentation indicator'
  30012. : 'first line';
  30013. const message = `Block scalar lines must not be less indented than their ${src}`;
  30014. onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);
  30015. indent = '';
  30016. }
  30017. if (type === Scalar.BLOCK_LITERAL) {
  30018. value += sep + indent.slice(trimIndent) + content;
  30019. sep = '\n';
  30020. }
  30021. else if (indent.length > trimIndent || content[0] === '\t') {
  30022. // more-indented content within a folded block
  30023. if (sep === ' ')
  30024. sep = '\n';
  30025. else if (!prevMoreIndented && sep === '\n')
  30026. sep = '\n\n';
  30027. value += sep + indent.slice(trimIndent) + content;
  30028. sep = '\n';
  30029. prevMoreIndented = true;
  30030. }
  30031. else if (content === '') {
  30032. // empty line
  30033. if (sep === '\n')
  30034. value += '\n';
  30035. else
  30036. sep = '\n';
  30037. }
  30038. else {
  30039. value += sep + content;
  30040. sep = ' ';
  30041. prevMoreIndented = false;
  30042. }
  30043. }
  30044. switch (header.chomp) {
  30045. case '-':
  30046. break;
  30047. case '+':
  30048. for (let i = chompStart; i < lines.length; ++i)
  30049. value += '\n' + lines[i][0].slice(trimIndent);
  30050. if (value[value.length - 1] !== '\n')
  30051. value += '\n';
  30052. break;
  30053. default:
  30054. value += '\n';
  30055. }
  30056. const end = start + header.length + scalar.source.length;
  30057. return { value, type, comment: header.comment, range: [start, end, end] };
  30058. }
  30059. function parseBlockScalarHeader({ offset, props }, strict, onError) {
  30060. /* istanbul ignore if should not happen */
  30061. if (props[0].type !== 'block-scalar-header') {
  30062. onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');
  30063. return null;
  30064. }
  30065. const { source } = props[0];
  30066. const mode = source[0];
  30067. let indent = 0;
  30068. let chomp = '';
  30069. let error = -1;
  30070. for (let i = 1; i < source.length; ++i) {
  30071. const ch = source[i];
  30072. if (!chomp && (ch === '-' || ch === '+'))
  30073. chomp = ch;
  30074. else {
  30075. const n = Number(ch);
  30076. if (!indent && n)
  30077. indent = n;
  30078. else if (error === -1)
  30079. error = offset + i;
  30080. }
  30081. }
  30082. if (error !== -1)
  30083. onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);
  30084. let hasSpace = false;
  30085. let comment = '';
  30086. let length = source.length;
  30087. for (let i = 1; i < props.length; ++i) {
  30088. const token = props[i];
  30089. switch (token.type) {
  30090. case 'space':
  30091. hasSpace = true;
  30092. // fallthrough
  30093. case 'newline':
  30094. length += token.source.length;
  30095. break;
  30096. case 'comment':
  30097. if (strict && !hasSpace) {
  30098. const message = 'Comments must be separated from other tokens by white space characters';
  30099. onError(token, 'MISSING_CHAR', message);
  30100. }
  30101. length += token.source.length;
  30102. comment = token.source.substring(1);
  30103. break;
  30104. case 'error':
  30105. onError(token, 'UNEXPECTED_TOKEN', token.message);
  30106. length += token.source.length;
  30107. break;
  30108. /* istanbul ignore next should not happen */
  30109. default: {
  30110. const message = `Unexpected token in block scalar header: ${token.type}`;
  30111. onError(token, 'UNEXPECTED_TOKEN', message);
  30112. const ts = token.source;
  30113. if (ts && typeof ts === 'string')
  30114. length += ts.length;
  30115. }
  30116. }
  30117. }
  30118. return { mode, indent, chomp, comment, length };
  30119. }
  30120. /** @returns Array of lines split up as `[indent, content]` */
  30121. function splitLines(source) {
  30122. const split = source.split(/\n( *)/);
  30123. const first = split[0];
  30124. const m = first.match(/^( *)/);
  30125. const line0 = m?.[1]
  30126. ? [m[1], first.slice(m[1].length)]
  30127. : ['', first];
  30128. const lines = [line0];
  30129. for (let i = 1; i < split.length; i += 2)
  30130. lines.push([split[i], split[i + 1]]);
  30131. return lines;
  30132. }
  30133. function resolveFlowScalar(scalar, strict, onError) {
  30134. const { offset, type, source, end } = scalar;
  30135. let _type;
  30136. let value;
  30137. const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
  30138. switch (type) {
  30139. case 'scalar':
  30140. _type = Scalar.PLAIN;
  30141. value = plainValue(source, _onError);
  30142. break;
  30143. case 'single-quoted-scalar':
  30144. _type = Scalar.QUOTE_SINGLE;
  30145. value = singleQuotedValue(source, _onError);
  30146. break;
  30147. case 'double-quoted-scalar':
  30148. _type = Scalar.QUOTE_DOUBLE;
  30149. value = doubleQuotedValue(source, _onError);
  30150. break;
  30151. /* istanbul ignore next should not happen */
  30152. default:
  30153. onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);
  30154. return {
  30155. value: '',
  30156. type: null,
  30157. comment: '',
  30158. range: [offset, offset + source.length, offset + source.length]
  30159. };
  30160. }
  30161. const valueEnd = offset + source.length;
  30162. const re = resolveEnd(end, valueEnd, strict, onError);
  30163. return {
  30164. value,
  30165. type: _type,
  30166. comment: re.comment,
  30167. range: [offset, valueEnd, re.offset]
  30168. };
  30169. }
  30170. function plainValue(source, onError) {
  30171. let badChar = '';
  30172. switch (source[0]) {
  30173. /* istanbul ignore next should not happen */
  30174. case '\t':
  30175. badChar = 'a tab character';
  30176. break;
  30177. case ',':
  30178. badChar = 'flow indicator character ,';
  30179. break;
  30180. case '%':
  30181. badChar = 'directive indicator character %';
  30182. break;
  30183. case '|':
  30184. case '>': {
  30185. badChar = `block scalar indicator ${source[0]}`;
  30186. break;
  30187. }
  30188. case '@':
  30189. case '`': {
  30190. badChar = `reserved character ${source[0]}`;
  30191. break;
  30192. }
  30193. }
  30194. if (badChar)
  30195. onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);
  30196. return foldLines(source);
  30197. }
  30198. function singleQuotedValue(source, onError) {
  30199. if (source[source.length - 1] !== "'" || source.length === 1)
  30200. onError(source.length, 'MISSING_CHAR', "Missing closing 'quote");
  30201. return foldLines(source.slice(1, -1)).replace(/''/g, "'");
  30202. }
  30203. function foldLines(source) {
  30204. /**
  30205. * The negative lookbehind here and in the `re` RegExp is to
  30206. * prevent causing a polynomial search time in certain cases.
  30207. *
  30208. * The try-catch is for Safari, which doesn't support this yet:
  30209. * https://caniuse.com/js-regexp-lookbehind
  30210. */
  30211. let first, line;
  30212. try {
  30213. first = new RegExp('(.*?)(?<![ \t])[ \t]*\r?\n', 'sy');
  30214. line = new RegExp('[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n', 'sy');
  30215. }
  30216. catch (_) {
  30217. first = /(.*?)[ \t]*\r?\n/sy;
  30218. line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
  30219. }
  30220. let match = first.exec(source);
  30221. if (!match)
  30222. return source;
  30223. let res = match[1];
  30224. let sep = ' ';
  30225. let pos = first.lastIndex;
  30226. line.lastIndex = pos;
  30227. while ((match = line.exec(source))) {
  30228. if (match[1] === '') {
  30229. if (sep === '\n')
  30230. res += sep;
  30231. else
  30232. sep = '\n';
  30233. }
  30234. else {
  30235. res += sep + match[1];
  30236. sep = ' ';
  30237. }
  30238. pos = line.lastIndex;
  30239. }
  30240. const last = /[ \t]*(.*)/sy;
  30241. last.lastIndex = pos;
  30242. match = last.exec(source);
  30243. return res + sep + (match?.[1] ?? '');
  30244. }
  30245. function doubleQuotedValue(source, onError) {
  30246. let res = '';
  30247. for (let i = 1; i < source.length - 1; ++i) {
  30248. const ch = source[i];
  30249. if (ch === '\r' && source[i + 1] === '\n')
  30250. continue;
  30251. if (ch === '\n') {
  30252. const { fold, offset } = foldNewline(source, i);
  30253. res += fold;
  30254. i = offset;
  30255. }
  30256. else if (ch === '\\') {
  30257. let next = source[++i];
  30258. const cc = escapeCodes[next];
  30259. if (cc)
  30260. res += cc;
  30261. else if (next === '\n') {
  30262. // skip escaped newlines, but still trim the following line
  30263. next = source[i + 1];
  30264. while (next === ' ' || next === '\t')
  30265. next = source[++i + 1];
  30266. }
  30267. else if (next === '\r' && source[i + 1] === '\n') {
  30268. // skip escaped CRLF newlines, but still trim the following line
  30269. next = source[++i + 1];
  30270. while (next === ' ' || next === '\t')
  30271. next = source[++i + 1];
  30272. }
  30273. else if (next === 'x' || next === 'u' || next === 'U') {
  30274. const length = { x: 2, u: 4, U: 8 }[next];
  30275. res += parseCharCode(source, i + 1, length, onError);
  30276. i += length;
  30277. }
  30278. else {
  30279. const raw = source.substr(i - 1, 2);
  30280. onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
  30281. res += raw;
  30282. }
  30283. }
  30284. else if (ch === ' ' || ch === '\t') {
  30285. // trim trailing whitespace
  30286. const wsStart = i;
  30287. let next = source[i + 1];
  30288. while (next === ' ' || next === '\t')
  30289. next = source[++i + 1];
  30290. if (next !== '\n' && !(next === '\r' && source[i + 2] === '\n'))
  30291. res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
  30292. }
  30293. else {
  30294. res += ch;
  30295. }
  30296. }
  30297. if (source[source.length - 1] !== '"' || source.length === 1)
  30298. onError(source.length, 'MISSING_CHAR', 'Missing closing "quote');
  30299. return res;
  30300. }
  30301. /**
  30302. * Fold a single newline into a space, multiple newlines to N - 1 newlines.
  30303. * Presumes `source[offset] === '\n'`
  30304. */
  30305. function foldNewline(source, offset) {
  30306. let fold = '';
  30307. let ch = source[offset + 1];
  30308. while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
  30309. if (ch === '\r' && source[offset + 2] !== '\n')
  30310. break;
  30311. if (ch === '\n')
  30312. fold += '\n';
  30313. offset += 1;
  30314. ch = source[offset + 1];
  30315. }
  30316. if (!fold)
  30317. fold = ' ';
  30318. return { fold, offset };
  30319. }
  30320. const escapeCodes = {
  30321. '0': '\0',
  30322. a: '\x07',
  30323. b: '\b',
  30324. e: '\x1b',
  30325. f: '\f',
  30326. n: '\n',
  30327. r: '\r',
  30328. t: '\t',
  30329. v: '\v',
  30330. N: '\u0085',
  30331. _: '\u00a0',
  30332. L: '\u2028',
  30333. P: '\u2029',
  30334. ' ': ' ',
  30335. '"': '"',
  30336. '/': '/',
  30337. '\\': '\\',
  30338. '\t': '\t'
  30339. };
  30340. function parseCharCode(source, offset, length, onError) {
  30341. const cc = source.substr(offset, length);
  30342. const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
  30343. const code = ok ? parseInt(cc, 16) : NaN;
  30344. if (isNaN(code)) {
  30345. const raw = source.substr(offset - 2, length + 2);
  30346. onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
  30347. return raw;
  30348. }
  30349. return String.fromCodePoint(code);
  30350. }
  30351. function composeScalar(ctx, token, tagToken, onError) {
  30352. const { value, type, comment, range } = token.type === 'block-scalar'
  30353. ? resolveBlockScalar(token, ctx.options.strict, onError)
  30354. : resolveFlowScalar(token, ctx.options.strict, onError);
  30355. const tagName = tagToken
  30356. ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))
  30357. : null;
  30358. const tag = tagToken && tagName
  30359. ? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError)
  30360. : token.type === 'scalar'
  30361. ? findScalarTagByTest(ctx, value, token, onError)
  30362. : ctx.schema[SCALAR$1];
  30363. let scalar;
  30364. try {
  30365. const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
  30366. scalar = isScalar$1(res) ? res : new Scalar(res);
  30367. }
  30368. catch (error) {
  30369. const msg = error instanceof Error ? error.message : String(error);
  30370. onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);
  30371. scalar = new Scalar(value);
  30372. }
  30373. scalar.range = range;
  30374. scalar.source = value;
  30375. if (type)
  30376. scalar.type = type;
  30377. if (tagName)
  30378. scalar.tag = tagName;
  30379. if (tag.format)
  30380. scalar.format = tag.format;
  30381. if (comment)
  30382. scalar.comment = comment;
  30383. return scalar;
  30384. }
  30385. function findScalarTagByName(schema, value, tagName, tagToken, onError) {
  30386. if (tagName === '!')
  30387. return schema[SCALAR$1]; // non-specific tag
  30388. const matchWithTest = [];
  30389. for (const tag of schema.tags) {
  30390. if (!tag.collection && tag.tag === tagName) {
  30391. if (tag.default && tag.test)
  30392. matchWithTest.push(tag);
  30393. else
  30394. return tag;
  30395. }
  30396. }
  30397. for (const tag of matchWithTest)
  30398. if (tag.test?.test(value))
  30399. return tag;
  30400. const kt = schema.knownTags[tagName];
  30401. if (kt && !kt.collection) {
  30402. // Ensure that the known tag is available for stringifying,
  30403. // but does not get used by default.
  30404. schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
  30405. return kt;
  30406. }
  30407. onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
  30408. return schema[SCALAR$1];
  30409. }
  30410. function findScalarTagByTest({ directives, schema }, value, token, onError) {
  30411. const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[SCALAR$1];
  30412. if (schema.compat) {
  30413. const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
  30414. schema[SCALAR$1];
  30415. if (tag.tag !== compat.tag) {
  30416. const ts = directives.tagString(tag.tag);
  30417. const cs = directives.tagString(compat.tag);
  30418. const msg = `Value may be parsed as either ${ts} or ${cs}`;
  30419. onError(token, 'TAG_RESOLVE_FAILED', msg, true);
  30420. }
  30421. }
  30422. return tag;
  30423. }
  30424. function emptyScalarPosition(offset, before, pos) {
  30425. if (before) {
  30426. if (pos === null)
  30427. pos = before.length;
  30428. for (let i = pos - 1; i >= 0; --i) {
  30429. let st = before[i];
  30430. switch (st.type) {
  30431. case 'space':
  30432. case 'comment':
  30433. case 'newline':
  30434. offset -= st.source.length;
  30435. continue;
  30436. }
  30437. // Technically, an empty scalar is immediately after the last non-empty
  30438. // node, but it's more useful to place it after any whitespace.
  30439. st = before[++i];
  30440. while (st?.type === 'space') {
  30441. offset += st.source.length;
  30442. st = before[++i];
  30443. }
  30444. break;
  30445. }
  30446. }
  30447. return offset;
  30448. }
  30449. const CN = { composeNode, composeEmptyNode };
  30450. function composeNode(ctx, token, props, onError) {
  30451. const { spaceBefore, comment, anchor, tag } = props;
  30452. let node;
  30453. let isSrcToken = true;
  30454. switch (token.type) {
  30455. case 'alias':
  30456. node = composeAlias(ctx, token, onError);
  30457. if (anchor || tag)
  30458. onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');
  30459. break;
  30460. case 'scalar':
  30461. case 'single-quoted-scalar':
  30462. case 'double-quoted-scalar':
  30463. case 'block-scalar':
  30464. node = composeScalar(ctx, token, tag, onError);
  30465. if (anchor)
  30466. node.anchor = anchor.source.substring(1);
  30467. break;
  30468. case 'block-map':
  30469. case 'block-seq':
  30470. case 'flow-collection':
  30471. node = composeCollection(CN, ctx, token, tag, onError);
  30472. if (anchor)
  30473. node.anchor = anchor.source.substring(1);
  30474. break;
  30475. default: {
  30476. const message = token.type === 'error'
  30477. ? token.message
  30478. : `Unsupported token (type: ${token.type})`;
  30479. onError(token, 'UNEXPECTED_TOKEN', message);
  30480. node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError);
  30481. isSrcToken = false;
  30482. }
  30483. }
  30484. if (anchor && node.anchor === '')
  30485. onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
  30486. if (spaceBefore)
  30487. node.spaceBefore = true;
  30488. if (comment) {
  30489. if (token.type === 'scalar' && token.source === '')
  30490. node.comment = comment;
  30491. else
  30492. node.commentBefore = comment;
  30493. }
  30494. // @ts-expect-error Type checking misses meaning of isSrcToken
  30495. if (ctx.options.keepSourceTokens && isSrcToken)
  30496. node.srcToken = token;
  30497. return node;
  30498. }
  30499. function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag }, onError) {
  30500. const token = {
  30501. type: 'scalar',
  30502. offset: emptyScalarPosition(offset, before, pos),
  30503. indent: -1,
  30504. source: ''
  30505. };
  30506. const node = composeScalar(ctx, token, tag, onError);
  30507. if (anchor) {
  30508. node.anchor = anchor.source.substring(1);
  30509. if (node.anchor === '')
  30510. onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
  30511. }
  30512. if (spaceBefore)
  30513. node.spaceBefore = true;
  30514. if (comment)
  30515. node.comment = comment;
  30516. return node;
  30517. }
  30518. function composeAlias({ options }, { offset, source, end }, onError) {
  30519. const alias = new Alias(source.substring(1));
  30520. if (alias.source === '')
  30521. onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');
  30522. if (alias.source.endsWith(':'))
  30523. onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);
  30524. const valueEnd = offset + source.length;
  30525. const re = resolveEnd(end, valueEnd, options.strict, onError);
  30526. alias.range = [offset, valueEnd, re.offset];
  30527. if (re.comment)
  30528. alias.comment = re.comment;
  30529. return alias;
  30530. }
  30531. function composeDoc(options, directives, { offset, start, value, end }, onError) {
  30532. const opts = Object.assign({ _directives: directives }, options);
  30533. const doc = new Document(undefined, opts);
  30534. const ctx = {
  30535. atRoot: true,
  30536. directives: doc.directives,
  30537. options: doc.options,
  30538. schema: doc.schema
  30539. };
  30540. const props = resolveProps(start, {
  30541. indicator: 'doc-start',
  30542. next: value ?? end?.[0],
  30543. offset,
  30544. onError,
  30545. startOnNewline: true
  30546. });
  30547. if (props.found) {
  30548. doc.directives.docStart = true;
  30549. if (value &&
  30550. (value.type === 'block-map' || value.type === 'block-seq') &&
  30551. !props.hasNewline)
  30552. onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
  30553. }
  30554. doc.contents = value
  30555. ? composeNode(ctx, value, props, onError)
  30556. : composeEmptyNode(ctx, props.end, start, null, props, onError);
  30557. const contentEnd = doc.contents.range[2];
  30558. const re = resolveEnd(end, contentEnd, false, onError);
  30559. if (re.comment)
  30560. doc.comment = re.comment;
  30561. doc.range = [offset, contentEnd, re.offset];
  30562. return doc;
  30563. }
  30564. function getErrorPos(src) {
  30565. if (typeof src === 'number')
  30566. return [src, src + 1];
  30567. if (Array.isArray(src))
  30568. return src.length === 2 ? src : [src[0], src[1]];
  30569. const { offset, source } = src;
  30570. return [offset, offset + (typeof source === 'string' ? source.length : 1)];
  30571. }
  30572. function parsePrelude(prelude) {
  30573. let comment = '';
  30574. let atComment = false;
  30575. let afterEmptyLine = false;
  30576. for (let i = 0; i < prelude.length; ++i) {
  30577. const source = prelude[i];
  30578. switch (source[0]) {
  30579. case '#':
  30580. comment +=
  30581. (comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') +
  30582. (source.substring(1) || ' ');
  30583. atComment = true;
  30584. afterEmptyLine = false;
  30585. break;
  30586. case '%':
  30587. if (prelude[i + 1]?.[0] !== '#')
  30588. i += 1;
  30589. atComment = false;
  30590. break;
  30591. default:
  30592. // This may be wrong after doc-end, but in that case it doesn't matter
  30593. if (!atComment)
  30594. afterEmptyLine = true;
  30595. atComment = false;
  30596. }
  30597. }
  30598. return { comment, afterEmptyLine };
  30599. }
  30600. /**
  30601. * Compose a stream of CST nodes into a stream of YAML Documents.
  30602. *
  30603. * ```ts
  30604. * import { Composer, Parser } from 'yaml'
  30605. *
  30606. * const src: string = ...
  30607. * const tokens = new Parser().parse(src)
  30608. * const docs = new Composer().compose(tokens)
  30609. * ```
  30610. */
  30611. class Composer {
  30612. constructor(options = {}) {
  30613. this.doc = null;
  30614. this.atDirectives = false;
  30615. this.prelude = [];
  30616. this.errors = [];
  30617. this.warnings = [];
  30618. this.onError = (source, code, message, warning) => {
  30619. const pos = getErrorPos(source);
  30620. if (warning)
  30621. this.warnings.push(new YAMLWarning(pos, code, message));
  30622. else
  30623. this.errors.push(new YAMLParseError(pos, code, message));
  30624. };
  30625. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
  30626. this.directives = new Directives({ version: options.version || '1.2' });
  30627. this.options = options;
  30628. }
  30629. decorate(doc, afterDoc) {
  30630. const { comment, afterEmptyLine } = parsePrelude(this.prelude);
  30631. //console.log({ dc: doc.comment, prelude, comment })
  30632. if (comment) {
  30633. const dc = doc.contents;
  30634. if (afterDoc) {
  30635. doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment;
  30636. }
  30637. else if (afterEmptyLine || doc.directives.docStart || !dc) {
  30638. doc.commentBefore = comment;
  30639. }
  30640. else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) {
  30641. let it = dc.items[0];
  30642. if (isPair(it))
  30643. it = it.key;
  30644. const cb = it.commentBefore;
  30645. it.commentBefore = cb ? `${comment}\n${cb}` : comment;
  30646. }
  30647. else {
  30648. const cb = dc.commentBefore;
  30649. dc.commentBefore = cb ? `${comment}\n${cb}` : comment;
  30650. }
  30651. }
  30652. if (afterDoc) {
  30653. Array.prototype.push.apply(doc.errors, this.errors);
  30654. Array.prototype.push.apply(doc.warnings, this.warnings);
  30655. }
  30656. else {
  30657. doc.errors = this.errors;
  30658. doc.warnings = this.warnings;
  30659. }
  30660. this.prelude = [];
  30661. this.errors = [];
  30662. this.warnings = [];
  30663. }
  30664. /**
  30665. * Current stream status information.
  30666. *
  30667. * Mostly useful at the end of input for an empty stream.
  30668. */
  30669. streamInfo() {
  30670. return {
  30671. comment: parsePrelude(this.prelude).comment,
  30672. directives: this.directives,
  30673. errors: this.errors,
  30674. warnings: this.warnings
  30675. };
  30676. }
  30677. /**
  30678. * Compose tokens into documents.
  30679. *
  30680. * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
  30681. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
  30682. */
  30683. *compose(tokens, forceDoc = false, endOffset = -1) {
  30684. for (const token of tokens)
  30685. yield* this.next(token);
  30686. yield* this.end(forceDoc, endOffset);
  30687. }
  30688. /** Advance the composer by one CST token. */
  30689. *next(token) {
  30690. switch (token.type) {
  30691. case 'directive':
  30692. this.directives.add(token.source, (offset, message, warning) => {
  30693. const pos = getErrorPos(token);
  30694. pos[0] += offset;
  30695. this.onError(pos, 'BAD_DIRECTIVE', message, warning);
  30696. });
  30697. this.prelude.push(token.source);
  30698. this.atDirectives = true;
  30699. break;
  30700. case 'document': {
  30701. const doc = composeDoc(this.options, this.directives, token, this.onError);
  30702. if (this.atDirectives && !doc.directives.docStart)
  30703. this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');
  30704. this.decorate(doc, false);
  30705. if (this.doc)
  30706. yield this.doc;
  30707. this.doc = doc;
  30708. this.atDirectives = false;
  30709. break;
  30710. }
  30711. case 'byte-order-mark':
  30712. case 'space':
  30713. break;
  30714. case 'comment':
  30715. case 'newline':
  30716. this.prelude.push(token.source);
  30717. break;
  30718. case 'error': {
  30719. const msg = token.source
  30720. ? `${token.message}: ${JSON.stringify(token.source)}`
  30721. : token.message;
  30722. const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);
  30723. if (this.atDirectives || !this.doc)
  30724. this.errors.push(error);
  30725. else
  30726. this.doc.errors.push(error);
  30727. break;
  30728. }
  30729. case 'doc-end': {
  30730. if (!this.doc) {
  30731. const msg = 'Unexpected doc-end without preceding document';
  30732. this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));
  30733. break;
  30734. }
  30735. this.doc.directives.docEnd = true;
  30736. const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
  30737. this.decorate(this.doc, true);
  30738. if (end.comment) {
  30739. const dc = this.doc.comment;
  30740. this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment;
  30741. }
  30742. this.doc.range[2] = end.offset;
  30743. break;
  30744. }
  30745. default:
  30746. this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));
  30747. }
  30748. }
  30749. /**
  30750. * Call at end of input to yield any remaining document.
  30751. *
  30752. * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
  30753. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
  30754. */
  30755. *end(forceDoc = false, endOffset = -1) {
  30756. if (this.doc) {
  30757. this.decorate(this.doc, true);
  30758. yield this.doc;
  30759. this.doc = null;
  30760. }
  30761. else if (forceDoc) {
  30762. const opts = Object.assign({ _directives: this.directives }, this.options);
  30763. const doc = new Document(undefined, opts);
  30764. if (this.atDirectives)
  30765. this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');
  30766. doc.range = [0, endOffset, endOffset];
  30767. this.decorate(doc, false);
  30768. yield doc;
  30769. }
  30770. }
  30771. }
  30772. function resolveAsScalar(token, strict = true, onError) {
  30773. if (token) {
  30774. const _onError = (pos, code, message) => {
  30775. const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
  30776. if (onError)
  30777. onError(offset, code, message);
  30778. else
  30779. throw new YAMLParseError([offset, offset + 1], code, message);
  30780. };
  30781. switch (token.type) {
  30782. case 'scalar':
  30783. case 'single-quoted-scalar':
  30784. case 'double-quoted-scalar':
  30785. return resolveFlowScalar(token, strict, _onError);
  30786. case 'block-scalar':
  30787. return resolveBlockScalar(token, strict, _onError);
  30788. }
  30789. }
  30790. return null;
  30791. }
  30792. /**
  30793. * Create a new scalar token with `value`
  30794. *
  30795. * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
  30796. * as this function does not support any schema operations and won't check for such conflicts.
  30797. *
  30798. * @param value The string representation of the value, which will have its content properly indented.
  30799. * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
  30800. * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
  30801. * @param context.indent The indent level of the token.
  30802. * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
  30803. * @param context.offset The offset position of the token.
  30804. * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
  30805. */
  30806. function createScalarToken(value, context) {
  30807. const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
  30808. const source = stringifyString({ type, value }, {
  30809. implicitKey,
  30810. indent: indent > 0 ? ' '.repeat(indent) : '',
  30811. inFlow,
  30812. options: { blockQuote: true, lineWidth: -1 }
  30813. });
  30814. const end = context.end ?? [
  30815. { type: 'newline', offset: -1, indent, source: '\n' }
  30816. ];
  30817. switch (source[0]) {
  30818. case '|':
  30819. case '>': {
  30820. const he = source.indexOf('\n');
  30821. const head = source.substring(0, he);
  30822. const body = source.substring(he + 1) + '\n';
  30823. const props = [
  30824. { type: 'block-scalar-header', offset, indent, source: head }
  30825. ];
  30826. if (!addEndtoBlockProps(props, end))
  30827. props.push({ type: 'newline', offset: -1, indent, source: '\n' });
  30828. return { type: 'block-scalar', offset, indent, props, source: body };
  30829. }
  30830. case '"':
  30831. return { type: 'double-quoted-scalar', offset, indent, source, end };
  30832. case "'":
  30833. return { type: 'single-quoted-scalar', offset, indent, source, end };
  30834. default:
  30835. return { type: 'scalar', offset, indent, source, end };
  30836. }
  30837. }
  30838. /**
  30839. * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
  30840. *
  30841. * Best efforts are made to retain any comments previously associated with the `token`,
  30842. * though all contents within a collection's `items` will be overwritten.
  30843. *
  30844. * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
  30845. * as this function does not support any schema operations and won't check for such conflicts.
  30846. *
  30847. * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
  30848. * @param value The string representation of the value, which will have its content properly indented.
  30849. * @param context.afterKey In most cases, values after a key should have an additional level of indentation.
  30850. * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
  30851. * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
  30852. * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
  30853. */
  30854. function setScalarValue(token, value, context = {}) {
  30855. let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
  30856. let indent = 'indent' in token ? token.indent : null;
  30857. if (afterKey && typeof indent === 'number')
  30858. indent += 2;
  30859. if (!type)
  30860. switch (token.type) {
  30861. case 'single-quoted-scalar':
  30862. type = 'QUOTE_SINGLE';
  30863. break;
  30864. case 'double-quoted-scalar':
  30865. type = 'QUOTE_DOUBLE';
  30866. break;
  30867. case 'block-scalar': {
  30868. const header = token.props[0];
  30869. if (header.type !== 'block-scalar-header')
  30870. throw new Error('Invalid block scalar header');
  30871. type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
  30872. break;
  30873. }
  30874. default:
  30875. type = 'PLAIN';
  30876. }
  30877. const source = stringifyString({ type, value }, {
  30878. implicitKey: implicitKey || indent === null,
  30879. indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
  30880. inFlow,
  30881. options: { blockQuote: true, lineWidth: -1 }
  30882. });
  30883. switch (source[0]) {
  30884. case '|':
  30885. case '>':
  30886. setBlockScalarValue(token, source);
  30887. break;
  30888. case '"':
  30889. setFlowScalarValue(token, source, 'double-quoted-scalar');
  30890. break;
  30891. case "'":
  30892. setFlowScalarValue(token, source, 'single-quoted-scalar');
  30893. break;
  30894. default:
  30895. setFlowScalarValue(token, source, 'scalar');
  30896. }
  30897. }
  30898. function setBlockScalarValue(token, source) {
  30899. const he = source.indexOf('\n');
  30900. const head = source.substring(0, he);
  30901. const body = source.substring(he + 1) + '\n';
  30902. if (token.type === 'block-scalar') {
  30903. const header = token.props[0];
  30904. if (header.type !== 'block-scalar-header')
  30905. throw new Error('Invalid block scalar header');
  30906. header.source = head;
  30907. token.source = body;
  30908. }
  30909. else {
  30910. const { offset } = token;
  30911. const indent = 'indent' in token ? token.indent : -1;
  30912. const props = [
  30913. { type: 'block-scalar-header', offset, indent, source: head }
  30914. ];
  30915. if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
  30916. props.push({ type: 'newline', offset: -1, indent, source: '\n' });
  30917. for (const key of Object.keys(token))
  30918. if (key !== 'type' && key !== 'offset')
  30919. delete token[key];
  30920. Object.assign(token, { type: 'block-scalar', indent, props, source: body });
  30921. }
  30922. }
  30923. /** @returns `true` if last token is a newline */
  30924. function addEndtoBlockProps(props, end) {
  30925. if (end)
  30926. for (const st of end)
  30927. switch (st.type) {
  30928. case 'space':
  30929. case 'comment':
  30930. props.push(st);
  30931. break;
  30932. case 'newline':
  30933. props.push(st);
  30934. return true;
  30935. }
  30936. return false;
  30937. }
  30938. function setFlowScalarValue(token, source, type) {
  30939. switch (token.type) {
  30940. case 'scalar':
  30941. case 'double-quoted-scalar':
  30942. case 'single-quoted-scalar':
  30943. token.type = type;
  30944. token.source = source;
  30945. break;
  30946. case 'block-scalar': {
  30947. const end = token.props.slice(1);
  30948. let oa = source.length;
  30949. if (token.props[0].type === 'block-scalar-header')
  30950. oa -= token.props[0].source.length;
  30951. for (const tok of end)
  30952. tok.offset += oa;
  30953. delete token.props;
  30954. Object.assign(token, { type, source, end });
  30955. break;
  30956. }
  30957. case 'block-map':
  30958. case 'block-seq': {
  30959. const offset = token.offset + source.length;
  30960. const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
  30961. delete token.items;
  30962. Object.assign(token, { type, source, end: [nl] });
  30963. break;
  30964. }
  30965. default: {
  30966. const indent = 'indent' in token ? token.indent : -1;
  30967. const end = 'end' in token && Array.isArray(token.end)
  30968. ? token.end.filter(st => st.type === 'space' ||
  30969. st.type === 'comment' ||
  30970. st.type === 'newline')
  30971. : [];
  30972. for (const key of Object.keys(token))
  30973. if (key !== 'type' && key !== 'offset')
  30974. delete token[key];
  30975. Object.assign(token, { type, indent, source, end });
  30976. }
  30977. }
  30978. }
  30979. /**
  30980. * Stringify a CST document, token, or collection item
  30981. *
  30982. * Fair warning: This applies no validation whatsoever, and
  30983. * simply concatenates the sources in their logical order.
  30984. */
  30985. const stringify$1 = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
  30986. function stringifyToken(token) {
  30987. switch (token.type) {
  30988. case 'block-scalar': {
  30989. let res = '';
  30990. for (const tok of token.props)
  30991. res += stringifyToken(tok);
  30992. return res + token.source;
  30993. }
  30994. case 'block-map':
  30995. case 'block-seq': {
  30996. let res = '';
  30997. for (const item of token.items)
  30998. res += stringifyItem(item);
  30999. return res;
  31000. }
  31001. case 'flow-collection': {
  31002. let res = token.start.source;
  31003. for (const item of token.items)
  31004. res += stringifyItem(item);
  31005. for (const st of token.end)
  31006. res += st.source;
  31007. return res;
  31008. }
  31009. case 'document': {
  31010. let res = stringifyItem(token);
  31011. if (token.end)
  31012. for (const st of token.end)
  31013. res += st.source;
  31014. return res;
  31015. }
  31016. default: {
  31017. let res = token.source;
  31018. if ('end' in token && token.end)
  31019. for (const st of token.end)
  31020. res += st.source;
  31021. return res;
  31022. }
  31023. }
  31024. }
  31025. function stringifyItem({ start, key, sep, value }) {
  31026. let res = '';
  31027. for (const st of start)
  31028. res += st.source;
  31029. if (key)
  31030. res += stringifyToken(key);
  31031. if (sep)
  31032. for (const st of sep)
  31033. res += st.source;
  31034. if (value)
  31035. res += stringifyToken(value);
  31036. return res;
  31037. }
  31038. const BREAK = Symbol('break visit');
  31039. const SKIP = Symbol('skip children');
  31040. const REMOVE = Symbol('remove item');
  31041. /**
  31042. * Apply a visitor to a CST document or item.
  31043. *
  31044. * Walks through the tree (depth-first) starting from the root, calling a
  31045. * `visitor` function with two arguments when entering each item:
  31046. * - `item`: The current item, which included the following members:
  31047. * - `start: SourceToken[]` – Source tokens before the key or value,
  31048. * possibly including its anchor or tag.
  31049. * - `key?: Token | null` – Set for pair values. May then be `null`, if
  31050. * the key before the `:` separator is empty.
  31051. * - `sep?: SourceToken[]` – Source tokens between the key and the value,
  31052. * which should include the `:` map value indicator if `value` is set.
  31053. * - `value?: Token` – The value of a sequence item, or of a map pair.
  31054. * - `path`: The steps from the root to the current node, as an array of
  31055. * `['key' | 'value', number]` tuples.
  31056. *
  31057. * The return value of the visitor may be used to control the traversal:
  31058. * - `undefined` (default): Do nothing and continue
  31059. * - `visit.SKIP`: Do not visit the children of this token, continue with
  31060. * next sibling
  31061. * - `visit.BREAK`: Terminate traversal completely
  31062. * - `visit.REMOVE`: Remove the current item, then continue with the next one
  31063. * - `number`: Set the index of the next step. This is useful especially if
  31064. * the index of the current token has changed.
  31065. * - `function`: Define the next visitor for this item. After the original
  31066. * visitor is called on item entry, next visitors are called after handling
  31067. * a non-empty `key` and when exiting the item.
  31068. */
  31069. function visit(cst, visitor) {
  31070. if ('type' in cst && cst.type === 'document')
  31071. cst = { start: cst.start, value: cst.value };
  31072. _visit(Object.freeze([]), cst, visitor);
  31073. }
  31074. // Without the `as symbol` casts, TS declares these in the `visit`
  31075. // namespace using `var`, but then complains about that because
  31076. // `unique symbol` must be `const`.
  31077. /** Terminate visit traversal completely */
  31078. visit.BREAK = BREAK;
  31079. /** Do not visit the children of the current item */
  31080. visit.SKIP = SKIP;
  31081. /** Remove the current item */
  31082. visit.REMOVE = REMOVE;
  31083. /** Find the item at `path` from `cst` as the root */
  31084. visit.itemAtPath = (cst, path) => {
  31085. let item = cst;
  31086. for (const [field, index] of path) {
  31087. const tok = item?.[field];
  31088. if (tok && 'items' in tok) {
  31089. item = tok.items[index];
  31090. }
  31091. else
  31092. return undefined;
  31093. }
  31094. return item;
  31095. };
  31096. /**
  31097. * Get the immediate parent collection of the item at `path` from `cst` as the root.
  31098. *
  31099. * Throws an error if the collection is not found, which should never happen if the item itself exists.
  31100. */
  31101. visit.parentCollection = (cst, path) => {
  31102. const parent = visit.itemAtPath(cst, path.slice(0, -1));
  31103. const field = path[path.length - 1][0];
  31104. const coll = parent?.[field];
  31105. if (coll && 'items' in coll)
  31106. return coll;
  31107. throw new Error('Parent collection not found');
  31108. };
  31109. function _visit(path, item, visitor) {
  31110. let ctrl = visitor(item, path);
  31111. if (typeof ctrl === 'symbol')
  31112. return ctrl;
  31113. for (const field of ['key', 'value']) {
  31114. const token = item[field];
  31115. if (token && 'items' in token) {
  31116. for (let i = 0; i < token.items.length; ++i) {
  31117. const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
  31118. if (typeof ci === 'number')
  31119. i = ci - 1;
  31120. else if (ci === BREAK)
  31121. return BREAK;
  31122. else if (ci === REMOVE) {
  31123. token.items.splice(i, 1);
  31124. i -= 1;
  31125. }
  31126. }
  31127. if (typeof ctrl === 'function' && field === 'key')
  31128. ctrl = ctrl(item, path);
  31129. }
  31130. }
  31131. return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;
  31132. }
  31133. /** The byte order mark */
  31134. const BOM = '\u{FEFF}';
  31135. /** Start of doc-mode */
  31136. const DOCUMENT = '\x02'; // C0: Start of Text
  31137. /** Unexpected end of flow-mode */
  31138. const FLOW_END = '\x18'; // C0: Cancel
  31139. /** Next token is a scalar value */
  31140. const SCALAR = '\x1f'; // C0: Unit Separator
  31141. /** @returns `true` if `token` is a flow or block collection */
  31142. const isCollection = (token) => !!token && 'items' in token;
  31143. /** @returns `true` if `token` is a flow or block scalar; not an alias */
  31144. const isScalar = (token) => !!token &&
  31145. (token.type === 'scalar' ||
  31146. token.type === 'single-quoted-scalar' ||
  31147. token.type === 'double-quoted-scalar' ||
  31148. token.type === 'block-scalar');
  31149. /* istanbul ignore next */
  31150. /** Get a printable representation of a lexer token */
  31151. function prettyToken(token) {
  31152. switch (token) {
  31153. case BOM:
  31154. return '<BOM>';
  31155. case DOCUMENT:
  31156. return '<DOC>';
  31157. case FLOW_END:
  31158. return '<FLOW_END>';
  31159. case SCALAR:
  31160. return '<SCALAR>';
  31161. default:
  31162. return JSON.stringify(token);
  31163. }
  31164. }
  31165. /** Identify the type of a lexer token. May return `null` for unknown tokens. */
  31166. function tokenType(source) {
  31167. switch (source) {
  31168. case BOM:
  31169. return 'byte-order-mark';
  31170. case DOCUMENT:
  31171. return 'doc-mode';
  31172. case FLOW_END:
  31173. return 'flow-error-end';
  31174. case SCALAR:
  31175. return 'scalar';
  31176. case '---':
  31177. return 'doc-start';
  31178. case '...':
  31179. return 'doc-end';
  31180. case '':
  31181. case '\n':
  31182. case '\r\n':
  31183. return 'newline';
  31184. case '-':
  31185. return 'seq-item-ind';
  31186. case '?':
  31187. return 'explicit-key-ind';
  31188. case ':':
  31189. return 'map-value-ind';
  31190. case '{':
  31191. return 'flow-map-start';
  31192. case '}':
  31193. return 'flow-map-end';
  31194. case '[':
  31195. return 'flow-seq-start';
  31196. case ']':
  31197. return 'flow-seq-end';
  31198. case ',':
  31199. return 'comma';
  31200. }
  31201. switch (source[0]) {
  31202. case ' ':
  31203. case '\t':
  31204. return 'space';
  31205. case '#':
  31206. return 'comment';
  31207. case '%':
  31208. return 'directive-line';
  31209. case '*':
  31210. return 'alias';
  31211. case '&':
  31212. return 'anchor';
  31213. case '!':
  31214. return 'tag';
  31215. case "'":
  31216. return 'single-quoted-scalar';
  31217. case '"':
  31218. return 'double-quoted-scalar';
  31219. case '|':
  31220. case '>':
  31221. return 'block-scalar-header';
  31222. }
  31223. return null;
  31224. }
  31225. var cst = {
  31226. __proto__: null,
  31227. BOM: BOM,
  31228. DOCUMENT: DOCUMENT,
  31229. FLOW_END: FLOW_END,
  31230. SCALAR: SCALAR,
  31231. createScalarToken: createScalarToken,
  31232. isCollection: isCollection,
  31233. isScalar: isScalar,
  31234. prettyToken: prettyToken,
  31235. resolveAsScalar: resolveAsScalar,
  31236. setScalarValue: setScalarValue,
  31237. stringify: stringify$1,
  31238. tokenType: tokenType,
  31239. visit: visit
  31240. };
  31241. /*
  31242. START -> stream
  31243. stream
  31244. directive -> line-end -> stream
  31245. indent + line-end -> stream
  31246. [else] -> line-start
  31247. line-end
  31248. comment -> line-end
  31249. newline -> .
  31250. input-end -> END
  31251. line-start
  31252. doc-start -> doc
  31253. doc-end -> stream
  31254. [else] -> indent -> block-start
  31255. block-start
  31256. seq-item-start -> block-start
  31257. explicit-key-start -> block-start
  31258. map-value-start -> block-start
  31259. [else] -> doc
  31260. doc
  31261. line-end -> line-start
  31262. spaces -> doc
  31263. anchor -> doc
  31264. tag -> doc
  31265. flow-start -> flow -> doc
  31266. flow-end -> error -> doc
  31267. seq-item-start -> error -> doc
  31268. explicit-key-start -> error -> doc
  31269. map-value-start -> doc
  31270. alias -> doc
  31271. quote-start -> quoted-scalar -> doc
  31272. block-scalar-header -> line-end -> block-scalar(min) -> line-start
  31273. [else] -> plain-scalar(false, min) -> doc
  31274. flow
  31275. line-end -> flow
  31276. spaces -> flow
  31277. anchor -> flow
  31278. tag -> flow
  31279. flow-start -> flow -> flow
  31280. flow-end -> .
  31281. seq-item-start -> error -> flow
  31282. explicit-key-start -> flow
  31283. map-value-start -> flow
  31284. alias -> flow
  31285. quote-start -> quoted-scalar -> flow
  31286. comma -> flow
  31287. [else] -> plain-scalar(true, 0) -> flow
  31288. quoted-scalar
  31289. quote-end -> .
  31290. [else] -> quoted-scalar
  31291. block-scalar(min)
  31292. newline + peek(indent < min) -> .
  31293. [else] -> block-scalar(min)
  31294. plain-scalar(is-flow, min)
  31295. scalar-end(is-flow) -> .
  31296. peek(newline + (indent < min)) -> .
  31297. [else] -> plain-scalar(min)
  31298. */
  31299. function isEmpty(ch) {
  31300. switch (ch) {
  31301. case undefined:
  31302. case ' ':
  31303. case '\n':
  31304. case '\r':
  31305. case '\t':
  31306. return true;
  31307. default:
  31308. return false;
  31309. }
  31310. }
  31311. const hexDigits = '0123456789ABCDEFabcdef'.split('');
  31312. const tagChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split('');
  31313. const invalidFlowScalarChars = ',[]{}'.split('');
  31314. const invalidAnchorChars = ' ,[]{}\n\r\t'.split('');
  31315. const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.includes(ch);
  31316. /**
  31317. * Splits an input string into lexical tokens, i.e. smaller strings that are
  31318. * easily identifiable by `tokens.tokenType()`.
  31319. *
  31320. * Lexing starts always in a "stream" context. Incomplete input may be buffered
  31321. * until a complete token can be emitted.
  31322. *
  31323. * In addition to slices of the original input, the following control characters
  31324. * may also be emitted:
  31325. *
  31326. * - `\x02` (Start of Text): A document starts with the next token
  31327. * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error)
  31328. * - `\x1f` (Unit Separator): Next token is a scalar value
  31329. * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents
  31330. */
  31331. class Lexer {
  31332. constructor() {
  31333. /**
  31334. * Flag indicating whether the end of the current buffer marks the end of
  31335. * all input
  31336. */
  31337. this.atEnd = false;
  31338. /**
  31339. * Explicit indent set in block scalar header, as an offset from the current
  31340. * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not
  31341. * explicitly set.
  31342. */
  31343. this.blockScalarIndent = -1;
  31344. /**
  31345. * Block scalars that include a + (keep) chomping indicator in their header
  31346. * include trailing empty lines, which are otherwise excluded from the
  31347. * scalar's contents.
  31348. */
  31349. this.blockScalarKeep = false;
  31350. /** Current input */
  31351. this.buffer = '';
  31352. /**
  31353. * Flag noting whether the map value indicator : can immediately follow this
  31354. * node within a flow context.
  31355. */
  31356. this.flowKey = false;
  31357. /** Count of surrounding flow collection levels. */
  31358. this.flowLevel = 0;
  31359. /**
  31360. * Minimum level of indentation required for next lines to be parsed as a
  31361. * part of the current scalar value.
  31362. */
  31363. this.indentNext = 0;
  31364. /** Indentation level of the current line. */
  31365. this.indentValue = 0;
  31366. /** Position of the next \n character. */
  31367. this.lineEndPos = null;
  31368. /** Stores the state of the lexer if reaching the end of incpomplete input */
  31369. this.next = null;
  31370. /** A pointer to `buffer`; the current position of the lexer. */
  31371. this.pos = 0;
  31372. }
  31373. /**
  31374. * Generate YAML tokens from the `source` string. If `incomplete`,
  31375. * a part of the last line may be left as a buffer for the next call.
  31376. *
  31377. * @returns A generator of lexical tokens
  31378. */
  31379. *lex(source, incomplete = false) {
  31380. if (source) {
  31381. this.buffer = this.buffer ? this.buffer + source : source;
  31382. this.lineEndPos = null;
  31383. }
  31384. this.atEnd = !incomplete;
  31385. let next = this.next ?? 'stream';
  31386. while (next && (incomplete || this.hasChars(1)))
  31387. next = yield* this.parseNext(next);
  31388. }
  31389. atLineEnd() {
  31390. let i = this.pos;
  31391. let ch = this.buffer[i];
  31392. while (ch === ' ' || ch === '\t')
  31393. ch = this.buffer[++i];
  31394. if (!ch || ch === '#' || ch === '\n')
  31395. return true;
  31396. if (ch === '\r')
  31397. return this.buffer[i + 1] === '\n';
  31398. return false;
  31399. }
  31400. charAt(n) {
  31401. return this.buffer[this.pos + n];
  31402. }
  31403. continueScalar(offset) {
  31404. let ch = this.buffer[offset];
  31405. if (this.indentNext > 0) {
  31406. let indent = 0;
  31407. while (ch === ' ')
  31408. ch = this.buffer[++indent + offset];
  31409. if (ch === '\r') {
  31410. const next = this.buffer[indent + offset + 1];
  31411. if (next === '\n' || (!next && !this.atEnd))
  31412. return offset + indent + 1;
  31413. }
  31414. return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd)
  31415. ? offset + indent
  31416. : -1;
  31417. }
  31418. if (ch === '-' || ch === '.') {
  31419. const dt = this.buffer.substr(offset, 3);
  31420. if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))
  31421. return -1;
  31422. }
  31423. return offset;
  31424. }
  31425. getLine() {
  31426. let end = this.lineEndPos;
  31427. if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {
  31428. end = this.buffer.indexOf('\n', this.pos);
  31429. this.lineEndPos = end;
  31430. }
  31431. if (end === -1)
  31432. return this.atEnd ? this.buffer.substring(this.pos) : null;
  31433. if (this.buffer[end - 1] === '\r')
  31434. end -= 1;
  31435. return this.buffer.substring(this.pos, end);
  31436. }
  31437. hasChars(n) {
  31438. return this.pos + n <= this.buffer.length;
  31439. }
  31440. setNext(state) {
  31441. this.buffer = this.buffer.substring(this.pos);
  31442. this.pos = 0;
  31443. this.lineEndPos = null;
  31444. this.next = state;
  31445. return null;
  31446. }
  31447. peek(n) {
  31448. return this.buffer.substr(this.pos, n);
  31449. }
  31450. *parseNext(next) {
  31451. switch (next) {
  31452. case 'stream':
  31453. return yield* this.parseStream();
  31454. case 'line-start':
  31455. return yield* this.parseLineStart();
  31456. case 'block-start':
  31457. return yield* this.parseBlockStart();
  31458. case 'doc':
  31459. return yield* this.parseDocument();
  31460. case 'flow':
  31461. return yield* this.parseFlowCollection();
  31462. case 'quoted-scalar':
  31463. return yield* this.parseQuotedScalar();
  31464. case 'block-scalar':
  31465. return yield* this.parseBlockScalar();
  31466. case 'plain-scalar':
  31467. return yield* this.parsePlainScalar();
  31468. }
  31469. }
  31470. *parseStream() {
  31471. let line = this.getLine();
  31472. if (line === null)
  31473. return this.setNext('stream');
  31474. if (line[0] === BOM) {
  31475. yield* this.pushCount(1);
  31476. line = line.substring(1);
  31477. }
  31478. if (line[0] === '%') {
  31479. let dirEnd = line.length;
  31480. const cs = line.indexOf('#');
  31481. if (cs !== -1) {
  31482. const ch = line[cs - 1];
  31483. if (ch === ' ' || ch === '\t')
  31484. dirEnd = cs - 1;
  31485. }
  31486. while (true) {
  31487. const ch = line[dirEnd - 1];
  31488. if (ch === ' ' || ch === '\t')
  31489. dirEnd -= 1;
  31490. else
  31491. break;
  31492. }
  31493. const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
  31494. yield* this.pushCount(line.length - n); // possible comment
  31495. this.pushNewline();
  31496. return 'stream';
  31497. }
  31498. if (this.atLineEnd()) {
  31499. const sp = yield* this.pushSpaces(true);
  31500. yield* this.pushCount(line.length - sp);
  31501. yield* this.pushNewline();
  31502. return 'stream';
  31503. }
  31504. yield DOCUMENT;
  31505. return yield* this.parseLineStart();
  31506. }
  31507. *parseLineStart() {
  31508. const ch = this.charAt(0);
  31509. if (!ch && !this.atEnd)
  31510. return this.setNext('line-start');
  31511. if (ch === '-' || ch === '.') {
  31512. if (!this.atEnd && !this.hasChars(4))
  31513. return this.setNext('line-start');
  31514. const s = this.peek(3);
  31515. if (s === '---' && isEmpty(this.charAt(3))) {
  31516. yield* this.pushCount(3);
  31517. this.indentValue = 0;
  31518. this.indentNext = 0;
  31519. return 'doc';
  31520. }
  31521. else if (s === '...' && isEmpty(this.charAt(3))) {
  31522. yield* this.pushCount(3);
  31523. return 'stream';
  31524. }
  31525. }
  31526. this.indentValue = yield* this.pushSpaces(false);
  31527. if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
  31528. this.indentNext = this.indentValue;
  31529. return yield* this.parseBlockStart();
  31530. }
  31531. *parseBlockStart() {
  31532. const [ch0, ch1] = this.peek(2);
  31533. if (!ch1 && !this.atEnd)
  31534. return this.setNext('block-start');
  31535. if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {
  31536. const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
  31537. this.indentNext = this.indentValue + 1;
  31538. this.indentValue += n;
  31539. return yield* this.parseBlockStart();
  31540. }
  31541. return 'doc';
  31542. }
  31543. *parseDocument() {
  31544. yield* this.pushSpaces(true);
  31545. const line = this.getLine();
  31546. if (line === null)
  31547. return this.setNext('doc');
  31548. let n = yield* this.pushIndicators();
  31549. switch (line[n]) {
  31550. case '#':
  31551. yield* this.pushCount(line.length - n);
  31552. // fallthrough
  31553. case undefined:
  31554. yield* this.pushNewline();
  31555. return yield* this.parseLineStart();
  31556. case '{':
  31557. case '[':
  31558. yield* this.pushCount(1);
  31559. this.flowKey = false;
  31560. this.flowLevel = 1;
  31561. return 'flow';
  31562. case '}':
  31563. case ']':
  31564. // this is an error
  31565. yield* this.pushCount(1);
  31566. return 'doc';
  31567. case '*':
  31568. yield* this.pushUntil(isNotAnchorChar);
  31569. return 'doc';
  31570. case '"':
  31571. case "'":
  31572. return yield* this.parseQuotedScalar();
  31573. case '|':
  31574. case '>':
  31575. n += yield* this.parseBlockScalarHeader();
  31576. n += yield* this.pushSpaces(true);
  31577. yield* this.pushCount(line.length - n);
  31578. yield* this.pushNewline();
  31579. return yield* this.parseBlockScalar();
  31580. default:
  31581. return yield* this.parsePlainScalar();
  31582. }
  31583. }
  31584. *parseFlowCollection() {
  31585. let nl, sp;
  31586. let indent = -1;
  31587. do {
  31588. nl = yield* this.pushNewline();
  31589. if (nl > 0) {
  31590. sp = yield* this.pushSpaces(false);
  31591. this.indentValue = indent = sp;
  31592. }
  31593. else {
  31594. sp = 0;
  31595. }
  31596. sp += yield* this.pushSpaces(true);
  31597. } while (nl + sp > 0);
  31598. const line = this.getLine();
  31599. if (line === null)
  31600. return this.setNext('flow');
  31601. if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||
  31602. (indent === 0 &&
  31603. (line.startsWith('---') || line.startsWith('...')) &&
  31604. isEmpty(line[3]))) {
  31605. // Allowing for the terminal ] or } at the same (rather than greater)
  31606. // indent level as the initial [ or { is technically invalid, but
  31607. // failing here would be surprising to users.
  31608. const atFlowEndMarker = indent === this.indentNext - 1 &&
  31609. this.flowLevel === 1 &&
  31610. (line[0] === ']' || line[0] === '}');
  31611. if (!atFlowEndMarker) {
  31612. // this is an error
  31613. this.flowLevel = 0;
  31614. yield FLOW_END;
  31615. return yield* this.parseLineStart();
  31616. }
  31617. }
  31618. let n = 0;
  31619. while (line[n] === ',') {
  31620. n += yield* this.pushCount(1);
  31621. n += yield* this.pushSpaces(true);
  31622. this.flowKey = false;
  31623. }
  31624. n += yield* this.pushIndicators();
  31625. switch (line[n]) {
  31626. case undefined:
  31627. return 'flow';
  31628. case '#':
  31629. yield* this.pushCount(line.length - n);
  31630. return 'flow';
  31631. case '{':
  31632. case '[':
  31633. yield* this.pushCount(1);
  31634. this.flowKey = false;
  31635. this.flowLevel += 1;
  31636. return 'flow';
  31637. case '}':
  31638. case ']':
  31639. yield* this.pushCount(1);
  31640. this.flowKey = true;
  31641. this.flowLevel -= 1;
  31642. return this.flowLevel ? 'flow' : 'doc';
  31643. case '*':
  31644. yield* this.pushUntil(isNotAnchorChar);
  31645. return 'flow';
  31646. case '"':
  31647. case "'":
  31648. this.flowKey = true;
  31649. return yield* this.parseQuotedScalar();
  31650. case ':': {
  31651. const next = this.charAt(1);
  31652. if (this.flowKey || isEmpty(next) || next === ',') {
  31653. this.flowKey = false;
  31654. yield* this.pushCount(1);
  31655. yield* this.pushSpaces(true);
  31656. return 'flow';
  31657. }
  31658. }
  31659. // fallthrough
  31660. default:
  31661. this.flowKey = false;
  31662. return yield* this.parsePlainScalar();
  31663. }
  31664. }
  31665. *parseQuotedScalar() {
  31666. const quote = this.charAt(0);
  31667. let end = this.buffer.indexOf(quote, this.pos + 1);
  31668. if (quote === "'") {
  31669. while (end !== -1 && this.buffer[end + 1] === "'")
  31670. end = this.buffer.indexOf("'", end + 2);
  31671. }
  31672. else {
  31673. // double-quote
  31674. while (end !== -1) {
  31675. let n = 0;
  31676. while (this.buffer[end - 1 - n] === '\\')
  31677. n += 1;
  31678. if (n % 2 === 0)
  31679. break;
  31680. end = this.buffer.indexOf('"', end + 1);
  31681. }
  31682. }
  31683. // Only looking for newlines within the quotes
  31684. const qb = this.buffer.substring(0, end);
  31685. let nl = qb.indexOf('\n', this.pos);
  31686. if (nl !== -1) {
  31687. while (nl !== -1) {
  31688. const cs = this.continueScalar(nl + 1);
  31689. if (cs === -1)
  31690. break;
  31691. nl = qb.indexOf('\n', cs);
  31692. }
  31693. if (nl !== -1) {
  31694. // this is an error caused by an unexpected unindent
  31695. end = nl - (qb[nl - 1] === '\r' ? 2 : 1);
  31696. }
  31697. }
  31698. if (end === -1) {
  31699. if (!this.atEnd)
  31700. return this.setNext('quoted-scalar');
  31701. end = this.buffer.length;
  31702. }
  31703. yield* this.pushToIndex(end + 1, false);
  31704. return this.flowLevel ? 'flow' : 'doc';
  31705. }
  31706. *parseBlockScalarHeader() {
  31707. this.blockScalarIndent = -1;
  31708. this.blockScalarKeep = false;
  31709. let i = this.pos;
  31710. while (true) {
  31711. const ch = this.buffer[++i];
  31712. if (ch === '+')
  31713. this.blockScalarKeep = true;
  31714. else if (ch > '0' && ch <= '9')
  31715. this.blockScalarIndent = Number(ch) - 1;
  31716. else if (ch !== '-')
  31717. break;
  31718. }
  31719. return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');
  31720. }
  31721. *parseBlockScalar() {
  31722. let nl = this.pos - 1; // may be -1 if this.pos === 0
  31723. let indent = 0;
  31724. let ch;
  31725. loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {
  31726. switch (ch) {
  31727. case ' ':
  31728. indent += 1;
  31729. break;
  31730. case '\n':
  31731. nl = i;
  31732. indent = 0;
  31733. break;
  31734. case '\r': {
  31735. const next = this.buffer[i + 1];
  31736. if (!next && !this.atEnd)
  31737. return this.setNext('block-scalar');
  31738. if (next === '\n')
  31739. break;
  31740. } // fallthrough
  31741. default:
  31742. break loop;
  31743. }
  31744. }
  31745. if (!ch && !this.atEnd)
  31746. return this.setNext('block-scalar');
  31747. if (indent >= this.indentNext) {
  31748. if (this.blockScalarIndent === -1)
  31749. this.indentNext = indent;
  31750. else
  31751. this.indentNext += this.blockScalarIndent;
  31752. do {
  31753. const cs = this.continueScalar(nl + 1);
  31754. if (cs === -1)
  31755. break;
  31756. nl = this.buffer.indexOf('\n', cs);
  31757. } while (nl !== -1);
  31758. if (nl === -1) {
  31759. if (!this.atEnd)
  31760. return this.setNext('block-scalar');
  31761. nl = this.buffer.length;
  31762. }
  31763. }
  31764. if (!this.blockScalarKeep) {
  31765. do {
  31766. let i = nl - 1;
  31767. let ch = this.buffer[i];
  31768. if (ch === '\r')
  31769. ch = this.buffer[--i];
  31770. const lastChar = i; // Drop the line if last char not more indented
  31771. while (ch === ' ' || ch === '\t')
  31772. ch = this.buffer[--i];
  31773. if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar)
  31774. nl = i;
  31775. else
  31776. break;
  31777. } while (true);
  31778. }
  31779. yield SCALAR;
  31780. yield* this.pushToIndex(nl + 1, true);
  31781. return yield* this.parseLineStart();
  31782. }
  31783. *parsePlainScalar() {
  31784. const inFlow = this.flowLevel > 0;
  31785. let end = this.pos - 1;
  31786. let i = this.pos - 1;
  31787. let ch;
  31788. while ((ch = this.buffer[++i])) {
  31789. if (ch === ':') {
  31790. const next = this.buffer[i + 1];
  31791. if (isEmpty(next) || (inFlow && next === ','))
  31792. break;
  31793. end = i;
  31794. }
  31795. else if (isEmpty(ch)) {
  31796. let next = this.buffer[i + 1];
  31797. if (ch === '\r') {
  31798. if (next === '\n') {
  31799. i += 1;
  31800. ch = '\n';
  31801. next = this.buffer[i + 1];
  31802. }
  31803. else
  31804. end = i;
  31805. }
  31806. if (next === '#' || (inFlow && invalidFlowScalarChars.includes(next)))
  31807. break;
  31808. if (ch === '\n') {
  31809. const cs = this.continueScalar(i + 1);
  31810. if (cs === -1)
  31811. break;
  31812. i = Math.max(i, cs - 2); // to advance, but still account for ' #'
  31813. }
  31814. }
  31815. else {
  31816. if (inFlow && invalidFlowScalarChars.includes(ch))
  31817. break;
  31818. end = i;
  31819. }
  31820. }
  31821. if (!ch && !this.atEnd)
  31822. return this.setNext('plain-scalar');
  31823. yield SCALAR;
  31824. yield* this.pushToIndex(end + 1, true);
  31825. return inFlow ? 'flow' : 'doc';
  31826. }
  31827. *pushCount(n) {
  31828. if (n > 0) {
  31829. yield this.buffer.substr(this.pos, n);
  31830. this.pos += n;
  31831. return n;
  31832. }
  31833. return 0;
  31834. }
  31835. *pushToIndex(i, allowEmpty) {
  31836. const s = this.buffer.slice(this.pos, i);
  31837. if (s) {
  31838. yield s;
  31839. this.pos += s.length;
  31840. return s.length;
  31841. }
  31842. else if (allowEmpty)
  31843. yield '';
  31844. return 0;
  31845. }
  31846. *pushIndicators() {
  31847. switch (this.charAt(0)) {
  31848. case '!':
  31849. return ((yield* this.pushTag()) +
  31850. (yield* this.pushSpaces(true)) +
  31851. (yield* this.pushIndicators()));
  31852. case '&':
  31853. return ((yield* this.pushUntil(isNotAnchorChar)) +
  31854. (yield* this.pushSpaces(true)) +
  31855. (yield* this.pushIndicators()));
  31856. case '-': // this is an error
  31857. case '?': // this is an error outside flow collections
  31858. case ':': {
  31859. const inFlow = this.flowLevel > 0;
  31860. const ch1 = this.charAt(1);
  31861. if (isEmpty(ch1) || (inFlow && invalidFlowScalarChars.includes(ch1))) {
  31862. if (!inFlow)
  31863. this.indentNext = this.indentValue + 1;
  31864. else if (this.flowKey)
  31865. this.flowKey = false;
  31866. return ((yield* this.pushCount(1)) +
  31867. (yield* this.pushSpaces(true)) +
  31868. (yield* this.pushIndicators()));
  31869. }
  31870. }
  31871. }
  31872. return 0;
  31873. }
  31874. *pushTag() {
  31875. if (this.charAt(1) === '<') {
  31876. let i = this.pos + 2;
  31877. let ch = this.buffer[i];
  31878. while (!isEmpty(ch) && ch !== '>')
  31879. ch = this.buffer[++i];
  31880. return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);
  31881. }
  31882. else {
  31883. let i = this.pos + 1;
  31884. let ch = this.buffer[i];
  31885. while (ch) {
  31886. if (tagChars.includes(ch))
  31887. ch = this.buffer[++i];
  31888. else if (ch === '%' &&
  31889. hexDigits.includes(this.buffer[i + 1]) &&
  31890. hexDigits.includes(this.buffer[i + 2])) {
  31891. ch = this.buffer[(i += 3)];
  31892. }
  31893. else
  31894. break;
  31895. }
  31896. return yield* this.pushToIndex(i, false);
  31897. }
  31898. }
  31899. *pushNewline() {
  31900. const ch = this.buffer[this.pos];
  31901. if (ch === '\n')
  31902. return yield* this.pushCount(1);
  31903. else if (ch === '\r' && this.charAt(1) === '\n')
  31904. return yield* this.pushCount(2);
  31905. else
  31906. return 0;
  31907. }
  31908. *pushSpaces(allowTabs) {
  31909. let i = this.pos - 1;
  31910. let ch;
  31911. do {
  31912. ch = this.buffer[++i];
  31913. } while (ch === ' ' || (allowTabs && ch === '\t'));
  31914. const n = i - this.pos;
  31915. if (n > 0) {
  31916. yield this.buffer.substr(this.pos, n);
  31917. this.pos = i;
  31918. }
  31919. return n;
  31920. }
  31921. *pushUntil(test) {
  31922. let i = this.pos;
  31923. let ch = this.buffer[i];
  31924. while (!test(ch))
  31925. ch = this.buffer[++i];
  31926. return yield* this.pushToIndex(i, false);
  31927. }
  31928. }
  31929. /**
  31930. * Tracks newlines during parsing in order to provide an efficient API for
  31931. * determining the one-indexed `{ line, col }` position for any offset
  31932. * within the input.
  31933. */
  31934. class LineCounter {
  31935. constructor() {
  31936. this.lineStarts = [];
  31937. /**
  31938. * Should be called in ascending order. Otherwise, call
  31939. * `lineCounter.lineStarts.sort()` before calling `linePos()`.
  31940. */
  31941. this.addNewLine = (offset) => this.lineStarts.push(offset);
  31942. /**
  31943. * Performs a binary search and returns the 1-indexed { line, col }
  31944. * position of `offset`. If `line === 0`, `addNewLine` has never been
  31945. * called or `offset` is before the first known newline.
  31946. */
  31947. this.linePos = (offset) => {
  31948. let low = 0;
  31949. let high = this.lineStarts.length;
  31950. while (low < high) {
  31951. const mid = (low + high) >> 1; // Math.floor((low + high) / 2)
  31952. if (this.lineStarts[mid] < offset)
  31953. low = mid + 1;
  31954. else
  31955. high = mid;
  31956. }
  31957. if (this.lineStarts[low] === offset)
  31958. return { line: low + 1, col: 1 };
  31959. if (low === 0)
  31960. return { line: 0, col: offset };
  31961. const start = this.lineStarts[low - 1];
  31962. return { line: low, col: offset - start + 1 };
  31963. };
  31964. }
  31965. }
  31966. function includesToken(list, type) {
  31967. for (let i = 0; i < list.length; ++i)
  31968. if (list[i].type === type)
  31969. return true;
  31970. return false;
  31971. }
  31972. function findNonEmptyIndex(list) {
  31973. for (let i = 0; i < list.length; ++i) {
  31974. switch (list[i].type) {
  31975. case 'space':
  31976. case 'comment':
  31977. case 'newline':
  31978. break;
  31979. default:
  31980. return i;
  31981. }
  31982. }
  31983. return -1;
  31984. }
  31985. function isFlowToken(token) {
  31986. switch (token?.type) {
  31987. case 'alias':
  31988. case 'scalar':
  31989. case 'single-quoted-scalar':
  31990. case 'double-quoted-scalar':
  31991. case 'flow-collection':
  31992. return true;
  31993. default:
  31994. return false;
  31995. }
  31996. }
  31997. function getPrevProps(parent) {
  31998. switch (parent.type) {
  31999. case 'document':
  32000. return parent.start;
  32001. case 'block-map': {
  32002. const it = parent.items[parent.items.length - 1];
  32003. return it.sep ?? it.start;
  32004. }
  32005. case 'block-seq':
  32006. return parent.items[parent.items.length - 1].start;
  32007. /* istanbul ignore next should not happen */
  32008. default:
  32009. return [];
  32010. }
  32011. }
  32012. /** Note: May modify input array */
  32013. function getFirstKeyStartProps(prev) {
  32014. if (prev.length === 0)
  32015. return [];
  32016. let i = prev.length;
  32017. loop: while (--i >= 0) {
  32018. switch (prev[i].type) {
  32019. case 'doc-start':
  32020. case 'explicit-key-ind':
  32021. case 'map-value-ind':
  32022. case 'seq-item-ind':
  32023. case 'newline':
  32024. break loop;
  32025. }
  32026. }
  32027. while (prev[++i]?.type === 'space') {
  32028. /* loop */
  32029. }
  32030. return prev.splice(i, prev.length);
  32031. }
  32032. function fixFlowSeqItems(fc) {
  32033. if (fc.start.type === 'flow-seq-start') {
  32034. for (const it of fc.items) {
  32035. if (it.sep &&
  32036. !it.value &&
  32037. !includesToken(it.start, 'explicit-key-ind') &&
  32038. !includesToken(it.sep, 'map-value-ind')) {
  32039. if (it.key)
  32040. it.value = it.key;
  32041. delete it.key;
  32042. if (isFlowToken(it.value)) {
  32043. if (it.value.end)
  32044. Array.prototype.push.apply(it.value.end, it.sep);
  32045. else
  32046. it.value.end = it.sep;
  32047. }
  32048. else
  32049. Array.prototype.push.apply(it.start, it.sep);
  32050. delete it.sep;
  32051. }
  32052. }
  32053. }
  32054. }
  32055. /**
  32056. * A YAML concrete syntax tree (CST) parser
  32057. *
  32058. * ```ts
  32059. * const src: string = ...
  32060. * for (const token of new Parser().parse(src)) {
  32061. * // token: Token
  32062. * }
  32063. * ```
  32064. *
  32065. * To use the parser with a user-provided lexer:
  32066. *
  32067. * ```ts
  32068. * function* parse(source: string, lexer: Lexer) {
  32069. * const parser = new Parser()
  32070. * for (const lexeme of lexer.lex(source))
  32071. * yield* parser.next(lexeme)
  32072. * yield* parser.end()
  32073. * }
  32074. *
  32075. * const src: string = ...
  32076. * const lexer = new Lexer()
  32077. * for (const token of parse(src, lexer)) {
  32078. * // token: Token
  32079. * }
  32080. * ```
  32081. */
  32082. class Parser {
  32083. /**
  32084. * @param onNewLine - If defined, called separately with the start position of
  32085. * each new line (in `parse()`, including the start of input).
  32086. */
  32087. constructor(onNewLine) {
  32088. /** If true, space and sequence indicators count as indentation */
  32089. this.atNewLine = true;
  32090. /** If true, next token is a scalar value */
  32091. this.atScalar = false;
  32092. /** Current indentation level */
  32093. this.indent = 0;
  32094. /** Current offset since the start of parsing */
  32095. this.offset = 0;
  32096. /** On the same line with a block map key */
  32097. this.onKeyLine = false;
  32098. /** Top indicates the node that's currently being built */
  32099. this.stack = [];
  32100. /** The source of the current token, set in parse() */
  32101. this.source = '';
  32102. /** The type of the current token, set in parse() */
  32103. this.type = '';
  32104. // Must be defined after `next()`
  32105. this.lexer = new Lexer();
  32106. this.onNewLine = onNewLine;
  32107. }
  32108. /**
  32109. * Parse `source` as a YAML stream.
  32110. * If `incomplete`, a part of the last line may be left as a buffer for the next call.
  32111. *
  32112. * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
  32113. *
  32114. * @returns A generator of tokens representing each directive, document, and other structure.
  32115. */
  32116. *parse(source, incomplete = false) {
  32117. if (this.onNewLine && this.offset === 0)
  32118. this.onNewLine(0);
  32119. for (const lexeme of this.lexer.lex(source, incomplete))
  32120. yield* this.next(lexeme);
  32121. if (!incomplete)
  32122. yield* this.end();
  32123. }
  32124. /**
  32125. * Advance the parser by the `source` of one lexical token.
  32126. */
  32127. *next(source) {
  32128. this.source = source;
  32129. if (this.atScalar) {
  32130. this.atScalar = false;
  32131. yield* this.step();
  32132. this.offset += source.length;
  32133. return;
  32134. }
  32135. const type = tokenType(source);
  32136. if (!type) {
  32137. const message = `Not a YAML token: ${source}`;
  32138. yield* this.pop({ type: 'error', offset: this.offset, message, source });
  32139. this.offset += source.length;
  32140. }
  32141. else if (type === 'scalar') {
  32142. this.atNewLine = false;
  32143. this.atScalar = true;
  32144. this.type = 'scalar';
  32145. }
  32146. else {
  32147. this.type = type;
  32148. yield* this.step();
  32149. switch (type) {
  32150. case 'newline':
  32151. this.atNewLine = true;
  32152. this.indent = 0;
  32153. if (this.onNewLine)
  32154. this.onNewLine(this.offset + source.length);
  32155. break;
  32156. case 'space':
  32157. if (this.atNewLine && source[0] === ' ')
  32158. this.indent += source.length;
  32159. break;
  32160. case 'explicit-key-ind':
  32161. case 'map-value-ind':
  32162. case 'seq-item-ind':
  32163. if (this.atNewLine)
  32164. this.indent += source.length;
  32165. break;
  32166. case 'doc-mode':
  32167. case 'flow-error-end':
  32168. return;
  32169. default:
  32170. this.atNewLine = false;
  32171. }
  32172. this.offset += source.length;
  32173. }
  32174. }
  32175. /** Call at end of input to push out any remaining constructions */
  32176. *end() {
  32177. while (this.stack.length > 0)
  32178. yield* this.pop();
  32179. }
  32180. get sourceToken() {
  32181. const st = {
  32182. type: this.type,
  32183. offset: this.offset,
  32184. indent: this.indent,
  32185. source: this.source
  32186. };
  32187. return st;
  32188. }
  32189. *step() {
  32190. const top = this.peek(1);
  32191. if (this.type === 'doc-end' && (!top || top.type !== 'doc-end')) {
  32192. while (this.stack.length > 0)
  32193. yield* this.pop();
  32194. this.stack.push({
  32195. type: 'doc-end',
  32196. offset: this.offset,
  32197. source: this.source
  32198. });
  32199. return;
  32200. }
  32201. if (!top)
  32202. return yield* this.stream();
  32203. switch (top.type) {
  32204. case 'document':
  32205. return yield* this.document(top);
  32206. case 'alias':
  32207. case 'scalar':
  32208. case 'single-quoted-scalar':
  32209. case 'double-quoted-scalar':
  32210. return yield* this.scalar(top);
  32211. case 'block-scalar':
  32212. return yield* this.blockScalar(top);
  32213. case 'block-map':
  32214. return yield* this.blockMap(top);
  32215. case 'block-seq':
  32216. return yield* this.blockSequence(top);
  32217. case 'flow-collection':
  32218. return yield* this.flowCollection(top);
  32219. case 'doc-end':
  32220. return yield* this.documentEnd(top);
  32221. }
  32222. /* istanbul ignore next should not happen */
  32223. yield* this.pop();
  32224. }
  32225. peek(n) {
  32226. return this.stack[this.stack.length - n];
  32227. }
  32228. *pop(error) {
  32229. const token = error ?? this.stack.pop();
  32230. /* istanbul ignore if should not happen */
  32231. if (!token) {
  32232. const message = 'Tried to pop an empty stack';
  32233. yield { type: 'error', offset: this.offset, source: '', message };
  32234. }
  32235. else if (this.stack.length === 0) {
  32236. yield token;
  32237. }
  32238. else {
  32239. const top = this.peek(1);
  32240. if (token.type === 'block-scalar') {
  32241. // Block scalars use their parent rather than header indent
  32242. token.indent = 'indent' in top ? top.indent : 0;
  32243. }
  32244. else if (token.type === 'flow-collection' && top.type === 'document') {
  32245. // Ignore all indent for top-level flow collections
  32246. token.indent = 0;
  32247. }
  32248. if (token.type === 'flow-collection')
  32249. fixFlowSeqItems(token);
  32250. switch (top.type) {
  32251. case 'document':
  32252. top.value = token;
  32253. break;
  32254. case 'block-scalar':
  32255. top.props.push(token); // error
  32256. break;
  32257. case 'block-map': {
  32258. const it = top.items[top.items.length - 1];
  32259. if (it.value) {
  32260. top.items.push({ start: [], key: token, sep: [] });
  32261. this.onKeyLine = true;
  32262. return;
  32263. }
  32264. else if (it.sep) {
  32265. it.value = token;
  32266. }
  32267. else {
  32268. Object.assign(it, { key: token, sep: [] });
  32269. this.onKeyLine = !includesToken(it.start, 'explicit-key-ind');
  32270. return;
  32271. }
  32272. break;
  32273. }
  32274. case 'block-seq': {
  32275. const it = top.items[top.items.length - 1];
  32276. if (it.value)
  32277. top.items.push({ start: [], value: token });
  32278. else
  32279. it.value = token;
  32280. break;
  32281. }
  32282. case 'flow-collection': {
  32283. const it = top.items[top.items.length - 1];
  32284. if (!it || it.value)
  32285. top.items.push({ start: [], key: token, sep: [] });
  32286. else if (it.sep)
  32287. it.value = token;
  32288. else
  32289. Object.assign(it, { key: token, sep: [] });
  32290. return;
  32291. }
  32292. /* istanbul ignore next should not happen */
  32293. default:
  32294. yield* this.pop();
  32295. yield* this.pop(token);
  32296. }
  32297. if ((top.type === 'document' ||
  32298. top.type === 'block-map' ||
  32299. top.type === 'block-seq') &&
  32300. (token.type === 'block-map' || token.type === 'block-seq')) {
  32301. const last = token.items[token.items.length - 1];
  32302. if (last &&
  32303. !last.sep &&
  32304. !last.value &&
  32305. last.start.length > 0 &&
  32306. findNonEmptyIndex(last.start) === -1 &&
  32307. (token.indent === 0 ||
  32308. last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {
  32309. if (top.type === 'document')
  32310. top.end = last.start;
  32311. else
  32312. top.items.push({ start: last.start });
  32313. token.items.splice(-1, 1);
  32314. }
  32315. }
  32316. }
  32317. }
  32318. *stream() {
  32319. switch (this.type) {
  32320. case 'directive-line':
  32321. yield { type: 'directive', offset: this.offset, source: this.source };
  32322. return;
  32323. case 'byte-order-mark':
  32324. case 'space':
  32325. case 'comment':
  32326. case 'newline':
  32327. yield this.sourceToken;
  32328. return;
  32329. case 'doc-mode':
  32330. case 'doc-start': {
  32331. const doc = {
  32332. type: 'document',
  32333. offset: this.offset,
  32334. start: []
  32335. };
  32336. if (this.type === 'doc-start')
  32337. doc.start.push(this.sourceToken);
  32338. this.stack.push(doc);
  32339. return;
  32340. }
  32341. }
  32342. yield {
  32343. type: 'error',
  32344. offset: this.offset,
  32345. message: `Unexpected ${this.type} token in YAML stream`,
  32346. source: this.source
  32347. };
  32348. }
  32349. *document(doc) {
  32350. if (doc.value)
  32351. return yield* this.lineEnd(doc);
  32352. switch (this.type) {
  32353. case 'doc-start': {
  32354. if (findNonEmptyIndex(doc.start) !== -1) {
  32355. yield* this.pop();
  32356. yield* this.step();
  32357. }
  32358. else
  32359. doc.start.push(this.sourceToken);
  32360. return;
  32361. }
  32362. case 'anchor':
  32363. case 'tag':
  32364. case 'space':
  32365. case 'comment':
  32366. case 'newline':
  32367. doc.start.push(this.sourceToken);
  32368. return;
  32369. }
  32370. const bv = this.startBlockValue(doc);
  32371. if (bv)
  32372. this.stack.push(bv);
  32373. else {
  32374. yield {
  32375. type: 'error',
  32376. offset: this.offset,
  32377. message: `Unexpected ${this.type} token in YAML document`,
  32378. source: this.source
  32379. };
  32380. }
  32381. }
  32382. *scalar(scalar) {
  32383. if (this.type === 'map-value-ind') {
  32384. const prev = getPrevProps(this.peek(2));
  32385. const start = getFirstKeyStartProps(prev);
  32386. let sep;
  32387. if (scalar.end) {
  32388. sep = scalar.end;
  32389. sep.push(this.sourceToken);
  32390. delete scalar.end;
  32391. }
  32392. else
  32393. sep = [this.sourceToken];
  32394. const map = {
  32395. type: 'block-map',
  32396. offset: scalar.offset,
  32397. indent: scalar.indent,
  32398. items: [{ start, key: scalar, sep }]
  32399. };
  32400. this.onKeyLine = true;
  32401. this.stack[this.stack.length - 1] = map;
  32402. }
  32403. else
  32404. yield* this.lineEnd(scalar);
  32405. }
  32406. *blockScalar(scalar) {
  32407. switch (this.type) {
  32408. case 'space':
  32409. case 'comment':
  32410. case 'newline':
  32411. scalar.props.push(this.sourceToken);
  32412. return;
  32413. case 'scalar':
  32414. scalar.source = this.source;
  32415. // block-scalar source includes trailing newline
  32416. this.atNewLine = true;
  32417. this.indent = 0;
  32418. if (this.onNewLine) {
  32419. let nl = this.source.indexOf('\n') + 1;
  32420. while (nl !== 0) {
  32421. this.onNewLine(this.offset + nl);
  32422. nl = this.source.indexOf('\n', nl) + 1;
  32423. }
  32424. }
  32425. yield* this.pop();
  32426. break;
  32427. /* istanbul ignore next should not happen */
  32428. default:
  32429. yield* this.pop();
  32430. yield* this.step();
  32431. }
  32432. }
  32433. *blockMap(map) {
  32434. const it = map.items[map.items.length - 1];
  32435. // it.sep is true-ish if pair already has key or : separator
  32436. switch (this.type) {
  32437. case 'newline':
  32438. this.onKeyLine = false;
  32439. if (it.value) {
  32440. const end = 'end' in it.value ? it.value.end : undefined;
  32441. const last = Array.isArray(end) ? end[end.length - 1] : undefined;
  32442. if (last?.type === 'comment')
  32443. end?.push(this.sourceToken);
  32444. else
  32445. map.items.push({ start: [this.sourceToken] });
  32446. }
  32447. else if (it.sep) {
  32448. it.sep.push(this.sourceToken);
  32449. }
  32450. else {
  32451. it.start.push(this.sourceToken);
  32452. }
  32453. return;
  32454. case 'space':
  32455. case 'comment':
  32456. if (it.value) {
  32457. map.items.push({ start: [this.sourceToken] });
  32458. }
  32459. else if (it.sep) {
  32460. it.sep.push(this.sourceToken);
  32461. }
  32462. else {
  32463. if (this.atIndentedComment(it.start, map.indent)) {
  32464. const prev = map.items[map.items.length - 2];
  32465. const end = prev?.value?.end;
  32466. if (Array.isArray(end)) {
  32467. Array.prototype.push.apply(end, it.start);
  32468. end.push(this.sourceToken);
  32469. map.items.pop();
  32470. return;
  32471. }
  32472. }
  32473. it.start.push(this.sourceToken);
  32474. }
  32475. return;
  32476. }
  32477. if (this.indent >= map.indent) {
  32478. const atNextItem = !this.onKeyLine && this.indent === map.indent && it.sep;
  32479. // For empty nodes, assign newline-separated not indented empty tokens to following node
  32480. let start = [];
  32481. if (atNextItem && it.sep && !it.value) {
  32482. const nl = [];
  32483. for (let i = 0; i < it.sep.length; ++i) {
  32484. const st = it.sep[i];
  32485. switch (st.type) {
  32486. case 'newline':
  32487. nl.push(i);
  32488. break;
  32489. case 'space':
  32490. break;
  32491. case 'comment':
  32492. if (st.indent > map.indent)
  32493. nl.length = 0;
  32494. break;
  32495. default:
  32496. nl.length = 0;
  32497. }
  32498. }
  32499. if (nl.length >= 2)
  32500. start = it.sep.splice(nl[1]);
  32501. }
  32502. switch (this.type) {
  32503. case 'anchor':
  32504. case 'tag':
  32505. if (atNextItem || it.value) {
  32506. start.push(this.sourceToken);
  32507. map.items.push({ start });
  32508. this.onKeyLine = true;
  32509. }
  32510. else if (it.sep) {
  32511. it.sep.push(this.sourceToken);
  32512. }
  32513. else {
  32514. it.start.push(this.sourceToken);
  32515. }
  32516. return;
  32517. case 'explicit-key-ind':
  32518. if (!it.sep && !includesToken(it.start, 'explicit-key-ind')) {
  32519. it.start.push(this.sourceToken);
  32520. }
  32521. else if (atNextItem || it.value) {
  32522. start.push(this.sourceToken);
  32523. map.items.push({ start });
  32524. }
  32525. else {
  32526. this.stack.push({
  32527. type: 'block-map',
  32528. offset: this.offset,
  32529. indent: this.indent,
  32530. items: [{ start: [this.sourceToken] }]
  32531. });
  32532. }
  32533. this.onKeyLine = true;
  32534. return;
  32535. case 'map-value-ind':
  32536. if (includesToken(it.start, 'explicit-key-ind')) {
  32537. if (!it.sep) {
  32538. if (includesToken(it.start, 'newline')) {
  32539. Object.assign(it, { key: null, sep: [this.sourceToken] });
  32540. }
  32541. else {
  32542. const start = getFirstKeyStartProps(it.start);
  32543. this.stack.push({
  32544. type: 'block-map',
  32545. offset: this.offset,
  32546. indent: this.indent,
  32547. items: [{ start, key: null, sep: [this.sourceToken] }]
  32548. });
  32549. }
  32550. }
  32551. else if (it.value) {
  32552. map.items.push({ start: [], key: null, sep: [this.sourceToken] });
  32553. }
  32554. else if (includesToken(it.sep, 'map-value-ind')) {
  32555. this.stack.push({
  32556. type: 'block-map',
  32557. offset: this.offset,
  32558. indent: this.indent,
  32559. items: [{ start, key: null, sep: [this.sourceToken] }]
  32560. });
  32561. }
  32562. else if (isFlowToken(it.key) &&
  32563. !includesToken(it.sep, 'newline')) {
  32564. const start = getFirstKeyStartProps(it.start);
  32565. const key = it.key;
  32566. const sep = it.sep;
  32567. sep.push(this.sourceToken);
  32568. // @ts-expect-error type guard is wrong here
  32569. delete it.key, delete it.sep;
  32570. this.stack.push({
  32571. type: 'block-map',
  32572. offset: this.offset,
  32573. indent: this.indent,
  32574. items: [{ start, key, sep }]
  32575. });
  32576. }
  32577. else if (start.length > 0) {
  32578. // Not actually at next item
  32579. it.sep = it.sep.concat(start, this.sourceToken);
  32580. }
  32581. else {
  32582. it.sep.push(this.sourceToken);
  32583. }
  32584. }
  32585. else {
  32586. if (!it.sep) {
  32587. Object.assign(it, { key: null, sep: [this.sourceToken] });
  32588. }
  32589. else if (it.value || atNextItem) {
  32590. map.items.push({ start, key: null, sep: [this.sourceToken] });
  32591. }
  32592. else if (includesToken(it.sep, 'map-value-ind')) {
  32593. this.stack.push({
  32594. type: 'block-map',
  32595. offset: this.offset,
  32596. indent: this.indent,
  32597. items: [{ start: [], key: null, sep: [this.sourceToken] }]
  32598. });
  32599. }
  32600. else {
  32601. it.sep.push(this.sourceToken);
  32602. }
  32603. }
  32604. this.onKeyLine = true;
  32605. return;
  32606. case 'alias':
  32607. case 'scalar':
  32608. case 'single-quoted-scalar':
  32609. case 'double-quoted-scalar': {
  32610. const fs = this.flowScalar(this.type);
  32611. if (atNextItem || it.value) {
  32612. map.items.push({ start, key: fs, sep: [] });
  32613. this.onKeyLine = true;
  32614. }
  32615. else if (it.sep) {
  32616. this.stack.push(fs);
  32617. }
  32618. else {
  32619. Object.assign(it, { key: fs, sep: [] });
  32620. this.onKeyLine = true;
  32621. }
  32622. return;
  32623. }
  32624. default: {
  32625. const bv = this.startBlockValue(map);
  32626. if (bv) {
  32627. if (atNextItem &&
  32628. bv.type !== 'block-seq' &&
  32629. includesToken(it.start, 'explicit-key-ind')) {
  32630. map.items.push({ start });
  32631. }
  32632. this.stack.push(bv);
  32633. return;
  32634. }
  32635. }
  32636. }
  32637. }
  32638. yield* this.pop();
  32639. yield* this.step();
  32640. }
  32641. *blockSequence(seq) {
  32642. const it = seq.items[seq.items.length - 1];
  32643. switch (this.type) {
  32644. case 'newline':
  32645. if (it.value) {
  32646. const end = 'end' in it.value ? it.value.end : undefined;
  32647. const last = Array.isArray(end) ? end[end.length - 1] : undefined;
  32648. if (last?.type === 'comment')
  32649. end?.push(this.sourceToken);
  32650. else
  32651. seq.items.push({ start: [this.sourceToken] });
  32652. }
  32653. else
  32654. it.start.push(this.sourceToken);
  32655. return;
  32656. case 'space':
  32657. case 'comment':
  32658. if (it.value)
  32659. seq.items.push({ start: [this.sourceToken] });
  32660. else {
  32661. if (this.atIndentedComment(it.start, seq.indent)) {
  32662. const prev = seq.items[seq.items.length - 2];
  32663. const end = prev?.value?.end;
  32664. if (Array.isArray(end)) {
  32665. Array.prototype.push.apply(end, it.start);
  32666. end.push(this.sourceToken);
  32667. seq.items.pop();
  32668. return;
  32669. }
  32670. }
  32671. it.start.push(this.sourceToken);
  32672. }
  32673. return;
  32674. case 'anchor':
  32675. case 'tag':
  32676. if (it.value || this.indent <= seq.indent)
  32677. break;
  32678. it.start.push(this.sourceToken);
  32679. return;
  32680. case 'seq-item-ind':
  32681. if (this.indent !== seq.indent)
  32682. break;
  32683. if (it.value || includesToken(it.start, 'seq-item-ind'))
  32684. seq.items.push({ start: [this.sourceToken] });
  32685. else
  32686. it.start.push(this.sourceToken);
  32687. return;
  32688. }
  32689. if (this.indent > seq.indent) {
  32690. const bv = this.startBlockValue(seq);
  32691. if (bv) {
  32692. this.stack.push(bv);
  32693. return;
  32694. }
  32695. }
  32696. yield* this.pop();
  32697. yield* this.step();
  32698. }
  32699. *flowCollection(fc) {
  32700. const it = fc.items[fc.items.length - 1];
  32701. if (this.type === 'flow-error-end') {
  32702. let top;
  32703. do {
  32704. yield* this.pop();
  32705. top = this.peek(1);
  32706. } while (top && top.type === 'flow-collection');
  32707. }
  32708. else if (fc.end.length === 0) {
  32709. switch (this.type) {
  32710. case 'comma':
  32711. case 'explicit-key-ind':
  32712. if (!it || it.sep)
  32713. fc.items.push({ start: [this.sourceToken] });
  32714. else
  32715. it.start.push(this.sourceToken);
  32716. return;
  32717. case 'map-value-ind':
  32718. if (!it || it.value)
  32719. fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
  32720. else if (it.sep)
  32721. it.sep.push(this.sourceToken);
  32722. else
  32723. Object.assign(it, { key: null, sep: [this.sourceToken] });
  32724. return;
  32725. case 'space':
  32726. case 'comment':
  32727. case 'newline':
  32728. case 'anchor':
  32729. case 'tag':
  32730. if (!it || it.value)
  32731. fc.items.push({ start: [this.sourceToken] });
  32732. else if (it.sep)
  32733. it.sep.push(this.sourceToken);
  32734. else
  32735. it.start.push(this.sourceToken);
  32736. return;
  32737. case 'alias':
  32738. case 'scalar':
  32739. case 'single-quoted-scalar':
  32740. case 'double-quoted-scalar': {
  32741. const fs = this.flowScalar(this.type);
  32742. if (!it || it.value)
  32743. fc.items.push({ start: [], key: fs, sep: [] });
  32744. else if (it.sep)
  32745. this.stack.push(fs);
  32746. else
  32747. Object.assign(it, { key: fs, sep: [] });
  32748. return;
  32749. }
  32750. case 'flow-map-end':
  32751. case 'flow-seq-end':
  32752. fc.end.push(this.sourceToken);
  32753. return;
  32754. }
  32755. const bv = this.startBlockValue(fc);
  32756. /* istanbul ignore else should not happen */
  32757. if (bv)
  32758. this.stack.push(bv);
  32759. else {
  32760. yield* this.pop();
  32761. yield* this.step();
  32762. }
  32763. }
  32764. else {
  32765. const parent = this.peek(2);
  32766. if (parent.type === 'block-map' &&
  32767. ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||
  32768. (this.type === 'newline' &&
  32769. !parent.items[parent.items.length - 1].sep))) {
  32770. yield* this.pop();
  32771. yield* this.step();
  32772. }
  32773. else if (this.type === 'map-value-ind' &&
  32774. parent.type !== 'flow-collection') {
  32775. const prev = getPrevProps(parent);
  32776. const start = getFirstKeyStartProps(prev);
  32777. fixFlowSeqItems(fc);
  32778. const sep = fc.end.splice(1, fc.end.length);
  32779. sep.push(this.sourceToken);
  32780. const map = {
  32781. type: 'block-map',
  32782. offset: fc.offset,
  32783. indent: fc.indent,
  32784. items: [{ start, key: fc, sep }]
  32785. };
  32786. this.onKeyLine = true;
  32787. this.stack[this.stack.length - 1] = map;
  32788. }
  32789. else {
  32790. yield* this.lineEnd(fc);
  32791. }
  32792. }
  32793. }
  32794. flowScalar(type) {
  32795. if (this.onNewLine) {
  32796. let nl = this.source.indexOf('\n') + 1;
  32797. while (nl !== 0) {
  32798. this.onNewLine(this.offset + nl);
  32799. nl = this.source.indexOf('\n', nl) + 1;
  32800. }
  32801. }
  32802. return {
  32803. type,
  32804. offset: this.offset,
  32805. indent: this.indent,
  32806. source: this.source
  32807. };
  32808. }
  32809. startBlockValue(parent) {
  32810. switch (this.type) {
  32811. case 'alias':
  32812. case 'scalar':
  32813. case 'single-quoted-scalar':
  32814. case 'double-quoted-scalar':
  32815. return this.flowScalar(this.type);
  32816. case 'block-scalar-header':
  32817. return {
  32818. type: 'block-scalar',
  32819. offset: this.offset,
  32820. indent: this.indent,
  32821. props: [this.sourceToken],
  32822. source: ''
  32823. };
  32824. case 'flow-map-start':
  32825. case 'flow-seq-start':
  32826. return {
  32827. type: 'flow-collection',
  32828. offset: this.offset,
  32829. indent: this.indent,
  32830. start: this.sourceToken,
  32831. items: [],
  32832. end: []
  32833. };
  32834. case 'seq-item-ind':
  32835. return {
  32836. type: 'block-seq',
  32837. offset: this.offset,
  32838. indent: this.indent,
  32839. items: [{ start: [this.sourceToken] }]
  32840. };
  32841. case 'explicit-key-ind': {
  32842. this.onKeyLine = true;
  32843. const prev = getPrevProps(parent);
  32844. const start = getFirstKeyStartProps(prev);
  32845. start.push(this.sourceToken);
  32846. return {
  32847. type: 'block-map',
  32848. offset: this.offset,
  32849. indent: this.indent,
  32850. items: [{ start }]
  32851. };
  32852. }
  32853. case 'map-value-ind': {
  32854. this.onKeyLine = true;
  32855. const prev = getPrevProps(parent);
  32856. const start = getFirstKeyStartProps(prev);
  32857. return {
  32858. type: 'block-map',
  32859. offset: this.offset,
  32860. indent: this.indent,
  32861. items: [{ start, key: null, sep: [this.sourceToken] }]
  32862. };
  32863. }
  32864. }
  32865. return null;
  32866. }
  32867. atIndentedComment(start, indent) {
  32868. if (this.type !== 'comment')
  32869. return false;
  32870. if (this.indent <= indent)
  32871. return false;
  32872. return start.every(st => st.type === 'newline' || st.type === 'space');
  32873. }
  32874. *documentEnd(docEnd) {
  32875. if (this.type !== 'doc-mode') {
  32876. if (docEnd.end)
  32877. docEnd.end.push(this.sourceToken);
  32878. else
  32879. docEnd.end = [this.sourceToken];
  32880. if (this.type === 'newline')
  32881. yield* this.pop();
  32882. }
  32883. }
  32884. *lineEnd(token) {
  32885. switch (this.type) {
  32886. case 'comma':
  32887. case 'doc-start':
  32888. case 'doc-end':
  32889. case 'flow-seq-end':
  32890. case 'flow-map-end':
  32891. case 'map-value-ind':
  32892. yield* this.pop();
  32893. yield* this.step();
  32894. break;
  32895. case 'newline':
  32896. this.onKeyLine = false;
  32897. // fallthrough
  32898. case 'space':
  32899. case 'comment':
  32900. default:
  32901. // all other values are errors
  32902. if (token.end)
  32903. token.end.push(this.sourceToken);
  32904. else
  32905. token.end = [this.sourceToken];
  32906. if (this.type === 'newline')
  32907. yield* this.pop();
  32908. }
  32909. }
  32910. }
  32911. function parseOptions(options) {
  32912. const prettyErrors = options.prettyErrors !== false;
  32913. const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null;
  32914. return { lineCounter, prettyErrors };
  32915. }
  32916. /**
  32917. * Parse the input as a stream of YAML documents.
  32918. *
  32919. * Documents should be separated from each other by `...` or `---` marker lines.
  32920. *
  32921. * @returns If an empty `docs` array is returned, it will be of type
  32922. * EmptyStream and contain additional stream information. In
  32923. * TypeScript, you should use `'empty' in docs` as a type guard for it.
  32924. */
  32925. function parseAllDocuments(source, options = {}) {
  32926. const { lineCounter, prettyErrors } = parseOptions(options);
  32927. const parser = new Parser(lineCounter?.addNewLine);
  32928. const composer = new Composer(options);
  32929. const docs = Array.from(composer.compose(parser.parse(source)));
  32930. if (prettyErrors && lineCounter)
  32931. for (const doc of docs) {
  32932. doc.errors.forEach(prettifyError(source, lineCounter));
  32933. doc.warnings.forEach(prettifyError(source, lineCounter));
  32934. }
  32935. if (docs.length > 0)
  32936. return docs;
  32937. return Object.assign([], { empty: true }, composer.streamInfo());
  32938. }
  32939. /** Parse an input string into a single YAML.Document */
  32940. function parseDocument(source, options = {}) {
  32941. const { lineCounter, prettyErrors } = parseOptions(options);
  32942. const parser = new Parser(lineCounter?.addNewLine);
  32943. const composer = new Composer(options);
  32944. // `doc` is always set by compose.end(true) at the very latest
  32945. let doc = null;
  32946. for (const _doc of composer.compose(parser.parse(source), true, source.length)) {
  32947. if (!doc)
  32948. doc = _doc;
  32949. else if (doc.options.logLevel !== 'silent') {
  32950. doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));
  32951. break;
  32952. }
  32953. }
  32954. if (prettyErrors && lineCounter) {
  32955. doc.errors.forEach(prettifyError(source, lineCounter));
  32956. doc.warnings.forEach(prettifyError(source, lineCounter));
  32957. }
  32958. return doc;
  32959. }
  32960. function parse$a(src, reviver, options) {
  32961. let _reviver = undefined;
  32962. if (typeof reviver === 'function') {
  32963. _reviver = reviver;
  32964. }
  32965. else if (options === undefined && reviver && typeof reviver === 'object') {
  32966. options = reviver;
  32967. }
  32968. const doc = parseDocument(src, options);
  32969. if (!doc)
  32970. return null;
  32971. doc.warnings.forEach(warning => warn(doc.options.logLevel, warning));
  32972. if (doc.errors.length > 0) {
  32973. if (doc.options.logLevel !== 'silent')
  32974. throw doc.errors[0];
  32975. else
  32976. doc.errors = [];
  32977. }
  32978. return doc.toJS(Object.assign({ reviver: _reviver }, options));
  32979. }
  32980. function stringify(value, replacer, options) {
  32981. let _replacer = null;
  32982. if (typeof replacer === 'function' || Array.isArray(replacer)) {
  32983. _replacer = replacer;
  32984. }
  32985. else if (options === undefined && replacer) {
  32986. options = replacer;
  32987. }
  32988. if (typeof options === 'string')
  32989. options = options.length;
  32990. if (typeof options === 'number') {
  32991. const indent = Math.round(options);
  32992. options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
  32993. }
  32994. if (value === undefined) {
  32995. const { keepUndefined } = options ?? replacer ?? {};
  32996. if (!keepUndefined)
  32997. return undefined;
  32998. }
  32999. return new Document(value, _replacer, options).toString(options);
  33000. }
  33001. var YAML = {
  33002. __proto__: null,
  33003. Alias: Alias,
  33004. CST: cst,
  33005. Composer: Composer,
  33006. Document: Document,
  33007. Lexer: Lexer,
  33008. LineCounter: LineCounter,
  33009. Pair: Pair,
  33010. Parser: Parser,
  33011. Scalar: Scalar,
  33012. Schema: Schema,
  33013. YAMLError: YAMLError,
  33014. YAMLMap: YAMLMap,
  33015. YAMLParseError: YAMLParseError,
  33016. YAMLSeq: YAMLSeq,
  33017. YAMLWarning: YAMLWarning,
  33018. isAlias: isAlias,
  33019. isCollection: isCollection$1,
  33020. isDocument: isDocument,
  33021. isMap: isMap,
  33022. isNode: isNode$1,
  33023. isPair: isPair,
  33024. isScalar: isScalar$1,
  33025. isSeq: isSeq,
  33026. parse: parse$a,
  33027. parseAllDocuments: parseAllDocuments,
  33028. parseDocument: parseDocument,
  33029. stringify: stringify,
  33030. visit: visit$1,
  33031. visitAsync: visitAsync
  33032. };
  33033. // `export * as default from ...` fails on Webpack v4
  33034. // https://github.com/eemeli/yaml/issues/228
  33035. var browser$2 = {
  33036. __proto__: null,
  33037. Alias: Alias,
  33038. CST: cst,
  33039. Composer: Composer,
  33040. Document: Document,
  33041. Lexer: Lexer,
  33042. LineCounter: LineCounter,
  33043. Pair: Pair,
  33044. Parser: Parser,
  33045. Scalar: Scalar,
  33046. Schema: Schema,
  33047. YAMLError: YAMLError,
  33048. YAMLMap: YAMLMap,
  33049. YAMLParseError: YAMLParseError,
  33050. YAMLSeq: YAMLSeq,
  33051. YAMLWarning: YAMLWarning,
  33052. default: YAML,
  33053. isAlias: isAlias,
  33054. isCollection: isCollection$1,
  33055. isDocument: isDocument,
  33056. isMap: isMap,
  33057. isNode: isNode$1,
  33058. isPair: isPair,
  33059. isScalar: isScalar$1,
  33060. isSeq: isSeq,
  33061. parse: parse$a,
  33062. parseAllDocuments: parseAllDocuments,
  33063. parseDocument: parseDocument,
  33064. stringify: stringify,
  33065. visit: visit$1,
  33066. visitAsync: visitAsync
  33067. };
  33068. var require$$3 = /*@__PURE__*/getAugmentedNamespace(browser$2);
  33069. // eslint-disable-next-line n/no-deprecated-api
  33070. const { createRequire, createRequireFromPath } = require$$0$8;
  33071. function req$2 (name, rootFile) {
  33072. const create = createRequire || createRequireFromPath;
  33073. const require = create(rootFile);
  33074. return require(name)
  33075. }
  33076. var req_1 = req$2;
  33077. const req$1 = req_1;
  33078. /**
  33079. * Load Options
  33080. *
  33081. * @private
  33082. * @method options
  33083. *
  33084. * @param {Object} config PostCSS Config
  33085. *
  33086. * @return {Object} options PostCSS Options
  33087. */
  33088. const options = (config, file) => {
  33089. if (config.parser && typeof config.parser === 'string') {
  33090. try {
  33091. config.parser = req$1(config.parser, file);
  33092. } catch (err) {
  33093. throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`)
  33094. }
  33095. }
  33096. if (config.syntax && typeof config.syntax === 'string') {
  33097. try {
  33098. config.syntax = req$1(config.syntax, file);
  33099. } catch (err) {
  33100. throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`)
  33101. }
  33102. }
  33103. if (config.stringifier && typeof config.stringifier === 'string') {
  33104. try {
  33105. config.stringifier = req$1(config.stringifier, file);
  33106. } catch (err) {
  33107. throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`)
  33108. }
  33109. }
  33110. if (config.plugins) {
  33111. delete config.plugins;
  33112. }
  33113. return config
  33114. };
  33115. var options_1 = options;
  33116. const req = req_1;
  33117. /**
  33118. * Plugin Loader
  33119. *
  33120. * @private
  33121. * @method load
  33122. *
  33123. * @param {String} plugin PostCSS Plugin Name
  33124. * @param {Object} options PostCSS Plugin Options
  33125. *
  33126. * @return {Function} PostCSS Plugin
  33127. */
  33128. const load = (plugin, options, file) => {
  33129. try {
  33130. if (
  33131. options === null ||
  33132. options === undefined ||
  33133. Object.keys(options).length === 0
  33134. ) {
  33135. return req(plugin, file)
  33136. } else {
  33137. return req(plugin, file)(options)
  33138. }
  33139. } catch (err) {
  33140. throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`)
  33141. }
  33142. };
  33143. /**
  33144. * Load Plugins
  33145. *
  33146. * @private
  33147. * @method plugins
  33148. *
  33149. * @param {Object} config PostCSS Config Plugins
  33150. *
  33151. * @return {Array} plugins PostCSS Plugins
  33152. */
  33153. const plugins = (config, file) => {
  33154. let plugins = [];
  33155. if (Array.isArray(config.plugins)) {
  33156. plugins = config.plugins.filter(Boolean);
  33157. } else {
  33158. plugins = Object.keys(config.plugins)
  33159. .filter((plugin) => {
  33160. return config.plugins[plugin] !== false ? plugin : ''
  33161. })
  33162. .map((plugin) => {
  33163. return load(plugin, config.plugins[plugin], file)
  33164. });
  33165. }
  33166. if (plugins.length && plugins.length > 0) {
  33167. plugins.forEach((plugin, i) => {
  33168. if (plugin.default) {
  33169. plugin = plugin.default;
  33170. }
  33171. if (plugin.postcss === true) {
  33172. plugin = plugin();
  33173. } else if (plugin.postcss) {
  33174. plugin = plugin.postcss;
  33175. }
  33176. if (
  33177. // eslint-disable-next-line
  33178. !(
  33179. (typeof plugin === 'object' && Array.isArray(plugin.plugins)) ||
  33180. (typeof plugin === 'object' && plugin.postcssPlugin) ||
  33181. (typeof plugin === 'function')
  33182. )
  33183. ) {
  33184. throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`)
  33185. }
  33186. });
  33187. }
  33188. return plugins
  33189. };
  33190. var plugins_1 = plugins;
  33191. const resolve = require$$0$4.resolve;
  33192. const url$4 = require$$0$9;
  33193. const config$1 = dist;
  33194. const yaml = require$$3;
  33195. const loadOptions = options_1;
  33196. const loadPlugins = plugins_1;
  33197. /* istanbul ignore next */
  33198. const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
  33199. /**
  33200. * Process the result from cosmiconfig
  33201. *
  33202. * @param {Object} ctx Config Context
  33203. * @param {Object} result Cosmiconfig result
  33204. *
  33205. * @return {Object} PostCSS Config
  33206. */
  33207. const processResult = (ctx, result) => {
  33208. const file = result.filepath || '';
  33209. let config = interopRequireDefault(result.config).default || {};
  33210. if (typeof config === 'function') {
  33211. config = config(ctx);
  33212. } else {
  33213. config = Object.assign({}, config, ctx);
  33214. }
  33215. if (!config.plugins) {
  33216. config.plugins = [];
  33217. }
  33218. return {
  33219. plugins: loadPlugins(config, file),
  33220. options: loadOptions(config, file),
  33221. file
  33222. }
  33223. };
  33224. /**
  33225. * Builds the Config Context
  33226. *
  33227. * @param {Object} ctx Config Context
  33228. *
  33229. * @return {Object} Config Context
  33230. */
  33231. const createContext = (ctx) => {
  33232. /**
  33233. * @type {Object}
  33234. *
  33235. * @prop {String} cwd=process.cwd() Config search start location
  33236. * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
  33237. */
  33238. ctx = Object.assign({
  33239. cwd: process.cwd(),
  33240. env: process.env.NODE_ENV
  33241. }, ctx);
  33242. if (!ctx.env) {
  33243. process.env.NODE_ENV = 'development';
  33244. }
  33245. return ctx
  33246. };
  33247. const importDefault = async filepath => {
  33248. const module = await import(url$4.pathToFileURL(filepath).href);
  33249. return module.default
  33250. };
  33251. const addTypeScriptLoader = (options = {}, loader) => {
  33252. const moduleName = 'postcss';
  33253. return {
  33254. ...options,
  33255. searchPlaces: [
  33256. ...(options.searchPlaces || []),
  33257. 'package.json',
  33258. `.${moduleName}rc`,
  33259. `.${moduleName}rc.json`,
  33260. `.${moduleName}rc.yaml`,
  33261. `.${moduleName}rc.yml`,
  33262. `.${moduleName}rc.ts`,
  33263. `.${moduleName}rc.js`,
  33264. `.${moduleName}rc.cjs`,
  33265. `.${moduleName}rc.mjs`,
  33266. `${moduleName}.config.ts`,
  33267. `${moduleName}.config.js`,
  33268. `${moduleName}.config.cjs`,
  33269. `${moduleName}.config.mjs`
  33270. ],
  33271. loaders: {
  33272. ...options.loaders,
  33273. '.yaml': (filepath, content) => yaml.parse(content),
  33274. '.yml': (filepath, content) => yaml.parse(content),
  33275. '.js': importDefault,
  33276. '.cjs': importDefault,
  33277. '.mjs': importDefault,
  33278. '.ts': loader
  33279. }
  33280. }
  33281. };
  33282. const withTypeScriptLoader = (rcFunc) => {
  33283. return (ctx, path, options) => {
  33284. return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => {
  33285. let registerer = { enabled () {} };
  33286. try {
  33287. // Register TypeScript compiler instance
  33288. registerer = __require('ts-node').register();
  33289. return __require(configFile)
  33290. } catch (err) {
  33291. if (err.code === 'MODULE_NOT_FOUND') {
  33292. throw new Error(
  33293. `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}`
  33294. )
  33295. }
  33296. throw err
  33297. } finally {
  33298. registerer.enabled(false);
  33299. }
  33300. }))
  33301. }
  33302. };
  33303. /**
  33304. * Load Config
  33305. *
  33306. * @method rc
  33307. *
  33308. * @param {Object} ctx Config Context
  33309. * @param {String} path Config Path
  33310. * @param {Object} options Config Options
  33311. *
  33312. * @return {Promise} config PostCSS Config
  33313. */
  33314. const rc = withTypeScriptLoader((ctx, path, options) => {
  33315. /**
  33316. * @type {Object} The full Config Context
  33317. */
  33318. ctx = createContext(ctx);
  33319. /**
  33320. * @type {String} `process.cwd()`
  33321. */
  33322. path = path ? resolve(path) : process.cwd();
  33323. return config$1.lilconfig('postcss', options)
  33324. .search(path)
  33325. .then((result) => {
  33326. if (!result) {
  33327. throw new Error(`No PostCSS Config found in: ${path}`)
  33328. }
  33329. return processResult(ctx, result)
  33330. })
  33331. });
  33332. /**
  33333. * Autoload Config for PostCSS
  33334. *
  33335. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  33336. * @license MIT
  33337. *
  33338. * @module postcss-load-config
  33339. * @version 2.1.0
  33340. *
  33341. * @requires comsiconfig
  33342. * @requires ./options
  33343. * @requires ./plugins
  33344. */
  33345. var src$1 = rc;
  33346. var postcssrc = /*@__PURE__*/getDefaultExportFromCjs(src$1);
  33347. function _stripLiteralAcorn(code, options) {
  33348. const FILL = options?.fillChar ?? " ";
  33349. const FILL_COMMENT = " ";
  33350. let result = "";
  33351. const filter = options?.filter ?? (() => true);
  33352. function fillupTo(index) {
  33353. if (index > result.length)
  33354. result += code.slice(result.length, index).replace(/[^\n]/g, FILL_COMMENT);
  33355. }
  33356. const tokens = [];
  33357. const pasers = tokenizer(code, {
  33358. ecmaVersion: "latest",
  33359. sourceType: "module",
  33360. allowHashBang: true,
  33361. allowAwaitOutsideFunction: true,
  33362. allowImportExportEverywhere: true
  33363. });
  33364. const iter = pasers[Symbol.iterator]();
  33365. let error;
  33366. try {
  33367. while (true) {
  33368. const { done, value: token } = iter.next();
  33369. if (done)
  33370. break;
  33371. tokens.push(token);
  33372. fillupTo(token.start);
  33373. if (token.type.label === "string") {
  33374. const body = code.slice(token.start + 1, token.end - 1);
  33375. if (filter(body)) {
  33376. result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
  33377. continue;
  33378. }
  33379. } else if (token.type.label === "template") {
  33380. const body = code.slice(token.start, token.end);
  33381. if (filter(body)) {
  33382. result += FILL.repeat(token.end - token.start);
  33383. continue;
  33384. }
  33385. } else if (token.type.label === "regexp") {
  33386. const body = code.slice(token.start, token.end);
  33387. if (filter(body)) {
  33388. result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
  33389. continue;
  33390. }
  33391. }
  33392. result += code.slice(token.start, token.end);
  33393. }
  33394. fillupTo(code.length);
  33395. } catch (e) {
  33396. error = e;
  33397. }
  33398. return {
  33399. error,
  33400. result,
  33401. tokens
  33402. };
  33403. }
  33404. const multilineCommentsRE = /\/\*([^*\/])*?\*\//gms;
  33405. const singlelineCommentsRE = /(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/gm;
  33406. const templateLiteralRE$1 = /\$\{(\s*(?:|{.*}|(?!\$\{).|\n|\r)*?\s*)\}/g;
  33407. const quotesRE = [
  33408. /(["'`])((?:\\\1|(?!\1)|.|\r)*?)\1/gm,
  33409. /([`])((?:\\\1|(?!\1)|.|\n|\r)*?)\1/gm
  33410. // multi-line strings (i.e. template literals only)
  33411. ];
  33412. function stripLiteralRegex(code, options) {
  33413. const FILL_COMMENT = " ";
  33414. const FILL = options?.fillChar ?? " ";
  33415. const filter = options?.filter ?? (() => true);
  33416. code = code.replace(multilineCommentsRE, (s) => filter(s) ? FILL_COMMENT.repeat(s.length) : s).replace(singlelineCommentsRE, (s) => filter(s) ? FILL_COMMENT.repeat(s.length) : s);
  33417. let expanded = code;
  33418. for (let i = 0; i < 16; i++) {
  33419. const before = expanded;
  33420. expanded = expanded.replace(templateLiteralRE$1, "` $1`");
  33421. if (expanded === before)
  33422. break;
  33423. }
  33424. quotesRE.forEach((re) => {
  33425. expanded = expanded.replace(re, (s, quote, body, index) => {
  33426. if (!filter(s.slice(1, -1)))
  33427. return s;
  33428. code = code.slice(0, index + 1) + FILL.repeat(s.length - 2) + code.slice(index + s.length - 1);
  33429. return quote + FILL.repeat(s.length - 2) + quote;
  33430. });
  33431. });
  33432. return code;
  33433. }
  33434. function stripLiteral(code, options) {
  33435. return stripLiteralDetailed(code, options).result;
  33436. }
  33437. function stripLiteralDetailed(code, options) {
  33438. const acorn = _stripLiteralAcorn(code, options);
  33439. if (!acorn.error) {
  33440. return {
  33441. mode: "acorn",
  33442. result: acorn.result,
  33443. acorn
  33444. };
  33445. }
  33446. return {
  33447. mode: "regex",
  33448. result: stripLiteralRegex(acorn.result + code.slice(acorn.result.length), options),
  33449. acorn
  33450. };
  33451. }
  33452. var main$1 = {exports: {}};
  33453. var name = "dotenv";
  33454. var version$1 = "16.3.1";
  33455. var description = "Loads environment variables from .env file";
  33456. var main = "lib/main.js";
  33457. var types = "lib/main.d.ts";
  33458. var exports = {
  33459. ".": {
  33460. types: "./lib/main.d.ts",
  33461. require: "./lib/main.js",
  33462. "default": "./lib/main.js"
  33463. },
  33464. "./config": "./config.js",
  33465. "./config.js": "./config.js",
  33466. "./lib/env-options": "./lib/env-options.js",
  33467. "./lib/env-options.js": "./lib/env-options.js",
  33468. "./lib/cli-options": "./lib/cli-options.js",
  33469. "./lib/cli-options.js": "./lib/cli-options.js",
  33470. "./package.json": "./package.json"
  33471. };
  33472. var scripts = {
  33473. "dts-check": "tsc --project tests/types/tsconfig.json",
  33474. lint: "standard",
  33475. "lint-readme": "standard-markdown",
  33476. pretest: "npm run lint && npm run dts-check",
  33477. test: "tap tests/*.js --100 -Rspec",
  33478. prerelease: "npm test",
  33479. release: "standard-version"
  33480. };
  33481. var repository = {
  33482. type: "git",
  33483. url: "git://github.com/motdotla/dotenv.git"
  33484. };
  33485. var funding = "https://github.com/motdotla/dotenv?sponsor=1";
  33486. var keywords = [
  33487. "dotenv",
  33488. "env",
  33489. ".env",
  33490. "environment",
  33491. "variables",
  33492. "config",
  33493. "settings"
  33494. ];
  33495. var readmeFilename = "README.md";
  33496. var license = "BSD-2-Clause";
  33497. var devDependencies = {
  33498. "@definitelytyped/dtslint": "^0.0.133",
  33499. "@types/node": "^18.11.3",
  33500. decache: "^4.6.1",
  33501. sinon: "^14.0.1",
  33502. standard: "^17.0.0",
  33503. "standard-markdown": "^7.1.0",
  33504. "standard-version": "^9.5.0",
  33505. tap: "^16.3.0",
  33506. tar: "^6.1.11",
  33507. typescript: "^4.8.4"
  33508. };
  33509. var engines = {
  33510. node: ">=12"
  33511. };
  33512. var browser$1 = {
  33513. fs: false
  33514. };
  33515. var require$$4 = {
  33516. name: name,
  33517. version: version$1,
  33518. description: description,
  33519. main: main,
  33520. types: types,
  33521. exports: exports,
  33522. scripts: scripts,
  33523. repository: repository,
  33524. funding: funding,
  33525. keywords: keywords,
  33526. readmeFilename: readmeFilename,
  33527. license: license,
  33528. devDependencies: devDependencies,
  33529. engines: engines,
  33530. browser: browser$1
  33531. };
  33532. const fs$9 = require$$0__default;
  33533. const path$9 = require$$0$4;
  33534. const os$2 = require$$2;
  33535. const crypto$1 = require$$3$1;
  33536. const packageJson = require$$4;
  33537. const version = packageJson.version;
  33538. const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  33539. // Parse src into an Object
  33540. function parse$9 (src) {
  33541. const obj = {};
  33542. // Convert buffer to string
  33543. let lines = src.toString();
  33544. // Convert line breaks to same format
  33545. lines = lines.replace(/\r\n?/mg, '\n');
  33546. let match;
  33547. while ((match = LINE.exec(lines)) != null) {
  33548. const key = match[1];
  33549. // Default undefined or null to empty string
  33550. let value = (match[2] || '');
  33551. // Remove whitespace
  33552. value = value.trim();
  33553. // Check if double quoted
  33554. const maybeQuote = value[0];
  33555. // Remove surrounding quotes
  33556. value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
  33557. // Expand newlines if double quoted
  33558. if (maybeQuote === '"') {
  33559. value = value.replace(/\\n/g, '\n');
  33560. value = value.replace(/\\r/g, '\r');
  33561. }
  33562. // Add to object
  33563. obj[key] = value;
  33564. }
  33565. return obj
  33566. }
  33567. function _parseVault (options) {
  33568. const vaultPath = _vaultPath(options);
  33569. // Parse .env.vault
  33570. const result = DotenvModule.configDotenv({ path: vaultPath });
  33571. if (!result.parsed) {
  33572. throw new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
  33573. }
  33574. // handle scenario for comma separated keys - for use with key rotation
  33575. // example: DOTENV_KEY="dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenv.org/vault/.env.vault?environment=prod"
  33576. const keys = _dotenvKey(options).split(',');
  33577. const length = keys.length;
  33578. let decrypted;
  33579. for (let i = 0; i < length; i++) {
  33580. try {
  33581. // Get full key
  33582. const key = keys[i].trim();
  33583. // Get instructions for decrypt
  33584. const attrs = _instructions(result, key);
  33585. // Decrypt
  33586. decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
  33587. break
  33588. } catch (error) {
  33589. // last key
  33590. if (i + 1 >= length) {
  33591. throw error
  33592. }
  33593. // try next key
  33594. }
  33595. }
  33596. // Parse decrypted .env string
  33597. return DotenvModule.parse(decrypted)
  33598. }
  33599. function _log (message) {
  33600. console.log(`[dotenv@${version}][INFO] ${message}`);
  33601. }
  33602. function _warn (message) {
  33603. console.log(`[dotenv@${version}][WARN] ${message}`);
  33604. }
  33605. function _debug (message) {
  33606. console.log(`[dotenv@${version}][DEBUG] ${message}`);
  33607. }
  33608. function _dotenvKey (options) {
  33609. // prioritize developer directly setting options.DOTENV_KEY
  33610. if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
  33611. return options.DOTENV_KEY
  33612. }
  33613. // secondary infra already contains a DOTENV_KEY environment variable
  33614. if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
  33615. return process.env.DOTENV_KEY
  33616. }
  33617. // fallback to empty string
  33618. return ''
  33619. }
  33620. function _instructions (result, dotenvKey) {
  33621. // Parse DOTENV_KEY. Format is a URI
  33622. let uri;
  33623. try {
  33624. uri = new URL(dotenvKey);
  33625. } catch (error) {
  33626. if (error.code === 'ERR_INVALID_URL') {
  33627. throw new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development')
  33628. }
  33629. throw error
  33630. }
  33631. // Get decrypt key
  33632. const key = uri.password;
  33633. if (!key) {
  33634. throw new Error('INVALID_DOTENV_KEY: Missing key part')
  33635. }
  33636. // Get environment
  33637. const environment = uri.searchParams.get('environment');
  33638. if (!environment) {
  33639. throw new Error('INVALID_DOTENV_KEY: Missing environment part')
  33640. }
  33641. // Get ciphertext payload
  33642. const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
  33643. const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION
  33644. if (!ciphertext) {
  33645. throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
  33646. }
  33647. return { ciphertext, key }
  33648. }
  33649. function _vaultPath (options) {
  33650. let dotenvPath = path$9.resolve(process.cwd(), '.env');
  33651. if (options && options.path && options.path.length > 0) {
  33652. dotenvPath = options.path;
  33653. }
  33654. // Locate .env.vault
  33655. return dotenvPath.endsWith('.vault') ? dotenvPath : `${dotenvPath}.vault`
  33656. }
  33657. function _resolveHome (envPath) {
  33658. return envPath[0] === '~' ? path$9.join(os$2.homedir(), envPath.slice(1)) : envPath
  33659. }
  33660. function _configVault (options) {
  33661. _log('Loading env from encrypted .env.vault');
  33662. const parsed = DotenvModule._parseVault(options);
  33663. let processEnv = process.env;
  33664. if (options && options.processEnv != null) {
  33665. processEnv = options.processEnv;
  33666. }
  33667. DotenvModule.populate(processEnv, parsed, options);
  33668. return { parsed }
  33669. }
  33670. function configDotenv (options) {
  33671. let dotenvPath = path$9.resolve(process.cwd(), '.env');
  33672. let encoding = 'utf8';
  33673. const debug = Boolean(options && options.debug);
  33674. if (options) {
  33675. if (options.path != null) {
  33676. dotenvPath = _resolveHome(options.path);
  33677. }
  33678. if (options.encoding != null) {
  33679. encoding = options.encoding;
  33680. }
  33681. }
  33682. try {
  33683. // Specifying an encoding returns a string instead of a buffer
  33684. const parsed = DotenvModule.parse(fs$9.readFileSync(dotenvPath, { encoding }));
  33685. let processEnv = process.env;
  33686. if (options && options.processEnv != null) {
  33687. processEnv = options.processEnv;
  33688. }
  33689. DotenvModule.populate(processEnv, parsed, options);
  33690. return { parsed }
  33691. } catch (e) {
  33692. if (debug) {
  33693. _debug(`Failed to load ${dotenvPath} ${e.message}`);
  33694. }
  33695. return { error: e }
  33696. }
  33697. }
  33698. // Populates process.env from .env file
  33699. function config (options) {
  33700. const vaultPath = _vaultPath(options);
  33701. // fallback to original dotenv if DOTENV_KEY is not set
  33702. if (_dotenvKey(options).length === 0) {
  33703. return DotenvModule.configDotenv(options)
  33704. }
  33705. // dotenvKey exists but .env.vault file does not exist
  33706. if (!fs$9.existsSync(vaultPath)) {
  33707. _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
  33708. return DotenvModule.configDotenv(options)
  33709. }
  33710. return DotenvModule._configVault(options)
  33711. }
  33712. function decrypt (encrypted, keyStr) {
  33713. const key = Buffer.from(keyStr.slice(-64), 'hex');
  33714. let ciphertext = Buffer.from(encrypted, 'base64');
  33715. const nonce = ciphertext.slice(0, 12);
  33716. const authTag = ciphertext.slice(-16);
  33717. ciphertext = ciphertext.slice(12, -16);
  33718. try {
  33719. const aesgcm = crypto$1.createDecipheriv('aes-256-gcm', key, nonce);
  33720. aesgcm.setAuthTag(authTag);
  33721. return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
  33722. } catch (error) {
  33723. const isRange = error instanceof RangeError;
  33724. const invalidKeyLength = error.message === 'Invalid key length';
  33725. const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data';
  33726. if (isRange || invalidKeyLength) {
  33727. const msg = 'INVALID_DOTENV_KEY: It must be 64 characters long (or more)';
  33728. throw new Error(msg)
  33729. } else if (decryptionFailed) {
  33730. const msg = 'DECRYPTION_FAILED: Please check your DOTENV_KEY';
  33731. throw new Error(msg)
  33732. } else {
  33733. console.error('Error: ', error.code);
  33734. console.error('Error: ', error.message);
  33735. throw error
  33736. }
  33737. }
  33738. }
  33739. // Populate process.env with parsed values
  33740. function populate (processEnv, parsed, options = {}) {
  33741. const debug = Boolean(options && options.debug);
  33742. const override = Boolean(options && options.override);
  33743. if (typeof parsed !== 'object') {
  33744. throw new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
  33745. }
  33746. // Set process.env
  33747. for (const key of Object.keys(parsed)) {
  33748. if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
  33749. if (override === true) {
  33750. processEnv[key] = parsed[key];
  33751. }
  33752. if (debug) {
  33753. if (override === true) {
  33754. _debug(`"${key}" is already defined and WAS overwritten`);
  33755. } else {
  33756. _debug(`"${key}" is already defined and was NOT overwritten`);
  33757. }
  33758. }
  33759. } else {
  33760. processEnv[key] = parsed[key];
  33761. }
  33762. }
  33763. }
  33764. const DotenvModule = {
  33765. configDotenv,
  33766. _configVault,
  33767. _parseVault,
  33768. config,
  33769. decrypt,
  33770. parse: parse$9,
  33771. populate
  33772. };
  33773. main$1.exports.configDotenv = DotenvModule.configDotenv;
  33774. main$1.exports._configVault = DotenvModule._configVault;
  33775. main$1.exports._parseVault = DotenvModule._parseVault;
  33776. main$1.exports.config = DotenvModule.config;
  33777. main$1.exports.decrypt = DotenvModule.decrypt;
  33778. var parse_1$1 = main$1.exports.parse = DotenvModule.parse;
  33779. main$1.exports.populate = DotenvModule.populate;
  33780. main$1.exports = DotenvModule;
  33781. function _interpolate (envValue, environment, config) {
  33782. const matches = envValue.match(/(.?\${*[\w]*(?::-[\w/]*)?}*)/g) || [];
  33783. return matches.reduce(function (newEnv, match, index) {
  33784. const parts = /(.?)\${*([\w]*(?::-[\w/]*)?)?}*/g.exec(match);
  33785. if (!parts || parts.length === 0) {
  33786. return newEnv
  33787. }
  33788. const prefix = parts[1];
  33789. let value, replacePart;
  33790. if (prefix === '\\') {
  33791. replacePart = parts[0];
  33792. value = replacePart.replace('\\$', '$');
  33793. } else {
  33794. // PATCH: compatible with env variables ended with unescaped $
  33795. if(!parts[2]) {
  33796. return newEnv
  33797. }
  33798. const keyParts = parts[2].split(':-');
  33799. const key = keyParts[0];
  33800. replacePart = parts[0].substring(prefix.length);
  33801. // process.env value 'wins' over .env file's value
  33802. value = Object.prototype.hasOwnProperty.call(environment, key)
  33803. ? environment[key]
  33804. : (config.parsed[key] || keyParts[1] || '');
  33805. // If the value is found, remove nested expansions.
  33806. if (keyParts.length > 1 && value) {
  33807. const replaceNested = matches[index + 1];
  33808. matches[index + 1] = '';
  33809. newEnv = newEnv.replace(replaceNested, '');
  33810. }
  33811. // Resolve recursive interpolations
  33812. value = _interpolate(value, environment, config);
  33813. }
  33814. return newEnv.replace(replacePart, value)
  33815. }, envValue)
  33816. }
  33817. function expand (config) {
  33818. // if ignoring process.env, use a blank object
  33819. const environment = config.ignoreProcessEnv ? {} : process.env;
  33820. for (const configKey in config.parsed) {
  33821. const value = Object.prototype.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey];
  33822. config.parsed[configKey] = _interpolate(value, environment, config);
  33823. }
  33824. // PATCH: don't write to process.env
  33825. // for (const processKey in config.parsed) {
  33826. // environment[processKey] = config.parsed[processKey]
  33827. // }
  33828. return config
  33829. }
  33830. var expand_1 = expand;
  33831. function loadEnv(mode, envDir, prefixes = 'VITE_') {
  33832. if (mode === 'local') {
  33833. throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
  33834. `the .local postfix for .env files.`);
  33835. }
  33836. prefixes = arraify(prefixes);
  33837. const env = {};
  33838. const envFiles = [
  33839. /** default file */ `.env`,
  33840. /** local file */ `.env.local`,
  33841. /** mode file */ `.env.${mode}`,
  33842. /** mode local file */ `.env.${mode}.local`,
  33843. ];
  33844. const parsed = Object.fromEntries(envFiles.flatMap((file) => {
  33845. const filePath = path$o.join(envDir, file);
  33846. if (!tryStatSync(filePath)?.isFile())
  33847. return [];
  33848. return Object.entries(parse_1$1(fs$l.readFileSync(filePath)));
  33849. }));
  33850. // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this
  33851. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
  33852. process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  33853. }
  33854. // support BROWSER and BROWSER_ARGS env variables
  33855. if (parsed.BROWSER && process.env.BROWSER === undefined) {
  33856. process.env.BROWSER = parsed.BROWSER;
  33857. }
  33858. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {
  33859. process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  33860. }
  33861. // let environment variables use each other
  33862. // `expand` patched in patches/dotenv-expand@9.0.0.patch
  33863. expand_1({ parsed });
  33864. // only keys that start with prefix are exposed to client
  33865. for (const [key, value] of Object.entries(parsed)) {
  33866. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  33867. env[key] = value;
  33868. }
  33869. }
  33870. // check if there are actual env variables starting with VITE_*
  33871. // these are typically provided inline and should be prioritized
  33872. for (const key in process.env) {
  33873. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  33874. env[key] = process.env[key];
  33875. }
  33876. }
  33877. return env;
  33878. }
  33879. function resolveEnvPrefix({ envPrefix = 'VITE_', }) {
  33880. envPrefix = arraify(envPrefix);
  33881. if (envPrefix.some((prefix) => prefix === '')) {
  33882. throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  33883. }
  33884. return envPrefix;
  33885. }
  33886. const modulePreloadPolyfillId = 'vite/modulepreload-polyfill';
  33887. const resolvedModulePreloadPolyfillId = '\0' + modulePreloadPolyfillId;
  33888. function modulePreloadPolyfillPlugin(config) {
  33889. // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`
  33890. const skip = config.command !== 'build' || config.build.ssr;
  33891. let polyfillString;
  33892. return {
  33893. name: 'vite:modulepreload-polyfill',
  33894. resolveId(id) {
  33895. if (id === modulePreloadPolyfillId) {
  33896. return resolvedModulePreloadPolyfillId;
  33897. }
  33898. },
  33899. load(id) {
  33900. if (id === resolvedModulePreloadPolyfillId) {
  33901. if (skip) {
  33902. return '';
  33903. }
  33904. if (!polyfillString) {
  33905. polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
  33906. }
  33907. return { code: polyfillString, moduleSideEffects: true };
  33908. }
  33909. },
  33910. };
  33911. }
  33912. function polyfill() {
  33913. const relList = document.createElement('link').relList;
  33914. if (relList && relList.supports && relList.supports('modulepreload')) {
  33915. return;
  33916. }
  33917. for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
  33918. processPreload(link);
  33919. }
  33920. new MutationObserver((mutations) => {
  33921. for (const mutation of mutations) {
  33922. if (mutation.type !== 'childList') {
  33923. continue;
  33924. }
  33925. for (const node of mutation.addedNodes) {
  33926. if (node.tagName === 'LINK' && node.rel === 'modulepreload')
  33927. processPreload(node);
  33928. }
  33929. }
  33930. }).observe(document, { childList: true, subtree: true });
  33931. function getFetchOpts(link) {
  33932. const fetchOpts = {};
  33933. if (link.integrity)
  33934. fetchOpts.integrity = link.integrity;
  33935. if (link.referrerPolicy)
  33936. fetchOpts.referrerPolicy = link.referrerPolicy;
  33937. if (link.crossOrigin === 'use-credentials')
  33938. fetchOpts.credentials = 'include';
  33939. else if (link.crossOrigin === 'anonymous')
  33940. fetchOpts.credentials = 'omit';
  33941. else
  33942. fetchOpts.credentials = 'same-origin';
  33943. return fetchOpts;
  33944. }
  33945. function processPreload(link) {
  33946. if (link.ep)
  33947. // ep marker = processed
  33948. return;
  33949. link.ep = true;
  33950. // prepopulate the load record
  33951. const fetchOpts = getFetchOpts(link);
  33952. fetch(link.href, fetchOpts);
  33953. }
  33954. }
  33955. const htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(js|css)$/;
  33956. const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
  33957. // Do not allow preceding '.', but do allow preceding '...' for spread operations
  33958. const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/g;
  33959. const htmlLangRE = /\.(?:html|htm)$/;
  33960. const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
  33961. const moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
  33962. const modulePreloadLinkRE = /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i;
  33963. const importMapAppendRE = new RegExp([moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join('|'), 'i');
  33964. const isHTMLProxy = (id) => htmlProxyRE$1.test(id);
  33965. const isHTMLRequest = (request) => htmlLangRE.test(request);
  33966. // HTML Proxy Caches are stored by config -> filePath -> index
  33967. const htmlProxyMap = new WeakMap();
  33968. // HTML Proxy Transform result are stored by config
  33969. // `${hash(importer)}_${query.index}` -> transformed css code
  33970. // PS: key like `hash(/vite/playground/assets/index.html)_1`)
  33971. const htmlProxyResult = new Map();
  33972. function htmlInlineProxyPlugin(config) {
  33973. // Should do this when `constructor` rather than when `buildStart`,
  33974. // `buildStart` will be triggered multiple times then the cached result will be emptied.
  33975. // https://github.com/vitejs/vite/issues/6372
  33976. htmlProxyMap.set(config, new Map());
  33977. return {
  33978. name: 'vite:html-inline-proxy',
  33979. resolveId(id) {
  33980. if (htmlProxyRE$1.test(id)) {
  33981. return id;
  33982. }
  33983. },
  33984. load(id) {
  33985. const proxyMatch = id.match(htmlProxyRE$1);
  33986. if (proxyMatch) {
  33987. const index = Number(proxyMatch[1]);
  33988. const file = cleanUrl(id);
  33989. const url = file.replace(normalizePath$3(config.root), '');
  33990. const result = htmlProxyMap.get(config).get(url)?.[index];
  33991. if (result) {
  33992. return result;
  33993. }
  33994. else {
  33995. throw new Error(`No matching HTML proxy module found from ${id}`);
  33996. }
  33997. }
  33998. },
  33999. };
  34000. }
  34001. function addToHTMLProxyCache(config, filePath, index, result) {
  34002. if (!htmlProxyMap.get(config)) {
  34003. htmlProxyMap.set(config, new Map());
  34004. }
  34005. if (!htmlProxyMap.get(config).get(filePath)) {
  34006. htmlProxyMap.get(config).set(filePath, []);
  34007. }
  34008. htmlProxyMap.get(config).get(filePath)[index] = result;
  34009. }
  34010. function addToHTMLProxyTransformResult(hash, code) {
  34011. htmlProxyResult.set(hash, code);
  34012. }
  34013. // this extends the config in @vue/compiler-sfc with <link href>
  34014. const assetAttrsConfig = {
  34015. link: ['href'],
  34016. video: ['src', 'poster'],
  34017. source: ['src', 'srcset'],
  34018. img: ['src', 'srcset'],
  34019. image: ['xlink:href', 'href'],
  34020. use: ['xlink:href', 'href'],
  34021. };
  34022. const isAsyncScriptMap = new WeakMap();
  34023. function nodeIsElement(node) {
  34024. return node.nodeName[0] !== '#';
  34025. }
  34026. function traverseNodes(node, visitor) {
  34027. visitor(node);
  34028. if (nodeIsElement(node) ||
  34029. node.nodeName === '#document' ||
  34030. node.nodeName === '#document-fragment') {
  34031. node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
  34032. }
  34033. }
  34034. async function traverseHtml(html, filePath, visitor) {
  34035. // lazy load compiler
  34036. const { parse } = await import('./dep-f0c7dae0.js');
  34037. const ast = parse(html, {
  34038. scriptingEnabled: false,
  34039. sourceCodeLocationInfo: true,
  34040. onParseError: (e) => {
  34041. handleParseError(e, html, filePath);
  34042. },
  34043. });
  34044. traverseNodes(ast, visitor);
  34045. }
  34046. function getScriptInfo(node) {
  34047. let src;
  34048. let sourceCodeLocation;
  34049. let isModule = false;
  34050. let isAsync = false;
  34051. for (const p of node.attrs) {
  34052. if (p.prefix !== undefined)
  34053. continue;
  34054. if (p.name === 'src') {
  34055. if (!src) {
  34056. src = p;
  34057. sourceCodeLocation = node.sourceCodeLocation?.attrs['src'];
  34058. }
  34059. }
  34060. else if (p.name === 'type' && p.value && p.value === 'module') {
  34061. isModule = true;
  34062. }
  34063. else if (p.name === 'async') {
  34064. isAsync = true;
  34065. }
  34066. }
  34067. return { src, sourceCodeLocation, isModule, isAsync };
  34068. }
  34069. const attrValueStartRE = /=\s*(.)/;
  34070. function overwriteAttrValue(s, sourceCodeLocation, newValue) {
  34071. const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset);
  34072. const valueStart = srcString.match(attrValueStartRE);
  34073. if (!valueStart) {
  34074. // overwrite attr value can only be called for a well-defined value
  34075. throw new Error(`[vite:html] internal error, failed to overwrite attribute value`);
  34076. }
  34077. const wrapOffset = valueStart[1] === '"' || valueStart[1] === "'" ? 1 : 0;
  34078. const valueOffset = valueStart.index + valueStart[0].length - 1;
  34079. s.update(sourceCodeLocation.startOffset + valueOffset + wrapOffset, sourceCodeLocation.endOffset - wrapOffset, newValue);
  34080. return s;
  34081. }
  34082. /**
  34083. * Format parse5 @type {ParserError} to @type {RollupError}
  34084. */
  34085. function formatParseError(parserError, id, html) {
  34086. const formattedError = {
  34087. code: parserError.code,
  34088. message: `parse5 error code ${parserError.code}`,
  34089. frame: generateCodeFrame(html, parserError.startOffset),
  34090. loc: {
  34091. file: id,
  34092. line: parserError.startLine,
  34093. column: parserError.startCol,
  34094. },
  34095. };
  34096. return formattedError;
  34097. }
  34098. function handleParseError(parserError, html, filePath) {
  34099. switch (parserError.code) {
  34100. case 'missing-doctype':
  34101. // ignore missing DOCTYPE
  34102. return;
  34103. case 'abandoned-head-element-child':
  34104. // Accept elements without closing tag in <head>
  34105. return;
  34106. case 'duplicate-attribute':
  34107. // Accept duplicate attributes #9566
  34108. // The first attribute is used, browsers silently ignore duplicates
  34109. return;
  34110. case 'non-void-html-element-start-tag-with-trailing-solidus':
  34111. // Allow self closing on non-void elements #10439
  34112. return;
  34113. }
  34114. const parseError = formatParseError(parserError, filePath, html);
  34115. throw new Error(`Unable to parse HTML; ${parseError.message}\n` +
  34116. ` at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` +
  34117. `${parseError.frame}`);
  34118. }
  34119. /**
  34120. * Compiles index.html into an entry js module
  34121. */
  34122. function buildHtmlPlugin(config) {
  34123. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  34124. preHooks.unshift(preImportMapHook(config));
  34125. preHooks.push(htmlEnvHook(config));
  34126. postHooks.push(postImportMapHook());
  34127. const processedHtml = new Map();
  34128. const isExcludedUrl = (url) => url[0] === '#' ||
  34129. isExternalUrl(url) ||
  34130. isDataUrl(url) ||
  34131. checkPublicFile(url, config);
  34132. // Same reason with `htmlInlineProxyPlugin`
  34133. isAsyncScriptMap.set(config, new Map());
  34134. return {
  34135. name: 'vite:build-html',
  34136. async transform(html, id) {
  34137. if (id.endsWith('.html')) {
  34138. const relativeUrlPath = path$o.posix.relative(config.root, normalizePath$3(id));
  34139. const publicPath = `/${relativeUrlPath}`;
  34140. const publicBase = getBaseInHTML(relativeUrlPath, config);
  34141. const publicToRelative = (filename, importer) => publicBase + filename;
  34142. const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(url.slice(1), 'public', relativeUrlPath, 'html', config, publicToRelative);
  34143. // pre-transform
  34144. html = await applyHtmlTransforms(html, preHooks, {
  34145. path: publicPath,
  34146. filename: id,
  34147. });
  34148. let js = '';
  34149. const s = new MagicString(html);
  34150. const assetUrls = [];
  34151. const scriptUrls = [];
  34152. const styleUrls = [];
  34153. let inlineModuleIndex = -1;
  34154. let everyScriptIsAsync = true;
  34155. let someScriptsAreAsync = false;
  34156. let someScriptsAreDefer = false;
  34157. await traverseHtml(html, id, (node) => {
  34158. if (!nodeIsElement(node)) {
  34159. return;
  34160. }
  34161. let shouldRemove = false;
  34162. // script tags
  34163. if (node.nodeName === 'script') {
  34164. const { src, sourceCodeLocation, isModule, isAsync } = getScriptInfo(node);
  34165. const url = src && src.value;
  34166. const isPublicFile = !!(url && checkPublicFile(url, config));
  34167. if (isPublicFile) {
  34168. // referencing public dir url, prefix with base
  34169. overwriteAttrValue(s, sourceCodeLocation, toOutputPublicFilePath(url));
  34170. }
  34171. if (isModule) {
  34172. inlineModuleIndex++;
  34173. if (url && !isExcludedUrl(url)) {
  34174. // <script type="module" src="..."/>
  34175. // add it as an import
  34176. js += `\nimport ${JSON.stringify(url)}`;
  34177. shouldRemove = true;
  34178. }
  34179. else if (node.childNodes.length) {
  34180. const scriptNode = node.childNodes.pop();
  34181. const contents = scriptNode.value;
  34182. // <script type="module">...</script>
  34183. const filePath = id.replace(normalizePath$3(config.root), '');
  34184. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  34185. code: contents,
  34186. });
  34187. js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  34188. shouldRemove = true;
  34189. }
  34190. everyScriptIsAsync && (everyScriptIsAsync = isAsync);
  34191. someScriptsAreAsync || (someScriptsAreAsync = isAsync);
  34192. someScriptsAreDefer || (someScriptsAreDefer = !isAsync);
  34193. }
  34194. else if (url && !isPublicFile) {
  34195. if (!isExcludedUrl(url)) {
  34196. config.logger.warn(`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`);
  34197. }
  34198. }
  34199. else if (node.childNodes.length) {
  34200. const scriptNode = node.childNodes.pop();
  34201. const cleanCode = stripLiteral(scriptNode.value);
  34202. let match;
  34203. inlineImportRE.lastIndex = 0;
  34204. while ((match = inlineImportRE.exec(cleanCode))) {
  34205. const { 1: url, index } = match;
  34206. const startUrl = cleanCode.indexOf(url, index);
  34207. const start = startUrl + 1;
  34208. const end = start + url.length - 2;
  34209. const startOffset = scriptNode.sourceCodeLocation.startOffset;
  34210. scriptUrls.push({
  34211. start: start + startOffset,
  34212. end: end + startOffset,
  34213. url: scriptNode.value.slice(start, end),
  34214. });
  34215. }
  34216. }
  34217. }
  34218. // For asset references in index.html, also generate an import
  34219. // statement for each - this will be handled by the asset plugin
  34220. const assetAttrs = assetAttrsConfig[node.nodeName];
  34221. if (assetAttrs) {
  34222. for (const p of node.attrs) {
  34223. const attrKey = getAttrKey(p);
  34224. if (p.value && assetAttrs.includes(attrKey)) {
  34225. const attrSourceCodeLocation = node.sourceCodeLocation.attrs[attrKey];
  34226. // assetsUrl may be encodeURI
  34227. const url = decodeURI(p.value);
  34228. if (!isExcludedUrl(url)) {
  34229. if (node.nodeName === 'link' &&
  34230. isCSSRequest(url) &&
  34231. // should not be converted if following attributes are present (#6748)
  34232. !node.attrs.some((p) => p.prefix === undefined &&
  34233. (p.name === 'media' || p.name === 'disabled'))) {
  34234. // CSS references, convert to import
  34235. const importExpression = `\nimport ${JSON.stringify(url)}`;
  34236. styleUrls.push({
  34237. url,
  34238. start: node.sourceCodeLocation.startOffset,
  34239. end: node.sourceCodeLocation.endOffset,
  34240. });
  34241. js += importExpression;
  34242. }
  34243. else {
  34244. assetUrls.push({
  34245. attr: p,
  34246. sourceCodeLocation: attrSourceCodeLocation,
  34247. });
  34248. }
  34249. }
  34250. else if (checkPublicFile(url, config)) {
  34251. overwriteAttrValue(s, attrSourceCodeLocation, toOutputPublicFilePath(url));
  34252. }
  34253. }
  34254. }
  34255. }
  34256. // <tag style="... url(...) or image-set(...) ..."></tag>
  34257. // extract inline styles as virtual css and add class attribute to tag for selecting
  34258. const inlineStyle = node.attrs.find((prop) => prop.prefix === undefined &&
  34259. prop.name === 'style' &&
  34260. // only url(...) or image-set(...) in css need to emit file
  34261. (prop.value.includes('url(') ||
  34262. prop.value.includes('image-set(')));
  34263. if (inlineStyle) {
  34264. inlineModuleIndex++;
  34265. // replace `inline style` to class
  34266. // and import css in js code
  34267. const code = inlineStyle.value;
  34268. const filePath = id.replace(normalizePath$3(config.root), '');
  34269. addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code });
  34270. // will transform with css plugin and cache result with css-post plugin
  34271. js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
  34272. const hash = getHash(cleanUrl(id));
  34273. // will transform in `applyHtmlTransforms`
  34274. const sourceCodeLocation = node.sourceCodeLocation.attrs['style'];
  34275. overwriteAttrValue(s, sourceCodeLocation, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  34276. }
  34277. // <style>...</style>
  34278. if (node.nodeName === 'style' && node.childNodes.length) {
  34279. const styleNode = node.childNodes.pop();
  34280. const filePath = id.replace(normalizePath$3(config.root), '');
  34281. inlineModuleIndex++;
  34282. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  34283. code: styleNode.value,
  34284. });
  34285. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  34286. const hash = getHash(cleanUrl(id));
  34287. // will transform in `applyHtmlTransforms`
  34288. s.update(styleNode.sourceCodeLocation.startOffset, styleNode.sourceCodeLocation.endOffset, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
  34289. }
  34290. if (shouldRemove) {
  34291. // remove the script tag from the html. we are going to inject new
  34292. // ones in the end.
  34293. s.remove(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset);
  34294. }
  34295. });
  34296. isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
  34297. if (someScriptsAreAsync && someScriptsAreDefer) {
  34298. config.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`);
  34299. }
  34300. // for each encountered asset url, rewrite original html so that it
  34301. // references the post-build location, ignoring empty attributes and
  34302. // attributes that directly reference named output.
  34303. const namedOutput = Object.keys(config?.build?.rollupOptions?.input || {});
  34304. for (const { attr, sourceCodeLocation } of assetUrls) {
  34305. // assetsUrl may be encodeURI
  34306. const content = decodeURI(attr.value);
  34307. if (content !== '' && // Empty attribute
  34308. !namedOutput.includes(content) && // Direct reference to named output
  34309. !namedOutput.includes(removeLeadingSlash(content)) // Allow for absolute references as named output can't be an absolute path
  34310. ) {
  34311. try {
  34312. const url = attr.prefix === undefined && attr.name === 'srcset'
  34313. ? await processSrcSet(content, ({ url }) => urlToBuiltUrl(url, id, config, this))
  34314. : await urlToBuiltUrl(content, id, config, this);
  34315. overwriteAttrValue(s, sourceCodeLocation, url);
  34316. }
  34317. catch (e) {
  34318. if (e.code !== 'ENOENT') {
  34319. throw e;
  34320. }
  34321. }
  34322. }
  34323. }
  34324. // emit <script>import("./aaa")</script> asset
  34325. for (const { start, end, url } of scriptUrls) {
  34326. if (!isExcludedUrl(url)) {
  34327. s.update(start, end, await urlToBuiltUrl(url, id, config, this));
  34328. }
  34329. else if (checkPublicFile(url, config)) {
  34330. s.update(start, end, toOutputPublicFilePath(url));
  34331. }
  34332. }
  34333. // ignore <link rel="stylesheet"> if its url can't be resolved
  34334. const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({
  34335. ...styleUrl,
  34336. resolved: await this.resolve(styleUrl.url, id),
  34337. })));
  34338. for (const { start, end, url, resolved } of resolvedStyleUrls) {
  34339. if (resolved == null) {
  34340. config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  34341. const importExpression = `\nimport ${JSON.stringify(url)}`;
  34342. js = js.replace(importExpression, '');
  34343. }
  34344. else {
  34345. s.remove(start, end);
  34346. }
  34347. }
  34348. processedHtml.set(id, s.toString());
  34349. // inject module preload polyfill only when configured and needed
  34350. const { modulePreload } = config.build;
  34351. if (modulePreload !== false &&
  34352. modulePreload.polyfill &&
  34353. (someScriptsAreAsync || someScriptsAreDefer)) {
  34354. js = `import "${modulePreloadPolyfillId}";\n${js}`;
  34355. }
  34356. // Force rollup to keep this module from being shared between other entry points.
  34357. // If the resulting chunk is empty, it will be removed in generateBundle.
  34358. return { code: js, moduleSideEffects: 'no-treeshake' };
  34359. }
  34360. },
  34361. async generateBundle(options, bundle) {
  34362. const analyzedChunk = new Map();
  34363. const inlineEntryChunk = new Set();
  34364. const getImportedChunks = (chunk, seen = new Set()) => {
  34365. const chunks = [];
  34366. chunk.imports.forEach((file) => {
  34367. const importee = bundle[file];
  34368. if (importee?.type === 'chunk' && !seen.has(file)) {
  34369. seen.add(file);
  34370. // post-order traversal
  34371. chunks.push(...getImportedChunks(importee, seen));
  34372. chunks.push(importee);
  34373. }
  34374. });
  34375. return chunks;
  34376. };
  34377. const toScriptTag = (chunk, toOutputPath, isAsync) => ({
  34378. tag: 'script',
  34379. attrs: {
  34380. ...(isAsync ? { async: true } : {}),
  34381. type: 'module',
  34382. crossorigin: true,
  34383. src: toOutputPath(chunk.fileName),
  34384. },
  34385. });
  34386. const toPreloadTag = (filename, toOutputPath) => ({
  34387. tag: 'link',
  34388. attrs: {
  34389. rel: 'modulepreload',
  34390. crossorigin: true,
  34391. href: toOutputPath(filename),
  34392. },
  34393. });
  34394. const getCssTagsForChunk = (chunk, toOutputPath, seen = new Set()) => {
  34395. const tags = [];
  34396. if (!analyzedChunk.has(chunk)) {
  34397. analyzedChunk.set(chunk, 1);
  34398. chunk.imports.forEach((file) => {
  34399. const importee = bundle[file];
  34400. if (importee?.type === 'chunk') {
  34401. tags.push(...getCssTagsForChunk(importee, toOutputPath, seen));
  34402. }
  34403. });
  34404. }
  34405. chunk.viteMetadata.importedCss.forEach((file) => {
  34406. if (!seen.has(file)) {
  34407. seen.add(file);
  34408. tags.push({
  34409. tag: 'link',
  34410. attrs: {
  34411. rel: 'stylesheet',
  34412. href: toOutputPath(file),
  34413. },
  34414. });
  34415. }
  34416. });
  34417. return tags;
  34418. };
  34419. for (const [id, html] of processedHtml) {
  34420. const relativeUrlPath = path$o.posix.relative(config.root, normalizePath$3(id));
  34421. const assetsBase = getBaseInHTML(relativeUrlPath, config);
  34422. const toOutputFilePath = (filename, type) => {
  34423. if (isExternalUrl(filename)) {
  34424. return filename;
  34425. }
  34426. else {
  34427. return toOutputFilePathInHtml(filename, type, relativeUrlPath, 'html', config, (filename, importer) => assetsBase + filename);
  34428. }
  34429. };
  34430. const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, 'asset');
  34431. const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, 'public');
  34432. const isAsync = isAsyncScriptMap.get(config).get(id);
  34433. let result = html;
  34434. // find corresponding entry chunk
  34435. const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' &&
  34436. chunk.isEntry &&
  34437. chunk.facadeModuleId === id);
  34438. let canInlineEntry = false;
  34439. // inject chunk asset links
  34440. if (chunk) {
  34441. // an entry chunk can be inlined if
  34442. // - it's an ES module (e.g. not generated by the legacy plugin)
  34443. // - it contains no meaningful code other than import statements
  34444. if (options.format === 'es' && isEntirelyImport(chunk.code)) {
  34445. canInlineEntry = true;
  34446. }
  34447. // when not inlined, inject <script> for entry and modulepreload its dependencies
  34448. // when inlined, discard entry chunk and inject <script> for everything in post-order
  34449. const imports = getImportedChunks(chunk);
  34450. let assetTags;
  34451. if (canInlineEntry) {
  34452. assetTags = imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync));
  34453. }
  34454. else {
  34455. assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
  34456. const { modulePreload } = config.build;
  34457. if (modulePreload !== false) {
  34458. const resolveDependencies = typeof modulePreload === 'object' &&
  34459. modulePreload.resolveDependencies;
  34460. const importsFileNames = imports.map((chunk) => chunk.fileName);
  34461. const resolvedDeps = resolveDependencies
  34462. ? resolveDependencies(chunk.fileName, importsFileNames, {
  34463. hostId: relativeUrlPath,
  34464. hostType: 'html',
  34465. })
  34466. : importsFileNames;
  34467. assetTags.push(...resolvedDeps.map((i) => toPreloadTag(i, toOutputAssetFilePath)));
  34468. }
  34469. }
  34470. assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
  34471. result = injectToHead(result, assetTags);
  34472. }
  34473. // inject css link when cssCodeSplit is false
  34474. if (!config.build.cssCodeSplit) {
  34475. const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css');
  34476. if (cssChunk) {
  34477. result = injectToHead(result, [
  34478. {
  34479. tag: 'link',
  34480. attrs: {
  34481. rel: 'stylesheet',
  34482. href: toOutputAssetFilePath(cssChunk.fileName),
  34483. },
  34484. },
  34485. ]);
  34486. }
  34487. }
  34488. // no use assets plugin because it will emit file
  34489. let match;
  34490. let s;
  34491. inlineCSSRE$1.lastIndex = 0;
  34492. while ((match = inlineCSSRE$1.exec(result))) {
  34493. s || (s = new MagicString(result));
  34494. const { 0: full, 1: scopedName } = match;
  34495. const cssTransformedCode = htmlProxyResult.get(scopedName);
  34496. s.update(match.index, match.index + full.length, cssTransformedCode);
  34497. }
  34498. if (s) {
  34499. result = s.toString();
  34500. }
  34501. result = await applyHtmlTransforms(result, [...normalHooks, ...postHooks], {
  34502. path: '/' + relativeUrlPath,
  34503. filename: id,
  34504. bundle,
  34505. chunk,
  34506. });
  34507. // resolve asset url references
  34508. result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  34509. return toOutputAssetFilePath(this.getFileName(fileHash)) + postfix;
  34510. });
  34511. result = result.replace(publicAssetUrlRE, (_, fileHash) => {
  34512. const publicAssetPath = toOutputPublicAssetFilePath(getPublicAssetFilename(fileHash, config));
  34513. return isUrl(publicAssetPath)
  34514. ? publicAssetPath
  34515. : normalizePath$3(publicAssetPath);
  34516. });
  34517. if (chunk && canInlineEntry) {
  34518. inlineEntryChunk.add(chunk.fileName);
  34519. }
  34520. const shortEmitName = normalizePath$3(path$o.relative(config.root, id));
  34521. this.emitFile({
  34522. type: 'asset',
  34523. fileName: shortEmitName,
  34524. source: result,
  34525. });
  34526. }
  34527. for (const fileName of inlineEntryChunk) {
  34528. // all imports from entry have been inlined to html, prevent rollup from outputting it
  34529. delete bundle[fileName];
  34530. }
  34531. },
  34532. };
  34533. }
  34534. function preImportMapHook(config) {
  34535. return (html, ctx) => {
  34536. const importMapIndex = html.match(importMapRE)?.index;
  34537. if (importMapIndex === undefined)
  34538. return;
  34539. const importMapAppendIndex = html.match(importMapAppendRE)?.index;
  34540. if (importMapAppendIndex === undefined)
  34541. return;
  34542. if (importMapAppendIndex < importMapIndex) {
  34543. const relativeHtml = normalizePath$3(path$o.relative(config.root, ctx.filename));
  34544. config.logger.warnOnce(colors$1.yellow(colors$1.bold(`(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`)));
  34545. }
  34546. };
  34547. }
  34548. /**
  34549. * Move importmap before the first module script and modulepreload link
  34550. */
  34551. function postImportMapHook() {
  34552. return (html) => {
  34553. if (!importMapAppendRE.test(html))
  34554. return;
  34555. let importMap;
  34556. html = html.replace(importMapRE, (match) => {
  34557. importMap = match;
  34558. return '';
  34559. });
  34560. if (importMap) {
  34561. html = html.replace(importMapAppendRE, (match) => `${importMap}\n${match}`);
  34562. }
  34563. return html;
  34564. };
  34565. }
  34566. /**
  34567. * Support `%ENV_NAME%` syntax in html files
  34568. */
  34569. function htmlEnvHook(config) {
  34570. const pattern = /%(\S+?)%/g;
  34571. const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
  34572. const env = { ...config.env };
  34573. // account for user env defines
  34574. for (const key in config.define) {
  34575. if (key.startsWith(`import.meta.env.`)) {
  34576. const val = config.define[key];
  34577. if (typeof val === 'string') {
  34578. try {
  34579. const parsed = JSON.parse(val);
  34580. env[key.slice(16)] = typeof parsed === 'string' ? parsed : val;
  34581. }
  34582. catch {
  34583. env[key.slice(16)] = val;
  34584. }
  34585. }
  34586. else {
  34587. env[key.slice(16)] = JSON.stringify(val);
  34588. }
  34589. }
  34590. }
  34591. return (html, ctx) => {
  34592. return html.replace(pattern, (text, key) => {
  34593. if (key in env) {
  34594. return env[key];
  34595. }
  34596. else {
  34597. if (envPrefix.some((prefix) => key.startsWith(prefix))) {
  34598. const relativeHtml = normalizePath$3(path$o.relative(config.root, ctx.filename));
  34599. config.logger.warn(colors$1.yellow(colors$1.bold(`(!) ${text} is not defined in env variables found in /${relativeHtml}. ` +
  34600. `Is the variable mistyped?`)));
  34601. }
  34602. return text;
  34603. }
  34604. });
  34605. };
  34606. }
  34607. function resolveHtmlTransforms(plugins) {
  34608. const preHooks = [];
  34609. const normalHooks = [];
  34610. const postHooks = [];
  34611. for (const plugin of plugins) {
  34612. const hook = plugin.transformIndexHtml;
  34613. if (!hook)
  34614. continue;
  34615. if (typeof hook === 'function') {
  34616. normalHooks.push(hook);
  34617. }
  34618. else {
  34619. // `enforce` had only two possible values for the `transformIndexHtml` hook
  34620. // `'pre'` and `'post'` (the default). `order` now works with three values
  34621. // to align with other hooks (`'pre'`, normal, and `'post'`). We map
  34622. // both `enforce: 'post'` to `order: undefined` to avoid a breaking change
  34623. const order = hook.order ?? (hook.enforce === 'pre' ? 'pre' : undefined);
  34624. // @ts-expect-error union type
  34625. const handler = hook.handler ?? hook.transform;
  34626. if (order === 'pre') {
  34627. preHooks.push(handler);
  34628. }
  34629. else if (order === 'post') {
  34630. postHooks.push(handler);
  34631. }
  34632. else {
  34633. normalHooks.push(handler);
  34634. }
  34635. }
  34636. }
  34637. return [preHooks, normalHooks, postHooks];
  34638. }
  34639. async function applyHtmlTransforms(html, hooks, ctx) {
  34640. for (const hook of hooks) {
  34641. const res = await hook(html, ctx);
  34642. if (!res) {
  34643. continue;
  34644. }
  34645. if (typeof res === 'string') {
  34646. html = res;
  34647. }
  34648. else {
  34649. let tags;
  34650. if (Array.isArray(res)) {
  34651. tags = res;
  34652. }
  34653. else {
  34654. html = res.html || html;
  34655. tags = res.tags;
  34656. }
  34657. const headTags = [];
  34658. const headPrependTags = [];
  34659. const bodyTags = [];
  34660. const bodyPrependTags = [];
  34661. for (const tag of tags) {
  34662. if (tag.injectTo === 'body') {
  34663. bodyTags.push(tag);
  34664. }
  34665. else if (tag.injectTo === 'body-prepend') {
  34666. bodyPrependTags.push(tag);
  34667. }
  34668. else if (tag.injectTo === 'head') {
  34669. headTags.push(tag);
  34670. }
  34671. else {
  34672. headPrependTags.push(tag);
  34673. }
  34674. }
  34675. html = injectToHead(html, headPrependTags, true);
  34676. html = injectToHead(html, headTags);
  34677. html = injectToBody(html, bodyPrependTags, true);
  34678. html = injectToBody(html, bodyTags);
  34679. }
  34680. }
  34681. return html;
  34682. }
  34683. const importRE = /\bimport\s*("[^"]*[^\\]"|'[^']*[^\\]');*/g;
  34684. const commentRE$1 = /\/\*[\s\S]*?\*\/|\/\/.*$/gm;
  34685. function isEntirelyImport(code) {
  34686. // only consider "side-effect" imports, which match <script type=module> semantics exactly
  34687. // the regexes will remove too little in some exotic cases, but false-negatives are alright
  34688. return !code.replace(importRE, '').replace(commentRE$1, '').trim().length;
  34689. }
  34690. function getBaseInHTML(urlRelativePath, config) {
  34691. // Prefer explicit URL if defined for linking to assets and public files from HTML,
  34692. // even when base relative is specified
  34693. return config.base === './' || config.base === ''
  34694. ? path$o.posix.join(path$o.posix.relative(urlRelativePath, '').slice(0, -2), './')
  34695. : config.base;
  34696. }
  34697. const headInjectRE = /([ \t]*)<\/head>/i;
  34698. const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
  34699. const htmlInjectRE = /<\/html>/i;
  34700. const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
  34701. const bodyInjectRE = /([ \t]*)<\/body>/i;
  34702. const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
  34703. const doctypePrependInjectRE = /<!doctype html>/i;
  34704. function injectToHead(html, tags, prepend = false) {
  34705. if (tags.length === 0)
  34706. return html;
  34707. if (prepend) {
  34708. // inject as the first element of head
  34709. if (headPrependInjectRE.test(html)) {
  34710. return html.replace(headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  34711. }
  34712. }
  34713. else {
  34714. // inject before head close
  34715. if (headInjectRE.test(html)) {
  34716. // respect indentation of head tag
  34717. return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  34718. }
  34719. // try to inject before the body tag
  34720. if (bodyPrependInjectRE.test(html)) {
  34721. return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
  34722. }
  34723. }
  34724. // if no head tag is present, we prepend the tag for both prepend and append
  34725. return prependInjectFallback(html, tags);
  34726. }
  34727. function injectToBody(html, tags, prepend = false) {
  34728. if (tags.length === 0)
  34729. return html;
  34730. if (prepend) {
  34731. // inject after body open
  34732. if (bodyPrependInjectRE.test(html)) {
  34733. return html.replace(bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  34734. }
  34735. // if no there is no body tag, inject after head or fallback to prepend in html
  34736. if (headInjectRE.test(html)) {
  34737. return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
  34738. }
  34739. return prependInjectFallback(html, tags);
  34740. }
  34741. else {
  34742. // inject before body close
  34743. if (bodyInjectRE.test(html)) {
  34744. return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  34745. }
  34746. // if no body tag is present, append to the html tag, or at the end of the file
  34747. if (htmlInjectRE.test(html)) {
  34748. return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
  34749. }
  34750. return html + `\n` + serializeTags(tags);
  34751. }
  34752. }
  34753. function prependInjectFallback(html, tags) {
  34754. // prepend to the html tag, append after doctype, or the document start
  34755. if (htmlPrependInjectRE.test(html)) {
  34756. return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
  34757. }
  34758. if (doctypePrependInjectRE.test(html)) {
  34759. return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
  34760. }
  34761. return serializeTags(tags) + html;
  34762. }
  34763. const unaryTags = new Set(['link', 'meta', 'base']);
  34764. function serializeTag({ tag, attrs, children }, indent = '') {
  34765. if (unaryTags.has(tag)) {
  34766. return `<${tag}${serializeAttrs(attrs)}>`;
  34767. }
  34768. else {
  34769. return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
  34770. }
  34771. }
  34772. function serializeTags(tags, indent = '') {
  34773. if (typeof tags === 'string') {
  34774. return tags;
  34775. }
  34776. else if (tags && tags.length) {
  34777. return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join('');
  34778. }
  34779. return '';
  34780. }
  34781. function serializeAttrs(attrs) {
  34782. let res = '';
  34783. for (const key in attrs) {
  34784. if (typeof attrs[key] === 'boolean') {
  34785. res += attrs[key] ? ` ${key}` : ``;
  34786. }
  34787. else {
  34788. res += ` ${key}=${JSON.stringify(attrs[key])}`;
  34789. }
  34790. }
  34791. return res;
  34792. }
  34793. function incrementIndent(indent = '') {
  34794. return `${indent}${indent[0] === '\t' ? '\t' : ' '}`;
  34795. }
  34796. function getAttrKey(attr) {
  34797. return attr.prefix === undefined ? attr.name : `${attr.prefix}:${attr.name}`;
  34798. }
  34799. function resolveCSSOptions(options) {
  34800. if (options?.lightningcss) {
  34801. return {
  34802. ...options,
  34803. lightningcss: {
  34804. ...options.lightningcss,
  34805. targets: options.lightningcss.targets ??
  34806. convertTargets(ESBUILD_MODULES_TARGET),
  34807. },
  34808. };
  34809. }
  34810. // TS doesn't narrow the type with the previous if :/
  34811. return options;
  34812. }
  34813. const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
  34814. const directRequestRE = /[?&]direct\b/;
  34815. const htmlProxyRE = /[?&]html-proxy\b/;
  34816. const commonjsProxyRE = /\?commonjs-proxy/;
  34817. const inlineRE$1 = /[?&]inline\b/;
  34818. const inlineCSSRE = /[?&]inline-css\b/;
  34819. const styleAttrRE = /[?&]style-attr\b/;
  34820. const usedRE = /[?&]used\b/;
  34821. const varRE = /^var\(/i;
  34822. const cssBundleName = 'style.css';
  34823. const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
  34824. const isModuleCSSRequest = (request) => cssModuleRE.test(request);
  34825. const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
  34826. const isDirectRequest = (request) => directRequestRE.test(request);
  34827. const cssModulesCache = new WeakMap();
  34828. const removedPureCssFilesCache = new WeakMap();
  34829. const postcssConfigCache = new WeakMap();
  34830. function encodePublicUrlsInCSS(config) {
  34831. return config.command === 'build';
  34832. }
  34833. /**
  34834. * Plugin applied before user plugins
  34835. */
  34836. function cssPlugin(config) {
  34837. let server;
  34838. let moduleCache;
  34839. const resolveUrl = config.createResolver({
  34840. preferRelative: true,
  34841. tryIndex: false,
  34842. extensions: [],
  34843. });
  34844. // warm up cache for resolved postcss config
  34845. if (config.css?.transformer !== 'lightningcss') {
  34846. resolvePostcssConfig(config);
  34847. }
  34848. return {
  34849. name: 'vite:css',
  34850. configureServer(_server) {
  34851. server = _server;
  34852. },
  34853. buildStart() {
  34854. // Ensure a new cache for every build (i.e. rebuilding in watch mode)
  34855. moduleCache = new Map();
  34856. cssModulesCache.set(config, moduleCache);
  34857. removedPureCssFilesCache.set(config, new Map());
  34858. },
  34859. async transform(raw, id, options) {
  34860. if (!isCSSRequest(id) ||
  34861. commonjsProxyRE.test(id) ||
  34862. SPECIAL_QUERY_RE.test(id)) {
  34863. return;
  34864. }
  34865. const ssr = options?.ssr === true;
  34866. const urlReplacer = async (url, importer) => {
  34867. if (checkPublicFile(url, config)) {
  34868. if (encodePublicUrlsInCSS(config)) {
  34869. return publicFileToBuiltUrl(url, config);
  34870. }
  34871. else {
  34872. return joinUrlSegments(config.base, url);
  34873. }
  34874. }
  34875. const resolved = await resolveUrl(url, importer);
  34876. if (resolved) {
  34877. return fileToUrl(resolved, config, this);
  34878. }
  34879. if (config.command === 'build') {
  34880. const isExternal = config.build.rollupOptions.external
  34881. ? resolveUserExternal(config.build.rollupOptions.external, url, // use URL as id since id could not be resolved
  34882. id, false)
  34883. : false;
  34884. if (!isExternal) {
  34885. // #9800 If we cannot resolve the css url, leave a warning.
  34886. config.logger.warnOnce(`\n${url} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
  34887. }
  34888. }
  34889. return url;
  34890. };
  34891. const { code: css, modules, deps, map, } = await compileCSS(id, raw, config, urlReplacer);
  34892. if (modules) {
  34893. moduleCache.set(id, modules);
  34894. }
  34895. // track deps for build watch mode
  34896. if (config.command === 'build' && config.build.watch && deps) {
  34897. for (const file of deps) {
  34898. this.addWatchFile(file);
  34899. }
  34900. }
  34901. // dev
  34902. if (server) {
  34903. // server only logic for handling CSS @import dependency hmr
  34904. const { moduleGraph } = server;
  34905. const thisModule = moduleGraph.getModuleById(id);
  34906. if (thisModule) {
  34907. // CSS modules cannot self-accept since it exports values
  34908. const isSelfAccepting = !modules && !inlineRE$1.test(id) && !htmlProxyRE.test(id);
  34909. if (deps) {
  34910. // record deps in the module graph so edits to @import css can trigger
  34911. // main import to hot update
  34912. const depModules = new Set();
  34913. const devBase = config.base;
  34914. for (const file of deps) {
  34915. depModules.add(isCSSRequest(file)
  34916. ? moduleGraph.createFileOnlyEntry(file)
  34917. : await moduleGraph.ensureEntryFromUrl(stripBase(await fileToUrl(file, config, this), (config.server?.origin ?? '') + devBase), ssr));
  34918. }
  34919. moduleGraph.updateModuleInfo(thisModule, depModules, null,
  34920. // The root CSS proxy module is self-accepting and should not
  34921. // have an explicit accept list
  34922. new Set(), null, isSelfAccepting, ssr);
  34923. for (const file of deps) {
  34924. this.addWatchFile(file);
  34925. }
  34926. }
  34927. else {
  34928. thisModule.isSelfAccepting = isSelfAccepting;
  34929. }
  34930. }
  34931. }
  34932. return {
  34933. code: css,
  34934. map,
  34935. };
  34936. },
  34937. };
  34938. }
  34939. /**
  34940. * Plugin applied after user plugins
  34941. */
  34942. function cssPostPlugin(config) {
  34943. // styles initialization in buildStart causes a styling loss in watch
  34944. const styles = new Map();
  34945. // list of css emit tasks to guarantee the files are emitted in a deterministic order
  34946. let emitTasks = [];
  34947. let pureCssChunks;
  34948. // when there are multiple rollup outputs and extracting CSS, only emit once,
  34949. // since output formats have no effect on the generated CSS.
  34950. let outputToExtractedCSSMap;
  34951. let hasEmitted = false;
  34952. const rollupOptionsOutput = config.build.rollupOptions.output;
  34953. const assetFileNames = (Array.isArray(rollupOptionsOutput)
  34954. ? rollupOptionsOutput[0]
  34955. : rollupOptionsOutput)?.assetFileNames;
  34956. const getCssAssetDirname = (cssAssetName) => {
  34957. if (!assetFileNames) {
  34958. return config.build.assetsDir;
  34959. }
  34960. else if (typeof assetFileNames === 'string') {
  34961. return path$o.dirname(assetFileNames);
  34962. }
  34963. else {
  34964. return path$o.dirname(assetFileNames({
  34965. name: cssAssetName,
  34966. type: 'asset',
  34967. source: '/* vite internal call, ignore */',
  34968. }));
  34969. }
  34970. };
  34971. return {
  34972. name: 'vite:css-post',
  34973. renderStart() {
  34974. // Ensure new caches for every build (i.e. rebuilding in watch mode)
  34975. pureCssChunks = new Set();
  34976. outputToExtractedCSSMap = new Map();
  34977. hasEmitted = false;
  34978. emitTasks = [];
  34979. },
  34980. async transform(css, id, options) {
  34981. if (!isCSSRequest(id) ||
  34982. commonjsProxyRE.test(id) ||
  34983. SPECIAL_QUERY_RE.test(id)) {
  34984. return;
  34985. }
  34986. css = stripBomTag(css);
  34987. const inlined = inlineRE$1.test(id);
  34988. const modules = cssModulesCache.get(config).get(id);
  34989. // #6984, #7552
  34990. // `foo.module.css` => modulesCode
  34991. // `foo.module.css?inline` => cssContent
  34992. const modulesCode = modules &&
  34993. !inlined &&
  34994. dataToEsm(modules, { namedExports: true, preferConst: true });
  34995. if (config.command === 'serve') {
  34996. const getContentWithSourcemap = async (content) => {
  34997. if (config.css?.devSourcemap) {
  34998. const sourcemap = this.getCombinedSourcemap();
  34999. if (sourcemap.mappings) {
  35000. await injectSourcesContent(sourcemap, cleanUrl(id), config.logger);
  35001. }
  35002. return getCodeWithSourcemap('css', content, sourcemap);
  35003. }
  35004. return content;
  35005. };
  35006. if (isDirectCSSRequest(id)) {
  35007. return null;
  35008. }
  35009. // server only
  35010. if (options?.ssr) {
  35011. return modulesCode || `export default ${JSON.stringify(css)}`;
  35012. }
  35013. if (inlined) {
  35014. return `export default ${JSON.stringify(css)}`;
  35015. }
  35016. const cssContent = await getContentWithSourcemap(css);
  35017. const code = [
  35018. `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path$o.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
  35019. `const __vite__id = ${JSON.stringify(id)}`,
  35020. `const __vite__css = ${JSON.stringify(cssContent)}`,
  35021. `__vite__updateStyle(__vite__id, __vite__css)`,
  35022. // css modules exports change on edit so it can't self accept
  35023. `${modulesCode ||
  35024. `import.meta.hot.accept()\nexport default __vite__css`}`,
  35025. `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`,
  35026. ].join('\n');
  35027. return { code, map: { mappings: '' } };
  35028. }
  35029. // build CSS handling ----------------------------------------------------
  35030. // record css
  35031. // cache css compile result to map
  35032. // and then use the cache replace inline-style-flag when `generateBundle` in vite:build-html plugin
  35033. const inlineCSS = inlineCSSRE.test(id);
  35034. const isHTMLProxy = htmlProxyRE.test(id);
  35035. const query = parseRequest(id);
  35036. if (inlineCSS && isHTMLProxy) {
  35037. if (styleAttrRE.test(id)) {
  35038. css = css.replace(/"/g, '&quot;');
  35039. }
  35040. addToHTMLProxyTransformResult(`${getHash(cleanUrl(id))}_${Number.parseInt(query.index)}`, css);
  35041. return `export default ''`;
  35042. }
  35043. if (!inlined) {
  35044. styles.set(id, css);
  35045. }
  35046. let code;
  35047. if (usedRE.test(id)) {
  35048. if (modulesCode) {
  35049. code = modulesCode;
  35050. }
  35051. else {
  35052. let content = css;
  35053. if (config.build.cssMinify) {
  35054. content = await minifyCSS(content, config);
  35055. }
  35056. code = `export default ${JSON.stringify(content)}`;
  35057. }
  35058. }
  35059. else {
  35060. // if moduleCode exists return it **even if** it does not have `?used`
  35061. // this will disable tree-shake to work with `import './foo.module.css'` but this usually does not happen
  35062. // this is a limitation of the current approach by `?used` to make tree-shake work
  35063. // See #8936 for more details
  35064. code = modulesCode || `export default ''`;
  35065. }
  35066. return {
  35067. code,
  35068. map: { mappings: '' },
  35069. // avoid the css module from being tree-shaken so that we can retrieve
  35070. // it in renderChunk()
  35071. moduleSideEffects: inlined ? false : 'no-treeshake',
  35072. };
  35073. },
  35074. async renderChunk(code, chunk, opts) {
  35075. let chunkCSS = '';
  35076. let isPureCssChunk = true;
  35077. const ids = Object.keys(chunk.modules);
  35078. for (const id of ids) {
  35079. if (styles.has(id)) {
  35080. chunkCSS += styles.get(id);
  35081. // a css module contains JS, so it makes this not a pure css chunk
  35082. if (cssModuleRE.test(id)) {
  35083. isPureCssChunk = false;
  35084. }
  35085. }
  35086. else {
  35087. // if the module does not have a style, then it's not a pure css chunk.
  35088. // this is true because in the `transform` hook above, only modules
  35089. // that are css gets added to the `styles` map.
  35090. isPureCssChunk = false;
  35091. }
  35092. }
  35093. if (!chunkCSS) {
  35094. return null;
  35095. }
  35096. const publicAssetUrlMap = publicAssetUrlCache.get(config);
  35097. // resolve asset URL placeholders to their built file URLs
  35098. const resolveAssetUrlsInCss = (chunkCSS, cssAssetName) => {
  35099. const encodedPublicUrls = encodePublicUrlsInCSS(config);
  35100. const relative = config.base === './' || config.base === '';
  35101. const cssAssetDirname = encodedPublicUrls || relative
  35102. ? getCssAssetDirname(cssAssetName)
  35103. : undefined;
  35104. const toRelative = (filename) => {
  35105. // relative base + extracted CSS
  35106. const relativePath = path$o.posix.relative(cssAssetDirname, filename);
  35107. return relativePath[0] === '.' ? relativePath : './' + relativePath;
  35108. };
  35109. // replace asset url references with resolved url.
  35110. chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  35111. const filename = this.getFileName(fileHash) + postfix;
  35112. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  35113. return toOutputFilePathInCss(filename, 'asset', cssAssetName, 'css', config, toRelative);
  35114. });
  35115. // resolve public URL from CSS paths
  35116. if (encodedPublicUrls) {
  35117. const relativePathToPublicFromCSS = path$o.posix.relative(cssAssetDirname, '');
  35118. chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
  35119. const publicUrl = publicAssetUrlMap.get(hash).slice(1);
  35120. return toOutputFilePathInCss(publicUrl, 'public', cssAssetName, 'css', config, () => `${relativePathToPublicFromCSS}/${publicUrl}`);
  35121. });
  35122. }
  35123. return chunkCSS;
  35124. };
  35125. function ensureFileExt(name, ext) {
  35126. return normalizePath$3(path$o.format({ ...path$o.parse(name), base: undefined, ext }));
  35127. }
  35128. if (config.build.cssCodeSplit) {
  35129. if (isPureCssChunk) {
  35130. // this is a shared CSS-only chunk that is empty.
  35131. pureCssChunks.add(chunk);
  35132. }
  35133. if (opts.format === 'es' || opts.format === 'cjs') {
  35134. const cssAssetName = chunk.facadeModuleId
  35135. ? normalizePath$3(path$o.relative(config.root, chunk.facadeModuleId))
  35136. : chunk.name;
  35137. const lang = path$o.extname(cssAssetName).slice(1);
  35138. const cssFileName = ensureFileExt(cssAssetName, '.css');
  35139. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
  35140. const previousTask = emitTasks[emitTasks.length - 1];
  35141. // finalizeCss is async which makes `emitFile` non-deterministic, so
  35142. // we use a `.then` to wait for previous tasks before finishing this
  35143. const thisTask = finalizeCss(chunkCSS, true, config).then((css) => {
  35144. chunkCSS = css;
  35145. // make sure the previous task is also finished, this works recursively
  35146. return previousTask;
  35147. });
  35148. // push this task so the next task can wait for this one
  35149. emitTasks.push(thisTask);
  35150. const emitTasksLength = emitTasks.length;
  35151. // wait for this and previous tasks to finish
  35152. await thisTask;
  35153. // emit corresponding css file
  35154. const referenceId = this.emitFile({
  35155. name: path$o.basename(cssFileName),
  35156. type: 'asset',
  35157. source: chunkCSS,
  35158. });
  35159. const originalName = isPreProcessor(lang) ? cssAssetName : cssFileName;
  35160. const isEntry = chunk.isEntry && isPureCssChunk;
  35161. generatedAssets
  35162. .get(config)
  35163. .set(referenceId, { originalName, isEntry });
  35164. chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
  35165. if (emitTasksLength === emitTasks.length) {
  35166. // this is the last task, clear `emitTasks` to free up memory
  35167. emitTasks = [];
  35168. }
  35169. }
  35170. else if (!config.build.ssr) {
  35171. // legacy build and inline css
  35172. // Entry chunk CSS will be collected into `chunk.viteMetadata.importedCss`
  35173. // and injected later by the `'vite:build-html'` plugin into the `index.html`
  35174. // so it will be duplicated. (https://github.com/vitejs/vite/issues/2062#issuecomment-782388010)
  35175. // But because entry chunk can be imported by dynamic import,
  35176. // we shouldn't remove the inlined CSS. (#10285)
  35177. chunkCSS = await finalizeCss(chunkCSS, true, config);
  35178. let cssString = JSON.stringify(chunkCSS);
  35179. cssString =
  35180. renderAssetUrlInJS(this, config, chunk, opts, cssString)?.toString() || cssString;
  35181. const style = `__vite_style__`;
  35182. const injectCode = `var ${style} = document.createElement('style');` +
  35183. `${style}.textContent = ${cssString};` +
  35184. `document.head.appendChild(${style});`;
  35185. let injectionPoint;
  35186. const wrapIdx = code.indexOf('System.register');
  35187. if (wrapIdx >= 0) {
  35188. const executeFnStart = code.indexOf('execute:', wrapIdx);
  35189. injectionPoint = code.indexOf('{', executeFnStart) + 1;
  35190. }
  35191. else {
  35192. const insertMark = "'use strict';";
  35193. injectionPoint = code.indexOf(insertMark) + insertMark.length;
  35194. }
  35195. const s = new MagicString(code);
  35196. s.appendRight(injectionPoint, injectCode);
  35197. if (config.build.sourcemap) {
  35198. // resolve public URL from CSS paths, we need to use absolute paths
  35199. return {
  35200. code: s.toString(),
  35201. map: s.generateMap({ hires: 'boundary' }),
  35202. };
  35203. }
  35204. else {
  35205. return { code: s.toString() };
  35206. }
  35207. }
  35208. }
  35209. else {
  35210. chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssBundleName);
  35211. // finalizeCss is called for the aggregated chunk in generateBundle
  35212. outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
  35213. }
  35214. return null;
  35215. },
  35216. augmentChunkHash(chunk) {
  35217. if (chunk.viteMetadata?.importedCss.size) {
  35218. let hash = '';
  35219. for (const id of chunk.viteMetadata.importedCss) {
  35220. hash += id;
  35221. }
  35222. return hash;
  35223. }
  35224. },
  35225. async generateBundle(opts, bundle) {
  35226. // @ts-expect-error asset emits are skipped in legacy bundle
  35227. if (opts.__vite_skip_asset_emit__) {
  35228. return;
  35229. }
  35230. // remove empty css chunks and their imports
  35231. if (pureCssChunks.size) {
  35232. // map each pure css chunk (rendered chunk) to it's corresponding bundle
  35233. // chunk. we check that by comparing the `moduleIds` as they have different
  35234. // filenames (rendered chunk has the !~{XXX}~ placeholder)
  35235. const pureCssChunkNames = [];
  35236. for (const pureCssChunk of pureCssChunks) {
  35237. for (const key in bundle) {
  35238. const bundleChunk = bundle[key];
  35239. if (bundleChunk.type === 'chunk' &&
  35240. arrayEqual(bundleChunk.moduleIds, pureCssChunk.moduleIds)) {
  35241. pureCssChunkNames.push(key);
  35242. break;
  35243. }
  35244. }
  35245. }
  35246. const emptyChunkFiles = pureCssChunkNames
  35247. .map((file) => path$o.basename(file))
  35248. .join('|')
  35249. .replace(/\./g, '\\.');
  35250. const emptyChunkRE = new RegExp(opts.format === 'es'
  35251. ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];\n?`
  35252. : `\\brequire\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\);\n?`, 'g');
  35253. for (const file in bundle) {
  35254. const chunk = bundle[file];
  35255. if (chunk.type === 'chunk') {
  35256. // remove pure css chunk from other chunk's imports,
  35257. // and also register the emitted CSS files under the importer
  35258. // chunks instead.
  35259. chunk.imports = chunk.imports.filter((file) => {
  35260. if (pureCssChunkNames.includes(file)) {
  35261. const { importedCss, importedAssets } = bundle[file].viteMetadata;
  35262. importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
  35263. importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
  35264. return false;
  35265. }
  35266. return true;
  35267. });
  35268. chunk.code = chunk.code.replace(emptyChunkRE,
  35269. // remove css import while preserving source map location
  35270. (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`);
  35271. }
  35272. }
  35273. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  35274. pureCssChunkNames.forEach((fileName) => {
  35275. removedPureCssFiles.set(fileName, bundle[fileName]);
  35276. delete bundle[fileName];
  35277. delete bundle[`${fileName}.map`];
  35278. });
  35279. }
  35280. let extractedCss = outputToExtractedCSSMap.get(opts);
  35281. if (extractedCss && !hasEmitted) {
  35282. hasEmitted = true;
  35283. extractedCss = await finalizeCss(extractedCss, true, config);
  35284. this.emitFile({
  35285. name: cssBundleName,
  35286. type: 'asset',
  35287. source: extractedCss,
  35288. });
  35289. }
  35290. },
  35291. };
  35292. }
  35293. function createCSSResolvers(config) {
  35294. let cssResolve;
  35295. let sassResolve;
  35296. let lessResolve;
  35297. return {
  35298. get css() {
  35299. return (cssResolve ||
  35300. (cssResolve = config.createResolver({
  35301. extensions: ['.css'],
  35302. mainFields: ['style'],
  35303. conditions: ['style'],
  35304. tryIndex: false,
  35305. preferRelative: true,
  35306. })));
  35307. },
  35308. get sass() {
  35309. return (sassResolve ||
  35310. (sassResolve = config.createResolver({
  35311. extensions: ['.scss', '.sass', '.css'],
  35312. mainFields: ['sass', 'style'],
  35313. conditions: ['sass', 'style'],
  35314. tryIndex: true,
  35315. tryPrefix: '_',
  35316. preferRelative: true,
  35317. })));
  35318. },
  35319. get less() {
  35320. return (lessResolve ||
  35321. (lessResolve = config.createResolver({
  35322. extensions: ['.less', '.css'],
  35323. mainFields: ['less', 'style'],
  35324. conditions: ['less', 'style'],
  35325. tryIndex: false,
  35326. preferRelative: true,
  35327. })));
  35328. },
  35329. };
  35330. }
  35331. function getCssResolversKeys(resolvers) {
  35332. return Object.keys(resolvers);
  35333. }
  35334. async function compileCSSPreprocessors(id, lang, code, config) {
  35335. const { preprocessorOptions, devSourcemap } = config.css ?? {};
  35336. const atImportResolvers = getAtImportResolvers(config);
  35337. const preProcessor = preProcessors[lang];
  35338. let opts = (preprocessorOptions && preprocessorOptions[lang]) || {};
  35339. // support @import from node dependencies by default
  35340. switch (lang) {
  35341. case "scss" /* PreprocessLang.scss */:
  35342. case "sass" /* PreprocessLang.sass */:
  35343. opts = {
  35344. includePaths: ['node_modules'],
  35345. alias: config.resolve.alias,
  35346. ...opts,
  35347. };
  35348. break;
  35349. case "less" /* PreprocessLang.less */:
  35350. case "styl" /* PreprocessLang.styl */:
  35351. case "stylus" /* PreprocessLang.stylus */:
  35352. opts = {
  35353. paths: ['node_modules'],
  35354. alias: config.resolve.alias,
  35355. ...opts,
  35356. };
  35357. }
  35358. // important: set this for relative import resolving
  35359. opts.filename = cleanUrl(id);
  35360. opts.enableSourcemap = devSourcemap ?? false;
  35361. const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers);
  35362. if (preprocessResult.error) {
  35363. throw preprocessResult.error;
  35364. }
  35365. let deps;
  35366. if (preprocessResult.deps) {
  35367. const normalizedFilename = normalizePath$3(opts.filename);
  35368. // sometimes sass registers the file itself as a dep
  35369. deps = new Set([...preprocessResult.deps].filter((dep) => normalizePath$3(dep) !== normalizedFilename));
  35370. }
  35371. return {
  35372. code: preprocessResult.code,
  35373. map: combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap),
  35374. deps,
  35375. };
  35376. }
  35377. const configToAtImportResolvers = new WeakMap();
  35378. function getAtImportResolvers(config) {
  35379. let atImportResolvers = configToAtImportResolvers.get(config);
  35380. if (!atImportResolvers) {
  35381. atImportResolvers = createCSSResolvers(config);
  35382. configToAtImportResolvers.set(config, atImportResolvers);
  35383. }
  35384. return atImportResolvers;
  35385. }
  35386. async function compileCSS(id, code, config, urlReplacer) {
  35387. if (config.css?.transformer === 'lightningcss') {
  35388. return compileLightningCSS(id, code, config, urlReplacer);
  35389. }
  35390. const { modules: modulesOptions, devSourcemap } = config.css || {};
  35391. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  35392. // although at serve time it can work without processing, we do need to
  35393. // crawl them in order to register watch dependencies.
  35394. const needInlineImport = code.includes('@import');
  35395. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  35396. const lang = id.match(CSS_LANGS_RE)?.[1];
  35397. const postcssConfig = await resolvePostcssConfig(config);
  35398. // 1. plain css that needs no processing
  35399. if (lang === 'css' &&
  35400. !postcssConfig &&
  35401. !isModule &&
  35402. !needInlineImport &&
  35403. !hasUrl) {
  35404. return { code, map: null };
  35405. }
  35406. let modules;
  35407. const deps = new Set();
  35408. // 2. pre-processors: sass etc.
  35409. let preprocessorMap;
  35410. if (isPreProcessor(lang)) {
  35411. const preprocessorResult = await compileCSSPreprocessors(id, lang, code, config);
  35412. code = preprocessorResult.code;
  35413. preprocessorMap = preprocessorResult.map;
  35414. preprocessorResult.deps?.forEach((dep) => deps.add(dep));
  35415. }
  35416. // 3. postcss
  35417. const atImportResolvers = getAtImportResolvers(config);
  35418. const postcssOptions = (postcssConfig && postcssConfig.options) || {};
  35419. const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
  35420. if (needInlineImport) {
  35421. postcssPlugins.unshift((await importPostcssImport()).default({
  35422. async resolve(id, basedir) {
  35423. const publicFile = checkPublicFile(id, config);
  35424. if (publicFile) {
  35425. return publicFile;
  35426. }
  35427. const resolved = await atImportResolvers.css(id, path$o.join(basedir, '*'));
  35428. if (resolved) {
  35429. return path$o.resolve(resolved);
  35430. }
  35431. // postcss-import falls back to `resolve` dep if this is unresolved,
  35432. // but we've shimmed to remove the `resolve` dep to cut on bundle size.
  35433. // warn here to provide a better error message.
  35434. if (!path$o.isAbsolute(id)) {
  35435. config.logger.error(colors$1.red(`Unable to resolve \`@import "${id}"\` from ${basedir}`));
  35436. }
  35437. return id;
  35438. },
  35439. async load(id) {
  35440. const code = await fs$l.promises.readFile(id, 'utf-8');
  35441. const lang = id.match(CSS_LANGS_RE)?.[1];
  35442. if (isPreProcessor(lang)) {
  35443. const result = await compileCSSPreprocessors(id, lang, code, config);
  35444. result.deps?.forEach((dep) => deps.add(dep));
  35445. // TODO: support source map
  35446. return result.code;
  35447. }
  35448. return code;
  35449. },
  35450. nameLayer(index) {
  35451. return `vite--anon-layer-${getHash(id)}-${index}`;
  35452. },
  35453. }));
  35454. }
  35455. if (urlReplacer) {
  35456. postcssPlugins.push(UrlRewritePostcssPlugin({
  35457. replacer: urlReplacer,
  35458. logger: config.logger,
  35459. }));
  35460. }
  35461. if (isModule) {
  35462. postcssPlugins.unshift((await importPostcssModules()).default({
  35463. ...modulesOptions,
  35464. localsConvention: modulesOptions?.localsConvention,
  35465. getJSON(cssFileName, _modules, outputFileName) {
  35466. modules = _modules;
  35467. if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
  35468. modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  35469. }
  35470. },
  35471. async resolve(id, importer) {
  35472. for (const key of getCssResolversKeys(atImportResolvers)) {
  35473. const resolved = await atImportResolvers[key](id, importer);
  35474. if (resolved) {
  35475. return path$o.resolve(resolved);
  35476. }
  35477. }
  35478. return id;
  35479. },
  35480. }));
  35481. }
  35482. if (!postcssPlugins.length) {
  35483. return {
  35484. code,
  35485. map: preprocessorMap,
  35486. deps,
  35487. };
  35488. }
  35489. let postcssResult;
  35490. try {
  35491. const source = removeDirectQuery(id);
  35492. const postcss = await importPostcss();
  35493. // postcss is an unbundled dep and should be lazy imported
  35494. postcssResult = await postcss.default(postcssPlugins).process(code, {
  35495. ...postcssOptions,
  35496. parser: lang === 'sss'
  35497. ? loadPreprocessor("sugarss" /* PostCssDialectLang.sss */, config.root)
  35498. : postcssOptions.parser,
  35499. to: source,
  35500. from: source,
  35501. ...(devSourcemap
  35502. ? {
  35503. map: {
  35504. inline: false,
  35505. annotation: false,
  35506. // postcss may return virtual files
  35507. // we cannot obtain content of them, so this needs to be enabled
  35508. sourcesContent: true,
  35509. // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
  35510. // prev: preprocessorMap,
  35511. },
  35512. }
  35513. : {}),
  35514. });
  35515. // record CSS dependencies from @imports
  35516. for (const message of postcssResult.messages) {
  35517. if (message.type === 'dependency') {
  35518. deps.add(normalizePath$3(message.file));
  35519. }
  35520. else if (message.type === 'dir-dependency') {
  35521. // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
  35522. const { dir, glob: globPattern = '**' } = message;
  35523. const pattern = glob.escapePath(normalizePath$3(path$o.resolve(path$o.dirname(id), dir))) +
  35524. `/` +
  35525. globPattern;
  35526. const files = glob.sync(pattern, {
  35527. ignore: ['**/node_modules/**'],
  35528. });
  35529. for (let i = 0; i < files.length; i++) {
  35530. deps.add(files[i]);
  35531. }
  35532. }
  35533. else if (message.type === 'warning') {
  35534. let msg = `[vite:css] ${message.text}`;
  35535. if (message.line && message.column) {
  35536. msg += `\n${generateCodeFrame(code, {
  35537. line: message.line,
  35538. column: message.column,
  35539. })}`;
  35540. }
  35541. config.logger.warn(colors$1.yellow(msg));
  35542. }
  35543. }
  35544. }
  35545. catch (e) {
  35546. e.message = `[postcss] ${e.message}`;
  35547. e.code = code;
  35548. e.loc = {
  35549. column: e.column,
  35550. line: e.line,
  35551. };
  35552. throw e;
  35553. }
  35554. if (!devSourcemap) {
  35555. return {
  35556. ast: postcssResult,
  35557. code: postcssResult.css,
  35558. map: { mappings: '' },
  35559. modules,
  35560. deps,
  35561. };
  35562. }
  35563. const rawPostcssMap = postcssResult.map.toJSON();
  35564. const postcssMap = await formatPostcssSourceMap(
  35565. // version property of rawPostcssMap is declared as string
  35566. // but actually it is a number
  35567. rawPostcssMap, cleanUrl(id));
  35568. return {
  35569. ast: postcssResult,
  35570. code: postcssResult.css,
  35571. map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap),
  35572. modules,
  35573. deps,
  35574. };
  35575. }
  35576. function createCachedImport(imp) {
  35577. let cached;
  35578. return () => {
  35579. if (!cached) {
  35580. cached = imp().then((module) => {
  35581. cached = module;
  35582. return module;
  35583. });
  35584. }
  35585. return cached;
  35586. };
  35587. }
  35588. const importPostcssImport = createCachedImport(() => import('./dep-7ec6f216.js').then(function (n) { return n.i; }));
  35589. const importPostcssModules = createCachedImport(() => import('./dep-f1e8587f.js').then(function (n) { return n.i; }));
  35590. const importPostcss = createCachedImport(() => import('postcss'));
  35591. /**
  35592. * @experimental
  35593. */
  35594. async function preprocessCSS(code, filename, config) {
  35595. return await compileCSS(filename, code, config);
  35596. }
  35597. const postcssReturnsVirtualFilesRE = /^<.+>$/;
  35598. async function formatPostcssSourceMap(rawMap, file) {
  35599. const inputFileDir = path$o.dirname(file);
  35600. const sources = rawMap.sources.map((source) => {
  35601. const cleanSource = cleanUrl(decodeURIComponent(source));
  35602. if (postcssReturnsVirtualFilesRE.test(cleanSource)) {
  35603. return `\0${cleanSource}`;
  35604. }
  35605. return normalizePath$3(path$o.resolve(inputFileDir, cleanSource));
  35606. });
  35607. return {
  35608. file,
  35609. mappings: rawMap.mappings,
  35610. names: rawMap.names,
  35611. sources,
  35612. sourcesContent: rawMap.sourcesContent,
  35613. version: rawMap.version,
  35614. };
  35615. }
  35616. function combineSourcemapsIfExists(filename, map1, map2) {
  35617. return map1 && map2
  35618. ? combineSourcemaps(filename, [
  35619. // type of version property of ExistingRawSourceMap is number
  35620. // but it is always 3
  35621. map1,
  35622. map2,
  35623. ])
  35624. : map1;
  35625. }
  35626. async function finalizeCss(css, minify, config) {
  35627. // hoist external @imports and @charset to the top of the CSS chunk per spec (#1845 and #6333)
  35628. if (css.includes('@import') || css.includes('@charset')) {
  35629. css = await hoistAtRules(css);
  35630. }
  35631. if (minify && config.build.cssMinify) {
  35632. css = await minifyCSS(css, config);
  35633. }
  35634. return css;
  35635. }
  35636. async function resolvePostcssConfig(config) {
  35637. let result = postcssConfigCache.get(config);
  35638. if (result !== undefined) {
  35639. return await result;
  35640. }
  35641. // inline postcss config via vite config
  35642. const inlineOptions = config.css?.postcss;
  35643. if (isObject$2(inlineOptions)) {
  35644. const options = { ...inlineOptions };
  35645. delete options.plugins;
  35646. result = {
  35647. options,
  35648. plugins: inlineOptions.plugins || [],
  35649. };
  35650. }
  35651. else {
  35652. const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
  35653. result = postcssrc({}, searchPath).catch((e) => {
  35654. if (!/No PostCSS Config found/.test(e.message)) {
  35655. if (e instanceof Error) {
  35656. const { name, message, stack } = e;
  35657. e.name = 'Failed to load PostCSS config';
  35658. e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
  35659. e.stack = ''; // add stack to message to retain stack
  35660. throw e;
  35661. }
  35662. else {
  35663. throw new Error(`Failed to load PostCSS config: ${e}`);
  35664. }
  35665. }
  35666. return null;
  35667. });
  35668. // replace cached promise to result object when finished
  35669. result.then((resolved) => {
  35670. postcssConfigCache.set(config, resolved);
  35671. });
  35672. }
  35673. postcssConfigCache.set(config, result);
  35674. return result;
  35675. }
  35676. // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
  35677. const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  35678. const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
  35679. const importCssRE = /@import ('[^']+\.css'|"[^"]+\.css"|[^'")]+\.css)/;
  35680. // Assuming a function name won't be longer than 256 chars
  35681. // eslint-disable-next-line regexp/no-unused-capturing-group -- doesn't detect asyncReplace usage
  35682. const cssImageSetRE = /(?<=image-set\()((?:[\w\-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
  35683. const UrlRewritePostcssPlugin = (opts) => {
  35684. if (!opts) {
  35685. throw new Error('base or replace is required');
  35686. }
  35687. return {
  35688. postcssPlugin: 'vite-url-rewrite',
  35689. Once(root) {
  35690. const promises = [];
  35691. root.walkDecls((declaration) => {
  35692. const importer = declaration.source?.input.file;
  35693. if (!importer) {
  35694. opts.logger.warnOnce('\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. ' +
  35695. 'This may cause imported assets to be incorrectly transformed. ' +
  35696. "If you've recently added a PostCSS plugin that raised this warning, " +
  35697. 'please contact the package author to fix the issue.');
  35698. }
  35699. const isCssUrl = cssUrlRE.test(declaration.value);
  35700. const isCssImageSet = cssImageSetRE.test(declaration.value);
  35701. if (isCssUrl || isCssImageSet) {
  35702. const replacerForDeclaration = (rawUrl) => {
  35703. return opts.replacer(rawUrl, importer);
  35704. };
  35705. const rewriterToUse = isCssImageSet
  35706. ? rewriteCssImageSet
  35707. : rewriteCssUrls;
  35708. promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => {
  35709. declaration.value = url;
  35710. }));
  35711. }
  35712. });
  35713. if (promises.length) {
  35714. return Promise.all(promises);
  35715. }
  35716. },
  35717. };
  35718. };
  35719. UrlRewritePostcssPlugin.postcss = true;
  35720. function rewriteCssUrls(css, replacer) {
  35721. return asyncReplace(css, cssUrlRE, async (match) => {
  35722. const [matched, rawUrl] = match;
  35723. return await doUrlReplace(rawUrl.trim(), matched, replacer);
  35724. });
  35725. }
  35726. function rewriteCssDataUris(css, replacer) {
  35727. return asyncReplace(css, cssDataUriRE, async (match) => {
  35728. const [matched, rawUrl] = match;
  35729. return await doUrlReplace(rawUrl.trim(), matched, replacer, 'data-uri');
  35730. });
  35731. }
  35732. function rewriteImportCss(css, replacer) {
  35733. return asyncReplace(css, importCssRE, async (match) => {
  35734. const [matched, rawUrl] = match;
  35735. return await doImportCSSReplace(rawUrl, matched, replacer);
  35736. });
  35737. }
  35738. // TODO: image and cross-fade could contain a "url" that needs to be processed
  35739. // https://drafts.csswg.org/css-images-4/#image-notation
  35740. // https://drafts.csswg.org/css-images-4/#cross-fade-function
  35741. const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
  35742. async function rewriteCssImageSet(css, replacer) {
  35743. return await asyncReplace(css, cssImageSetRE, async (match) => {
  35744. const [, rawUrl] = match;
  35745. const url = await processSrcSet(rawUrl, async ({ url }) => {
  35746. // the url maybe url(...)
  35747. if (cssUrlRE.test(url)) {
  35748. return await rewriteCssUrls(url, replacer);
  35749. }
  35750. if (!cssNotProcessedRE.test(url)) {
  35751. return await doUrlReplace(url, url, replacer);
  35752. }
  35753. return url;
  35754. });
  35755. return url;
  35756. });
  35757. }
  35758. function skipUrlReplacer(rawUrl) {
  35759. return (isExternalUrl(rawUrl) ||
  35760. isDataUrl(rawUrl) ||
  35761. rawUrl[0] === '#' ||
  35762. varRE.test(rawUrl));
  35763. }
  35764. async function doUrlReplace(rawUrl, matched, replacer, funcName = 'url') {
  35765. let wrap = '';
  35766. const first = rawUrl[0];
  35767. if (first === `"` || first === `'`) {
  35768. wrap = first;
  35769. rawUrl = rawUrl.slice(1, -1);
  35770. }
  35771. if (skipUrlReplacer(rawUrl)) {
  35772. return matched;
  35773. }
  35774. const newUrl = await replacer(rawUrl);
  35775. if (wrap === '' && newUrl !== encodeURI(newUrl)) {
  35776. // The new url might need wrapping even if the original did not have it, e.g. if a space was added during replacement
  35777. wrap = "'";
  35778. }
  35779. return `${funcName}(${wrap}${newUrl}${wrap})`;
  35780. }
  35781. async function doImportCSSReplace(rawUrl, matched, replacer) {
  35782. let wrap = '';
  35783. const first = rawUrl[0];
  35784. if (first === `"` || first === `'`) {
  35785. wrap = first;
  35786. rawUrl = rawUrl.slice(1, -1);
  35787. }
  35788. if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === '#') {
  35789. return matched;
  35790. }
  35791. return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
  35792. }
  35793. async function minifyCSS(css, config) {
  35794. if (config.build.cssMinify === 'lightningcss') {
  35795. const { code, warnings } = (await importLightningCSS()).transform({
  35796. ...config.css?.lightningcss,
  35797. targets: convertTargets(config.build.cssTarget),
  35798. cssModules: undefined,
  35799. filename: cssBundleName,
  35800. code: Buffer.from(css),
  35801. minify: true,
  35802. });
  35803. if (warnings.length) {
  35804. config.logger.warn(colors$1.yellow(`warnings when minifying css:\n${warnings
  35805. .map((w) => w.message)
  35806. .join('\n')}`));
  35807. }
  35808. return code.toString();
  35809. }
  35810. try {
  35811. const { code, warnings } = await transform$1(css, {
  35812. loader: 'css',
  35813. target: config.build.cssTarget || undefined,
  35814. ...resolveMinifyCssEsbuildOptions(config.esbuild || {}),
  35815. });
  35816. if (warnings.length) {
  35817. const msgs = await formatMessages(warnings, { kind: 'warning' });
  35818. config.logger.warn(colors$1.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
  35819. }
  35820. return code;
  35821. }
  35822. catch (e) {
  35823. if (e.errors) {
  35824. e.message = '[esbuild css minify] ' + e.message;
  35825. const msgs = await formatMessages(e.errors, { kind: 'error' });
  35826. e.frame = '\n' + msgs.join('\n');
  35827. e.loc = e.errors[0].location;
  35828. }
  35829. throw e;
  35830. }
  35831. }
  35832. function resolveMinifyCssEsbuildOptions(options) {
  35833. const base = {
  35834. charset: options.charset ?? 'utf8',
  35835. logLevel: options.logLevel,
  35836. logLimit: options.logLimit,
  35837. logOverride: options.logOverride,
  35838. legalComments: options.legalComments,
  35839. };
  35840. if (options.minifyIdentifiers != null ||
  35841. options.minifySyntax != null ||
  35842. options.minifyWhitespace != null) {
  35843. return {
  35844. ...base,
  35845. minifyIdentifiers: options.minifyIdentifiers ?? true,
  35846. minifySyntax: options.minifySyntax ?? true,
  35847. minifyWhitespace: options.minifyWhitespace ?? true,
  35848. };
  35849. }
  35850. else {
  35851. return { ...base, minify: true };
  35852. }
  35853. }
  35854. async function hoistAtRules(css) {
  35855. const s = new MagicString(css);
  35856. const cleanCss = emptyCssComments(css);
  35857. let match;
  35858. // #1845
  35859. // CSS @import can only appear at top of the file. We need to hoist all @import
  35860. // to top when multiple files are concatenated.
  35861. // match until semicolon that's not in quotes
  35862. const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  35863. while ((match = atImportRE.exec(cleanCss))) {
  35864. s.remove(match.index, match.index + match[0].length);
  35865. // Use `appendLeft` instead of `prepend` to preserve original @import order
  35866. s.appendLeft(0, match[0]);
  35867. }
  35868. // #6333
  35869. // CSS @charset must be the top-first in the file, hoist the first to top
  35870. const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
  35871. let foundCharset = false;
  35872. while ((match = atCharsetRE.exec(cleanCss))) {
  35873. s.remove(match.index, match.index + match[0].length);
  35874. if (!foundCharset) {
  35875. s.prepend(match[0]);
  35876. foundCharset = true;
  35877. }
  35878. }
  35879. return s.toString();
  35880. }
  35881. const loadedPreprocessors = {};
  35882. // TODO: use dynamic import
  35883. const _require$2 = createRequire$1(import.meta.url);
  35884. function loadPreprocessor(lang, root) {
  35885. if (lang in loadedPreprocessors) {
  35886. return loadedPreprocessors[lang];
  35887. }
  35888. try {
  35889. const resolved = requireResolveFromRootWithFallback(root, lang);
  35890. return (loadedPreprocessors[lang] = _require$2(resolved));
  35891. }
  35892. catch (e) {
  35893. if (e.code === 'MODULE_NOT_FOUND') {
  35894. const installCommand = getPackageManagerCommand('install');
  35895. throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`);
  35896. }
  35897. else {
  35898. const message = new Error(`Preprocessor dependency "${lang}" failed to load:\n${e.message}`);
  35899. message.stack = e.stack + '\n' + message.stack;
  35900. throw message;
  35901. }
  35902. }
  35903. }
  35904. // in unix, scss might append `location.href` in environments that shim `location`
  35905. // see https://github.com/sass/dart-sass/issues/710
  35906. function cleanScssBugUrl(url) {
  35907. if (
  35908. // check bug via `window` and `location` global
  35909. typeof window !== 'undefined' &&
  35910. typeof location !== 'undefined' &&
  35911. typeof location?.href === 'string') {
  35912. const prefix = location.href.replace(/\/$/, '');
  35913. return url.replace(prefix, '');
  35914. }
  35915. else {
  35916. return url;
  35917. }
  35918. }
  35919. function fixScssBugImportValue(data) {
  35920. // the scss bug doesn't load files properly so we have to load it ourselves
  35921. // to prevent internal error when it loads itself
  35922. if (
  35923. // check bug via `window` and `location` global
  35924. typeof window !== 'undefined' &&
  35925. typeof location !== 'undefined' &&
  35926. data &&
  35927. 'file' in data &&
  35928. (!('contents' in data) || data.contents == null)) {
  35929. // @ts-expect-error we need to preserve file property for HMR
  35930. data.contents = fs$l.readFileSync(data.file, 'utf-8');
  35931. }
  35932. return data;
  35933. }
  35934. // .scss/.sass processor
  35935. const scss = async (source, root, options, resolvers) => {
  35936. const render = loadPreprocessor("sass" /* PreprocessLang.sass */, root).render;
  35937. // NOTE: `sass` always runs it's own importer first, and only falls back to
  35938. // the `importer` option when it can't resolve a path
  35939. const internalImporter = (url, importer, done) => {
  35940. importer = cleanScssBugUrl(importer);
  35941. resolvers.sass(url, importer).then((resolved) => {
  35942. if (resolved) {
  35943. rebaseUrls(resolved, options.filename, options.alias, '$')
  35944. .then((data) => done?.(fixScssBugImportValue(data)))
  35945. .catch((data) => done?.(data));
  35946. }
  35947. else {
  35948. done?.(null);
  35949. }
  35950. });
  35951. };
  35952. const importer = [internalImporter];
  35953. if (options.importer) {
  35954. Array.isArray(options.importer)
  35955. ? importer.unshift(...options.importer)
  35956. : importer.unshift(options.importer);
  35957. }
  35958. const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  35959. const finalOptions = {
  35960. ...options,
  35961. data,
  35962. file: options.filename,
  35963. outFile: options.filename,
  35964. importer,
  35965. ...(options.enableSourcemap
  35966. ? {
  35967. sourceMap: true,
  35968. omitSourceMapUrl: true,
  35969. sourceMapRoot: path$o.dirname(options.filename),
  35970. }
  35971. : {}),
  35972. };
  35973. try {
  35974. const result = await new Promise((resolve, reject) => {
  35975. render(finalOptions, (err, res) => {
  35976. if (err) {
  35977. reject(err);
  35978. }
  35979. else {
  35980. resolve(res);
  35981. }
  35982. });
  35983. });
  35984. const deps = result.stats.includedFiles.map((f) => cleanScssBugUrl(f));
  35985. const map = result.map
  35986. ? JSON.parse(result.map.toString())
  35987. : undefined;
  35988. return {
  35989. code: result.css.toString(),
  35990. map,
  35991. additionalMap,
  35992. deps,
  35993. };
  35994. }
  35995. catch (e) {
  35996. // normalize SASS error
  35997. e.message = `[sass] ${e.message}`;
  35998. e.id = e.file;
  35999. e.frame = e.formatted;
  36000. return { code: '', error: e, deps: [] };
  36001. }
  36002. };
  36003. const sass = (source, root, options, aliasResolver) => scss(source, root, {
  36004. ...options,
  36005. indentedSyntax: true,
  36006. }, aliasResolver);
  36007. /**
  36008. * relative url() inside \@imported sass and less files must be rebased to use
  36009. * root file as base.
  36010. */
  36011. async function rebaseUrls(file, rootFile, alias, variablePrefix) {
  36012. file = path$o.resolve(file); // ensure os-specific flashes
  36013. // in the same dir, no need to rebase
  36014. const fileDir = path$o.dirname(file);
  36015. const rootDir = path$o.dirname(rootFile);
  36016. if (fileDir === rootDir) {
  36017. return { file };
  36018. }
  36019. const content = await fsp.readFile(file, 'utf-8');
  36020. // no url()
  36021. const hasUrls = cssUrlRE.test(content);
  36022. // data-uri() calls
  36023. const hasDataUris = cssDataUriRE.test(content);
  36024. // no @import xxx.css
  36025. const hasImportCss = importCssRE.test(content);
  36026. if (!hasUrls && !hasDataUris && !hasImportCss) {
  36027. return { file };
  36028. }
  36029. let rebased;
  36030. const rebaseFn = (url) => {
  36031. if (url[0] === '/')
  36032. return url;
  36033. // ignore url's starting with variable
  36034. if (url.startsWith(variablePrefix))
  36035. return url;
  36036. // match alias, no need to rewrite
  36037. for (const { find } of alias) {
  36038. const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
  36039. if (matches) {
  36040. return url;
  36041. }
  36042. }
  36043. const absolute = path$o.resolve(fileDir, url);
  36044. const relative = path$o.relative(rootDir, absolute);
  36045. return normalizePath$3(relative);
  36046. };
  36047. // fix css imports in less such as `@import "foo.css"`
  36048. if (hasImportCss) {
  36049. rebased = await rewriteImportCss(content, rebaseFn);
  36050. }
  36051. if (hasUrls) {
  36052. rebased = await rewriteCssUrls(rebased || content, rebaseFn);
  36053. }
  36054. if (hasDataUris) {
  36055. rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
  36056. }
  36057. return {
  36058. file,
  36059. contents: rebased,
  36060. };
  36061. }
  36062. // .less
  36063. const less = async (source, root, options, resolvers) => {
  36064. const nodeLess = loadPreprocessor("less" /* PreprocessLang.less */, root);
  36065. const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers);
  36066. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  36067. let result;
  36068. try {
  36069. result = await nodeLess.render(content, {
  36070. ...options,
  36071. plugins: [viteResolverPlugin, ...(options.plugins || [])],
  36072. ...(options.enableSourcemap
  36073. ? {
  36074. sourceMap: {
  36075. outputSourceFiles: true,
  36076. sourceMapFileInline: false,
  36077. },
  36078. }
  36079. : {}),
  36080. });
  36081. }
  36082. catch (e) {
  36083. const error = e;
  36084. // normalize error info
  36085. const normalizedError = new Error(`[less] ${error.message || error.type}`);
  36086. normalizedError.loc = {
  36087. file: error.filename || options.filename,
  36088. line: error.line,
  36089. column: error.column,
  36090. };
  36091. return { code: '', error: normalizedError, deps: [] };
  36092. }
  36093. const map = result.map && JSON.parse(result.map);
  36094. if (map) {
  36095. delete map.sourcesContent;
  36096. }
  36097. return {
  36098. code: result.css.toString(),
  36099. map,
  36100. additionalMap,
  36101. deps: result.imports,
  36102. };
  36103. };
  36104. /**
  36105. * Less manager, lazy initialized
  36106. */
  36107. let ViteLessManager;
  36108. function createViteLessPlugin(less, rootFile, alias, resolvers) {
  36109. if (!ViteLessManager) {
  36110. ViteLessManager = class ViteManager extends less.FileManager {
  36111. constructor(rootFile, resolvers, alias) {
  36112. super();
  36113. this.rootFile = rootFile;
  36114. this.resolvers = resolvers;
  36115. this.alias = alias;
  36116. }
  36117. supports(filename) {
  36118. return !isExternalUrl(filename);
  36119. }
  36120. supportsSync() {
  36121. return false;
  36122. }
  36123. async loadFile(filename, dir, opts, env) {
  36124. const resolved = await this.resolvers.less(filename, path$o.join(dir, '*'));
  36125. if (resolved) {
  36126. const result = await rebaseUrls(resolved, this.rootFile, this.alias, '@');
  36127. let contents;
  36128. if (result && 'contents' in result) {
  36129. contents = result.contents;
  36130. }
  36131. else {
  36132. contents = await fsp.readFile(resolved, 'utf-8');
  36133. }
  36134. return {
  36135. filename: path$o.resolve(resolved),
  36136. contents,
  36137. };
  36138. }
  36139. else {
  36140. return super.loadFile(filename, dir, opts, env);
  36141. }
  36142. }
  36143. };
  36144. }
  36145. return {
  36146. install(_, pluginManager) {
  36147. pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias));
  36148. },
  36149. minVersion: [3, 0, 0],
  36150. };
  36151. }
  36152. // .styl
  36153. const styl = async (source, root, options) => {
  36154. const nodeStylus = loadPreprocessor("stylus" /* PreprocessLang.stylus */, root);
  36155. // Get source with preprocessor options.additionalData. Make sure a new line separator
  36156. // is added to avoid any render error, as added stylus content may not have semi-colon separators
  36157. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap, '\n');
  36158. // Get preprocessor options.imports dependencies as stylus
  36159. // does not return them with its builtin `.deps()` method
  36160. const importsDeps = (options.imports ?? []).map((dep) => path$o.resolve(dep));
  36161. try {
  36162. const ref = nodeStylus(content, options);
  36163. if (options.define) {
  36164. for (const key in options.define) {
  36165. ref.define(key, options.define[key]);
  36166. }
  36167. }
  36168. if (options.enableSourcemap) {
  36169. ref.set('sourcemap', {
  36170. comment: false,
  36171. inline: false,
  36172. basePath: root,
  36173. });
  36174. }
  36175. const result = ref.render();
  36176. // Concat imports deps with computed deps
  36177. const deps = [...ref.deps(), ...importsDeps];
  36178. // @ts-expect-error sourcemap exists
  36179. const map = ref.sourcemap;
  36180. return {
  36181. code: result,
  36182. map: formatStylusSourceMap(map, root),
  36183. additionalMap,
  36184. deps,
  36185. };
  36186. }
  36187. catch (e) {
  36188. e.message = `[stylus] ${e.message}`;
  36189. return { code: '', error: e, deps: [] };
  36190. }
  36191. };
  36192. function formatStylusSourceMap(mapBefore, root) {
  36193. if (!mapBefore)
  36194. return undefined;
  36195. const map = { ...mapBefore };
  36196. const resolveFromRoot = (p) => normalizePath$3(path$o.resolve(root, p));
  36197. if (map.file) {
  36198. map.file = resolveFromRoot(map.file);
  36199. }
  36200. map.sources = map.sources.map(resolveFromRoot);
  36201. return map;
  36202. }
  36203. async function getSource(source, filename, additionalData, enableSourcemap, sep = '') {
  36204. if (!additionalData)
  36205. return { content: source };
  36206. if (typeof additionalData === 'function') {
  36207. const newContent = await additionalData(source, filename);
  36208. if (typeof newContent === 'string') {
  36209. return { content: newContent };
  36210. }
  36211. return newContent;
  36212. }
  36213. if (!enableSourcemap) {
  36214. return { content: additionalData + sep + source };
  36215. }
  36216. const ms = new MagicString(source);
  36217. ms.appendLeft(0, sep);
  36218. ms.appendLeft(0, additionalData);
  36219. const map = ms.generateMap({ hires: 'boundary' });
  36220. map.file = filename;
  36221. map.sources = [filename];
  36222. return {
  36223. content: ms.toString(),
  36224. map,
  36225. };
  36226. }
  36227. const preProcessors = Object.freeze({
  36228. ["less" /* PreprocessLang.less */]: less,
  36229. ["sass" /* PreprocessLang.sass */]: sass,
  36230. ["scss" /* PreprocessLang.scss */]: scss,
  36231. ["styl" /* PreprocessLang.styl */]: styl,
  36232. ["stylus" /* PreprocessLang.stylus */]: styl,
  36233. });
  36234. function isPreProcessor(lang) {
  36235. return lang && lang in preProcessors;
  36236. }
  36237. const importLightningCSS = createCachedImport(() => import('lightningcss'));
  36238. async function compileLightningCSS(id, src, config, urlReplacer) {
  36239. const deps = new Set();
  36240. // Relative path is needed to get stable hash when using CSS modules
  36241. const filename = cleanUrl(path$o.relative(config.root, id));
  36242. const toAbsolute = (filePath) => path$o.isAbsolute(filePath) ? filePath : path$o.join(config.root, filePath);
  36243. const res = styleAttrRE.test(id)
  36244. ? (await importLightningCSS()).transformStyleAttribute({
  36245. filename,
  36246. code: Buffer.from(src),
  36247. targets: config.css?.lightningcss?.targets,
  36248. minify: config.isProduction && !!config.build.cssMinify,
  36249. analyzeDependencies: true,
  36250. })
  36251. : await (await importLightningCSS()).bundleAsync({
  36252. filename,
  36253. resolver: {
  36254. read(filePath) {
  36255. if (filePath === filename) {
  36256. return src;
  36257. }
  36258. // This happens with html-proxy (#13776)
  36259. if (!filePath.endsWith('.css')) {
  36260. return src;
  36261. }
  36262. return fs$l.readFileSync(toAbsolute(filePath), 'utf-8');
  36263. },
  36264. async resolve(id, from) {
  36265. const publicFile = checkPublicFile(id, config);
  36266. if (publicFile) {
  36267. return publicFile;
  36268. }
  36269. const resolved = await getAtImportResolvers(config).css(id, toAbsolute(from));
  36270. if (resolved) {
  36271. deps.add(resolved);
  36272. return resolved;
  36273. }
  36274. return id;
  36275. },
  36276. },
  36277. targets: config.css?.lightningcss?.targets,
  36278. minify: config.isProduction && !!config.build.cssMinify,
  36279. sourceMap: config.css?.devSourcemap,
  36280. analyzeDependencies: true,
  36281. cssModules: cssModuleRE.test(id)
  36282. ? config.css?.lightningcss?.cssModules ?? true
  36283. : undefined,
  36284. drafts: config.css?.lightningcss?.drafts,
  36285. });
  36286. let css = res.code.toString();
  36287. for (const dep of res.dependencies) {
  36288. switch (dep.type) {
  36289. case 'url':
  36290. if (skipUrlReplacer(dep.url)) {
  36291. css = css.replace(dep.placeholder, dep.url);
  36292. break;
  36293. }
  36294. deps.add(dep.url);
  36295. if (urlReplacer) {
  36296. css = css.replace(dep.placeholder, await urlReplacer(dep.url, id));
  36297. }
  36298. break;
  36299. default:
  36300. throw new Error(`Unsupported dependency type: ${dep.type}`);
  36301. }
  36302. }
  36303. let modules;
  36304. if ('exports' in res && res.exports) {
  36305. modules = {};
  36306. // https://github.com/parcel-bundler/lightningcss/issues/291
  36307. const sortedEntries = Object.entries(res.exports).sort((a, b) => a[0].localeCompare(b[0]));
  36308. for (const [key, value] of sortedEntries) {
  36309. modules[key] = value.name;
  36310. // https://lightningcss.dev/css-modules.html#class-composition
  36311. for (const c of value.composes) {
  36312. modules[key] += ' ' + c.name;
  36313. }
  36314. }
  36315. }
  36316. return {
  36317. code: css,
  36318. map: 'map' in res ? res.map?.toString() : undefined,
  36319. deps,
  36320. modules,
  36321. };
  36322. }
  36323. // Convert https://esbuild.github.io/api/#target
  36324. // To https://github.com/parcel-bundler/lightningcss/blob/master/node/targets.d.ts
  36325. const map = {
  36326. chrome: 'chrome',
  36327. edge: 'edge',
  36328. firefox: 'firefox',
  36329. hermes: false,
  36330. ie: 'ie',
  36331. ios: 'ios_saf',
  36332. node: false,
  36333. opera: 'opera',
  36334. rhino: false,
  36335. safari: 'safari',
  36336. };
  36337. const esMap = {
  36338. // https://caniuse.com/?search=es2015
  36339. 2015: ['chrome49', 'edge13', 'safari10', 'firefox44', 'opera36'],
  36340. // https://caniuse.com/?search=es2016
  36341. 2016: ['chrome50', 'edge13', 'safari10', 'firefox43', 'opera37'],
  36342. // https://caniuse.com/?search=es2017
  36343. 2017: ['chrome58', 'edge15', 'safari11', 'firefox52', 'opera45'],
  36344. // https://caniuse.com/?search=es2018
  36345. 2018: ['chrome63', 'edge79', 'safari12', 'firefox58', 'opera50'],
  36346. // https://caniuse.com/?search=es2019
  36347. 2019: ['chrome73', 'edge79', 'safari12.1', 'firefox64', 'opera60'],
  36348. // https://caniuse.com/?search=es2020
  36349. 2020: ['chrome80', 'edge80', 'safari14.1', 'firefox80', 'opera67'],
  36350. // https://caniuse.com/?search=es2021
  36351. 2021: ['chrome85', 'edge85', 'safari14.1', 'firefox80', 'opera71'],
  36352. // https://caniuse.com/?search=es2022
  36353. 2022: ['chrome94', 'edge94', 'safari16.4', 'firefox93', 'opera80'],
  36354. };
  36355. const esRE = /es(\d{4})/;
  36356. const versionRE = /\d/;
  36357. const convertTargetsCache = new Map();
  36358. const convertTargets = (esbuildTarget) => {
  36359. if (!esbuildTarget)
  36360. return {};
  36361. const cached = convertTargetsCache.get(esbuildTarget);
  36362. if (cached)
  36363. return cached;
  36364. const targets = {};
  36365. const entriesWithoutES = arraify(esbuildTarget).flatMap((e) => {
  36366. const match = e.match(esRE);
  36367. if (!match)
  36368. return e;
  36369. const year = Number(match[1]);
  36370. if (!esMap[year])
  36371. throw new Error(`Unsupported target "${e}"`);
  36372. return esMap[year];
  36373. });
  36374. for (const entry of entriesWithoutES) {
  36375. if (entry === 'esnext')
  36376. continue;
  36377. const index = entry.match(versionRE)?.index;
  36378. if (index) {
  36379. const browser = map[entry.slice(0, index)];
  36380. if (browser === false)
  36381. continue; // No mapping available
  36382. if (browser) {
  36383. const [major, minor = 0] = entry
  36384. .slice(index)
  36385. .split('.')
  36386. .map((v) => parseInt(v, 10));
  36387. if (!isNaN(major) && !isNaN(minor)) {
  36388. const version = (major << 16) | (minor << 8);
  36389. if (!targets[browser] || version < targets[browser]) {
  36390. targets[browser] = version;
  36391. }
  36392. continue;
  36393. }
  36394. }
  36395. }
  36396. throw new Error(`Unsupported target "${entry}"`);
  36397. }
  36398. convertTargetsCache.set(esbuildTarget, targets);
  36399. return targets;
  36400. };
  36401. const externalWithConversionNamespace = 'vite:dep-pre-bundle:external-conversion';
  36402. const convertedExternalPrefix = 'vite-dep-pre-bundle-external:';
  36403. const cjsExternalFacadeNamespace = 'vite:cjs-external-facade';
  36404. const nonFacadePrefix = 'vite-cjs-external-facade:';
  36405. const externalTypes = [
  36406. 'css',
  36407. // supported pre-processor types
  36408. 'less',
  36409. 'sass',
  36410. 'scss',
  36411. 'styl',
  36412. 'stylus',
  36413. 'pcss',
  36414. 'postcss',
  36415. // wasm
  36416. 'wasm',
  36417. // known SFC types
  36418. 'vue',
  36419. 'svelte',
  36420. 'marko',
  36421. 'astro',
  36422. 'imba',
  36423. // JSX/TSX may be configured to be compiled differently from how esbuild
  36424. // handles it by default, so exclude them as well
  36425. 'jsx',
  36426. 'tsx',
  36427. ...KNOWN_ASSET_TYPES,
  36428. ];
  36429. function esbuildDepPlugin(qualified, external, config, ssr) {
  36430. const { extensions } = getDepOptimizationConfig(config, ssr);
  36431. // remove optimizable extensions from `externalTypes` list
  36432. const allExternalTypes = extensions
  36433. ? externalTypes.filter((type) => !extensions?.includes('.' + type))
  36434. : externalTypes;
  36435. // use separate package cache for optimizer as it caches paths around node_modules
  36436. // and it's unlikely for the core Vite process to traverse into node_modules again
  36437. const esmPackageCache = new Map();
  36438. const cjsPackageCache = new Map();
  36439. // default resolver which prefers ESM
  36440. const _resolve = config.createResolver({
  36441. asSrc: false,
  36442. scan: true,
  36443. packageCache: esmPackageCache,
  36444. });
  36445. // cjs resolver that prefers Node
  36446. const _resolveRequire = config.createResolver({
  36447. asSrc: false,
  36448. isRequire: true,
  36449. scan: true,
  36450. packageCache: cjsPackageCache,
  36451. });
  36452. const resolve = (id, importer, kind, resolveDir) => {
  36453. let _importer;
  36454. // explicit resolveDir - this is passed only during yarn pnp resolve for
  36455. // entries
  36456. if (resolveDir) {
  36457. _importer = normalizePath$3(path$o.join(resolveDir, '*'));
  36458. }
  36459. else {
  36460. // map importer ids to file paths for correct resolution
  36461. _importer = importer in qualified ? qualified[importer] : importer;
  36462. }
  36463. const resolver = kind.startsWith('require') ? _resolveRequire : _resolve;
  36464. return resolver(id, _importer, undefined, ssr);
  36465. };
  36466. const resolveResult = (id, resolved) => {
  36467. if (resolved.startsWith(browserExternalId)) {
  36468. return {
  36469. path: id,
  36470. namespace: 'browser-external',
  36471. };
  36472. }
  36473. if (resolved.startsWith(optionalPeerDepId)) {
  36474. return {
  36475. path: resolved,
  36476. namespace: 'optional-peer-dep',
  36477. };
  36478. }
  36479. if (ssr && isBuiltin(resolved)) {
  36480. return;
  36481. }
  36482. if (isExternalUrl(resolved)) {
  36483. return {
  36484. path: resolved,
  36485. external: true,
  36486. };
  36487. }
  36488. return {
  36489. path: path$o.resolve(resolved),
  36490. };
  36491. };
  36492. return {
  36493. name: 'vite:dep-pre-bundle',
  36494. setup(build) {
  36495. // clear package cache when esbuild is finished
  36496. build.onEnd(() => {
  36497. esmPackageCache.clear();
  36498. cjsPackageCache.clear();
  36499. });
  36500. // externalize assets and commonly known non-js file types
  36501. // See #8459 for more details about this require-import conversion
  36502. build.onResolve({
  36503. filter: new RegExp(`\\.(` + allExternalTypes.join('|') + `)(\\?.*)?$`),
  36504. }, async ({ path: id, importer, kind }) => {
  36505. // if the prefix exist, it is already converted to `import`, so set `external: true`
  36506. if (id.startsWith(convertedExternalPrefix)) {
  36507. return {
  36508. path: id.slice(convertedExternalPrefix.length),
  36509. external: true,
  36510. };
  36511. }
  36512. const resolved = await resolve(id, importer, kind);
  36513. if (resolved) {
  36514. if (kind === 'require-call') {
  36515. // here it is not set to `external: true` to convert `require` to `import`
  36516. return {
  36517. path: resolved,
  36518. namespace: externalWithConversionNamespace,
  36519. };
  36520. }
  36521. return {
  36522. path: resolved,
  36523. external: true,
  36524. };
  36525. }
  36526. });
  36527. build.onLoad({ filter: /./, namespace: externalWithConversionNamespace }, (args) => {
  36528. // import itself with prefix (this is the actual part of require-import conversion)
  36529. const modulePath = `"${convertedExternalPrefix}${args.path}"`;
  36530. return {
  36531. contents: isCSSRequest(args.path) && !isModuleCSSRequest(args.path)
  36532. ? `import ${modulePath};`
  36533. : `export { default } from ${modulePath};` +
  36534. `export * from ${modulePath};`,
  36535. loader: 'js',
  36536. };
  36537. });
  36538. function resolveEntry(id) {
  36539. const flatId = flattenId(id);
  36540. if (flatId in qualified) {
  36541. return {
  36542. path: qualified[flatId],
  36543. };
  36544. }
  36545. }
  36546. build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => {
  36547. if (moduleListContains(external, id)) {
  36548. return {
  36549. path: id,
  36550. external: true,
  36551. };
  36552. }
  36553. // ensure esbuild uses our resolved entries
  36554. let entry;
  36555. // if this is an entry, return entry namespace resolve result
  36556. if (!importer) {
  36557. if ((entry = resolveEntry(id)))
  36558. return entry;
  36559. // check if this is aliased to an entry - also return entry namespace
  36560. const aliased = await _resolve(id, undefined, true);
  36561. if (aliased && (entry = resolveEntry(aliased))) {
  36562. return entry;
  36563. }
  36564. }
  36565. // use vite's own resolver
  36566. const resolved = await resolve(id, importer, kind);
  36567. if (resolved) {
  36568. return resolveResult(id, resolved);
  36569. }
  36570. });
  36571. build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path }) => {
  36572. if (config.isProduction) {
  36573. return {
  36574. contents: 'module.exports = {}',
  36575. };
  36576. }
  36577. else {
  36578. return {
  36579. // Return in CJS to intercept named imports. Use `Object.create` to
  36580. // create the Proxy in the prototype to workaround esbuild issue. Why?
  36581. //
  36582. // In short, esbuild cjs->esm flow:
  36583. // 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
  36584. // 2. Assign props of `module.exports` to the object.
  36585. // 3. Return object for ESM use.
  36586. //
  36587. // If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
  36588. // step 2 does nothing as there's no props for `module.exports`. The final object
  36589. // is just an empty object.
  36590. //
  36591. // Creating the Proxy in the prototype satisfies step 1 immediately, which means
  36592. // the returned object is a Proxy that we can intercept.
  36593. //
  36594. // Note: Skip keys that are accessed by esbuild and browser devtools.
  36595. contents: `\
  36596. module.exports = Object.create(new Proxy({}, {
  36597. get(_, key) {
  36598. if (
  36599. key !== '__esModule' &&
  36600. key !== '__proto__' &&
  36601. key !== 'constructor' &&
  36602. key !== 'splice'
  36603. ) {
  36604. console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
  36605. }
  36606. }
  36607. }))`,
  36608. };
  36609. }
  36610. });
  36611. build.onLoad({ filter: /.*/, namespace: 'optional-peer-dep' }, ({ path }) => {
  36612. if (config.isProduction) {
  36613. return {
  36614. contents: 'module.exports = {}',
  36615. };
  36616. }
  36617. else {
  36618. const [, peerDep, parentDep] = path.split(':');
  36619. return {
  36620. contents: `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
  36621. };
  36622. }
  36623. });
  36624. },
  36625. };
  36626. }
  36627. const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
  36628. // esbuild doesn't transpile `require('foo')` into `import` statements if 'foo' is externalized
  36629. // https://github.com/evanw/esbuild/issues/566#issuecomment-735551834
  36630. function esbuildCjsExternalPlugin(externals, platform) {
  36631. return {
  36632. name: 'cjs-external',
  36633. setup(build) {
  36634. const filter = new RegExp(externals.map(matchesEntireLine).join('|'));
  36635. build.onResolve({ filter: new RegExp(`^${nonFacadePrefix}`) }, (args) => {
  36636. return {
  36637. path: args.path.slice(nonFacadePrefix.length),
  36638. external: true,
  36639. };
  36640. });
  36641. build.onResolve({ filter }, (args) => {
  36642. // preserve `require` for node because it's more accurate than converting it to import
  36643. if (args.kind === 'require-call' && platform !== 'node') {
  36644. return {
  36645. path: args.path,
  36646. namespace: cjsExternalFacadeNamespace,
  36647. };
  36648. }
  36649. return {
  36650. path: args.path,
  36651. external: true,
  36652. };
  36653. });
  36654. build.onLoad({ filter: /.*/, namespace: cjsExternalFacadeNamespace }, (args) => ({
  36655. contents: `import * as m from ${JSON.stringify(nonFacadePrefix + args.path)};` + `module.exports = m;`,
  36656. }));
  36657. },
  36658. };
  36659. }
  36660. const debug$c = createDebugger('vite:ssr-external');
  36661. /**
  36662. * Converts "parent > child" syntax to just "child"
  36663. */
  36664. function stripNesting(packages) {
  36665. return packages.map((s) => {
  36666. const arr = s.split('>');
  36667. return arr[arr.length - 1].trim();
  36668. });
  36669. }
  36670. /**
  36671. * Heuristics for determining whether a dependency should be externalized for
  36672. * server-side rendering.
  36673. */
  36674. function cjsSsrResolveExternals(config, knownImports) {
  36675. // strip nesting since knownImports may be passed in from optimizeDeps which
  36676. // supports a "parent > child" syntax
  36677. knownImports = stripNesting(knownImports);
  36678. const ssrConfig = config.ssr;
  36679. if (ssrConfig?.noExternal === true) {
  36680. return [];
  36681. }
  36682. const ssrExternals = new Set();
  36683. const seen = new Set();
  36684. ssrConfig?.external?.forEach((id) => {
  36685. ssrExternals.add(id);
  36686. seen.add(id);
  36687. });
  36688. cjsSsrCollectExternals(config.root, config.resolve, ssrExternals, seen, config.logger);
  36689. const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
  36690. for (const dep of importedDeps) {
  36691. // Assume external if not yet seen
  36692. // At this point, the project root and any linked packages have had their dependencies checked,
  36693. // so we can safely mark any knownImports not yet seen as external. They are guaranteed to be
  36694. // dependencies of packages in node_modules.
  36695. if (!seen.has(dep)) {
  36696. ssrExternals.add(dep);
  36697. }
  36698. }
  36699. // ensure `vite/dynamic-import-polyfill` is bundled (issue #1865)
  36700. ssrExternals.delete('vite');
  36701. let externals = [...ssrExternals];
  36702. if (ssrConfig?.noExternal) {
  36703. externals = externals.filter(createFilter(undefined, ssrConfig.noExternal, { resolve: false }));
  36704. }
  36705. return externals;
  36706. }
  36707. const CJS_CONTENT_RE = /\bmodule\.exports\b|\bexports[.[]|\brequire\s*\(|\bObject\.(?:defineProperty|defineProperties|assign)\s*\(\s*exports\b/;
  36708. // TODO: use import()
  36709. const _require$1 = createRequire$1(import.meta.url);
  36710. const isSsrExternalCache = new WeakMap();
  36711. function shouldExternalizeForSSR(id, importer, config) {
  36712. let isSsrExternal = isSsrExternalCache.get(config);
  36713. if (!isSsrExternal) {
  36714. isSsrExternal = createIsSsrExternal(config);
  36715. isSsrExternalCache.set(config, isSsrExternal);
  36716. }
  36717. return isSsrExternal(id, importer);
  36718. }
  36719. function createIsConfiguredAsSsrExternal(config) {
  36720. const { ssr, root } = config;
  36721. const noExternal = ssr?.noExternal;
  36722. const noExternalFilter = noExternal !== 'undefined' &&
  36723. typeof noExternal !== 'boolean' &&
  36724. createFilter(undefined, noExternal, { resolve: false });
  36725. const targetConditions = config.ssr.resolve?.externalConditions || [];
  36726. const resolveOptions = {
  36727. ...config.resolve,
  36728. root,
  36729. isProduction: false,
  36730. isBuild: true,
  36731. conditions: targetConditions,
  36732. };
  36733. const isExternalizable = (id, importer, configuredAsExternal) => {
  36734. if (!bareImportRE.test(id) || id.includes('\0')) {
  36735. return false;
  36736. }
  36737. try {
  36738. return !!tryNodeResolve(id,
  36739. // Skip passing importer in build to avoid externalizing non-hoisted dependencies
  36740. // unresolveable from root (which would be unresolvable from output bundles also)
  36741. config.command === 'build' ? undefined : importer, resolveOptions, ssr?.target === 'webworker', undefined, true,
  36742. // try to externalize, will return undefined or an object without
  36743. // a external flag if it isn't externalizable
  36744. true,
  36745. // Allow linked packages to be externalized if they are explicitly
  36746. // configured as external
  36747. !!configuredAsExternal)?.external;
  36748. }
  36749. catch (e) {
  36750. debug$c?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
  36751. // may be an invalid import that's resolved by a plugin
  36752. return false;
  36753. }
  36754. };
  36755. // Returns true if it is configured as external, false if it is filtered
  36756. // by noExternal and undefined if it isn't affected by the explicit config
  36757. return (id, importer) => {
  36758. const { ssr } = config;
  36759. if (ssr) {
  36760. if (
  36761. // If this id is defined as external, force it as external
  36762. // Note that individual package entries are allowed in ssr.external
  36763. ssr.external?.includes(id)) {
  36764. return true;
  36765. }
  36766. const pkgName = getNpmPackageName(id);
  36767. if (!pkgName) {
  36768. return isExternalizable(id, importer);
  36769. }
  36770. if (
  36771. // A package name in ssr.external externalizes every
  36772. // externalizable package entry
  36773. ssr.external?.includes(pkgName)) {
  36774. return isExternalizable(id, importer, true);
  36775. }
  36776. if (typeof noExternal === 'boolean') {
  36777. return !noExternal;
  36778. }
  36779. if (noExternalFilter && !noExternalFilter(pkgName)) {
  36780. return false;
  36781. }
  36782. }
  36783. return isExternalizable(id, importer);
  36784. };
  36785. }
  36786. function createIsSsrExternal(config) {
  36787. const processedIds = new Map();
  36788. const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
  36789. return (id, importer) => {
  36790. if (processedIds.has(id)) {
  36791. return processedIds.get(id);
  36792. }
  36793. let external = false;
  36794. if (id[0] !== '.' && !path$o.isAbsolute(id)) {
  36795. external = isBuiltin(id) || isConfiguredAsExternal(id, importer);
  36796. }
  36797. processedIds.set(id, external);
  36798. return external;
  36799. };
  36800. }
  36801. // When config.experimental.buildSsrCjsExternalHeuristics is enabled, this function
  36802. // is used reverting to the Vite 2.9 SSR externalization heuristics
  36803. function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger) {
  36804. const rootPkgPath = lookupFile(root, ['package.json']);
  36805. if (!rootPkgPath) {
  36806. return;
  36807. }
  36808. const rootPkgContent = fs$l.readFileSync(rootPkgPath, 'utf-8');
  36809. if (!rootPkgContent) {
  36810. return;
  36811. }
  36812. const rootPkg = JSON.parse(rootPkgContent);
  36813. const deps = {
  36814. ...rootPkg.devDependencies,
  36815. ...rootPkg.dependencies,
  36816. };
  36817. const internalResolveOptions = {
  36818. ...resolveOptions,
  36819. root,
  36820. isProduction: false,
  36821. isBuild: true,
  36822. };
  36823. const depsToTrace = new Set();
  36824. for (const id in deps) {
  36825. if (seen.has(id))
  36826. continue;
  36827. seen.add(id);
  36828. let esmEntry;
  36829. let requireEntry;
  36830. try {
  36831. esmEntry = tryNodeResolve(id, undefined, internalResolveOptions, true, // we set `targetWeb` to `true` to get the ESM entry
  36832. undefined, true)?.id;
  36833. // normalizePath required for windows. tryNodeResolve uses normalizePath
  36834. // which returns with '/', require.resolve returns with '\\'
  36835. requireEntry = normalizePath$3(_require$1.resolve(id, { paths: [root] }));
  36836. }
  36837. catch (e) {
  36838. // no main entry, but deep imports may be allowed
  36839. const pkgDir = resolvePackageData(id, root)?.dir;
  36840. if (pkgDir) {
  36841. if (isInNodeModules(pkgDir)) {
  36842. ssrExternals.add(id);
  36843. }
  36844. else {
  36845. depsToTrace.add(path$o.dirname(pkgDir));
  36846. }
  36847. continue;
  36848. }
  36849. // resolve failed, assume include
  36850. debug$c?.(`Failed to resolve entries for package "${id}"\n`, e);
  36851. continue;
  36852. }
  36853. // no esm entry but has require entry
  36854. if (!esmEntry) {
  36855. ssrExternals.add(id);
  36856. }
  36857. // trace the dependencies of linked packages
  36858. else if (!isInNodeModules(esmEntry)) {
  36859. const pkgDir = resolvePackageData(id, root)?.dir;
  36860. if (pkgDir) {
  36861. depsToTrace.add(pkgDir);
  36862. }
  36863. }
  36864. // has separate esm/require entry, assume require entry is cjs
  36865. else if (esmEntry !== requireEntry) {
  36866. ssrExternals.add(id);
  36867. }
  36868. // if we're externalizing ESM and CJS should basically just always do it?
  36869. // or are there others like SystemJS / AMD that we'd need to handle?
  36870. // for now, we'll just leave this as is
  36871. else if (/\.m?js$/.test(esmEntry)) {
  36872. const pkg = resolvePackageData(id, root)?.data;
  36873. if (!pkg) {
  36874. continue;
  36875. }
  36876. if (pkg.type === 'module' || esmEntry.endsWith('.mjs')) {
  36877. ssrExternals.add(id);
  36878. continue;
  36879. }
  36880. // check if the entry is cjs
  36881. const content = fs$l.readFileSync(esmEntry, 'utf-8');
  36882. if (CJS_CONTENT_RE.test(content)) {
  36883. ssrExternals.add(id);
  36884. continue;
  36885. }
  36886. logger.warn(`${id} doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.`);
  36887. }
  36888. }
  36889. for (const depRoot of depsToTrace) {
  36890. cjsSsrCollectExternals(depRoot, resolveOptions, ssrExternals, seen, logger);
  36891. }
  36892. }
  36893. function cjsShouldExternalizeForSSR(id, externals) {
  36894. if (!externals) {
  36895. return false;
  36896. }
  36897. const should = externals.some((e) => {
  36898. if (id === e) {
  36899. return true;
  36900. }
  36901. // deep imports, check ext before externalizing - only externalize
  36902. // extension-less imports and explicit .js imports
  36903. if (id.startsWith(withTrailingSlash(e)) &&
  36904. (!path$o.extname(id) || id.endsWith('.js'))) {
  36905. return true;
  36906. }
  36907. });
  36908. return should;
  36909. }
  36910. /**
  36911. * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
  36912. *
  36913. * This source code is licensed under the MIT license found in the
  36914. * LICENSE file at
  36915. * https://github.com/rollup/plugins/blob/master/LICENSE
  36916. */
  36917. // Custom json filter for vite
  36918. const jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/;
  36919. const jsonLangs = `\\.(?:json|json5)(?:$|\\?)`;
  36920. const jsonLangRE = new RegExp(jsonLangs);
  36921. const isJSONRequest = (request) => jsonLangRE.test(request);
  36922. function jsonPlugin(options = {}, isBuild) {
  36923. return {
  36924. name: 'vite:json',
  36925. transform(json, id) {
  36926. if (!jsonExtRE.test(id))
  36927. return null;
  36928. if (SPECIAL_QUERY_RE.test(id))
  36929. return null;
  36930. json = stripBomTag(json);
  36931. try {
  36932. if (options.stringify) {
  36933. if (isBuild) {
  36934. return {
  36935. // during build, parse then double-stringify to remove all
  36936. // unnecessary whitespaces to reduce bundle size.
  36937. code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`,
  36938. map: { mappings: '' },
  36939. };
  36940. }
  36941. else {
  36942. return `export default JSON.parse(${JSON.stringify(json)})`;
  36943. }
  36944. }
  36945. const parsed = JSON.parse(json);
  36946. return {
  36947. code: dataToEsm(parsed, {
  36948. preferConst: true,
  36949. namedExports: options.namedExports,
  36950. }),
  36951. map: { mappings: '' },
  36952. };
  36953. }
  36954. catch (e) {
  36955. const errorMessageList = /\d+/.exec(e.message);
  36956. const position = errorMessageList && parseInt(errorMessageList[0], 10);
  36957. const msg = position
  36958. ? `, invalid JSON syntax found at line ${position}`
  36959. : `.`;
  36960. this.error(`Failed to parse JSON file` + msg, e.idx);
  36961. }
  36962. },
  36963. };
  36964. }
  36965. const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR';
  36966. const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP';
  36967. const debug$b = createDebugger('vite:optimize-deps');
  36968. function optimizedDepsPlugin(config) {
  36969. return {
  36970. name: 'vite:optimized-deps',
  36971. resolveId(id, source, { ssr }) {
  36972. if (getDepsOptimizer(config, ssr)?.isOptimizedDepFile(id)) {
  36973. return id;
  36974. }
  36975. },
  36976. // this.load({ id }) isn't implemented in PluginContainer
  36977. // The logic to register an id to wait until it is processed
  36978. // is in importAnalysis, see call to delayDepsOptimizerUntil
  36979. async load(id, options) {
  36980. const ssr = options?.ssr === true;
  36981. const depsOptimizer = getDepsOptimizer(config, ssr);
  36982. if (depsOptimizer?.isOptimizedDepFile(id)) {
  36983. const metadata = depsOptimizer.metadata;
  36984. const file = cleanUrl(id);
  36985. const versionMatch = id.match(DEP_VERSION_RE);
  36986. const browserHash = versionMatch
  36987. ? versionMatch[1].split('=')[1]
  36988. : undefined;
  36989. // Search in both the currently optimized and newly discovered deps
  36990. const info = optimizedDepInfoFromFile(metadata, file);
  36991. if (info) {
  36992. if (browserHash && info.browserHash !== browserHash) {
  36993. throwOutdatedRequest(id);
  36994. }
  36995. try {
  36996. // This is an entry point, it may still not be bundled
  36997. await info.processing;
  36998. }
  36999. catch {
  37000. // If the refresh has not happened after timeout, Vite considers
  37001. // something unexpected has happened. In this case, Vite
  37002. // returns an empty response that will error.
  37003. throwProcessingError(id);
  37004. return;
  37005. }
  37006. const newMetadata = depsOptimizer.metadata;
  37007. if (metadata !== newMetadata) {
  37008. const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
  37009. if (info.browserHash !== currentInfo?.browserHash) {
  37010. throwOutdatedRequest(id);
  37011. }
  37012. }
  37013. }
  37014. debug$b?.(`load ${colors$1.cyan(file)}`);
  37015. // Load the file from the cache instead of waiting for other plugin
  37016. // load hooks to avoid race conditions, once processing is resolved,
  37017. // we are sure that the file has been properly save to disk
  37018. try {
  37019. return await fsp.readFile(file, 'utf-8');
  37020. }
  37021. catch (e) {
  37022. // Outdated non-entry points (CHUNK), loaded after a rerun
  37023. throwOutdatedRequest(id);
  37024. }
  37025. }
  37026. },
  37027. };
  37028. }
  37029. function optimizedDepsBuildPlugin(config) {
  37030. let buildStartCalled = false;
  37031. return {
  37032. name: 'vite:optimized-deps-build',
  37033. buildStart() {
  37034. // Only reset the registered ids after a rebuild during build --watch
  37035. if (!config.isWorker && buildStartCalled) {
  37036. getDepsOptimizer(config)?.resetRegisteredIds();
  37037. }
  37038. buildStartCalled = true;
  37039. },
  37040. async resolveId(id, importer, options) {
  37041. const depsOptimizer = getDepsOptimizer(config);
  37042. if (!depsOptimizer)
  37043. return;
  37044. if (depsOptimizer.isOptimizedDepFile(id)) {
  37045. return id;
  37046. }
  37047. else {
  37048. if (options?.custom?.['vite:pre-alias']) {
  37049. // Skip registering the id if it is being resolved from the pre-alias plugin
  37050. // When a optimized dep is aliased, we need to avoid waiting for it before optimizing
  37051. return;
  37052. }
  37053. const resolved = await this.resolve(id, importer, {
  37054. ...options,
  37055. skipSelf: true,
  37056. });
  37057. if (resolved && !resolved.external) {
  37058. depsOptimizer.delayDepsOptimizerUntil(resolved.id, async () => {
  37059. await this.load(resolved);
  37060. });
  37061. }
  37062. return resolved;
  37063. }
  37064. },
  37065. async load(id) {
  37066. const depsOptimizer = getDepsOptimizer(config);
  37067. if (!depsOptimizer?.isOptimizedDepFile(id)) {
  37068. return;
  37069. }
  37070. depsOptimizer?.ensureFirstRun();
  37071. const file = cleanUrl(id);
  37072. // Search in both the currently optimized and newly discovered deps
  37073. // If all the inputs are dependencies, we aren't going to get any
  37074. const info = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
  37075. if (info) {
  37076. await info.processing;
  37077. debug$b?.(`load ${colors$1.cyan(file)}`);
  37078. }
  37079. else {
  37080. throw new Error(`Something unexpected happened while optimizing "${id}".`);
  37081. }
  37082. // Load the file from the cache instead of waiting for other plugin
  37083. // load hooks to avoid race conditions, once processing is resolved,
  37084. // we are sure that the file has been properly save to disk
  37085. return fsp.readFile(file, 'utf-8');
  37086. },
  37087. };
  37088. }
  37089. function throwProcessingError(id) {
  37090. const err = new Error(`Something unexpected happened while optimizing "${id}". ` +
  37091. `The current page should have reloaded by now`);
  37092. err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
  37093. // This error will be caught by the transform middleware that will
  37094. // send a 504 status code request timeout
  37095. throw err;
  37096. }
  37097. function throwOutdatedRequest(id) {
  37098. const err = new Error(`There is a new version of the pre-bundle for "${id}", ` +
  37099. `a page reload is going to ask for it.`);
  37100. err.code = ERR_OUTDATED_OPTIMIZED_DEP;
  37101. // This error will be caught by the transform middleware that will
  37102. // send a 504 status code request timeout
  37103. throw err;
  37104. }
  37105. // AST walker module for Mozilla Parser API compatible trees
  37106. function makeTest(test) {
  37107. if (typeof test === "string")
  37108. { return function (type) { return type === test; } }
  37109. else if (!test)
  37110. { return function () { return true; } }
  37111. else
  37112. { return test }
  37113. }
  37114. var Found = function Found(node, state) { this.node = node; this.state = state; };
  37115. // Find a node with a given start, end, and type (all are optional,
  37116. // null can be used as wildcard). Returns a {node, state} object, or
  37117. // undefined when it doesn't find a matching node.
  37118. function findNodeAt(node, start, end, test, baseVisitor, state) {
  37119. if (!baseVisitor) { baseVisitor = base; }
  37120. test = makeTest(test);
  37121. try {
  37122. (function c(node, st, override) {
  37123. var type = override || node.type;
  37124. if ((start == null || node.start <= start) &&
  37125. (end == null || node.end >= end))
  37126. { baseVisitor[type](node, st, c); }
  37127. if ((start == null || node.start === start) &&
  37128. (end == null || node.end === end) &&
  37129. test(type, node))
  37130. { throw new Found(node, st) }
  37131. })(node, state);
  37132. } catch (e) {
  37133. if (e instanceof Found) { return e }
  37134. throw e
  37135. }
  37136. }
  37137. function skipThrough(node, st, c) { c(node, st); }
  37138. function ignore(_node, _st, _c) {}
  37139. // Node walkers.
  37140. var base = {};
  37141. base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
  37142. for (var i = 0, list = node.body; i < list.length; i += 1)
  37143. {
  37144. var stmt = list[i];
  37145. c(stmt, st, "Statement");
  37146. }
  37147. };
  37148. base.Statement = skipThrough;
  37149. base.EmptyStatement = ignore;
  37150. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  37151. function (node, st, c) { return c(node.expression, st, "Expression"); };
  37152. base.IfStatement = function (node, st, c) {
  37153. c(node.test, st, "Expression");
  37154. c(node.consequent, st, "Statement");
  37155. if (node.alternate) { c(node.alternate, st, "Statement"); }
  37156. };
  37157. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  37158. base.BreakStatement = base.ContinueStatement = ignore;
  37159. base.WithStatement = function (node, st, c) {
  37160. c(node.object, st, "Expression");
  37161. c(node.body, st, "Statement");
  37162. };
  37163. base.SwitchStatement = function (node, st, c) {
  37164. c(node.discriminant, st, "Expression");
  37165. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  37166. var cs = list$1[i$1];
  37167. if (cs.test) { c(cs.test, st, "Expression"); }
  37168. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  37169. {
  37170. var cons = list[i];
  37171. c(cons, st, "Statement");
  37172. }
  37173. }
  37174. };
  37175. base.SwitchCase = function (node, st, c) {
  37176. if (node.test) { c(node.test, st, "Expression"); }
  37177. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  37178. {
  37179. var cons = list[i];
  37180. c(cons, st, "Statement");
  37181. }
  37182. };
  37183. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  37184. if (node.argument) { c(node.argument, st, "Expression"); }
  37185. };
  37186. base.ThrowStatement = base.SpreadElement =
  37187. function (node, st, c) { return c(node.argument, st, "Expression"); };
  37188. base.TryStatement = function (node, st, c) {
  37189. c(node.block, st, "Statement");
  37190. if (node.handler) { c(node.handler, st); }
  37191. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  37192. };
  37193. base.CatchClause = function (node, st, c) {
  37194. if (node.param) { c(node.param, st, "Pattern"); }
  37195. c(node.body, st, "Statement");
  37196. };
  37197. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  37198. c(node.test, st, "Expression");
  37199. c(node.body, st, "Statement");
  37200. };
  37201. base.ForStatement = function (node, st, c) {
  37202. if (node.init) { c(node.init, st, "ForInit"); }
  37203. if (node.test) { c(node.test, st, "Expression"); }
  37204. if (node.update) { c(node.update, st, "Expression"); }
  37205. c(node.body, st, "Statement");
  37206. };
  37207. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  37208. c(node.left, st, "ForInit");
  37209. c(node.right, st, "Expression");
  37210. c(node.body, st, "Statement");
  37211. };
  37212. base.ForInit = function (node, st, c) {
  37213. if (node.type === "VariableDeclaration") { c(node, st); }
  37214. else { c(node, st, "Expression"); }
  37215. };
  37216. base.DebuggerStatement = ignore;
  37217. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  37218. base.VariableDeclaration = function (node, st, c) {
  37219. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  37220. {
  37221. var decl = list[i];
  37222. c(decl, st);
  37223. }
  37224. };
  37225. base.VariableDeclarator = function (node, st, c) {
  37226. c(node.id, st, "Pattern");
  37227. if (node.init) { c(node.init, st, "Expression"); }
  37228. };
  37229. base.Function = function (node, st, c) {
  37230. if (node.id) { c(node.id, st, "Pattern"); }
  37231. for (var i = 0, list = node.params; i < list.length; i += 1)
  37232. {
  37233. var param = list[i];
  37234. c(param, st, "Pattern");
  37235. }
  37236. c(node.body, st, node.expression ? "Expression" : "Statement");
  37237. };
  37238. base.Pattern = function (node, st, c) {
  37239. if (node.type === "Identifier")
  37240. { c(node, st, "VariablePattern"); }
  37241. else if (node.type === "MemberExpression")
  37242. { c(node, st, "MemberPattern"); }
  37243. else
  37244. { c(node, st); }
  37245. };
  37246. base.VariablePattern = ignore;
  37247. base.MemberPattern = skipThrough;
  37248. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  37249. base.ArrayPattern = function (node, st, c) {
  37250. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  37251. var elt = list[i];
  37252. if (elt) { c(elt, st, "Pattern"); }
  37253. }
  37254. };
  37255. base.ObjectPattern = function (node, st, c) {
  37256. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  37257. var prop = list[i];
  37258. if (prop.type === "Property") {
  37259. if (prop.computed) { c(prop.key, st, "Expression"); }
  37260. c(prop.value, st, "Pattern");
  37261. } else if (prop.type === "RestElement") {
  37262. c(prop.argument, st, "Pattern");
  37263. }
  37264. }
  37265. };
  37266. base.Expression = skipThrough;
  37267. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  37268. base.ArrayExpression = function (node, st, c) {
  37269. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  37270. var elt = list[i];
  37271. if (elt) { c(elt, st, "Expression"); }
  37272. }
  37273. };
  37274. base.ObjectExpression = function (node, st, c) {
  37275. for (var i = 0, list = node.properties; i < list.length; i += 1)
  37276. {
  37277. var prop = list[i];
  37278. c(prop, st);
  37279. }
  37280. };
  37281. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  37282. base.SequenceExpression = function (node, st, c) {
  37283. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  37284. {
  37285. var expr = list[i];
  37286. c(expr, st, "Expression");
  37287. }
  37288. };
  37289. base.TemplateLiteral = function (node, st, c) {
  37290. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  37291. {
  37292. var quasi = list[i];
  37293. c(quasi, st);
  37294. }
  37295. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  37296. {
  37297. var expr = list$1[i$1];
  37298. c(expr, st, "Expression");
  37299. }
  37300. };
  37301. base.TemplateElement = ignore;
  37302. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  37303. c(node.argument, st, "Expression");
  37304. };
  37305. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  37306. c(node.left, st, "Expression");
  37307. c(node.right, st, "Expression");
  37308. };
  37309. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  37310. c(node.left, st, "Pattern");
  37311. c(node.right, st, "Expression");
  37312. };
  37313. base.ConditionalExpression = function (node, st, c) {
  37314. c(node.test, st, "Expression");
  37315. c(node.consequent, st, "Expression");
  37316. c(node.alternate, st, "Expression");
  37317. };
  37318. base.NewExpression = base.CallExpression = function (node, st, c) {
  37319. c(node.callee, st, "Expression");
  37320. if (node.arguments)
  37321. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  37322. {
  37323. var arg = list[i];
  37324. c(arg, st, "Expression");
  37325. } }
  37326. };
  37327. base.MemberExpression = function (node, st, c) {
  37328. c(node.object, st, "Expression");
  37329. if (node.computed) { c(node.property, st, "Expression"); }
  37330. };
  37331. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  37332. if (node.declaration)
  37333. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  37334. if (node.source) { c(node.source, st, "Expression"); }
  37335. };
  37336. base.ExportAllDeclaration = function (node, st, c) {
  37337. if (node.exported)
  37338. { c(node.exported, st); }
  37339. c(node.source, st, "Expression");
  37340. };
  37341. base.ImportDeclaration = function (node, st, c) {
  37342. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  37343. {
  37344. var spec = list[i];
  37345. c(spec, st);
  37346. }
  37347. c(node.source, st, "Expression");
  37348. };
  37349. base.ImportExpression = function (node, st, c) {
  37350. c(node.source, st, "Expression");
  37351. };
  37352. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
  37353. base.TaggedTemplateExpression = function (node, st, c) {
  37354. c(node.tag, st, "Expression");
  37355. c(node.quasi, st, "Expression");
  37356. };
  37357. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  37358. base.Class = function (node, st, c) {
  37359. if (node.id) { c(node.id, st, "Pattern"); }
  37360. if (node.superClass) { c(node.superClass, st, "Expression"); }
  37361. c(node.body, st);
  37362. };
  37363. base.ClassBody = function (node, st, c) {
  37364. for (var i = 0, list = node.body; i < list.length; i += 1)
  37365. {
  37366. var elt = list[i];
  37367. c(elt, st);
  37368. }
  37369. };
  37370. base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
  37371. if (node.computed) { c(node.key, st, "Expression"); }
  37372. if (node.value) { c(node.value, st, "Expression"); }
  37373. };
  37374. const { isMatch: isMatch$1, scan } = micromatch$2;
  37375. function getAffectedGlobModules(file, server) {
  37376. const modules = [];
  37377. for (const [id, allGlobs] of server._importGlobMap) {
  37378. // (glob1 || glob2) && !glob3 && !glob4...
  37379. if (allGlobs.some(({ affirmed, negated }) => (!affirmed.length || affirmed.some((glob) => isMatch$1(file, glob))) &&
  37380. (!negated.length || negated.every((glob) => isMatch$1(file, glob))))) {
  37381. const mod = server.moduleGraph.getModuleById(id);
  37382. if (mod)
  37383. modules.push(mod);
  37384. }
  37385. }
  37386. modules.forEach((i) => {
  37387. if (i?.file)
  37388. server.moduleGraph.onFileChange(i.file);
  37389. });
  37390. return modules;
  37391. }
  37392. function importGlobPlugin(config) {
  37393. let server;
  37394. return {
  37395. name: 'vite:import-glob',
  37396. configureServer(_server) {
  37397. server = _server;
  37398. server._importGlobMap.clear();
  37399. },
  37400. async transform(code, id) {
  37401. if (!code.includes('import.meta.glob'))
  37402. return;
  37403. const result = await transformGlobImport(code, id, config.root, (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im), config.isProduction, config.experimental.importGlobRestoreExtension);
  37404. if (result) {
  37405. if (server) {
  37406. const allGlobs = result.matches.map((i) => i.globsResolved);
  37407. server._importGlobMap.set(id, allGlobs.map((globs) => {
  37408. const affirmed = [];
  37409. const negated = [];
  37410. for (const glob of globs) {
  37411. (glob[0] === '!' ? negated : affirmed).push(glob);
  37412. }
  37413. return { affirmed, negated };
  37414. }));
  37415. }
  37416. return transformStableResult(result.s, id, config);
  37417. }
  37418. },
  37419. };
  37420. }
  37421. const importGlobRE = /\bimport\.meta\.(glob|globEager|globEagerDefault)(?:<\w+>)?\s*\(/g;
  37422. const knownOptions = {
  37423. as: ['string'],
  37424. eager: ['boolean'],
  37425. import: ['string'],
  37426. exhaustive: ['boolean'],
  37427. query: ['object', 'string'],
  37428. };
  37429. const forceDefaultAs = ['raw', 'url'];
  37430. function err$1(e, pos) {
  37431. const error = new Error(e);
  37432. error.pos = pos;
  37433. return error;
  37434. }
  37435. function parseGlobOptions(rawOpts, optsStartIndex) {
  37436. let opts = {};
  37437. try {
  37438. opts = evalValue(rawOpts);
  37439. }
  37440. catch {
  37441. throw err$1('Vite is unable to parse the glob options as the value is not static', optsStartIndex);
  37442. }
  37443. if (opts == null) {
  37444. return {};
  37445. }
  37446. for (const key in opts) {
  37447. if (!(key in knownOptions)) {
  37448. throw err$1(`Unknown glob option "${key}"`, optsStartIndex);
  37449. }
  37450. const allowedTypes = knownOptions[key];
  37451. const valueType = typeof opts[key];
  37452. if (!allowedTypes.includes(valueType)) {
  37453. throw err$1(`Expected glob option "${key}" to be of type ${allowedTypes.join(' or ')}, but got ${valueType}`, optsStartIndex);
  37454. }
  37455. }
  37456. if (typeof opts.query === 'object') {
  37457. for (const key in opts.query) {
  37458. const value = opts.query[key];
  37459. if (!['string', 'number', 'boolean'].includes(typeof value)) {
  37460. throw err$1(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`, optsStartIndex);
  37461. }
  37462. }
  37463. }
  37464. if (opts.as && forceDefaultAs.includes(opts.as)) {
  37465. if (opts.import && opts.import !== 'default' && opts.import !== '*')
  37466. throw err$1(`Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`, optsStartIndex);
  37467. opts.import = opts.import || 'default';
  37468. }
  37469. if (opts.as && opts.query)
  37470. throw err$1('Options "as" and "query" cannot be used together', optsStartIndex);
  37471. if (opts.as)
  37472. opts.query = opts.as;
  37473. return opts;
  37474. }
  37475. async function parseImportGlob(code, importer, root, resolveId) {
  37476. let cleanCode;
  37477. try {
  37478. cleanCode = stripLiteral(code);
  37479. }
  37480. catch (e) {
  37481. // skip invalid js code
  37482. return [];
  37483. }
  37484. const matches = Array.from(cleanCode.matchAll(importGlobRE));
  37485. const tasks = matches.map(async (match, index) => {
  37486. const type = match[1];
  37487. const start = match.index;
  37488. const err = (msg) => {
  37489. const e = new Error(`Invalid glob import syntax: ${msg}`);
  37490. e.pos = start;
  37491. return e;
  37492. };
  37493. let ast;
  37494. let lastTokenPos;
  37495. try {
  37496. ast = parseExpressionAt(code, start, {
  37497. ecmaVersion: 'latest',
  37498. sourceType: 'module',
  37499. ranges: true,
  37500. onToken: (token) => {
  37501. lastTokenPos = token.end;
  37502. },
  37503. });
  37504. }
  37505. catch (e) {
  37506. const _e = e;
  37507. if (_e.message && _e.message.startsWith('Unterminated string constant'))
  37508. return undefined;
  37509. if (lastTokenPos == null || lastTokenPos <= start)
  37510. throw _e;
  37511. // tailing comma in object or array will make the parser think it's a comma operation
  37512. // we try to parse again removing the comma
  37513. try {
  37514. const statement = code.slice(start, lastTokenPos).replace(/[,\s]*$/, '');
  37515. ast = parseExpressionAt(' '.repeat(start) + statement, // to keep the ast position
  37516. start, {
  37517. ecmaVersion: 'latest',
  37518. sourceType: 'module',
  37519. ranges: true,
  37520. });
  37521. }
  37522. catch {
  37523. throw _e;
  37524. }
  37525. }
  37526. const found = findNodeAt(ast, start, undefined, 'CallExpression');
  37527. if (!found)
  37528. throw err(`Expect CallExpression, got ${ast.type}`);
  37529. ast = found.node;
  37530. if (ast.arguments.length < 1 || ast.arguments.length > 2)
  37531. throw err(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
  37532. const arg1 = ast.arguments[0];
  37533. const arg2 = ast.arguments[1];
  37534. const globs = [];
  37535. const validateLiteral = (element) => {
  37536. if (!element)
  37537. return;
  37538. if (element.type === 'Literal') {
  37539. if (typeof element.value !== 'string')
  37540. throw err(`Expected glob to be a string, but got "${typeof element.value}"`);
  37541. globs.push(element.value);
  37542. }
  37543. else if (element.type === 'TemplateLiteral') {
  37544. if (element.expressions.length !== 0) {
  37545. throw err(`Expected glob to be a string, but got dynamic template literal`);
  37546. }
  37547. globs.push(element.quasis[0].value.raw);
  37548. }
  37549. else {
  37550. throw err('Could only use literals');
  37551. }
  37552. };
  37553. if (arg1.type === 'ArrayExpression') {
  37554. for (const element of arg1.elements) {
  37555. validateLiteral(element);
  37556. }
  37557. }
  37558. else {
  37559. validateLiteral(arg1);
  37560. }
  37561. // arg2
  37562. let options = {};
  37563. if (arg2) {
  37564. if (arg2.type !== 'ObjectExpression')
  37565. throw err(`Expected the second argument to be an object literal, but got "${arg2.type}"`);
  37566. options = parseGlobOptions(code.slice(arg2.range[0], arg2.range[1]), arg2.range[0]);
  37567. }
  37568. const end = ast.range[1];
  37569. const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId)));
  37570. const isRelative = globs.every((i) => '.!'.includes(i[0]));
  37571. return {
  37572. match,
  37573. index,
  37574. globs,
  37575. globsResolved,
  37576. isRelative,
  37577. options,
  37578. type,
  37579. start,
  37580. end,
  37581. };
  37582. });
  37583. return (await Promise.all(tasks)).filter(Boolean);
  37584. }
  37585. const importPrefix = '__vite_glob_';
  37586. const { basename, dirname, relative, join } = posix$1;
  37587. const warnedCSSDefaultImportVarName = '__vite_warned_css_default_import';
  37588. const jsonStringifyInOneline = (input) => JSON.stringify(input).replace(/[{,:]/g, '$& ').replace(/\}/g, ' }');
  37589. const createCssDefaultImportWarning = (globs, options) => `if (!${warnedCSSDefaultImportVarName}) {` +
  37590. `${warnedCSSDefaultImportVarName} = true;` +
  37591. `console.warn(${JSON.stringify('Default import of CSS without `?inline` is deprecated. ' +
  37592. "Add the `{ query: '?inline' }` glob option to fix this.\n" +
  37593. `For example: \`import.meta.glob(${jsonStringifyInOneline(globs.length === 1 ? globs[0] : globs)}, ${jsonStringifyInOneline({ ...options, query: '?inline' })})\``)});` +
  37594. `}`;
  37595. /**
  37596. * @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
  37597. */
  37598. async function transformGlobImport(code, id, root, resolveId, isProduction, restoreQueryExtension = false) {
  37599. id = slash$1(id);
  37600. root = slash$1(root);
  37601. const isVirtual = isVirtualModule(id);
  37602. const dir = isVirtual ? undefined : dirname(id);
  37603. const matches = await parseImportGlob(code, isVirtual ? undefined : id, root, resolveId);
  37604. const matchedFiles = new Set();
  37605. // TODO: backwards compatibility
  37606. matches.forEach((i) => {
  37607. if (i.type === 'globEager')
  37608. i.options.eager = true;
  37609. if (i.type === 'globEagerDefault') {
  37610. i.options.eager = true;
  37611. i.options.import = 'default';
  37612. }
  37613. });
  37614. if (!matches.length)
  37615. return null;
  37616. const s = new MagicString(code);
  37617. const staticImports = (await Promise.all(matches.map(async ({ globs, globsResolved, isRelative, options, index, start, end, }) => {
  37618. const cwd = getCommonBase(globsResolved) ?? root;
  37619. const files = (await glob(globsResolved, {
  37620. cwd,
  37621. absolute: true,
  37622. dot: !!options.exhaustive,
  37623. ignore: options.exhaustive
  37624. ? []
  37625. : [join(cwd, '**/node_modules/**')],
  37626. }))
  37627. .filter((file) => file !== id)
  37628. .sort();
  37629. const objectProps = [];
  37630. const staticImports = [];
  37631. let query = !options.query
  37632. ? ''
  37633. : typeof options.query === 'string'
  37634. ? options.query
  37635. : stringifyQuery(options.query);
  37636. if (query && query[0] !== '?')
  37637. query = `?${query}`;
  37638. const resolvePaths = (file) => {
  37639. if (!dir) {
  37640. if (isRelative)
  37641. throw new Error("In virtual modules, all globs must start with '/'");
  37642. const filePath = `/${relative(root, file)}`;
  37643. return { filePath, importPath: filePath };
  37644. }
  37645. let importPath = relative(dir, file);
  37646. if (importPath[0] !== '.')
  37647. importPath = `./${importPath}`;
  37648. let filePath;
  37649. if (isRelative) {
  37650. filePath = importPath;
  37651. }
  37652. else {
  37653. filePath = relative(root, file);
  37654. if (filePath[0] !== '.')
  37655. filePath = `/${filePath}`;
  37656. }
  37657. return { filePath, importPath };
  37658. };
  37659. let includesCSS = false;
  37660. files.forEach((file, i) => {
  37661. const paths = resolvePaths(file);
  37662. const filePath = paths.filePath;
  37663. let importPath = paths.importPath;
  37664. let importQuery = query;
  37665. if (importQuery && importQuery !== '?raw') {
  37666. const fileExtension = basename(file).split('.').slice(-1)[0];
  37667. if (fileExtension && restoreQueryExtension)
  37668. importQuery = `${importQuery}&lang.${fileExtension}`;
  37669. }
  37670. importPath = `${importPath}${importQuery}`;
  37671. const isCSS = !query && isCSSRequest(file) && !isModuleCSSRequest(file);
  37672. includesCSS || (includesCSS = isCSS);
  37673. const importKey = options.import && options.import !== '*'
  37674. ? options.import
  37675. : undefined;
  37676. if (options.eager) {
  37677. const variableName = `${importPrefix}${index}_${i}`;
  37678. const expression = importKey
  37679. ? `{ ${importKey} as ${variableName} }`
  37680. : `* as ${variableName}`;
  37681. staticImports.push(`import ${expression} from ${JSON.stringify(importPath)}`);
  37682. if (!isProduction && isCSS) {
  37683. objectProps.push(`get ${JSON.stringify(filePath)}() { ${createCssDefaultImportWarning(globs, options)} return ${variableName} }`);
  37684. }
  37685. else {
  37686. objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`);
  37687. }
  37688. }
  37689. else {
  37690. let importStatement = `import(${JSON.stringify(importPath)})`;
  37691. if (importKey)
  37692. importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
  37693. if (!isProduction && isCSS) {
  37694. objectProps.push(`${JSON.stringify(filePath)}: () => { ${createCssDefaultImportWarning(globs, options)} return ${importStatement}}`);
  37695. }
  37696. else {
  37697. objectProps.push(`${JSON.stringify(filePath)}: () => ${importStatement}`);
  37698. }
  37699. }
  37700. });
  37701. files.forEach((i) => matchedFiles.add(i));
  37702. const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
  37703. const lineBreaks = originalLineBreakCount > 0
  37704. ? '\n'.repeat(originalLineBreakCount)
  37705. : '';
  37706. let replacement;
  37707. if (!isProduction && includesCSS) {
  37708. replacement =
  37709. '/* #__PURE__ */ Object.assign(' +
  37710. '(() => {' +
  37711. `let ${warnedCSSDefaultImportVarName} = false;` +
  37712. `return {${objectProps.join(',')}${lineBreaks}};` +
  37713. '})()' +
  37714. ')';
  37715. }
  37716. else {
  37717. replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(',')}${lineBreaks}})`;
  37718. }
  37719. s.overwrite(start, end, replacement);
  37720. return staticImports;
  37721. }))).flat();
  37722. if (staticImports.length)
  37723. s.prepend(`${staticImports.join(';')};`);
  37724. return {
  37725. s,
  37726. matches,
  37727. files: matchedFiles,
  37728. };
  37729. }
  37730. function globSafePath(path) {
  37731. // slash path to ensure \ is converted to / as \ could lead to a double escape scenario
  37732. // see https://github.com/mrmlnc/fast-glob#advanced-syntax
  37733. return glob.escapePath(normalizePath$3(path));
  37734. }
  37735. function lastNthChar(str, n) {
  37736. return str.charAt(str.length - 1 - n);
  37737. }
  37738. function globSafeResolvedPath(resolved, glob) {
  37739. // we have to escape special glob characters in the resolved path, but keep the user specified globby suffix
  37740. // walk back both strings until a character difference is found
  37741. // then slice up the resolved path at that pos and escape the first part
  37742. let numEqual = 0;
  37743. const maxEqual = Math.min(resolved.length, glob.length);
  37744. while (numEqual < maxEqual &&
  37745. lastNthChar(resolved, numEqual) === lastNthChar(glob, numEqual)) {
  37746. numEqual += 1;
  37747. }
  37748. const staticPartEnd = resolved.length - numEqual;
  37749. const staticPart = resolved.slice(0, staticPartEnd);
  37750. const dynamicPart = resolved.slice(staticPartEnd);
  37751. return globSafePath(staticPart) + dynamicPart;
  37752. }
  37753. async function toAbsoluteGlob(glob, root, importer, resolveId) {
  37754. let pre = '';
  37755. if (glob[0] === '!') {
  37756. pre = '!';
  37757. glob = glob.slice(1);
  37758. }
  37759. root = globSafePath(root);
  37760. const dir = importer ? globSafePath(dirname(importer)) : root;
  37761. if (glob[0] === '/')
  37762. return pre + posix$1.join(root, glob.slice(1));
  37763. if (glob.startsWith('./'))
  37764. return pre + posix$1.join(dir, glob.slice(2));
  37765. if (glob.startsWith('../'))
  37766. return pre + posix$1.join(dir, glob);
  37767. if (glob.startsWith('**'))
  37768. return pre + glob;
  37769. const isSubImportsPattern = glob[0] === '#' && glob.includes('*');
  37770. const resolved = normalizePath$3((await resolveId(glob, importer, {
  37771. custom: { 'vite:import-glob': { isSubImportsPattern } },
  37772. })) || glob);
  37773. if (isSubImportsPattern) {
  37774. return join(root, resolved);
  37775. }
  37776. if (isAbsolute$2(resolved)) {
  37777. return pre + globSafeResolvedPath(resolved, glob);
  37778. }
  37779. throw new Error(`Invalid glob: "${glob}" (resolved: "${resolved}"). It must start with '/' or './'`);
  37780. }
  37781. function getCommonBase(globsResolved) {
  37782. const bases = globsResolved
  37783. .filter((g) => g[0] !== '!')
  37784. .map((glob) => {
  37785. let { base } = scan(glob);
  37786. // `scan('a/foo.js')` returns `base: 'a/foo.js'`
  37787. if (posix$1.basename(base).includes('.'))
  37788. base = posix$1.dirname(base);
  37789. return base;
  37790. });
  37791. if (!bases.length)
  37792. return null;
  37793. let commonAncestor = '';
  37794. const dirS = bases[0].split('/');
  37795. for (let i = 0; i < dirS.length; i++) {
  37796. const candidate = dirS.slice(0, i + 1).join('/');
  37797. if (bases.every((base) => base.startsWith(candidate)))
  37798. commonAncestor = candidate;
  37799. else
  37800. break;
  37801. }
  37802. if (!commonAncestor)
  37803. commonAncestor = '/';
  37804. return commonAncestor;
  37805. }
  37806. function isVirtualModule(id) {
  37807. // https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention
  37808. return id.startsWith('virtual:') || id[0] === '\0' || !id.includes('/');
  37809. }
  37810. const debugHmr = createDebugger('vite:hmr');
  37811. const whitespaceRE = /\s/;
  37812. const normalizedClientDir = normalizePath$3(CLIENT_DIR);
  37813. function getShortName(file, root) {
  37814. return file.startsWith(withTrailingSlash(root))
  37815. ? path$o.posix.relative(root, file)
  37816. : file;
  37817. }
  37818. async function handleHMRUpdate(file, server, configOnly) {
  37819. const { ws, config, moduleGraph } = server;
  37820. const shortFile = getShortName(file, config.root);
  37821. const fileName = path$o.basename(file);
  37822. const isConfig = file === config.configFile;
  37823. const isConfigDependency = config.configFileDependencies.some((name) => file === name);
  37824. const isEnv = config.inlineConfig.envFile !== false &&
  37825. (fileName === '.env' || fileName.startsWith('.env.'));
  37826. if (isConfig || isConfigDependency || isEnv) {
  37827. // auto restart server
  37828. debugHmr?.(`[config change] ${colors$1.dim(shortFile)}`);
  37829. config.logger.info(colors$1.green(`${path$o.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true });
  37830. try {
  37831. await server.restart();
  37832. }
  37833. catch (e) {
  37834. config.logger.error(colors$1.red(e));
  37835. }
  37836. return;
  37837. }
  37838. if (configOnly) {
  37839. return;
  37840. }
  37841. debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`);
  37842. // (dev only) the client itself cannot be hot updated.
  37843. if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
  37844. ws.send({
  37845. type: 'full-reload',
  37846. path: '*',
  37847. });
  37848. return;
  37849. }
  37850. const mods = moduleGraph.getModulesByFile(file);
  37851. // check if any plugin wants to perform custom HMR handling
  37852. const timestamp = Date.now();
  37853. const hmrContext = {
  37854. file,
  37855. timestamp,
  37856. modules: mods ? [...mods] : [],
  37857. read: () => readModifiedFile(file),
  37858. server,
  37859. };
  37860. for (const hook of config.getSortedPluginHooks('handleHotUpdate')) {
  37861. const filteredModules = await hook(hmrContext);
  37862. if (filteredModules) {
  37863. hmrContext.modules = filteredModules;
  37864. }
  37865. }
  37866. if (!hmrContext.modules.length) {
  37867. // html file cannot be hot updated
  37868. if (file.endsWith('.html')) {
  37869. config.logger.info(colors$1.green(`page reload `) + colors$1.dim(shortFile), {
  37870. clear: true,
  37871. timestamp: true,
  37872. });
  37873. ws.send({
  37874. type: 'full-reload',
  37875. path: config.server.middlewareMode
  37876. ? '*'
  37877. : '/' + normalizePath$3(path$o.relative(config.root, file)),
  37878. });
  37879. }
  37880. else {
  37881. // loaded but not in the module graph, probably not js
  37882. debugHmr?.(`[no modules matched] ${colors$1.dim(shortFile)}`);
  37883. }
  37884. return;
  37885. }
  37886. updateModules(shortFile, hmrContext.modules, timestamp, server);
  37887. }
  37888. function updateModules(file, modules, timestamp, { config, ws, moduleGraph }, afterInvalidation) {
  37889. const updates = [];
  37890. const invalidatedModules = new Set();
  37891. const traversedModules = new Set();
  37892. let needFullReload = false;
  37893. for (const mod of modules) {
  37894. const boundaries = [];
  37895. const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
  37896. moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true, boundaries.map((b) => b.boundary));
  37897. if (needFullReload) {
  37898. continue;
  37899. }
  37900. if (hasDeadEnd) {
  37901. needFullReload = true;
  37902. continue;
  37903. }
  37904. updates.push(...boundaries.map(({ boundary, acceptedVia }) => ({
  37905. type: `${boundary.type}-update`,
  37906. timestamp,
  37907. path: normalizeHmrUrl(boundary.url),
  37908. explicitImportRequired: boundary.type === 'js'
  37909. ? isExplicitImportRequired(acceptedVia.url)
  37910. : undefined,
  37911. acceptedPath: normalizeHmrUrl(acceptedVia.url),
  37912. })));
  37913. }
  37914. if (needFullReload) {
  37915. config.logger.info(colors$1.green(`page reload `) + colors$1.dim(file), {
  37916. clear: !afterInvalidation,
  37917. timestamp: true,
  37918. });
  37919. ws.send({
  37920. type: 'full-reload',
  37921. });
  37922. return;
  37923. }
  37924. if (updates.length === 0) {
  37925. debugHmr?.(colors$1.yellow(`no update happened `) + colors$1.dim(file));
  37926. return;
  37927. }
  37928. config.logger.info(colors$1.green(`hmr update `) +
  37929. colors$1.dim([...new Set(updates.map((u) => u.path))].join(', ')), { clear: !afterInvalidation, timestamp: true });
  37930. ws.send({
  37931. type: 'update',
  37932. updates,
  37933. });
  37934. }
  37935. async function handleFileAddUnlink(file, server) {
  37936. const modules = [...(server.moduleGraph.getModulesByFile(file) || [])];
  37937. modules.push(...getAffectedGlobModules(file, server));
  37938. if (modules.length > 0) {
  37939. updateModules(getShortName(file, server.config.root), unique(modules), Date.now(), server);
  37940. }
  37941. }
  37942. function areAllImportsAccepted(importedBindings, acceptedExports) {
  37943. for (const binding of importedBindings) {
  37944. if (!acceptedExports.has(binding)) {
  37945. return false;
  37946. }
  37947. }
  37948. return true;
  37949. }
  37950. function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
  37951. if (traversedModules.has(node)) {
  37952. return false;
  37953. }
  37954. traversedModules.add(node);
  37955. // #7561
  37956. // if the imports of `node` have not been analyzed, then `node` has not
  37957. // been loaded in the browser and we should stop propagation.
  37958. if (node.id && node.isSelfAccepting === undefined) {
  37959. debugHmr?.(`[propagate update] stop propagation because not analyzed: ${colors$1.dim(node.id)}`);
  37960. return false;
  37961. }
  37962. if (node.isSelfAccepting) {
  37963. boundaries.push({ boundary: node, acceptedVia: node });
  37964. // additionally check for CSS importers, since a PostCSS plugin like
  37965. // Tailwind JIT may register any file as a dependency to a CSS file.
  37966. for (const importer of node.importers) {
  37967. if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
  37968. propagateUpdate(importer, traversedModules, boundaries, currentChain.concat(importer));
  37969. }
  37970. }
  37971. return false;
  37972. }
  37973. // A partially accepted module with no importers is considered self accepting,
  37974. // because the deal is "there are parts of myself I can't self accept if they
  37975. // are used outside of me".
  37976. // Also, the imported module (this one) must be updated before the importers,
  37977. // so that they do get the fresh imported module when/if they are reloaded.
  37978. if (node.acceptedHmrExports) {
  37979. boundaries.push({ boundary: node, acceptedVia: node });
  37980. }
  37981. else {
  37982. if (!node.importers.size) {
  37983. return true;
  37984. }
  37985. // #3716, #3913
  37986. // For a non-CSS file, if all of its importers are CSS files (registered via
  37987. // PostCSS plugins) it should be considered a dead end and force full reload.
  37988. if (!isCSSRequest(node.url) &&
  37989. [...node.importers].every((i) => isCSSRequest(i.url))) {
  37990. return true;
  37991. }
  37992. }
  37993. for (const importer of node.importers) {
  37994. const subChain = currentChain.concat(importer);
  37995. if (importer.acceptedHmrDeps.has(node)) {
  37996. boundaries.push({ boundary: importer, acceptedVia: node });
  37997. continue;
  37998. }
  37999. if (node.id && node.acceptedHmrExports && importer.importedBindings) {
  38000. const importedBindingsFromNode = importer.importedBindings.get(node.id);
  38001. if (importedBindingsFromNode &&
  38002. areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) {
  38003. continue;
  38004. }
  38005. }
  38006. if (currentChain.includes(importer)) {
  38007. // circular deps is considered dead end
  38008. return true;
  38009. }
  38010. if (propagateUpdate(importer, traversedModules, boundaries, subChain)) {
  38011. return true;
  38012. }
  38013. }
  38014. return false;
  38015. }
  38016. function handlePrunedModules(mods, { ws }) {
  38017. // update the disposed modules' hmr timestamp
  38018. // since if it's re-imported, it should re-apply side effects
  38019. // and without the timestamp the browser will not re-import it!
  38020. const t = Date.now();
  38021. mods.forEach((mod) => {
  38022. mod.lastHMRTimestamp = t;
  38023. debugHmr?.(`[dispose] ${colors$1.dim(mod.file)}`);
  38024. });
  38025. ws.send({
  38026. type: 'prune',
  38027. paths: [...mods].map((m) => m.url),
  38028. });
  38029. }
  38030. /**
  38031. * Lex import.meta.hot.accept() for accepted deps.
  38032. * Since hot.accept() can only accept string literals or array of string
  38033. * literals, we don't really need a heavy @babel/parse call on the entire source.
  38034. *
  38035. * @returns selfAccepts
  38036. */
  38037. function lexAcceptedHmrDeps(code, start, urls) {
  38038. let state = 0 /* LexerState.inCall */;
  38039. // the state can only be 2 levels deep so no need for a stack
  38040. let prevState = 0 /* LexerState.inCall */;
  38041. let currentDep = '';
  38042. function addDep(index) {
  38043. urls.add({
  38044. url: currentDep,
  38045. start: index - currentDep.length - 1,
  38046. end: index + 1,
  38047. });
  38048. currentDep = '';
  38049. }
  38050. for (let i = start; i < code.length; i++) {
  38051. const char = code.charAt(i);
  38052. switch (state) {
  38053. case 0 /* LexerState.inCall */:
  38054. case 4 /* LexerState.inArray */:
  38055. if (char === `'`) {
  38056. prevState = state;
  38057. state = 1 /* LexerState.inSingleQuoteString */;
  38058. }
  38059. else if (char === `"`) {
  38060. prevState = state;
  38061. state = 2 /* LexerState.inDoubleQuoteString */;
  38062. }
  38063. else if (char === '`') {
  38064. prevState = state;
  38065. state = 3 /* LexerState.inTemplateString */;
  38066. }
  38067. else if (whitespaceRE.test(char)) {
  38068. continue;
  38069. }
  38070. else {
  38071. if (state === 0 /* LexerState.inCall */) {
  38072. if (char === `[`) {
  38073. state = 4 /* LexerState.inArray */;
  38074. }
  38075. else {
  38076. // reaching here means the first arg is neither a string literal
  38077. // nor an Array literal (direct callback) or there is no arg
  38078. // in both case this indicates a self-accepting module
  38079. return true; // done
  38080. }
  38081. }
  38082. else if (state === 4 /* LexerState.inArray */) {
  38083. if (char === `]`) {
  38084. return false; // done
  38085. }
  38086. else if (char === ',') {
  38087. continue;
  38088. }
  38089. else {
  38090. error$1(i);
  38091. }
  38092. }
  38093. }
  38094. break;
  38095. case 1 /* LexerState.inSingleQuoteString */:
  38096. if (char === `'`) {
  38097. addDep(i);
  38098. if (prevState === 0 /* LexerState.inCall */) {
  38099. // accept('foo', ...)
  38100. return false;
  38101. }
  38102. else {
  38103. state = prevState;
  38104. }
  38105. }
  38106. else {
  38107. currentDep += char;
  38108. }
  38109. break;
  38110. case 2 /* LexerState.inDoubleQuoteString */:
  38111. if (char === `"`) {
  38112. addDep(i);
  38113. if (prevState === 0 /* LexerState.inCall */) {
  38114. // accept('foo', ...)
  38115. return false;
  38116. }
  38117. else {
  38118. state = prevState;
  38119. }
  38120. }
  38121. else {
  38122. currentDep += char;
  38123. }
  38124. break;
  38125. case 3 /* LexerState.inTemplateString */:
  38126. if (char === '`') {
  38127. addDep(i);
  38128. if (prevState === 0 /* LexerState.inCall */) {
  38129. // accept('foo', ...)
  38130. return false;
  38131. }
  38132. else {
  38133. state = prevState;
  38134. }
  38135. }
  38136. else if (char === '$' && code.charAt(i + 1) === '{') {
  38137. error$1(i);
  38138. }
  38139. else {
  38140. currentDep += char;
  38141. }
  38142. break;
  38143. default:
  38144. throw new Error('unknown import.meta.hot lexer state');
  38145. }
  38146. }
  38147. return false;
  38148. }
  38149. function lexAcceptedHmrExports(code, start, exportNames) {
  38150. const urls = new Set();
  38151. lexAcceptedHmrDeps(code, start, urls);
  38152. for (const { url } of urls) {
  38153. exportNames.add(url);
  38154. }
  38155. return urls.size > 0;
  38156. }
  38157. function normalizeHmrUrl(url) {
  38158. if (url[0] !== '.' && url[0] !== '/') {
  38159. url = wrapId(url);
  38160. }
  38161. return url;
  38162. }
  38163. function error$1(pos) {
  38164. const err = new Error(`import.meta.hot.accept() can only accept string literals or an ` +
  38165. `Array of string literals.`);
  38166. err.pos = pos;
  38167. throw err;
  38168. }
  38169. // vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
  38170. // change event and sometimes this can be too early and get an empty buffer.
  38171. // Poll until the file's modified time has changed before reading again.
  38172. async function readModifiedFile(file) {
  38173. const content = await fsp.readFile(file, 'utf-8');
  38174. if (!content) {
  38175. const mtime = (await fsp.stat(file)).mtimeMs;
  38176. await new Promise((r) => {
  38177. let n = 0;
  38178. const poll = async () => {
  38179. n++;
  38180. const newMtime = (await fsp.stat(file)).mtimeMs;
  38181. if (newMtime !== mtime || n > 10) {
  38182. r(0);
  38183. }
  38184. else {
  38185. setTimeout(poll, 10);
  38186. }
  38187. };
  38188. setTimeout(poll, 10);
  38189. });
  38190. return await fsp.readFile(file, 'utf-8');
  38191. }
  38192. else {
  38193. return content;
  38194. }
  38195. }
  38196. const debug$a = createDebugger('vite:import-analysis');
  38197. const clientDir = normalizePath$3(CLIENT_DIR);
  38198. const skipRE = /\.(?:map|json)(?:$|\?)/;
  38199. const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  38200. const optimizedDepChunkRE$1 = /\/chunk-[A-Z\d]{8}\.js/;
  38201. const optimizedDepDynamicRE$1 = /-[A-Z\d]{8}\.js/;
  38202. const hasImportInQueryParamsRE = /[?&]import=?\b/;
  38203. const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
  38204. const cleanUpRawUrlRE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm;
  38205. const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
  38206. const templateLiteralRE = /^\s*`(.*)`\s*$/;
  38207. function isExplicitImportRequired(url) {
  38208. return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
  38209. }
  38210. function markExplicitImport(url) {
  38211. if (isExplicitImportRequired(url)) {
  38212. return injectQuery(url, 'import');
  38213. }
  38214. return url;
  38215. }
  38216. function extractImportedBindings(id, source, importSpec, importedBindings) {
  38217. let bindings = importedBindings.get(id);
  38218. if (!bindings) {
  38219. bindings = new Set();
  38220. importedBindings.set(id, bindings);
  38221. }
  38222. const isDynamic = importSpec.d > -1;
  38223. const isMeta = importSpec.d === -2;
  38224. if (isDynamic || isMeta) {
  38225. // this basically means the module will be impacted by any change in its dep
  38226. bindings.add('*');
  38227. return;
  38228. }
  38229. const exp = source.slice(importSpec.ss, importSpec.se);
  38230. const [match0] = findStaticImports(exp);
  38231. if (!match0) {
  38232. return;
  38233. }
  38234. const parsed = parseStaticImport(match0);
  38235. if (!parsed) {
  38236. return;
  38237. }
  38238. if (parsed.namespacedImport) {
  38239. bindings.add('*');
  38240. }
  38241. if (parsed.defaultImport) {
  38242. bindings.add('default');
  38243. }
  38244. if (parsed.namedImports) {
  38245. for (const name of Object.keys(parsed.namedImports)) {
  38246. bindings.add(name);
  38247. }
  38248. }
  38249. }
  38250. /**
  38251. * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.
  38252. *
  38253. * - Imports are resolved to ensure they exist on disk
  38254. *
  38255. * - Lexes HMR accept calls and updates import relationships in the module graph
  38256. *
  38257. * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
  38258. * absolute file paths, e.g.
  38259. *
  38260. * ```js
  38261. * import 'foo'
  38262. * ```
  38263. * is rewritten to
  38264. * ```js
  38265. * import '/@fs//project/node_modules/foo/dist/foo.js'
  38266. * ```
  38267. *
  38268. * - CSS imports are appended with `.js` since both the js module and the actual
  38269. * css (referenced via `<link>`) may go through the transform pipeline:
  38270. *
  38271. * ```js
  38272. * import './style.css'
  38273. * ```
  38274. * is rewritten to
  38275. * ```js
  38276. * import './style.css.js'
  38277. * ```
  38278. */
  38279. function importAnalysisPlugin(config) {
  38280. const { root, base } = config;
  38281. const clientPublicPath = path$o.posix.join(base, CLIENT_PUBLIC_PATH);
  38282. const enablePartialAccept = config.experimental?.hmrPartialAccept;
  38283. let server;
  38284. let _env;
  38285. function getEnv(ssr) {
  38286. if (!_env) {
  38287. _env = `import.meta.env = ${JSON.stringify({
  38288. ...config.env,
  38289. SSR: '__vite__ssr__',
  38290. })};`;
  38291. // account for user env defines
  38292. for (const key in config.define) {
  38293. if (key.startsWith(`import.meta.env.`)) {
  38294. const val = config.define[key];
  38295. _env += `${key} = ${typeof val === 'string' ? val : JSON.stringify(val)};`;
  38296. }
  38297. }
  38298. }
  38299. return _env.replace('"__vite__ssr__"', ssr + '');
  38300. }
  38301. return {
  38302. name: 'vite:import-analysis',
  38303. configureServer(_server) {
  38304. server = _server;
  38305. },
  38306. async transform(source, importer, options) {
  38307. // In a real app `server` is always defined, but it is undefined when
  38308. // running src/node/server/__tests__/pluginContainer.spec.ts
  38309. if (!server) {
  38310. return null;
  38311. }
  38312. const ssr = options?.ssr === true;
  38313. const prettyImporter = prettifyUrl(importer, root);
  38314. if (canSkipImportAnalysis(importer)) {
  38315. debug$a?.(colors$1.dim(`[skipped] ${prettyImporter}`));
  38316. return null;
  38317. }
  38318. const start = performance.now();
  38319. await init;
  38320. let imports;
  38321. let exports;
  38322. source = stripBomTag(source);
  38323. try {
  38324. [imports, exports] = parse$e(source);
  38325. }
  38326. catch (e) {
  38327. const isVue = importer.endsWith('.vue');
  38328. const isJsx = importer.endsWith('.jsx') || importer.endsWith('.tsx');
  38329. const maybeJSX = !isVue && isJSRequest(importer);
  38330. const msg = isVue
  38331. ? `Install @vitejs/plugin-vue to handle .vue files.`
  38332. : maybeJSX
  38333. ? isJsx
  38334. ? `If you use tsconfig.json, make sure to not set jsx to preserve.`
  38335. : `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`
  38336. : `You may need to install appropriate plugins to handle the ${path$o.extname(importer)} file format, or if it's an asset, add "**/*${path$o.extname(importer)}" to \`assetsInclude\` in your configuration.`;
  38337. this.error(`Failed to parse source for import analysis because the content ` +
  38338. `contains invalid JS syntax. ` +
  38339. msg, e.idx);
  38340. }
  38341. const depsOptimizer = getDepsOptimizer(config, ssr);
  38342. const { moduleGraph } = server;
  38343. // since we are already in the transform phase of the importer, it must
  38344. // have been loaded so its entry is guaranteed in the module graph.
  38345. const importerModule = moduleGraph.getModuleById(importer);
  38346. if (!importerModule) {
  38347. // This request is no longer valid. It could happen for optimized deps
  38348. // requests. A full reload is going to request this id again.
  38349. // Throwing an outdated error so we properly finish the request with a
  38350. // 504 sent to the browser.
  38351. throwOutdatedRequest(importer);
  38352. }
  38353. if (!imports.length && !this._addedImports) {
  38354. importerModule.isSelfAccepting = false;
  38355. debug$a?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettyImporter}`)}`);
  38356. return source;
  38357. }
  38358. let hasHMR = false;
  38359. let isSelfAccepting = false;
  38360. let hasEnv = false;
  38361. let needQueryInjectHelper = false;
  38362. let s;
  38363. const str = () => s || (s = new MagicString(source));
  38364. let isPartiallySelfAccepting = false;
  38365. const importedBindings = enablePartialAccept
  38366. ? new Map()
  38367. : null;
  38368. const toAbsoluteUrl = (url) => path$o.posix.resolve(path$o.posix.dirname(importerModule.url), url);
  38369. const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => {
  38370. url = stripBase(url, base);
  38371. let importerFile = importer;
  38372. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  38373. if (moduleListContains(optimizeDeps?.exclude, url)) {
  38374. if (depsOptimizer) {
  38375. await depsOptimizer.scanProcessing;
  38376. // if the dependency encountered in the optimized file was excluded from the optimization
  38377. // the dependency needs to be resolved starting from the original source location of the optimized file
  38378. // because starting from node_modules/.vite will not find the dependency if it was not hoisted
  38379. // (that is, if it is under node_modules directory in the package source of the optimized file)
  38380. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  38381. if (!optimizedModule.src)
  38382. continue; // Ignore chunks
  38383. if (optimizedModule.file === importerModule.file) {
  38384. importerFile = optimizedModule.src;
  38385. }
  38386. }
  38387. }
  38388. }
  38389. const resolved = await this.resolve(url, importerFile);
  38390. if (!resolved) {
  38391. // in ssr, we should let node handle the missing modules
  38392. if (ssr) {
  38393. return [url, url];
  38394. }
  38395. // fix#9534, prevent the importerModuleNode being stopped from propagating updates
  38396. importerModule.isSelfAccepting = false;
  38397. return this.error(`Failed to resolve import "${url}" from "${path$o.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
  38398. }
  38399. const isRelative = url[0] === '.';
  38400. const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
  38401. // normalize all imports into resolved URLs
  38402. // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
  38403. if (resolved.id.startsWith(withTrailingSlash(root))) {
  38404. // in root: infer short absolute path from root
  38405. url = resolved.id.slice(root.length);
  38406. }
  38407. else if (depsOptimizer?.isOptimizedDepFile(resolved.id) ||
  38408. fs$l.existsSync(cleanUrl(resolved.id))) {
  38409. // an optimized deps may not yet exists in the filesystem, or
  38410. // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
  38411. url = path$o.posix.join(FS_PREFIX, resolved.id);
  38412. }
  38413. else {
  38414. url = resolved.id;
  38415. }
  38416. if (isExternalUrl(url)) {
  38417. return [url, url];
  38418. }
  38419. // if the resolved id is not a valid browser import specifier,
  38420. // prefix it to make it valid. We will strip this before feeding it
  38421. // back into the transform pipeline
  38422. if (url[0] !== '.' && url[0] !== '/') {
  38423. url = wrapId(resolved.id);
  38424. }
  38425. // make the URL browser-valid if not SSR
  38426. if (!ssr) {
  38427. // mark non-js/css imports with `?import`
  38428. url = markExplicitImport(url);
  38429. // If the url isn't a request for a pre-bundled common chunk,
  38430. // for relative js/css imports, or self-module virtual imports
  38431. // (e.g. vue blocks), inherit importer's version query
  38432. // do not do this for unknown type imports, otherwise the appended
  38433. // query can break 3rd party plugin's extension checks.
  38434. if ((isRelative || isSelfImport) &&
  38435. !hasImportInQueryParamsRE.test(url) &&
  38436. !url.match(DEP_VERSION_RE)) {
  38437. const versionMatch = importer.match(DEP_VERSION_RE);
  38438. if (versionMatch) {
  38439. url = injectQuery(url, versionMatch[1]);
  38440. }
  38441. }
  38442. // check if the dep has been hmr updated. If yes, we need to attach
  38443. // its last updated timestamp to force the browser to fetch the most
  38444. // up-to-date version of this module.
  38445. try {
  38446. // delay setting `isSelfAccepting` until the file is actually used (#7870)
  38447. // We use an internal function to avoid resolving the url again
  38448. const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), ssr, canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved);
  38449. if (depModule.lastHMRTimestamp > 0) {
  38450. url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  38451. }
  38452. }
  38453. catch (e) {
  38454. // it's possible that the dep fails to resolve (non-existent import)
  38455. // attach location to the missing import
  38456. e.pos = pos;
  38457. throw e;
  38458. }
  38459. // prepend base
  38460. url = joinUrlSegments(base, url);
  38461. }
  38462. return [url, resolved.id];
  38463. };
  38464. const orderedImportedUrls = new Array(imports.length);
  38465. const orderedAcceptedUrls = new Array(imports.length);
  38466. const orderedAcceptedExports = new Array(imports.length);
  38467. await Promise.all(imports.map(async (importSpecifier, index) => {
  38468. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: assertIndex, } = importSpecifier;
  38469. // #2083 User may use escape path,
  38470. // so use imports[index].n to get the unescaped string
  38471. let specifier = importSpecifier.n;
  38472. const rawUrl = source.slice(start, end);
  38473. // check import.meta usage
  38474. if (rawUrl === 'import.meta') {
  38475. const prop = source.slice(end, end + 4);
  38476. if (prop === '.hot') {
  38477. hasHMR = true;
  38478. const endHot = end + 4 + (source[end + 4] === '?' ? 1 : 0);
  38479. if (source.slice(endHot, endHot + 7) === '.accept') {
  38480. // further analyze accepted modules
  38481. if (source.slice(endHot, endHot + 14) === '.acceptExports') {
  38482. const importAcceptedExports = (orderedAcceptedExports[index] =
  38483. new Set());
  38484. lexAcceptedHmrExports(source, source.indexOf('(', endHot + 14) + 1, importAcceptedExports);
  38485. isPartiallySelfAccepting = true;
  38486. }
  38487. else {
  38488. const importAcceptedUrls = (orderedAcceptedUrls[index] =
  38489. new Set());
  38490. if (lexAcceptedHmrDeps(source, source.indexOf('(', endHot + 7) + 1, importAcceptedUrls)) {
  38491. isSelfAccepting = true;
  38492. }
  38493. }
  38494. }
  38495. }
  38496. else if (prop === '.env') {
  38497. hasEnv = true;
  38498. }
  38499. return;
  38500. }
  38501. else if (templateLiteralRE.test(rawUrl)) {
  38502. // If the import has backticks but isn't transformed as a glob import
  38503. // (as there's nothing to glob), check if it's simply a plain string.
  38504. // If so, we can replace the specifier as a plain string to prevent
  38505. // an incorrect "cannot be analyzed" warning.
  38506. if (!(rawUrl.includes('${') && rawUrl.includes('}'))) {
  38507. specifier = rawUrl.replace(templateLiteralRE, '$1');
  38508. }
  38509. }
  38510. const isDynamicImport = dynamicIndex > -1;
  38511. // strip import assertions as we can process them ourselves
  38512. if (!isDynamicImport && assertIndex > -1) {
  38513. str().remove(end + 1, expEnd);
  38514. }
  38515. // static import or valid string in dynamic import
  38516. // If resolvable, let's resolve it
  38517. if (specifier) {
  38518. // skip external / data uri
  38519. if (isExternalUrl(specifier) || isDataUrl(specifier)) {
  38520. return;
  38521. }
  38522. // skip ssr external
  38523. if (ssr) {
  38524. if (config.legacy?.buildSsrCjsExternalHeuristics) {
  38525. if (cjsShouldExternalizeForSSR(specifier, server._ssrExternals)) {
  38526. return;
  38527. }
  38528. }
  38529. else if (shouldExternalizeForSSR(specifier, importer, config)) {
  38530. return;
  38531. }
  38532. if (isBuiltin(specifier)) {
  38533. return;
  38534. }
  38535. }
  38536. // skip client
  38537. if (specifier === clientPublicPath) {
  38538. return;
  38539. }
  38540. // warn imports to non-asset /public files
  38541. if (specifier[0] === '/' &&
  38542. !(config.assetsInclude(cleanUrl(specifier)) ||
  38543. urlRE$1.test(specifier)) &&
  38544. checkPublicFile(specifier, config)) {
  38545. throw new Error(`Cannot import non-asset file ${specifier} which is inside /public. ` +
  38546. `JS/CSS files inside /public are copied as-is on build and ` +
  38547. `can only be referenced via <script src> or <link href> in html. ` +
  38548. `If you want to get the URL of that file, use ${injectQuery(specifier, 'url')} instead.`);
  38549. }
  38550. // normalize
  38551. const [url, resolvedId] = await normalizeUrl(specifier, start);
  38552. if (!isDynamicImport &&
  38553. specifier &&
  38554. !specifier.includes('?') && // ignore custom queries
  38555. isCSSRequest(resolvedId) &&
  38556. !isModuleCSSRequest(resolvedId)) {
  38557. const sourceExp = source.slice(expStart, start);
  38558. if (sourceExp.includes('from') && // check default and named imports
  38559. !sourceExp.includes('__vite_glob_') // glob handles deprecation message itself
  38560. ) {
  38561. const newImport = sourceExp + specifier + `?inline` + source.slice(end, expEnd);
  38562. this.warn(`\n` +
  38563. colors$1.cyan(importerModule.file) +
  38564. `\n` +
  38565. colors$1.reset(generateCodeFrame(source, start)) +
  38566. `\n` +
  38567. colors$1.yellow(`Default and named imports from CSS files are deprecated. ` +
  38568. `Use the ?inline query instead. ` +
  38569. `For example: ${newImport}`));
  38570. }
  38571. }
  38572. // record as safe modules
  38573. // safeModulesPath should not include the base prefix.
  38574. // See https://github.com/vitejs/vite/issues/9438#issuecomment-1465270409
  38575. server?.moduleGraph.safeModulesPath.add(fsPathFromUrl(stripBase(url, base)));
  38576. if (url !== specifier) {
  38577. let rewriteDone = false;
  38578. if (depsOptimizer?.isOptimizedDepFile(resolvedId) &&
  38579. !resolvedId.match(optimizedDepChunkRE$1)) {
  38580. // for optimized cjs deps, support named imports by rewriting named imports to const assignments.
  38581. // internal optimized chunks don't need es interop and are excluded
  38582. // The browserHash in resolvedId could be stale in which case there will be a full
  38583. // page reload. We could return a 404 in that case but it is safe to return the request
  38584. const file = cleanUrl(resolvedId); // Remove ?v={hash}
  38585. const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config, ssr);
  38586. if (needsInterop === undefined) {
  38587. // Non-entry dynamic imports from dependencies will reach here as there isn't
  38588. // optimize info for them, but they don't need es interop. If the request isn't
  38589. // a dynamic import, then it is an internal Vite error
  38590. if (!file.match(optimizedDepDynamicRE$1)) {
  38591. config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
  38592. }
  38593. }
  38594. else if (needsInterop) {
  38595. debug$a?.(`${url} needs interop`);
  38596. interopNamedImports(str(), importSpecifier, url, index, importer, config);
  38597. rewriteDone = true;
  38598. }
  38599. }
  38600. // If source code imports builtin modules via named imports, the stub proxy export
  38601. // would fail as it's `export default` only. Apply interop for builtin modules to
  38602. // correctly throw the error message.
  38603. else if (url.includes(browserExternalId) &&
  38604. source.slice(expStart, start).includes('{')) {
  38605. interopNamedImports(str(), importSpecifier, url, index, importer, config);
  38606. rewriteDone = true;
  38607. }
  38608. if (!rewriteDone) {
  38609. const rewrittenUrl = JSON.stringify(url);
  38610. const s = isDynamicImport ? start : start - 1;
  38611. const e = isDynamicImport ? end : end + 1;
  38612. str().overwrite(s, e, rewrittenUrl, {
  38613. contentOnly: true,
  38614. });
  38615. }
  38616. }
  38617. // record for HMR import chain analysis
  38618. // make sure to unwrap and normalize away base
  38619. const hmrUrl = unwrapId(stripBase(url, base));
  38620. const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
  38621. if (isLocalImport) {
  38622. orderedImportedUrls[index] = hmrUrl;
  38623. }
  38624. if (enablePartialAccept && importedBindings) {
  38625. extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
  38626. }
  38627. if (!isDynamicImport &&
  38628. isLocalImport &&
  38629. config.server.preTransformRequests) {
  38630. // pre-transform known direct imports
  38631. // These requests will also be registered in transformRequest to be awaited
  38632. // by the deps optimizer
  38633. const url = removeImportQuery(hmrUrl);
  38634. server.transformRequest(url, { ssr }).catch((e) => {
  38635. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP ||
  38636. e?.code === ERR_CLOSED_SERVER) {
  38637. // these are expected errors
  38638. return;
  38639. }
  38640. // Unexpected error, log the issue but avoid an unhandled exception
  38641. config.logger.error(e.message, { error: e });
  38642. });
  38643. }
  38644. }
  38645. else if (!importer.startsWith(withTrailingSlash(clientDir))) {
  38646. if (!isInNodeModules(importer)) {
  38647. // check @vite-ignore which suppresses dynamic import warning
  38648. const hasViteIgnore = hasViteIgnoreRE.test(
  38649. // complete expression inside parens
  38650. source.slice(dynamicIndex + 1, end));
  38651. if (!hasViteIgnore) {
  38652. this.warn(`\n` +
  38653. colors$1.cyan(importerModule.file) +
  38654. `\n` +
  38655. colors$1.reset(generateCodeFrame(source, start)) +
  38656. colors$1.yellow(`\nThe above dynamic import cannot be analyzed by Vite.\n` +
  38657. `See ${colors$1.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} ` +
  38658. `for supported dynamic import formats. ` +
  38659. `If this is intended to be left as-is, you can use the ` +
  38660. `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`));
  38661. }
  38662. }
  38663. if (!ssr) {
  38664. const url = rawUrl.replace(cleanUpRawUrlRE, '').trim();
  38665. if (!urlIsStringRE.test(url) ||
  38666. isExplicitImportRequired(url.slice(1, -1))) {
  38667. needQueryInjectHelper = true;
  38668. str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`, { contentOnly: true });
  38669. }
  38670. }
  38671. }
  38672. }));
  38673. const importedUrls = new Set(orderedImportedUrls.filter(Boolean));
  38674. const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
  38675. const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
  38676. if (hasEnv) {
  38677. // inject import.meta.env
  38678. str().prepend(getEnv(ssr));
  38679. }
  38680. if (hasHMR && !ssr) {
  38681. debugHmr?.(`${isSelfAccepting
  38682. ? `[self-accepts]`
  38683. : isPartiallySelfAccepting
  38684. ? `[accepts-exports]`
  38685. : acceptedUrls.size
  38686. ? `[accepts-deps]`
  38687. : `[detected api usage]`} ${prettyImporter}`);
  38688. // inject hot context
  38689. str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
  38690. `import.meta.hot = __vite__createHotContext(${JSON.stringify(normalizeHmrUrl(importerModule.url))});`);
  38691. }
  38692. if (needQueryInjectHelper) {
  38693. str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
  38694. }
  38695. // normalize and rewrite accepted urls
  38696. const normalizedAcceptedUrls = new Set();
  38697. for (const { url, start, end } of acceptedUrls) {
  38698. const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(url), ssr);
  38699. normalizedAcceptedUrls.add(normalized);
  38700. str().overwrite(start, end, JSON.stringify(normalized), {
  38701. contentOnly: true,
  38702. });
  38703. }
  38704. // update the module graph for HMR analysis.
  38705. // node CSS imports does its own graph update in the css plugin so we
  38706. // only handle js graph updates here.
  38707. if (!isCSSRequest(importer)) {
  38708. // attached by pluginContainer.addWatchFile
  38709. const pluginImports = this._addedImports;
  38710. if (pluginImports) {
  38711. (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0, true)))).forEach(([url]) => importedUrls.add(url));
  38712. }
  38713. // HMR transforms are no-ops in SSR, so an `accept` call will
  38714. // never be injected. Avoid updating the `isSelfAccepting`
  38715. // property for our module node in that case.
  38716. if (ssr && importerModule.isSelfAccepting) {
  38717. isSelfAccepting = true;
  38718. }
  38719. // a partially accepted module that accepts all its exports
  38720. // behaves like a self-accepted module in practice
  38721. if (!isSelfAccepting &&
  38722. isPartiallySelfAccepting &&
  38723. acceptedExports.size >= exports.length &&
  38724. exports.every((e) => acceptedExports.has(e.n))) {
  38725. isSelfAccepting = true;
  38726. }
  38727. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, importedBindings, normalizedAcceptedUrls, isPartiallySelfAccepting ? acceptedExports : null, isSelfAccepting, ssr);
  38728. if (hasHMR && prunedImports) {
  38729. handlePrunedModules(prunedImports, server);
  38730. }
  38731. }
  38732. debug$a?.(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
  38733. if (s) {
  38734. return transformStableResult(s, importer, config);
  38735. }
  38736. else {
  38737. return source;
  38738. }
  38739. },
  38740. };
  38741. }
  38742. function mergeAcceptedUrls(orderedUrls) {
  38743. const acceptedUrls = new Set();
  38744. for (const urls of orderedUrls) {
  38745. if (!urls)
  38746. continue;
  38747. for (const url of urls)
  38748. acceptedUrls.add(url);
  38749. }
  38750. return acceptedUrls;
  38751. }
  38752. function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
  38753. const source = str.original;
  38754. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = importSpecifier;
  38755. const exp = source.slice(expStart, expEnd);
  38756. if (dynamicIndex > -1) {
  38757. // rewrite `import('package')` to expose the default directly
  38758. str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))` +
  38759. getLineBreaks(exp), { contentOnly: true });
  38760. }
  38761. else {
  38762. const rawUrl = source.slice(start, end);
  38763. const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex, importer, config);
  38764. if (rewritten) {
  38765. str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), {
  38766. contentOnly: true,
  38767. });
  38768. }
  38769. else {
  38770. // #1439 export * from '...'
  38771. str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), {
  38772. contentOnly: true,
  38773. });
  38774. }
  38775. }
  38776. }
  38777. // get line breaks to preserve line count for not breaking source maps
  38778. function getLineBreaks(str) {
  38779. return str.includes('\n') ? '\n'.repeat(str.split('\n').length - 1) : '';
  38780. }
  38781. /**
  38782. * Detect import statements to a known optimized CJS dependency and provide
  38783. * ES named imports interop. We do this by rewriting named imports to a variable
  38784. * assignment to the corresponding property on the `module.exports` of the cjs
  38785. * module. Note this doesn't support dynamic re-assignments from within the cjs
  38786. * module.
  38787. *
  38788. * Note that es-module-lexer treats `export * from '...'` as an import as well,
  38789. * so, we may encounter ExportAllDeclaration here, in which case `undefined`
  38790. * will be returned.
  38791. *
  38792. * Credits \@csr632 via #837
  38793. */
  38794. function transformCjsImport(importExp, url, rawUrl, importIndex, importer, config) {
  38795. const node = parse$b(importExp, {
  38796. ecmaVersion: 'latest',
  38797. sourceType: 'module',
  38798. }).body[0];
  38799. // `export * from '...'` may cause unexpected problem, so give it a warning
  38800. if (config.command === 'serve' &&
  38801. node.type === 'ExportAllDeclaration' &&
  38802. !node.exported) {
  38803. config.logger.warn(colors$1.yellow(`\nUnable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``));
  38804. }
  38805. else if (node.type === 'ImportDeclaration' ||
  38806. node.type === 'ExportNamedDeclaration') {
  38807. if (!node.specifiers.length) {
  38808. return `import "${url}"`;
  38809. }
  38810. const importNames = [];
  38811. const exportNames = [];
  38812. let defaultExports = '';
  38813. for (const spec of node.specifiers) {
  38814. if (spec.type === 'ImportSpecifier' &&
  38815. spec.imported.type === 'Identifier') {
  38816. const importedName = spec.imported.name;
  38817. const localName = spec.local.name;
  38818. importNames.push({ importedName, localName });
  38819. }
  38820. else if (spec.type === 'ImportDefaultSpecifier') {
  38821. importNames.push({
  38822. importedName: 'default',
  38823. localName: spec.local.name,
  38824. });
  38825. }
  38826. else if (spec.type === 'ImportNamespaceSpecifier') {
  38827. importNames.push({ importedName: '*', localName: spec.local.name });
  38828. }
  38829. else if (spec.type === 'ExportSpecifier' &&
  38830. spec.exported.type === 'Identifier') {
  38831. // for ExportSpecifier, local name is same as imported name
  38832. // prefix the variable name to avoid clashing with other local variables
  38833. const importedName = spec.local.name;
  38834. // we want to specify exported name as variable and re-export it
  38835. const exportedName = spec.exported.name;
  38836. if (exportedName === 'default') {
  38837. defaultExports = makeLegalIdentifier(`__vite__cjsExportDefault_${importIndex}`);
  38838. importNames.push({ importedName, localName: defaultExports });
  38839. }
  38840. else {
  38841. const localName = makeLegalIdentifier(`__vite__cjsExport_${exportedName}`);
  38842. importNames.push({ importedName, localName });
  38843. exportNames.push(`${localName} as ${exportedName}`);
  38844. }
  38845. }
  38846. }
  38847. // If there is multiple import for same id in one file,
  38848. // importIndex will prevent the cjsModuleName to be duplicate
  38849. const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
  38850. const lines = [`import ${cjsModuleName} from "${url}"`];
  38851. importNames.forEach(({ importedName, localName }) => {
  38852. if (importedName === '*') {
  38853. lines.push(`const ${localName} = ${cjsModuleName}`);
  38854. }
  38855. else if (importedName === 'default') {
  38856. lines.push(`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`);
  38857. }
  38858. else {
  38859. lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  38860. }
  38861. });
  38862. if (defaultExports) {
  38863. lines.push(`export default ${defaultExports}`);
  38864. }
  38865. if (exportNames.length) {
  38866. lines.push(`export { ${exportNames.join(', ')} }`);
  38867. }
  38868. return lines.join('; ');
  38869. }
  38870. }
  38871. const process_env_NODE_ENV_RE = /(\bglobal(This)?\.)?\bprocess\.env\.NODE_ENV\b/g;
  38872. // ids in transform are normalized to unix style
  38873. const normalizedClientEntry = normalizePath$3(CLIENT_ENTRY);
  38874. const normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
  38875. /**
  38876. * some values used by the client needs to be dynamically injected by the server
  38877. * @server-only
  38878. */
  38879. function clientInjectionsPlugin(config) {
  38880. let injectConfigValues;
  38881. return {
  38882. name: 'vite:client-inject',
  38883. async buildStart() {
  38884. const resolvedServerHostname = (await resolveHostname(config.server.host))
  38885. .name;
  38886. const resolvedServerPort = config.server.port;
  38887. const devBase = config.base;
  38888. const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
  38889. let hmrConfig = config.server.hmr;
  38890. hmrConfig = isObject$2(hmrConfig) ? hmrConfig : undefined;
  38891. const host = hmrConfig?.host || null;
  38892. const protocol = hmrConfig?.protocol || null;
  38893. const timeout = hmrConfig?.timeout || 30000;
  38894. const overlay = hmrConfig?.overlay !== false;
  38895. const isHmrServerSpecified = !!hmrConfig?.server;
  38896. // hmr.clientPort -> hmr.port
  38897. // -> (24678 if middleware mode and HMR server is not specified) -> new URL(import.meta.url).port
  38898. let port = hmrConfig?.clientPort || hmrConfig?.port || null;
  38899. if (config.server.middlewareMode && !isHmrServerSpecified) {
  38900. port || (port = 24678);
  38901. }
  38902. let directTarget = hmrConfig?.host || resolvedServerHostname;
  38903. directTarget += `:${hmrConfig?.port || resolvedServerPort}`;
  38904. directTarget += devBase;
  38905. let hmrBase = devBase;
  38906. if (hmrConfig?.path) {
  38907. hmrBase = path$o.posix.join(hmrBase, hmrConfig.path);
  38908. }
  38909. const serializedDefines = serializeDefine(config.define || {});
  38910. const modeReplacement = escapeReplacement(config.mode);
  38911. const baseReplacement = escapeReplacement(devBase);
  38912. const definesReplacement = () => serializedDefines;
  38913. const serverHostReplacement = escapeReplacement(serverHost);
  38914. const hmrProtocolReplacement = escapeReplacement(protocol);
  38915. const hmrHostnameReplacement = escapeReplacement(host);
  38916. const hmrPortReplacement = escapeReplacement(port);
  38917. const hmrDirectTargetReplacement = escapeReplacement(directTarget);
  38918. const hmrBaseReplacement = escapeReplacement(hmrBase);
  38919. const hmrTimeoutReplacement = escapeReplacement(timeout);
  38920. const hmrEnableOverlayReplacement = escapeReplacement(overlay);
  38921. const wsTokenReplacement = escapeReplacement(config.webSocketToken);
  38922. injectConfigValues = (code) => {
  38923. return code
  38924. .replace(`__MODE__`, modeReplacement)
  38925. .replace(/__BASE__/g, baseReplacement)
  38926. .replace(`__DEFINES__`, definesReplacement)
  38927. .replace(`__SERVER_HOST__`, serverHostReplacement)
  38928. .replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement)
  38929. .replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement)
  38930. .replace(`__HMR_PORT__`, hmrPortReplacement)
  38931. .replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement)
  38932. .replace(`__HMR_BASE__`, hmrBaseReplacement)
  38933. .replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement)
  38934. .replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement)
  38935. .replace(`__WS_TOKEN__`, wsTokenReplacement);
  38936. };
  38937. },
  38938. transform(code, id, options) {
  38939. if (id === normalizedClientEntry || id === normalizedEnvEntry) {
  38940. return injectConfigValues(code);
  38941. }
  38942. else if (!options?.ssr && code.includes('process.env.NODE_ENV')) {
  38943. // replace process.env.NODE_ENV instead of defining a global
  38944. // for it to avoid shimming a `process` object during dev,
  38945. // avoiding inconsistencies between dev and build
  38946. return code.replace(process_env_NODE_ENV_RE, config.define?.['process.env.NODE_ENV'] ||
  38947. JSON.stringify(process.env.NODE_ENV || config.mode));
  38948. }
  38949. },
  38950. };
  38951. }
  38952. function escapeReplacement(value) {
  38953. const jsonValue = JSON.stringify(value);
  38954. return () => jsonValue;
  38955. }
  38956. function serializeDefine(define) {
  38957. let res = `{`;
  38958. for (const key in define) {
  38959. const val = define[key];
  38960. res += `${JSON.stringify(key)}: ${typeof val === 'string' ? `(${val})` : JSON.stringify(val)}, `;
  38961. }
  38962. return res + `}`;
  38963. }
  38964. const wasmHelperId = '\0vite/wasm-helper';
  38965. const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
  38966. const wasmHelper = async (opts = {}, url) => {
  38967. let result;
  38968. if (url.startsWith('data:')) {
  38969. const urlContent = url.replace(/^data:.*?base64,/, '');
  38970. let bytes;
  38971. if (typeof Buffer === 'function' && typeof Buffer.from === 'function') {
  38972. bytes = Buffer.from(urlContent, 'base64');
  38973. }
  38974. else if (typeof atob === 'function') {
  38975. const binaryString = atob(urlContent);
  38976. bytes = new Uint8Array(binaryString.length);
  38977. for (let i = 0; i < binaryString.length; i++) {
  38978. bytes[i] = binaryString.charCodeAt(i);
  38979. }
  38980. }
  38981. else {
  38982. throw new Error('Failed to decode base64-encoded data URL, Buffer and atob are not supported');
  38983. }
  38984. result = await WebAssembly.instantiate(bytes, opts);
  38985. }
  38986. else {
  38987. // https://github.com/mdn/webassembly-examples/issues/5
  38988. // WebAssembly.instantiateStreaming requires the server to provide the
  38989. // correct MIME type for .wasm files, which unfortunately doesn't work for
  38990. // a lot of static file servers, so we just work around it by getting the
  38991. // raw buffer.
  38992. const response = await fetch(url);
  38993. const contentType = response.headers.get('Content-Type') || '';
  38994. if ('instantiateStreaming' in WebAssembly &&
  38995. contentType.startsWith('application/wasm')) {
  38996. result = await WebAssembly.instantiateStreaming(response, opts);
  38997. }
  38998. else {
  38999. const buffer = await response.arrayBuffer();
  39000. result = await WebAssembly.instantiate(buffer, opts);
  39001. }
  39002. }
  39003. return result.instance;
  39004. };
  39005. const wasmHelperCode = wasmHelper.toString();
  39006. const wasmHelperPlugin = (config) => {
  39007. return {
  39008. name: 'vite:wasm-helper',
  39009. resolveId(id) {
  39010. if (id === wasmHelperId) {
  39011. return id;
  39012. }
  39013. },
  39014. async load(id) {
  39015. if (id === wasmHelperId) {
  39016. return `export default ${wasmHelperCode}`;
  39017. }
  39018. if (!wasmInitRE.test(id)) {
  39019. return;
  39020. }
  39021. const url = await fileToUrl(id, config, this);
  39022. return `
  39023. import initWasm from "${wasmHelperId}"
  39024. export default opts => initWasm(opts, ${JSON.stringify(url)})
  39025. `;
  39026. },
  39027. };
  39028. };
  39029. const wasmFallbackPlugin = () => {
  39030. return {
  39031. name: 'vite:wasm-fallback',
  39032. async load(id) {
  39033. if (!id.endsWith('.wasm')) {
  39034. return;
  39035. }
  39036. throw new Error('"ESM integration proposal for Wasm" is not supported currently. ' +
  39037. 'Use vite-plugin-wasm or other community plugins to handle this. ' +
  39038. 'Alternatively, you can use `.wasm?init` or `.wasm?url`. ' +
  39039. 'See https://vitejs.dev/guide/features.html#webassembly for more details.');
  39040. },
  39041. };
  39042. };
  39043. const WORKER_FILE_ID = 'worker_file';
  39044. const workerCache = new WeakMap();
  39045. function saveEmitWorkerAsset(config, asset) {
  39046. const fileName = asset.fileName;
  39047. const workerMap = workerCache.get(config.mainConfig || config);
  39048. workerMap.assets.set(fileName, asset);
  39049. }
  39050. // Ensure that only one rollup build is called at the same time to avoid
  39051. // leaking state in plugins between worker builds.
  39052. // TODO: Review if we can parallelize the bundling of workers.
  39053. const workerConfigSemaphore = new WeakMap();
  39054. async function bundleWorkerEntry(config, id, query) {
  39055. const processing = workerConfigSemaphore.get(config);
  39056. if (processing) {
  39057. await processing;
  39058. return bundleWorkerEntry(config, id, query);
  39059. }
  39060. const promise = serialBundleWorkerEntry(config, id, query);
  39061. workerConfigSemaphore.set(config, promise);
  39062. promise.then(() => workerConfigSemaphore.delete(config));
  39063. return promise;
  39064. }
  39065. async function serialBundleWorkerEntry(config, id, query) {
  39066. // bundle the file as entry to support imports
  39067. const { rollup } = await import('rollup');
  39068. const { plugins, rollupOptions, format } = config.worker;
  39069. const bundle = await rollup({
  39070. ...rollupOptions,
  39071. input: cleanUrl(id),
  39072. plugins,
  39073. onwarn(warning, warn) {
  39074. onRollupWarning(warning, warn, config);
  39075. },
  39076. preserveEntrySignatures: false,
  39077. });
  39078. let chunk;
  39079. try {
  39080. const workerOutputConfig = config.worker.rollupOptions.output;
  39081. const workerConfig = workerOutputConfig
  39082. ? Array.isArray(workerOutputConfig)
  39083. ? workerOutputConfig[0] || {}
  39084. : workerOutputConfig
  39085. : {};
  39086. const { output: [outputChunk, ...outputChunks], } = await bundle.generate({
  39087. entryFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
  39088. chunkFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'),
  39089. assetFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
  39090. ...workerConfig,
  39091. format,
  39092. sourcemap: config.build.sourcemap,
  39093. });
  39094. chunk = outputChunk;
  39095. outputChunks.forEach((outputChunk) => {
  39096. if (outputChunk.type === 'asset') {
  39097. saveEmitWorkerAsset(config, outputChunk);
  39098. }
  39099. else if (outputChunk.type === 'chunk') {
  39100. saveEmitWorkerAsset(config, {
  39101. fileName: outputChunk.fileName,
  39102. source: outputChunk.code,
  39103. type: 'asset',
  39104. });
  39105. }
  39106. });
  39107. }
  39108. finally {
  39109. await bundle.close();
  39110. }
  39111. return emitSourcemapForWorkerEntry(config, query, chunk);
  39112. }
  39113. function emitSourcemapForWorkerEntry(config, query, chunk) {
  39114. const { map: sourcemap } = chunk;
  39115. if (sourcemap) {
  39116. if (config.build.sourcemap === 'hidden' ||
  39117. config.build.sourcemap === true) {
  39118. const data = sourcemap.toString();
  39119. const mapFileName = chunk.fileName + '.map';
  39120. saveEmitWorkerAsset(config, {
  39121. fileName: mapFileName,
  39122. type: 'asset',
  39123. source: data,
  39124. });
  39125. }
  39126. }
  39127. return chunk;
  39128. }
  39129. const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
  39130. function encodeWorkerAssetFileName(fileName, workerCache) {
  39131. const { fileNameHash } = workerCache;
  39132. const hash = getHash(fileName);
  39133. if (!fileNameHash.get(hash)) {
  39134. fileNameHash.set(hash, fileName);
  39135. }
  39136. return `__VITE_WORKER_ASSET__${hash}__`;
  39137. }
  39138. async function workerFileToUrl(config, id, query) {
  39139. const workerMap = workerCache.get(config.mainConfig || config);
  39140. let fileName = workerMap.bundle.get(id);
  39141. if (!fileName) {
  39142. const outputChunk = await bundleWorkerEntry(config, id, query);
  39143. fileName = outputChunk.fileName;
  39144. saveEmitWorkerAsset(config, {
  39145. fileName,
  39146. source: outputChunk.code,
  39147. type: 'asset',
  39148. });
  39149. workerMap.bundle.set(id, fileName);
  39150. }
  39151. return encodeWorkerAssetFileName(fileName, workerMap);
  39152. }
  39153. function webWorkerPostPlugin() {
  39154. return {
  39155. name: 'vite:worker-post',
  39156. resolveImportMeta(property, { chunkId, format }) {
  39157. // document is undefined in the worker, so we need to avoid it in iife
  39158. if (property === 'url' && format === 'iife') {
  39159. return 'self.location.href';
  39160. }
  39161. return null;
  39162. },
  39163. };
  39164. }
  39165. function webWorkerPlugin(config) {
  39166. const isBuild = config.command === 'build';
  39167. let server;
  39168. const isWorker = config.isWorker;
  39169. const isWorkerQueryId = (id) => {
  39170. const parsedQuery = parseRequest(id);
  39171. if (parsedQuery &&
  39172. (parsedQuery.worker ?? parsedQuery.sharedworker) != null) {
  39173. return true;
  39174. }
  39175. return false;
  39176. };
  39177. return {
  39178. name: 'vite:worker',
  39179. configureServer(_server) {
  39180. server = _server;
  39181. },
  39182. buildStart() {
  39183. if (isWorker) {
  39184. return;
  39185. }
  39186. workerCache.set(config, {
  39187. assets: new Map(),
  39188. bundle: new Map(),
  39189. fileNameHash: new Map(),
  39190. });
  39191. },
  39192. load(id) {
  39193. if (isBuild && isWorkerQueryId(id)) {
  39194. return '';
  39195. }
  39196. },
  39197. shouldTransformCachedModule({ id }) {
  39198. if (isBuild && isWorkerQueryId(id) && config.build.watch) {
  39199. return true;
  39200. }
  39201. },
  39202. async transform(raw, id, options) {
  39203. const ssr = options?.ssr === true;
  39204. const query = parseRequest(id);
  39205. if (query && query[WORKER_FILE_ID] != null) {
  39206. // if import worker by worker constructor will have query.type
  39207. // other type will be import worker by esm
  39208. const workerType = query['type'];
  39209. let injectEnv = '';
  39210. const scriptPath = JSON.stringify(path$o.posix.join(config.base, ENV_PUBLIC_PATH));
  39211. if (workerType === 'classic') {
  39212. injectEnv = `importScripts(${scriptPath})\n`;
  39213. }
  39214. else if (workerType === 'module') {
  39215. injectEnv = `import ${scriptPath}\n`;
  39216. }
  39217. else if (workerType === 'ignore') {
  39218. if (isBuild) {
  39219. injectEnv = '';
  39220. }
  39221. else if (server) {
  39222. // dynamic worker type we can't know how import the env
  39223. // so we copy /@vite/env code of server transform result into file header
  39224. const { moduleGraph } = server;
  39225. const module = moduleGraph.getModuleById(ENV_ENTRY);
  39226. injectEnv = module?.transformResult?.code || '';
  39227. }
  39228. }
  39229. if (injectEnv) {
  39230. const s = new MagicString(raw);
  39231. s.prepend(injectEnv);
  39232. return {
  39233. code: s.toString(),
  39234. map: s.generateMap({ hires: 'boundary' }),
  39235. };
  39236. }
  39237. return;
  39238. }
  39239. if (query == null ||
  39240. (query && (query.worker ?? query.sharedworker) == null)) {
  39241. return;
  39242. }
  39243. // stringified url or `new URL(...)`
  39244. let url;
  39245. const { format } = config.worker;
  39246. const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
  39247. const workerType = isBuild
  39248. ? format === 'es'
  39249. ? 'module'
  39250. : 'classic'
  39251. : 'module';
  39252. const workerOptions = workerType === 'classic' ? '' : ',{type: "module"}';
  39253. if (isBuild) {
  39254. getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
  39255. if (query.inline != null) {
  39256. const chunk = await bundleWorkerEntry(config, id, query);
  39257. const encodedJs = `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";`;
  39258. const code =
  39259. // Using blob URL for SharedWorker results in multiple instances of a same worker
  39260. workerConstructor === 'Worker'
  39261. ? `${encodedJs}
  39262. const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
  39263. export default function WorkerWrapper() {
  39264. let objURL;
  39265. try {
  39266. objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
  39267. if (!objURL) throw ''
  39268. return new ${workerConstructor}(objURL)
  39269. } catch(e) {
  39270. return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
  39271. } finally {
  39272. objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
  39273. }
  39274. }`
  39275. : `${encodedJs}
  39276. export default function WorkerWrapper() {
  39277. return new ${workerConstructor}("data:application/javascript;base64," + encodedJs${workerOptions});
  39278. }
  39279. `;
  39280. return {
  39281. code,
  39282. // Empty sourcemap to suppress Rollup warning
  39283. map: { mappings: '' },
  39284. };
  39285. }
  39286. else {
  39287. url = await workerFileToUrl(config, id, query);
  39288. }
  39289. }
  39290. else {
  39291. url = await fileToUrl(cleanUrl(id), config, this);
  39292. url = injectQuery(url, WORKER_FILE_ID);
  39293. url = injectQuery(url, `type=${workerType}`);
  39294. }
  39295. if (query.url != null) {
  39296. return {
  39297. code: `export default ${JSON.stringify(url)}`,
  39298. map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
  39299. };
  39300. }
  39301. return {
  39302. code: `export default function WorkerWrapper() {
  39303. return new ${workerConstructor}(${JSON.stringify(url)}${workerOptions})
  39304. }`,
  39305. map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
  39306. };
  39307. },
  39308. renderChunk(code, chunk, outputOptions) {
  39309. let s;
  39310. const result = () => {
  39311. return (s && {
  39312. code: s.toString(),
  39313. map: config.build.sourcemap
  39314. ? s.generateMap({ hires: 'boundary' })
  39315. : null,
  39316. });
  39317. };
  39318. if (code.match(workerAssetUrlRE)) {
  39319. const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, config.isWorker);
  39320. let match;
  39321. s = new MagicString(code);
  39322. workerAssetUrlRE.lastIndex = 0;
  39323. // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
  39324. const workerMap = workerCache.get(config.mainConfig || config);
  39325. const { fileNameHash } = workerMap;
  39326. while ((match = workerAssetUrlRE.exec(code))) {
  39327. const [full, hash] = match;
  39328. const filename = fileNameHash.get(hash);
  39329. const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime);
  39330. const replacementString = typeof replacement === 'string'
  39331. ? JSON.stringify(replacement).slice(1, -1)
  39332. : `"+${replacement.runtime}+"`;
  39333. s.update(match.index, match.index + full.length, replacementString);
  39334. }
  39335. }
  39336. return result();
  39337. },
  39338. generateBundle(opts) {
  39339. // @ts-expect-error asset emits are skipped in legacy bundle
  39340. if (opts.__vite_skip_asset_emit__ || isWorker) {
  39341. return;
  39342. }
  39343. const workerMap = workerCache.get(config);
  39344. workerMap.assets.forEach((asset) => {
  39345. this.emitFile(asset);
  39346. workerMap.assets.delete(asset.fileName);
  39347. });
  39348. },
  39349. };
  39350. }
  39351. /**
  39352. * A plugin to avoid an aliased AND optimized dep from being aliased in src
  39353. */
  39354. function preAliasPlugin(config) {
  39355. const findPatterns = getAliasPatterns(config.resolve.alias);
  39356. const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config);
  39357. const isBuild = config.command === 'build';
  39358. return {
  39359. name: 'vite:pre-alias',
  39360. async resolveId(id, importer, options) {
  39361. const ssr = options?.ssr === true;
  39362. const depsOptimizer = getDepsOptimizer(config, ssr);
  39363. if (importer &&
  39364. depsOptimizer &&
  39365. bareImportRE.test(id) &&
  39366. !options?.scan &&
  39367. id !== '@vite/client' &&
  39368. id !== '@vite/env') {
  39369. if (findPatterns.find((pattern) => matches(pattern, id))) {
  39370. const optimizedId = await tryOptimizedResolve(depsOptimizer, id, importer, config.resolve.preserveSymlinks, config.packageCache);
  39371. if (optimizedId) {
  39372. return optimizedId; // aliased dep already optimized
  39373. }
  39374. if (depsOptimizer.options.noDiscovery) {
  39375. return;
  39376. }
  39377. const resolved = await this.resolve(id, importer, {
  39378. ...options,
  39379. custom: { ...options.custom, 'vite:pre-alias': true },
  39380. skipSelf: true,
  39381. });
  39382. if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
  39383. const optimizeDeps = depsOptimizer.options;
  39384. const resolvedId = cleanUrl(resolved.id);
  39385. const isVirtual = resolvedId === id || resolvedId.includes('\0');
  39386. if (!isVirtual &&
  39387. fs$l.existsSync(resolvedId) &&
  39388. !moduleListContains(optimizeDeps.exclude, id) &&
  39389. path$o.isAbsolute(resolvedId) &&
  39390. (isInNodeModules(resolvedId) ||
  39391. optimizeDeps.include?.includes(id)) &&
  39392. isOptimizable(resolvedId, optimizeDeps) &&
  39393. !(isBuild && ssr && isConfiguredAsExternal(id, importer)) &&
  39394. (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
  39395. // aliased dep has not yet been optimized
  39396. const optimizedInfo = depsOptimizer.registerMissingImport(id, resolvedId);
  39397. return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
  39398. }
  39399. }
  39400. return resolved;
  39401. }
  39402. }
  39403. },
  39404. };
  39405. }
  39406. function optimizeAliasReplacementForSSR(id, optimizeDeps) {
  39407. if (optimizeDeps.include?.includes(id)) {
  39408. return true;
  39409. }
  39410. // In the regular resolution, the default for non-external modules is to
  39411. // be optimized if they are CJS. Here, we don't have the package id but
  39412. // only the replacement file path. We could find the package.json from
  39413. // the id and respect the same default in the future.
  39414. // Default to not optimize an aliased replacement for now, forcing the
  39415. // user to explicitly add it to the ssr.optimizeDeps.include list.
  39416. return false;
  39417. }
  39418. // In sync with rollup plugin alias logic
  39419. function matches(pattern, importee) {
  39420. if (pattern instanceof RegExp) {
  39421. return pattern.test(importee);
  39422. }
  39423. if (importee.length < pattern.length) {
  39424. return false;
  39425. }
  39426. if (importee === pattern) {
  39427. return true;
  39428. }
  39429. return importee.startsWith(withTrailingSlash(pattern));
  39430. }
  39431. function getAliasPatterns(entries) {
  39432. if (!entries) {
  39433. return [];
  39434. }
  39435. if (Array.isArray(entries)) {
  39436. return entries.map((entry) => entry.find);
  39437. }
  39438. return Object.entries(entries).map(([find]) => find);
  39439. }
  39440. const nonJsRe = /\.json(?:$|\?)/;
  39441. const metaEnvRe = /import\.meta\.env\.(.+)/;
  39442. const isNonJsRequest = (request) => nonJsRe.test(request);
  39443. function definePlugin(config) {
  39444. const isBuild = config.command === 'build';
  39445. const isBuildLib = isBuild && config.build.lib;
  39446. // ignore replace process.env in lib build
  39447. const processEnv = {};
  39448. const processNodeEnv = {};
  39449. if (!isBuildLib) {
  39450. const nodeEnv = process.env.NODE_ENV || config.mode;
  39451. Object.assign(processEnv, {
  39452. 'process.env.': `({}).`,
  39453. 'global.process.env.': `({}).`,
  39454. 'globalThis.process.env.': `({}).`,
  39455. });
  39456. Object.assign(processNodeEnv, {
  39457. 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
  39458. 'global.process.env.NODE_ENV': JSON.stringify(nodeEnv),
  39459. 'globalThis.process.env.NODE_ENV': JSON.stringify(nodeEnv),
  39460. __vite_process_env_NODE_ENV: JSON.stringify(nodeEnv),
  39461. });
  39462. }
  39463. const userDefine = {};
  39464. const userDefineEnv = {};
  39465. for (const key in config.define) {
  39466. const val = config.define[key];
  39467. userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val);
  39468. // make sure `import.meta.env` object has user define properties
  39469. if (isBuild) {
  39470. const match = key.match(metaEnvRe);
  39471. if (match) {
  39472. userDefineEnv[match[1]] = `__vite__define__${key}__define__vite__`;
  39473. }
  39474. }
  39475. }
  39476. // during dev, import.meta properties are handled by importAnalysis plugin.
  39477. const importMetaKeys = {};
  39478. const importMetaFallbackKeys = {};
  39479. if (isBuild) {
  39480. // set here to allow override with config.define
  39481. importMetaKeys['import.meta.hot'] = `undefined`;
  39482. for (const key in config.env) {
  39483. importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(config.env[key]);
  39484. }
  39485. Object.assign(importMetaFallbackKeys, {
  39486. 'import.meta.env.': `({}).`,
  39487. 'import.meta.env': JSON.stringify({
  39488. ...config.env,
  39489. SSR: '__vite__ssr__',
  39490. ...userDefineEnv,
  39491. }).replace(/"__vite__define__(.+?)__define__vite__"/g, (_, key) => userDefine[key]),
  39492. });
  39493. }
  39494. function getImportMetaKeys(ssr) {
  39495. if (!isBuild)
  39496. return {};
  39497. return {
  39498. ...importMetaKeys,
  39499. 'import.meta.env.SSR': ssr + '',
  39500. };
  39501. }
  39502. function getImportMetaFallbackKeys(ssr) {
  39503. if (!isBuild)
  39504. return {};
  39505. return {
  39506. ...importMetaFallbackKeys,
  39507. 'import.meta.env': importMetaFallbackKeys['import.meta.env'].replace('"__vite__ssr__"', ssr + ''),
  39508. };
  39509. }
  39510. function generatePattern(ssr) {
  39511. const replaceProcessEnv = !ssr || config.ssr?.target === 'webworker';
  39512. const replacements = {
  39513. ...(replaceProcessEnv ? processNodeEnv : {}),
  39514. ...getImportMetaKeys(ssr),
  39515. ...userDefine,
  39516. ...getImportMetaFallbackKeys(ssr),
  39517. ...(replaceProcessEnv ? processEnv : {}),
  39518. };
  39519. if (isBuild && !replaceProcessEnv) {
  39520. replacements['__vite_process_env_NODE_ENV'] = 'process.env.NODE_ENV';
  39521. }
  39522. const replacementsKeys = Object.keys(replacements);
  39523. const pattern = replacementsKeys.length
  39524. ? new RegExp(
  39525. // Mustn't be preceded by a char that can be part of an identifier
  39526. // or a '.' that isn't part of a spread operator
  39527. '(?<![\\p{L}\\p{N}_$]|(?<!\\.\\.)\\.)(' +
  39528. replacementsKeys.map(escapeRegex).join('|') +
  39529. // Mustn't be followed by a char that can be part of an identifier
  39530. // or an assignment (but allow equality operators)
  39531. ')(?:(?<=\\.)|(?![\\p{L}\\p{N}_$]|\\s*?=[^=]))', 'gu')
  39532. : null;
  39533. return [replacements, pattern];
  39534. }
  39535. const defaultPattern = generatePattern(false);
  39536. const ssrPattern = generatePattern(true);
  39537. return {
  39538. name: 'vite:define',
  39539. transform(code, id, options) {
  39540. const ssr = options?.ssr === true;
  39541. if (!ssr && !isBuild) {
  39542. // for dev we inject actual global defines in the vite client to
  39543. // avoid the transform cost.
  39544. return;
  39545. }
  39546. if (
  39547. // exclude html, css and static assets for performance
  39548. isHTMLRequest(id) ||
  39549. isCSSRequest(id) ||
  39550. isNonJsRequest(id) ||
  39551. config.assetsInclude(id)) {
  39552. return;
  39553. }
  39554. const [replacements, pattern] = ssr ? ssrPattern : defaultPattern;
  39555. if (!pattern) {
  39556. return null;
  39557. }
  39558. if (ssr && !isBuild) {
  39559. // ssr + dev, simple replace
  39560. return code.replace(pattern, (_, match) => {
  39561. return '' + replacements[match];
  39562. });
  39563. }
  39564. const s = new MagicString(code);
  39565. let hasReplaced = false;
  39566. let match;
  39567. while ((match = pattern.exec(code))) {
  39568. hasReplaced = true;
  39569. const start = match.index;
  39570. const end = start + match[0].length;
  39571. const replacement = '' + replacements[match[1]];
  39572. s.update(start, end, replacement);
  39573. }
  39574. if (!hasReplaced) {
  39575. return null;
  39576. }
  39577. return transformStableResult(s, id, config);
  39578. },
  39579. };
  39580. }
  39581. function err(e, pos) {
  39582. const error = new Error(e);
  39583. error.pos = pos;
  39584. return error;
  39585. }
  39586. function parseWorkerOptions(rawOpts, optsStartIndex) {
  39587. let opts = {};
  39588. try {
  39589. opts = evalValue(rawOpts);
  39590. }
  39591. catch {
  39592. throw err('Vite is unable to parse the worker options as the value is not static.' +
  39593. 'To ignore this error, please use /* @vite-ignore */ in the worker options.', optsStartIndex);
  39594. }
  39595. if (opts == null) {
  39596. return {};
  39597. }
  39598. if (typeof opts !== 'object') {
  39599. throw err(`Expected worker options to be an object, got ${typeof opts}`, optsStartIndex);
  39600. }
  39601. return opts;
  39602. }
  39603. function getWorkerType(raw, clean, i) {
  39604. const commaIndex = clean.indexOf(',', i);
  39605. if (commaIndex === -1) {
  39606. return 'classic';
  39607. }
  39608. const endIndex = clean.indexOf(')', i);
  39609. // case: ') ... ,' mean no worker options params
  39610. if (commaIndex > endIndex) {
  39611. return 'classic';
  39612. }
  39613. // need to find in comment code
  39614. const workerOptString = raw
  39615. .substring(commaIndex + 1, endIndex)
  39616. .replace(/\}[\s\S]*,/g, '}'); // strip trailing comma for parsing
  39617. const hasViteIgnore = hasViteIgnoreRE.test(workerOptString);
  39618. if (hasViteIgnore) {
  39619. return 'ignore';
  39620. }
  39621. // need to find in no comment code
  39622. const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex).trim();
  39623. if (!cleanWorkerOptString.length) {
  39624. return 'classic';
  39625. }
  39626. const workerOpts = parseWorkerOptions(workerOptString, commaIndex + 1);
  39627. if (workerOpts.type && ['classic', 'module'].includes(workerOpts.type)) {
  39628. return workerOpts.type;
  39629. }
  39630. return 'classic';
  39631. }
  39632. function workerImportMetaUrlPlugin(config) {
  39633. const isBuild = config.command === 'build';
  39634. let workerResolver;
  39635. const fsResolveOptions = {
  39636. ...config.resolve,
  39637. root: config.root,
  39638. isProduction: config.isProduction,
  39639. isBuild: config.command === 'build',
  39640. packageCache: config.packageCache,
  39641. ssrConfig: config.ssr,
  39642. asSrc: true,
  39643. };
  39644. return {
  39645. name: 'vite:worker-import-meta-url',
  39646. async transform(code, id, options) {
  39647. const ssr = options?.ssr === true;
  39648. if (!options?.ssr &&
  39649. (code.includes('new Worker') || code.includes('new SharedWorker')) &&
  39650. code.includes('new URL') &&
  39651. code.includes(`import.meta.url`)) {
  39652. const query = parseRequest(id);
  39653. let s;
  39654. const cleanString = stripLiteral(code);
  39655. const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/g;
  39656. let match;
  39657. while ((match = workerImportMetaUrlRE.exec(cleanString))) {
  39658. const { 0: allExp, 1: exp, 2: emptyUrl, index } = match;
  39659. const urlIndex = allExp.indexOf(exp) + index;
  39660. const urlStart = cleanString.indexOf(emptyUrl, index);
  39661. const urlEnd = urlStart + emptyUrl.length;
  39662. const rawUrl = code.slice(urlStart, urlEnd);
  39663. // potential dynamic template string
  39664. if (rawUrl[0] === '`' && rawUrl.includes('${')) {
  39665. this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
  39666. }
  39667. s || (s = new MagicString(code));
  39668. const workerType = getWorkerType(code, cleanString, index + allExp.length);
  39669. const url = rawUrl.slice(1, -1);
  39670. let file;
  39671. if (url[0] === '.') {
  39672. file = path$o.resolve(path$o.dirname(id), url);
  39673. file = tryFsResolve(file, fsResolveOptions) ?? file;
  39674. }
  39675. else {
  39676. workerResolver ?? (workerResolver = config.createResolver({
  39677. extensions: [],
  39678. tryIndex: false,
  39679. preferRelative: true,
  39680. }));
  39681. file = await workerResolver(url, id);
  39682. file ?? (file = url[0] === '/'
  39683. ? slash$1(path$o.join(config.publicDir, url))
  39684. : slash$1(path$o.resolve(path$o.dirname(id), url)));
  39685. }
  39686. let builtUrl;
  39687. if (isBuild) {
  39688. getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
  39689. builtUrl = await workerFileToUrl(config, file, query);
  39690. }
  39691. else {
  39692. builtUrl = await fileToUrl(cleanUrl(file), config, this);
  39693. builtUrl = injectQuery(builtUrl, WORKER_FILE_ID);
  39694. builtUrl = injectQuery(builtUrl, `type=${workerType}`);
  39695. }
  39696. s.update(urlIndex, urlIndex + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`);
  39697. }
  39698. if (s) {
  39699. return transformStableResult(s, id, config);
  39700. }
  39701. return null;
  39702. }
  39703. },
  39704. };
  39705. }
  39706. /**
  39707. * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
  39708. *
  39709. * Supports template string with dynamic segments:
  39710. * ```
  39711. * new URL(`./dir/${name}.png`, import.meta.url)
  39712. * // transformed to
  39713. * import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
  39714. * ```
  39715. */
  39716. function assetImportMetaUrlPlugin(config) {
  39717. const normalizedPublicDir = normalizePath$3(config.publicDir);
  39718. let assetResolver;
  39719. const fsResolveOptions = {
  39720. ...config.resolve,
  39721. root: config.root,
  39722. isProduction: config.isProduction,
  39723. isBuild: config.command === 'build',
  39724. packageCache: config.packageCache,
  39725. ssrConfig: config.ssr,
  39726. asSrc: true,
  39727. };
  39728. return {
  39729. name: 'vite:asset-import-meta-url',
  39730. async transform(code, id, options) {
  39731. if (!options?.ssr &&
  39732. id !== preloadHelperId &&
  39733. id !== CLIENT_ENTRY &&
  39734. code.includes('new URL') &&
  39735. code.includes(`import.meta.url`)) {
  39736. let s;
  39737. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
  39738. const cleanString = stripLiteral(code);
  39739. let match;
  39740. while ((match = assetImportMetaUrlRE.exec(cleanString))) {
  39741. const { 0: exp, 1: emptyUrl, index } = match;
  39742. const urlStart = cleanString.indexOf(emptyUrl, index);
  39743. const urlEnd = urlStart + emptyUrl.length;
  39744. const rawUrl = code.slice(urlStart, urlEnd);
  39745. if (!s)
  39746. s = new MagicString(code);
  39747. // potential dynamic template string
  39748. if (rawUrl[0] === '`' && rawUrl.includes('${')) {
  39749. const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl);
  39750. const hasQueryDelimiter = queryDelimiterIndex !== -1;
  39751. const pureUrl = hasQueryDelimiter
  39752. ? rawUrl.slice(0, queryDelimiterIndex) + '`'
  39753. : rawUrl;
  39754. const queryString = hasQueryDelimiter
  39755. ? rawUrl.slice(queryDelimiterIndex, -1)
  39756. : '';
  39757. const ast = this.parse(pureUrl);
  39758. const templateLiteral = ast.body[0].expression;
  39759. if (templateLiteral.expressions.length) {
  39760. const pattern = buildGlobPattern(templateLiteral);
  39761. if (pattern.startsWith('**')) {
  39762. // don't transform for patterns like this
  39763. // because users won't intend to do that in most cases
  39764. continue;
  39765. }
  39766. const globOptions = {
  39767. eager: true,
  39768. import: 'default',
  39769. // A hack to allow 'as' & 'query' exist at the same time
  39770. query: injectQuery(queryString, 'url'),
  39771. };
  39772. // Note: native import.meta.url is not supported in the baseline
  39773. // target so we use the global location here. It can be
  39774. // window.location or self.location in case it is used in a Web Worker.
  39775. // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
  39776. s.update(index, index + exp.length, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], self.location)`);
  39777. continue;
  39778. }
  39779. }
  39780. const url = rawUrl.slice(1, -1);
  39781. let file;
  39782. if (url[0] === '.') {
  39783. file = slash$1(path$o.resolve(path$o.dirname(id), url));
  39784. file = tryFsResolve(file, fsResolveOptions) ?? file;
  39785. }
  39786. else {
  39787. assetResolver ?? (assetResolver = config.createResolver({
  39788. extensions: [],
  39789. mainFields: [],
  39790. tryIndex: false,
  39791. preferRelative: true,
  39792. }));
  39793. file = await assetResolver(url, id);
  39794. file ?? (file = url[0] === '/'
  39795. ? slash$1(path$o.join(config.publicDir, url))
  39796. : slash$1(path$o.resolve(path$o.dirname(id), url)));
  39797. }
  39798. // Get final asset URL. If the file does not exist,
  39799. // we fall back to the initial URL and let it resolve in runtime
  39800. let builtUrl;
  39801. if (file) {
  39802. try {
  39803. if (isParentDirectory(normalizedPublicDir, file)) {
  39804. const publicPath = '/' + path$o.posix.relative(normalizedPublicDir, file);
  39805. builtUrl = await fileToUrl(publicPath, config, this);
  39806. }
  39807. else {
  39808. builtUrl = await fileToUrl(file, config, this);
  39809. }
  39810. }
  39811. catch {
  39812. // do nothing, we'll log a warning after this
  39813. }
  39814. }
  39815. if (!builtUrl) {
  39816. const rawExp = code.slice(index, index + exp.length);
  39817. config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  39818. builtUrl = url;
  39819. }
  39820. s.update(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`);
  39821. }
  39822. if (s) {
  39823. return transformStableResult(s, id, config);
  39824. }
  39825. }
  39826. return null;
  39827. },
  39828. };
  39829. }
  39830. function buildGlobPattern(ast) {
  39831. let pattern = '';
  39832. let lastElementIndex = -1;
  39833. for (const exp of ast.expressions) {
  39834. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  39835. const el = ast.quasis[i];
  39836. if (el.end < exp.start) {
  39837. pattern += el.value.raw;
  39838. lastElementIndex = i;
  39839. }
  39840. }
  39841. pattern += '**';
  39842. }
  39843. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  39844. pattern += ast.quasis[i].value.raw;
  39845. }
  39846. return pattern;
  39847. }
  39848. function getQueryDelimiterIndex(rawUrl) {
  39849. let bracketsStack = 0;
  39850. for (let i = 0; i < rawUrl.length; i++) {
  39851. if (rawUrl[i] === '{') {
  39852. bracketsStack++;
  39853. }
  39854. else if (rawUrl[i] === '}') {
  39855. bracketsStack--;
  39856. }
  39857. else if (rawUrl[i] === '?' && bracketsStack === 0) {
  39858. return i;
  39859. }
  39860. }
  39861. return -1;
  39862. }
  39863. /**
  39864. * plugin to ensure rollup can watch correctly.
  39865. */
  39866. function ensureWatchPlugin() {
  39867. return {
  39868. name: 'vite:ensure-watch',
  39869. load(id) {
  39870. if (queryRE.test(id)) {
  39871. this.addWatchFile(cleanUrl(id));
  39872. }
  39873. return null;
  39874. },
  39875. };
  39876. }
  39877. /**
  39878. * Prepares the rendered chunks to contain additional metadata during build.
  39879. */
  39880. function metadataPlugin() {
  39881. return {
  39882. name: 'vite:build-metadata',
  39883. async renderChunk(_code, chunk) {
  39884. chunk.viteMetadata = {
  39885. importedAssets: new Set(),
  39886. importedCss: new Set(),
  39887. };
  39888. return null;
  39889. },
  39890. };
  39891. }
  39892. class VariableDynamicImportError extends Error {}
  39893. /* eslint-disable-next-line no-template-curly-in-string */
  39894. const example = 'For example: import(`./foo/${bar}.js`).';
  39895. function sanitizeString(str) {
  39896. if (str.includes('*')) {
  39897. throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');
  39898. }
  39899. return str;
  39900. }
  39901. function templateLiteralToGlob(node) {
  39902. let glob = '';
  39903. for (let i = 0; i < node.quasis.length; i += 1) {
  39904. glob += sanitizeString(node.quasis[i].value.raw);
  39905. if (node.expressions[i]) {
  39906. glob += expressionToGlob(node.expressions[i]);
  39907. }
  39908. }
  39909. return glob;
  39910. }
  39911. function callExpressionToGlob(node) {
  39912. const { callee } = node;
  39913. if (
  39914. callee.type === 'MemberExpression' &&
  39915. callee.property.type === 'Identifier' &&
  39916. callee.property.name === 'concat'
  39917. ) {
  39918. return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;
  39919. }
  39920. return '*';
  39921. }
  39922. function binaryExpressionToGlob(node) {
  39923. if (node.operator !== '+') {
  39924. throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  39925. }
  39926. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  39927. }
  39928. function expressionToGlob(node) {
  39929. switch (node.type) {
  39930. case 'TemplateLiteral':
  39931. return templateLiteralToGlob(node);
  39932. case 'CallExpression':
  39933. return callExpressionToGlob(node);
  39934. case 'BinaryExpression':
  39935. return binaryExpressionToGlob(node);
  39936. case 'Literal': {
  39937. return sanitizeString(node.value);
  39938. }
  39939. default:
  39940. return '*';
  39941. }
  39942. }
  39943. const defaultProtocol = 'file:';
  39944. const ignoredProtocols = ['data:', 'http:', 'https:'];
  39945. function shouldIgnore(glob) {
  39946. const containsAsterisk = glob.includes('*');
  39947. const globURL = new URL(glob, defaultProtocol);
  39948. const containsIgnoredProtocol = ignoredProtocols.some(
  39949. (ignoredProtocol) => ignoredProtocol === globURL.protocol
  39950. );
  39951. return !containsAsterisk || containsIgnoredProtocol;
  39952. }
  39953. function dynamicImportToGlob(node, sourceString) {
  39954. let glob = expressionToGlob(node);
  39955. if (shouldIgnore(glob)) {
  39956. return null;
  39957. }
  39958. glob = glob.replace(/\*\*/g, '*');
  39959. if (glob.startsWith('*')) {
  39960. throw new VariableDynamicImportError(
  39961. `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
  39962. );
  39963. }
  39964. if (glob.startsWith('/')) {
  39965. throw new VariableDynamicImportError(
  39966. `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  39967. );
  39968. }
  39969. if (!glob.startsWith('./') && !glob.startsWith('../')) {
  39970. throw new VariableDynamicImportError(
  39971. `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  39972. );
  39973. }
  39974. // Disallow ./*.ext
  39975. const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/;
  39976. if (ownDirectoryStarExtension.test(glob)) {
  39977. throw new VariableDynamicImportError(
  39978. `${
  39979. `invalid import "${sourceString}". Variable imports cannot import their own directory, ` +
  39980. 'place imports in a separate directory or make the import filename more specific. '
  39981. }${example}`
  39982. );
  39983. }
  39984. if (require$$0$4.extname(glob) === '') {
  39985. throw new VariableDynamicImportError(
  39986. `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
  39987. );
  39988. }
  39989. return glob;
  39990. }
  39991. const dynamicImportHelperId = '\0vite/dynamic-import-helper';
  39992. const relativePathRE = /^\.{1,2}\//;
  39993. // fast path to check if source contains a dynamic import. we check for a
  39994. // trailing slash too as a dynamic import statement can have comments between
  39995. // the `import` and the `(`.
  39996. const hasDynamicImportRE = /\bimport\s*[(/]/;
  39997. const dynamicImportHelper = (glob, path) => {
  39998. const v = glob[path];
  39999. if (v) {
  40000. return typeof v === 'function' ? v() : Promise.resolve(v);
  40001. }
  40002. return new Promise((_, reject) => {
  40003. (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(reject.bind(null, new Error('Unknown variable dynamic import: ' + path)));
  40004. });
  40005. };
  40006. function parseDynamicImportPattern(strings) {
  40007. const filename = strings.slice(1, -1);
  40008. const rawQuery = parseRequest(filename);
  40009. let globParams = null;
  40010. const ast = parse$b(strings, {
  40011. ecmaVersion: 'latest',
  40012. sourceType: 'module',
  40013. }).body[0].expression;
  40014. const userPatternQuery = dynamicImportToGlob(ast, filename);
  40015. if (!userPatternQuery) {
  40016. return null;
  40017. }
  40018. const [userPattern] = userPatternQuery.split(requestQuerySplitRE, 2);
  40019. const [rawPattern] = filename.split(requestQuerySplitRE, 2);
  40020. if (rawQuery?.raw !== undefined) {
  40021. globParams = { as: 'raw' };
  40022. }
  40023. if (rawQuery?.url !== undefined) {
  40024. globParams = { as: 'url' };
  40025. }
  40026. if (rawQuery?.worker !== undefined) {
  40027. globParams = { as: 'worker' };
  40028. }
  40029. return {
  40030. globParams,
  40031. userPattern,
  40032. rawPattern,
  40033. };
  40034. }
  40035. async function transformDynamicImport(importSource, importer, resolve, root) {
  40036. if (importSource[1] !== '.' && importSource[1] !== '/') {
  40037. const resolvedFileName = await resolve(importSource.slice(1, -1), importer);
  40038. if (!resolvedFileName) {
  40039. return null;
  40040. }
  40041. const relativeFileName = posix$1.relative(posix$1.dirname(normalizePath$3(importer)), normalizePath$3(resolvedFileName));
  40042. importSource = normalizePath$3('`' + (relativeFileName[0] === '.' ? '' : './') + relativeFileName + '`');
  40043. }
  40044. const dynamicImportPattern = parseDynamicImportPattern(importSource);
  40045. if (!dynamicImportPattern) {
  40046. return null;
  40047. }
  40048. const { globParams, rawPattern, userPattern } = dynamicImportPattern;
  40049. const params = globParams
  40050. ? `, ${JSON.stringify({ ...globParams, import: '*' })}`
  40051. : '';
  40052. let newRawPattern = posix$1.relative(posix$1.dirname(importer), await toAbsoluteGlob(rawPattern, root, importer, resolve));
  40053. if (!relativePathRE.test(newRawPattern)) {
  40054. newRawPattern = `./${newRawPattern}`;
  40055. }
  40056. const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
  40057. return {
  40058. rawPattern: newRawPattern,
  40059. pattern: userPattern,
  40060. glob: exp,
  40061. };
  40062. }
  40063. function dynamicImportVarsPlugin(config) {
  40064. const resolve = config.createResolver({
  40065. preferRelative: true,
  40066. tryIndex: false,
  40067. extensions: [],
  40068. });
  40069. const { include, exclude, warnOnError } = config.build.dynamicImportVarsOptions;
  40070. const filter = createFilter(include, exclude);
  40071. return {
  40072. name: 'vite:dynamic-import-vars',
  40073. resolveId(id) {
  40074. if (id === dynamicImportHelperId) {
  40075. return id;
  40076. }
  40077. },
  40078. load(id) {
  40079. if (id === dynamicImportHelperId) {
  40080. return 'export default ' + dynamicImportHelper.toString();
  40081. }
  40082. },
  40083. async transform(source, importer) {
  40084. if (!filter(importer) ||
  40085. importer === CLIENT_ENTRY ||
  40086. !hasDynamicImportRE.test(source)) {
  40087. return;
  40088. }
  40089. await init;
  40090. let imports = [];
  40091. try {
  40092. imports = parse$e(source)[0];
  40093. }
  40094. catch (e) {
  40095. // ignore as it might not be a JS file, the subsequent plugins will catch the error
  40096. return null;
  40097. }
  40098. if (!imports.length) {
  40099. return null;
  40100. }
  40101. let s;
  40102. let needDynamicImportHelper = false;
  40103. for (let index = 0; index < imports.length; index++) {
  40104. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = imports[index];
  40105. if (dynamicIndex === -1 || source[start] !== '`') {
  40106. continue;
  40107. }
  40108. if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) {
  40109. continue;
  40110. }
  40111. s || (s = new MagicString(source));
  40112. let result;
  40113. try {
  40114. // When import string is using backticks, es-module-lexer `end` captures
  40115. // until the closing parenthesis, instead of the closing backtick.
  40116. // There may be inline comments between the backtick and the closing
  40117. // parenthesis, so we manually remove them for now.
  40118. // See https://github.com/guybedford/es-module-lexer/issues/118
  40119. const importSource = removeComments(source.slice(start, end)).trim();
  40120. result = await transformDynamicImport(importSource, importer, resolve, config.root);
  40121. }
  40122. catch (error) {
  40123. if (warnOnError) {
  40124. this.warn(error);
  40125. }
  40126. else {
  40127. this.error(error);
  40128. }
  40129. }
  40130. if (!result) {
  40131. continue;
  40132. }
  40133. const { rawPattern, glob } = result;
  40134. needDynamicImportHelper = true;
  40135. s.overwrite(expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`);
  40136. }
  40137. if (s) {
  40138. if (needDynamicImportHelper) {
  40139. s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
  40140. }
  40141. return transformStableResult(s, importer, config);
  40142. }
  40143. },
  40144. };
  40145. }
  40146. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  40147. const isBuild = config.command === 'build';
  40148. const isWatch = isBuild && !!config.build.watch;
  40149. const buildPlugins = isBuild
  40150. ? await (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config)
  40151. : { pre: [], post: [] };
  40152. const { modulePreload } = config.build;
  40153. return [
  40154. ...(isDepsOptimizerEnabled(config, false) ||
  40155. isDepsOptimizerEnabled(config, true)
  40156. ? [
  40157. isBuild
  40158. ? optimizedDepsBuildPlugin(config)
  40159. : optimizedDepsPlugin(config),
  40160. ]
  40161. : []),
  40162. isWatch ? ensureWatchPlugin() : null,
  40163. isBuild ? metadataPlugin() : null,
  40164. watchPackageDataPlugin(config.packageCache),
  40165. preAliasPlugin(config),
  40166. alias$1({ entries: config.resolve.alias }),
  40167. ...prePlugins,
  40168. modulePreload !== false && modulePreload.polyfill
  40169. ? modulePreloadPolyfillPlugin(config)
  40170. : null,
  40171. resolvePlugin({
  40172. ...config.resolve,
  40173. root: config.root,
  40174. isProduction: config.isProduction,
  40175. isBuild,
  40176. packageCache: config.packageCache,
  40177. ssrConfig: config.ssr,
  40178. asSrc: true,
  40179. getDepsOptimizer: (ssr) => getDepsOptimizer(config, ssr),
  40180. shouldExternalize: isBuild && config.build.ssr && config.ssr?.format !== 'cjs'
  40181. ? (id, importer) => shouldExternalizeForSSR(id, importer, config)
  40182. : undefined,
  40183. }),
  40184. htmlInlineProxyPlugin(config),
  40185. cssPlugin(config),
  40186. config.esbuild !== false ? esbuildPlugin(config) : null,
  40187. jsonPlugin({
  40188. namedExports: true,
  40189. ...config.json,
  40190. }, isBuild),
  40191. wasmHelperPlugin(config),
  40192. webWorkerPlugin(config),
  40193. assetPlugin(config),
  40194. ...normalPlugins,
  40195. wasmFallbackPlugin(),
  40196. definePlugin(config),
  40197. cssPostPlugin(config),
  40198. isBuild && buildHtmlPlugin(config),
  40199. workerImportMetaUrlPlugin(config),
  40200. assetImportMetaUrlPlugin(config),
  40201. ...buildPlugins.pre,
  40202. dynamicImportVarsPlugin(config),
  40203. importGlobPlugin(config),
  40204. ...postPlugins,
  40205. ...buildPlugins.post,
  40206. // internal server-only plugins are always applied after everything else
  40207. ...(isBuild
  40208. ? []
  40209. : [clientInjectionsPlugin(config), importAnalysisPlugin(config)]),
  40210. ].filter(Boolean);
  40211. }
  40212. function createPluginHookUtils(plugins) {
  40213. // sort plugins per hook
  40214. const sortedPluginsCache = new Map();
  40215. function getSortedPlugins(hookName) {
  40216. if (sortedPluginsCache.has(hookName))
  40217. return sortedPluginsCache.get(hookName);
  40218. const sorted = getSortedPluginsByHook(hookName, plugins);
  40219. sortedPluginsCache.set(hookName, sorted);
  40220. return sorted;
  40221. }
  40222. function getSortedPluginHooks(hookName) {
  40223. const plugins = getSortedPlugins(hookName);
  40224. return plugins
  40225. .map((p) => {
  40226. const hook = p[hookName];
  40227. return typeof hook === 'object' && 'handler' in hook
  40228. ? hook.handler
  40229. : hook;
  40230. })
  40231. .filter(Boolean);
  40232. }
  40233. return {
  40234. getSortedPlugins,
  40235. getSortedPluginHooks,
  40236. };
  40237. }
  40238. function getSortedPluginsByHook(hookName, plugins) {
  40239. const pre = [];
  40240. const normal = [];
  40241. const post = [];
  40242. for (const plugin of plugins) {
  40243. const hook = plugin[hookName];
  40244. if (hook) {
  40245. if (typeof hook === 'object') {
  40246. if (hook.order === 'pre') {
  40247. pre.push(plugin);
  40248. continue;
  40249. }
  40250. if (hook.order === 'post') {
  40251. post.push(plugin);
  40252. continue;
  40253. }
  40254. }
  40255. normal.push(plugin);
  40256. }
  40257. }
  40258. return [...pre, ...normal, ...post];
  40259. }
  40260. function ansiRegex({onlyFirst = false} = {}) {
  40261. const pattern = [
  40262. '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
  40263. '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
  40264. ].join('|');
  40265. return new RegExp(pattern, onlyFirst ? undefined : 'g');
  40266. }
  40267. const regex = ansiRegex();
  40268. function stripAnsi(string) {
  40269. if (typeof string !== 'string') {
  40270. throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
  40271. }
  40272. // Even though the regex is global, we don't need to reset the `.lastIndex`
  40273. // because unlike `.exec()` and `.test()`, `.replace()` does it automatically
  40274. // and doing it manually has a performance penalty.
  40275. return string.replace(regex, '');
  40276. }
  40277. function prepareError(err) {
  40278. // only copy the information we need and avoid serializing unnecessary
  40279. // properties, since some errors may attach full objects (e.g. PostCSS)
  40280. return {
  40281. message: stripAnsi(err.message),
  40282. stack: stripAnsi(cleanStack(err.stack || '')),
  40283. id: err.id,
  40284. frame: stripAnsi(err.frame || ''),
  40285. plugin: err.plugin,
  40286. pluginCode: err.pluginCode?.toString(),
  40287. loc: err.loc,
  40288. };
  40289. }
  40290. function buildErrorMessage(err, args = [], includeStack = true) {
  40291. if (err.plugin)
  40292. args.push(` Plugin: ${colors$1.magenta(err.plugin)}`);
  40293. const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : '';
  40294. if (err.id)
  40295. args.push(` File: ${colors$1.cyan(err.id)}${loc}`);
  40296. if (err.frame)
  40297. args.push(colors$1.yellow(pad$1(err.frame)));
  40298. if (includeStack && err.stack)
  40299. args.push(pad$1(cleanStack(err.stack)));
  40300. return args.join('\n');
  40301. }
  40302. function cleanStack(stack) {
  40303. return stack
  40304. .split(/\n/g)
  40305. .filter((l) => /^\s*at/.test(l))
  40306. .join('\n');
  40307. }
  40308. function logError(server, err) {
  40309. const msg = buildErrorMessage(err, [
  40310. colors$1.red(`Internal server error: ${err.message}`),
  40311. ]);
  40312. server.config.logger.error(msg, {
  40313. clear: true,
  40314. timestamp: true,
  40315. error: err,
  40316. });
  40317. server.ws.send({
  40318. type: 'error',
  40319. err: prepareError(err),
  40320. });
  40321. }
  40322. function errorMiddleware(server, allowNext = false) {
  40323. // note the 4 args must be kept for connect to treat this as error middleware
  40324. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  40325. return function viteErrorMiddleware(err, _req, res, next) {
  40326. logError(server, err);
  40327. if (allowNext) {
  40328. next();
  40329. }
  40330. else {
  40331. res.statusCode = 500;
  40332. res.end(`
  40333. <!DOCTYPE html>
  40334. <html lang="en">
  40335. <head>
  40336. <meta charset="UTF-8" />
  40337. <title>Error</title>
  40338. <script type="module">
  40339. import { ErrorOverlay } from '/@vite/client'
  40340. document.body.appendChild(new ErrorOverlay(${JSON.stringify(prepareError(err)).replace(/</g, '\\u003c')}))
  40341. </script>
  40342. </head>
  40343. <body>
  40344. </body>
  40345. </html>
  40346. `);
  40347. }
  40348. };
  40349. }
  40350. /**
  40351. * This file is refactored into TypeScript based on
  40352. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  40353. */
  40354. /**
  40355. https://github.com/preactjs/wmr/blob/master/LICENSE
  40356. MIT License
  40357. Copyright (c) 2020 The Preact Authors
  40358. Permission is hereby granted, free of charge, to any person obtaining a copy
  40359. of this software and associated documentation files (the "Software"), to deal
  40360. in the Software without restriction, including without limitation the rights
  40361. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40362. copies of the Software, and to permit persons to whom the Software is
  40363. furnished to do so, subject to the following conditions:
  40364. The above copyright notice and this permission notice shall be included in all
  40365. copies or substantial portions of the Software.
  40366. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40367. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40368. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40369. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40370. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40371. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  40372. SOFTWARE.
  40373. */
  40374. const noop$3 = () => { };
  40375. const ERR_CLOSED_SERVER = 'ERR_CLOSED_SERVER';
  40376. function throwClosedServerError() {
  40377. const err = new Error('The server is being restarted or closed. Request is outdated');
  40378. err.code = ERR_CLOSED_SERVER;
  40379. // This error will be caught by the transform middleware that will
  40380. // send a 504 status code request timeout
  40381. throw err;
  40382. }
  40383. let parser = Parser$1;
  40384. async function createPluginContainer(config, moduleGraph, watcher) {
  40385. const { plugins, logger, root, build: { rollupOptions }, } = config;
  40386. const { getSortedPluginHooks, getSortedPlugins } = createPluginHookUtils(plugins);
  40387. const seenResolves = {};
  40388. const debugResolve = createDebugger('vite:resolve');
  40389. const debugPluginResolve = createDebugger('vite:plugin-resolve', {
  40390. onlyWhenFocused: 'vite:plugin',
  40391. });
  40392. const debugPluginTransform = createDebugger('vite:plugin-transform', {
  40393. onlyWhenFocused: 'vite:plugin',
  40394. });
  40395. const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
  40396. const debugSourcemapCombine = createDebugger('vite:sourcemap-combine', {
  40397. onlyWhenFocused: true,
  40398. });
  40399. // ---------------------------------------------------------------------------
  40400. const watchFiles = new Set();
  40401. const minimalContext = {
  40402. meta: {
  40403. rollupVersion: VERSION,
  40404. watchMode: true,
  40405. },
  40406. debug: noop$3,
  40407. info: noop$3,
  40408. warn: noop$3,
  40409. // @ts-expect-error noop
  40410. error: noop$3,
  40411. };
  40412. function warnIncompatibleMethod(method, plugin) {
  40413. logger.warn(colors$1.cyan(`[plugin:${plugin}] `) +
  40414. colors$1.yellow(`context method ${colors$1.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
  40415. }
  40416. // parallel, ignores returns
  40417. async function hookParallel(hookName, context, args) {
  40418. const parallelPromises = [];
  40419. for (const plugin of getSortedPlugins(hookName)) {
  40420. // Don't throw here if closed, so buildEnd and closeBundle hooks can finish running
  40421. const hook = plugin[hookName];
  40422. if (!hook)
  40423. continue;
  40424. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  40425. // @ts-ignore hook is not a primitive
  40426. const handler = 'handler' in hook ? hook.handler : hook;
  40427. if (hook.sequential) {
  40428. await Promise.all(parallelPromises);
  40429. parallelPromises.length = 0;
  40430. await handler.apply(context(plugin), args(plugin));
  40431. }
  40432. else {
  40433. parallelPromises.push(handler.apply(context(plugin), args(plugin)));
  40434. }
  40435. }
  40436. await Promise.all(parallelPromises);
  40437. }
  40438. // throw when an unsupported ModuleInfo property is accessed,
  40439. // so that incompatible plugins fail in a non-cryptic way.
  40440. const ModuleInfoProxy = {
  40441. get(info, key) {
  40442. if (key in info) {
  40443. return info[key];
  40444. }
  40445. // Don't throw an error when returning from an async function
  40446. if (key === 'then') {
  40447. return undefined;
  40448. }
  40449. throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
  40450. },
  40451. };
  40452. // same default value of "moduleInfo.meta" as in Rollup
  40453. const EMPTY_OBJECT = Object.freeze({});
  40454. function getModuleInfo(id) {
  40455. const module = moduleGraph?.getModuleById(id);
  40456. if (!module) {
  40457. return null;
  40458. }
  40459. if (!module.info) {
  40460. module.info = new Proxy({ id, meta: module.meta || EMPTY_OBJECT }, ModuleInfoProxy);
  40461. }
  40462. return module.info;
  40463. }
  40464. function updateModuleInfo(id, { meta }) {
  40465. if (meta) {
  40466. const moduleInfo = getModuleInfo(id);
  40467. if (moduleInfo) {
  40468. moduleInfo.meta = { ...moduleInfo.meta, ...meta };
  40469. }
  40470. }
  40471. }
  40472. // we should create a new context for each async hook pipeline so that the
  40473. // active plugin in that pipeline can be tracked in a concurrency-safe manner.
  40474. // using a class to make creating new contexts more efficient
  40475. class Context {
  40476. constructor(initialPlugin) {
  40477. this.meta = minimalContext.meta;
  40478. this.ssr = false;
  40479. this._scan = false;
  40480. this._activeId = null;
  40481. this._activeCode = null;
  40482. this._addedImports = null;
  40483. this.debug = noop$3;
  40484. this.info = noop$3;
  40485. this._activePlugin = initialPlugin || null;
  40486. }
  40487. parse(code, opts = {}) {
  40488. return parser.parse(code, {
  40489. sourceType: 'module',
  40490. ecmaVersion: 'latest',
  40491. locations: true,
  40492. ...opts,
  40493. });
  40494. }
  40495. async resolve(id, importer, options) {
  40496. let skip;
  40497. if (options?.skipSelf && this._activePlugin) {
  40498. skip = new Set(this._resolveSkips);
  40499. skip.add(this._activePlugin);
  40500. }
  40501. let out = await container.resolveId(id, importer, {
  40502. assertions: options?.assertions,
  40503. custom: options?.custom,
  40504. isEntry: !!options?.isEntry,
  40505. skip,
  40506. ssr: this.ssr,
  40507. scan: this._scan,
  40508. });
  40509. if (typeof out === 'string')
  40510. out = { id: out };
  40511. return out;
  40512. }
  40513. async load(options) {
  40514. // We may not have added this to our module graph yet, so ensure it exists
  40515. await moduleGraph?.ensureEntryFromUrl(unwrapId(options.id), this.ssr);
  40516. // Not all options passed to this function make sense in the context of loading individual files,
  40517. // but we can at least update the module info properties we support
  40518. updateModuleInfo(options.id, options);
  40519. await container.load(options.id, { ssr: this.ssr });
  40520. const moduleInfo = this.getModuleInfo(options.id);
  40521. // This shouldn't happen due to calling ensureEntryFromUrl, but 1) our types can't ensure that
  40522. // and 2) moduleGraph may not have been provided (though in the situations where that happens,
  40523. // we should never have plugins calling this.load)
  40524. if (!moduleInfo)
  40525. throw Error(`Failed to load module with id ${options.id}`);
  40526. return moduleInfo;
  40527. }
  40528. getModuleInfo(id) {
  40529. return getModuleInfo(id);
  40530. }
  40531. getModuleIds() {
  40532. return moduleGraph
  40533. ? moduleGraph.idToModuleMap.keys()
  40534. : Array.prototype[Symbol.iterator]();
  40535. }
  40536. addWatchFile(id) {
  40537. watchFiles.add(id);
  40538. (this._addedImports || (this._addedImports = new Set())).add(id);
  40539. if (watcher)
  40540. ensureWatchedFile(watcher, id, root);
  40541. }
  40542. getWatchFiles() {
  40543. return [...watchFiles];
  40544. }
  40545. emitFile(assetOrFile) {
  40546. warnIncompatibleMethod(`emitFile`, this._activePlugin.name);
  40547. return '';
  40548. }
  40549. setAssetSource() {
  40550. warnIncompatibleMethod(`setAssetSource`, this._activePlugin.name);
  40551. }
  40552. getFileName() {
  40553. warnIncompatibleMethod(`getFileName`, this._activePlugin.name);
  40554. return '';
  40555. }
  40556. warn(e, position) {
  40557. const err = formatError(typeof e === 'function' ? e() : e, position, this);
  40558. const msg = buildErrorMessage(err, [colors$1.yellow(`warning: ${err.message}`)], false);
  40559. logger.warn(msg, {
  40560. clear: true,
  40561. timestamp: true,
  40562. });
  40563. }
  40564. error(e, position) {
  40565. // error thrown here is caught by the transform middleware and passed on
  40566. // the the error middleware.
  40567. throw formatError(e, position, this);
  40568. }
  40569. }
  40570. function formatError(e, position, ctx) {
  40571. const err = (typeof e === 'string' ? new Error(e) : e);
  40572. if (err.pluginCode) {
  40573. return err; // The plugin likely called `this.error`
  40574. }
  40575. if (err.file && err.name === 'CssSyntaxError') {
  40576. err.id = normalizePath$3(err.file);
  40577. }
  40578. if (ctx._activePlugin)
  40579. err.plugin = ctx._activePlugin.name;
  40580. if (ctx._activeId && !err.id)
  40581. err.id = ctx._activeId;
  40582. if (ctx._activeCode) {
  40583. err.pluginCode = ctx._activeCode;
  40584. // some rollup plugins, e.g. json, sets err.position instead of err.pos
  40585. const pos = position ?? err.pos ?? err.position;
  40586. if (pos != null) {
  40587. let errLocation;
  40588. try {
  40589. errLocation = numberToPos(ctx._activeCode, pos);
  40590. }
  40591. catch (err2) {
  40592. logger.error(colors$1.red(`Error in error handler:\n${err2.stack || err2.message}\n`),
  40593. // print extra newline to separate the two errors
  40594. { error: err2 });
  40595. throw err;
  40596. }
  40597. err.loc = err.loc || {
  40598. file: err.id,
  40599. ...errLocation,
  40600. };
  40601. err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos);
  40602. }
  40603. else if (err.loc) {
  40604. // css preprocessors may report errors in an included file
  40605. if (!err.frame) {
  40606. let code = ctx._activeCode;
  40607. if (err.loc.file) {
  40608. err.id = normalizePath$3(err.loc.file);
  40609. try {
  40610. code = fs$l.readFileSync(err.loc.file, 'utf-8');
  40611. }
  40612. catch { }
  40613. }
  40614. err.frame = generateCodeFrame(code, err.loc);
  40615. }
  40616. }
  40617. else if (err.line && err.column) {
  40618. err.loc = {
  40619. file: err.id,
  40620. line: err.line,
  40621. column: err.column,
  40622. };
  40623. err.frame = err.frame || generateCodeFrame(err.id, err.loc);
  40624. }
  40625. if (ctx instanceof TransformContext &&
  40626. typeof err.loc?.line === 'number' &&
  40627. typeof err.loc?.column === 'number') {
  40628. const rawSourceMap = ctx._getCombinedSourcemap();
  40629. if (rawSourceMap) {
  40630. const traced = new TraceMap(rawSourceMap);
  40631. const { source, line, column } = originalPositionFor$1(traced, {
  40632. line: Number(err.loc.line),
  40633. column: Number(err.loc.column),
  40634. });
  40635. if (source && line != null && column != null) {
  40636. err.loc = { file: source, line, column };
  40637. }
  40638. }
  40639. }
  40640. }
  40641. else if (err.loc) {
  40642. if (!err.frame) {
  40643. let code = err.pluginCode;
  40644. if (err.loc.file) {
  40645. err.id = normalizePath$3(err.loc.file);
  40646. if (!code) {
  40647. try {
  40648. code = fs$l.readFileSync(err.loc.file, 'utf-8');
  40649. }
  40650. catch { }
  40651. }
  40652. }
  40653. if (code) {
  40654. err.frame = generateCodeFrame(`${code}`, err.loc);
  40655. }
  40656. }
  40657. }
  40658. if (typeof err.loc?.column !== 'number' &&
  40659. typeof err.loc?.line !== 'number' &&
  40660. !err.loc?.file) {
  40661. delete err.loc;
  40662. }
  40663. return err;
  40664. }
  40665. class TransformContext extends Context {
  40666. constructor(filename, code, inMap) {
  40667. super();
  40668. this.originalSourcemap = null;
  40669. this.sourcemapChain = [];
  40670. this.combinedMap = null;
  40671. this.filename = filename;
  40672. this.originalCode = code;
  40673. if (inMap) {
  40674. if (debugSourcemapCombine) {
  40675. // @ts-expect-error inject name for debug purpose
  40676. inMap.name = '$inMap';
  40677. }
  40678. this.sourcemapChain.push(inMap);
  40679. }
  40680. }
  40681. _getCombinedSourcemap(createIfNull = false) {
  40682. if (debugSourcemapCombine &&
  40683. debugSourcemapCombineFilter &&
  40684. this.filename.includes(debugSourcemapCombineFilter)) {
  40685. debugSourcemapCombine('----------', this.filename);
  40686. debugSourcemapCombine(this.combinedMap);
  40687. debugSourcemapCombine(this.sourcemapChain);
  40688. debugSourcemapCombine('----------');
  40689. }
  40690. let combinedMap = this.combinedMap;
  40691. for (let m of this.sourcemapChain) {
  40692. if (typeof m === 'string')
  40693. m = JSON.parse(m);
  40694. if (!('version' in m)) {
  40695. // empty, nullified source map
  40696. combinedMap = this.combinedMap = null;
  40697. this.sourcemapChain.length = 0;
  40698. break;
  40699. }
  40700. if (!combinedMap) {
  40701. combinedMap = m;
  40702. }
  40703. else {
  40704. combinedMap = combineSourcemaps(cleanUrl(this.filename), [
  40705. m,
  40706. combinedMap,
  40707. ]);
  40708. }
  40709. }
  40710. if (!combinedMap) {
  40711. return createIfNull
  40712. ? new MagicString(this.originalCode).generateMap({
  40713. includeContent: true,
  40714. hires: 'boundary',
  40715. source: cleanUrl(this.filename),
  40716. })
  40717. : null;
  40718. }
  40719. if (combinedMap !== this.combinedMap) {
  40720. this.combinedMap = combinedMap;
  40721. this.sourcemapChain.length = 0;
  40722. }
  40723. return this.combinedMap;
  40724. }
  40725. getCombinedSourcemap() {
  40726. return this._getCombinedSourcemap(true);
  40727. }
  40728. }
  40729. let closed = false;
  40730. const processesing = new Set();
  40731. // keeps track of hook promises so that we can wait for them all to finish upon closing the server
  40732. function handleHookPromise(maybePromise) {
  40733. if (!maybePromise?.then) {
  40734. return maybePromise;
  40735. }
  40736. const promise = maybePromise;
  40737. processesing.add(promise);
  40738. return promise.finally(() => processesing.delete(promise));
  40739. }
  40740. const container = {
  40741. options: await (async () => {
  40742. let options = rollupOptions;
  40743. for (const optionsHook of getSortedPluginHooks('options')) {
  40744. if (closed)
  40745. throwClosedServerError();
  40746. options =
  40747. (await handleHookPromise(optionsHook.call(minimalContext, options))) || options;
  40748. }
  40749. if (options.acornInjectPlugins) {
  40750. parser = Parser$1.extend(...arraify(options.acornInjectPlugins));
  40751. }
  40752. return {
  40753. acorn,
  40754. acornInjectPlugins: [],
  40755. ...options,
  40756. };
  40757. })(),
  40758. getModuleInfo,
  40759. async buildStart() {
  40760. await handleHookPromise(hookParallel('buildStart', (plugin) => new Context(plugin), () => [container.options]));
  40761. },
  40762. async resolveId(rawId, importer = join$2(root, 'index.html'), options) {
  40763. const skip = options?.skip;
  40764. const ssr = options?.ssr;
  40765. const scan = !!options?.scan;
  40766. const ctx = new Context();
  40767. ctx.ssr = !!ssr;
  40768. ctx._scan = scan;
  40769. ctx._resolveSkips = skip;
  40770. const resolveStart = debugResolve ? performance.now() : 0;
  40771. let id = null;
  40772. const partial = {};
  40773. for (const plugin of getSortedPlugins('resolveId')) {
  40774. if (closed && !ssr)
  40775. throwClosedServerError();
  40776. if (!plugin.resolveId)
  40777. continue;
  40778. if (skip?.has(plugin))
  40779. continue;
  40780. ctx._activePlugin = plugin;
  40781. const pluginResolveStart = debugPluginResolve ? performance.now() : 0;
  40782. const handler = 'handler' in plugin.resolveId
  40783. ? plugin.resolveId.handler
  40784. : plugin.resolveId;
  40785. const result = await handleHookPromise(handler.call(ctx, rawId, importer, {
  40786. assertions: options?.assertions ?? {},
  40787. custom: options?.custom,
  40788. isEntry: !!options?.isEntry,
  40789. ssr,
  40790. scan,
  40791. }));
  40792. if (!result)
  40793. continue;
  40794. if (typeof result === 'string') {
  40795. id = result;
  40796. }
  40797. else {
  40798. id = result.id;
  40799. Object.assign(partial, result);
  40800. }
  40801. debugPluginResolve?.(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, root));
  40802. // resolveId() is hookFirst - first non-null result is returned.
  40803. break;
  40804. }
  40805. if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  40806. const key = rawId + id;
  40807. // avoid spamming
  40808. if (!seenResolves[key]) {
  40809. seenResolves[key] = true;
  40810. debugResolve(`${timeFrom(resolveStart)} ${colors$1.cyan(rawId)} -> ${colors$1.dim(id)}`);
  40811. }
  40812. }
  40813. if (id) {
  40814. partial.id = isExternalUrl(id) ? id : normalizePath$3(id);
  40815. return partial;
  40816. }
  40817. else {
  40818. return null;
  40819. }
  40820. },
  40821. async load(id, options) {
  40822. const ssr = options?.ssr;
  40823. const ctx = new Context();
  40824. ctx.ssr = !!ssr;
  40825. for (const plugin of getSortedPlugins('load')) {
  40826. if (closed && !ssr)
  40827. throwClosedServerError();
  40828. if (!plugin.load)
  40829. continue;
  40830. ctx._activePlugin = plugin;
  40831. const handler = 'handler' in plugin.load ? plugin.load.handler : plugin.load;
  40832. const result = await handleHookPromise(handler.call(ctx, id, { ssr }));
  40833. if (result != null) {
  40834. if (isObject$2(result)) {
  40835. updateModuleInfo(id, result);
  40836. }
  40837. return result;
  40838. }
  40839. }
  40840. return null;
  40841. },
  40842. async transform(code, id, options) {
  40843. const inMap = options?.inMap;
  40844. const ssr = options?.ssr;
  40845. const ctx = new TransformContext(id, code, inMap);
  40846. ctx.ssr = !!ssr;
  40847. for (const plugin of getSortedPlugins('transform')) {
  40848. if (closed && !ssr)
  40849. throwClosedServerError();
  40850. if (!plugin.transform)
  40851. continue;
  40852. ctx._activePlugin = plugin;
  40853. ctx._activeId = id;
  40854. ctx._activeCode = code;
  40855. const start = debugPluginTransform ? performance.now() : 0;
  40856. let result;
  40857. const handler = 'handler' in plugin.transform
  40858. ? plugin.transform.handler
  40859. : plugin.transform;
  40860. try {
  40861. result = await handleHookPromise(handler.call(ctx, code, id, { ssr }));
  40862. }
  40863. catch (e) {
  40864. ctx.error(e);
  40865. }
  40866. if (!result)
  40867. continue;
  40868. debugPluginTransform?.(timeFrom(start), plugin.name, prettifyUrl(id, root));
  40869. if (isObject$2(result)) {
  40870. if (result.code !== undefined) {
  40871. code = result.code;
  40872. if (result.map) {
  40873. if (debugSourcemapCombine) {
  40874. // @ts-expect-error inject plugin name for debug purpose
  40875. result.map.name = plugin.name;
  40876. }
  40877. ctx.sourcemapChain.push(result.map);
  40878. }
  40879. }
  40880. updateModuleInfo(id, result);
  40881. }
  40882. else {
  40883. code = result;
  40884. }
  40885. }
  40886. return {
  40887. code,
  40888. map: ctx._getCombinedSourcemap(),
  40889. };
  40890. },
  40891. async close() {
  40892. if (closed)
  40893. return;
  40894. closed = true;
  40895. await Promise.allSettled(Array.from(processesing));
  40896. const ctx = new Context();
  40897. await hookParallel('buildEnd', () => ctx, () => []);
  40898. await hookParallel('closeBundle', () => ctx, () => []);
  40899. },
  40900. };
  40901. return container;
  40902. }
  40903. const debug$9 = createDebugger('vite:deps');
  40904. const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
  40905. // A simple regex to detect import sources. This is only used on
  40906. // <script lang="ts"> blocks in vue (setup only) or svelte files, since
  40907. // seemingly unused imports are dropped by esbuild when transpiling TS which
  40908. // prevents it from crawling further.
  40909. // We can't use es-module-lexer because it can't handle TS, and don't want to
  40910. // use Acorn because it's slow. Luckily this doesn't have to be bullet proof
  40911. // since even missed imports can be caught at runtime, and false positives will
  40912. // simply be ignored.
  40913. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  40914. function scanImports(config) {
  40915. // Only used to scan non-ssr code
  40916. const start = performance.now();
  40917. const deps = {};
  40918. const missing = {};
  40919. let entries;
  40920. const scanContext = { cancelled: false };
  40921. const esbuildContext = computeEntries(config).then((computedEntries) => {
  40922. entries = computedEntries;
  40923. if (!entries.length) {
  40924. if (!config.optimizeDeps.entries && !config.optimizeDeps.include) {
  40925. config.logger.warn(colors$1.yellow('(!) Could not auto-determine entry point from rollupOptions or html files ' +
  40926. 'and there are no explicit optimizeDeps.include patterns. ' +
  40927. 'Skipping dependency pre-bundling.'));
  40928. }
  40929. return;
  40930. }
  40931. if (scanContext.cancelled)
  40932. return;
  40933. debug$9?.(`Crawling dependencies using entries: ${entries
  40934. .map((entry) => `\n ${colors$1.dim(entry)}`)
  40935. .join('')}`);
  40936. return prepareEsbuildScanner(config, entries, deps, missing, scanContext);
  40937. });
  40938. const result = esbuildContext
  40939. .then((context) => {
  40940. function disposeContext() {
  40941. return context?.dispose().catch((e) => {
  40942. config.logger.error('Failed to dispose esbuild context', { error: e });
  40943. });
  40944. }
  40945. if (!context || scanContext?.cancelled) {
  40946. disposeContext();
  40947. return { deps: {}, missing: {} };
  40948. }
  40949. return context
  40950. .rebuild()
  40951. .then(() => {
  40952. return {
  40953. // Ensure a fixed order so hashes are stable and improve logs
  40954. deps: orderedDependencies(deps),
  40955. missing,
  40956. };
  40957. })
  40958. .finally(() => {
  40959. return disposeContext();
  40960. });
  40961. })
  40962. .catch(async (e) => {
  40963. if (e.errors && e.message.includes('The build was canceled')) {
  40964. // esbuild logs an error when cancelling, but this is expected so
  40965. // return an empty result instead
  40966. return { deps: {}, missing: {} };
  40967. }
  40968. const prependMessage = colors$1.red(`\
  40969. Failed to scan for dependencies from entries:
  40970. ${entries.join('\n')}
  40971. `);
  40972. if (e.errors) {
  40973. const msgs = await formatMessages(e.errors, {
  40974. kind: 'error',
  40975. color: true,
  40976. });
  40977. e.message = prependMessage + msgs.join('\n');
  40978. }
  40979. else {
  40980. e.message = prependMessage + e.message;
  40981. }
  40982. throw e;
  40983. })
  40984. .finally(() => {
  40985. if (debug$9) {
  40986. const duration = (performance.now() - start).toFixed(2);
  40987. const depsStr = Object.keys(orderedDependencies(deps))
  40988. .sort()
  40989. .map((id) => `\n ${colors$1.cyan(id)} -> ${colors$1.dim(deps[id])}`)
  40990. .join('') || colors$1.dim('no dependencies found');
  40991. debug$9(`Scan completed in ${duration}ms: ${depsStr}`);
  40992. }
  40993. });
  40994. return {
  40995. cancel: async () => {
  40996. scanContext.cancelled = true;
  40997. return esbuildContext.then((context) => context?.cancel());
  40998. },
  40999. result,
  41000. };
  41001. }
  41002. async function computeEntries(config) {
  41003. let entries = [];
  41004. const explicitEntryPatterns = config.optimizeDeps.entries;
  41005. const buildInput = config.build.rollupOptions?.input;
  41006. if (explicitEntryPatterns) {
  41007. entries = await globEntries(explicitEntryPatterns, config);
  41008. }
  41009. else if (buildInput) {
  41010. const resolvePath = (p) => path$o.resolve(config.root, p);
  41011. if (typeof buildInput === 'string') {
  41012. entries = [resolvePath(buildInput)];
  41013. }
  41014. else if (Array.isArray(buildInput)) {
  41015. entries = buildInput.map(resolvePath);
  41016. }
  41017. else if (isObject$2(buildInput)) {
  41018. entries = Object.values(buildInput).map(resolvePath);
  41019. }
  41020. else {
  41021. throw new Error('invalid rollupOptions.input value.');
  41022. }
  41023. }
  41024. else {
  41025. entries = await globEntries('**/*.html', config);
  41026. }
  41027. // Non-supported entry file types and virtual files should not be scanned for
  41028. // dependencies.
  41029. entries = entries.filter((entry) => isScannable(entry) && fs$l.existsSync(entry));
  41030. return entries;
  41031. }
  41032. async function prepareEsbuildScanner(config, entries, deps, missing, scanContext) {
  41033. const container = await createPluginContainer(config);
  41034. if (scanContext?.cancelled)
  41035. return;
  41036. const plugin = esbuildScanPlugin(config, container, deps, missing, entries);
  41037. const { plugins = [], tsconfig, tsconfigRaw, ...esbuildOptions } = config.optimizeDeps?.esbuildOptions ?? {};
  41038. return await esbuild.context({
  41039. absWorkingDir: process.cwd(),
  41040. write: false,
  41041. stdin: {
  41042. contents: entries.map((e) => `import ${JSON.stringify(e)}`).join('\n'),
  41043. loader: 'js',
  41044. },
  41045. bundle: true,
  41046. format: 'esm',
  41047. logLevel: 'silent',
  41048. plugins: [...plugins, plugin],
  41049. tsconfig,
  41050. tsconfigRaw: resolveTsconfigRaw(tsconfig, tsconfigRaw),
  41051. ...esbuildOptions,
  41052. });
  41053. }
  41054. function orderedDependencies(deps) {
  41055. const depsList = Object.entries(deps);
  41056. // Ensure the same browserHash for the same set of dependencies
  41057. depsList.sort((a, b) => a[0].localeCompare(b[0]));
  41058. return Object.fromEntries(depsList);
  41059. }
  41060. function globEntries(pattern, config) {
  41061. return glob(pattern, {
  41062. cwd: config.root,
  41063. ignore: [
  41064. '**/node_modules/**',
  41065. `**/${config.build.outDir}/**`,
  41066. // if there aren't explicit entries, also ignore other common folders
  41067. ...(config.optimizeDeps.entries
  41068. ? []
  41069. : [`**/__tests__/**`, `**/coverage/**`]),
  41070. ],
  41071. absolute: true,
  41072. suppressErrors: true, // suppress EACCES errors
  41073. });
  41074. }
  41075. const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
  41076. const commentRE = /<!--.*?-->/gs;
  41077. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  41078. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  41079. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  41080. const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
  41081. function esbuildScanPlugin(config, container, depImports, missing, entries) {
  41082. const seen = new Map();
  41083. const resolve = async (id, importer, options) => {
  41084. const key = id + (importer && path$o.dirname(importer));
  41085. if (seen.has(key)) {
  41086. return seen.get(key);
  41087. }
  41088. const resolved = await container.resolveId(id, importer && normalizePath$3(importer), {
  41089. ...options,
  41090. scan: true,
  41091. });
  41092. const res = resolved?.id;
  41093. seen.set(key, res);
  41094. return res;
  41095. };
  41096. const include = config.optimizeDeps?.include;
  41097. const exclude = [
  41098. ...(config.optimizeDeps?.exclude || []),
  41099. '@vite/client',
  41100. '@vite/env',
  41101. ];
  41102. const externalUnlessEntry = ({ path }) => ({
  41103. path,
  41104. external: !entries.includes(path),
  41105. });
  41106. const doTransformGlobImport = async (contents, id, loader) => {
  41107. let transpiledContents;
  41108. // transpile because `transformGlobImport` only expects js
  41109. if (loader !== 'js') {
  41110. transpiledContents = (await transform$1(contents, { loader })).code;
  41111. }
  41112. else {
  41113. transpiledContents = contents;
  41114. }
  41115. const result = await transformGlobImport(transpiledContents, id, config.root, resolve, config.isProduction);
  41116. return result?.s.toString() || transpiledContents;
  41117. };
  41118. return {
  41119. name: 'vite:dep-scan',
  41120. setup(build) {
  41121. const scripts = {};
  41122. // external urls
  41123. build.onResolve({ filter: externalRE }, ({ path }) => ({
  41124. path,
  41125. external: true,
  41126. }));
  41127. // data urls
  41128. build.onResolve({ filter: dataUrlRE }, ({ path }) => ({
  41129. path,
  41130. external: true,
  41131. }));
  41132. // local scripts (`<script>` in Svelte and `<script setup>` in Vue)
  41133. build.onResolve({ filter: virtualModuleRE }, ({ path }) => {
  41134. return {
  41135. // strip prefix to get valid filesystem path so esbuild can resolve imports in the file
  41136. path: path.replace(virtualModulePrefix, ''),
  41137. namespace: 'script',
  41138. };
  41139. });
  41140. build.onLoad({ filter: /.*/, namespace: 'script' }, ({ path }) => {
  41141. return scripts[path];
  41142. });
  41143. // html types: extract script contents -----------------------------------
  41144. build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {
  41145. const resolved = await resolve(path, importer);
  41146. if (!resolved)
  41147. return;
  41148. // It is possible for the scanner to scan html types in node_modules.
  41149. // If we can optimize this html type, skip it so it's handled by the
  41150. // bare import resolve, and recorded as optimization dep.
  41151. if (isInNodeModules(resolved) &&
  41152. isOptimizable(resolved, config.optimizeDeps))
  41153. return;
  41154. return {
  41155. path: resolved,
  41156. namespace: 'html',
  41157. };
  41158. });
  41159. // extract scripts inside HTML-like files and treat it as a js module
  41160. build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => {
  41161. let raw = await fsp.readFile(path, 'utf-8');
  41162. // Avoid matching the content of the comment
  41163. raw = raw.replace(commentRE, '<!---->');
  41164. const isHtml = path.endsWith('.html');
  41165. scriptRE.lastIndex = 0;
  41166. let js = '';
  41167. let scriptId = 0;
  41168. let match;
  41169. while ((match = scriptRE.exec(raw))) {
  41170. const [, openTag, content] = match;
  41171. const typeMatch = openTag.match(typeRE);
  41172. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  41173. const langMatch = openTag.match(langRE);
  41174. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  41175. // skip non type module script
  41176. if (isHtml && type !== 'module') {
  41177. continue;
  41178. }
  41179. // skip type="application/ld+json" and other non-JS types
  41180. if (type &&
  41181. !(type.includes('javascript') ||
  41182. type.includes('ecmascript') ||
  41183. type === 'module')) {
  41184. continue;
  41185. }
  41186. let loader = 'js';
  41187. if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {
  41188. loader = lang;
  41189. }
  41190. else if (path.endsWith('.astro')) {
  41191. loader = 'ts';
  41192. }
  41193. const srcMatch = openTag.match(srcRE);
  41194. if (srcMatch) {
  41195. const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
  41196. js += `import ${JSON.stringify(src)}\n`;
  41197. }
  41198. else if (content.trim()) {
  41199. // The reason why virtual modules are needed:
  41200. // 1. There can be module scripts (`<script context="module">` in Svelte and `<script>` in Vue)
  41201. // or local scripts (`<script>` in Svelte and `<script setup>` in Vue)
  41202. // 2. There can be multiple module scripts in html
  41203. // We need to handle these separately in case variable names are reused between them
  41204. // append imports in TS to prevent esbuild from removing them
  41205. // since they may be used in the template
  41206. const contents = content +
  41207. (loader.startsWith('ts') ? extractImportPaths(content) : '');
  41208. const key = `${path}?id=${scriptId++}`;
  41209. if (contents.includes('import.meta.glob')) {
  41210. scripts[key] = {
  41211. loader: 'js',
  41212. contents: await doTransformGlobImport(contents, path, loader),
  41213. pluginData: {
  41214. htmlType: { loader },
  41215. },
  41216. };
  41217. }
  41218. else {
  41219. scripts[key] = {
  41220. loader,
  41221. contents,
  41222. pluginData: {
  41223. htmlType: { loader },
  41224. },
  41225. };
  41226. }
  41227. const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
  41228. const contextMatch = openTag.match(contextRE);
  41229. const context = contextMatch &&
  41230. (contextMatch[1] || contextMatch[2] || contextMatch[3]);
  41231. // Especially for Svelte files, exports in <script context="module"> means module exports,
  41232. // exports in <script> means component props. To avoid having two same export name from the
  41233. // star exports, we need to ignore exports in <script>
  41234. if (path.endsWith('.svelte') && context !== 'module') {
  41235. js += `import ${virtualModulePath}\n`;
  41236. }
  41237. else {
  41238. js += `export * from ${virtualModulePath}\n`;
  41239. }
  41240. }
  41241. }
  41242. // This will trigger incorrectly if `export default` is contained
  41243. // anywhere in a string. Svelte and Astro files can't have
  41244. // `export default` as code so we know if it's encountered it's a
  41245. // false positive (e.g. contained in a string)
  41246. if (!path.endsWith('.vue') || !js.includes('export default')) {
  41247. js += '\nexport default {}';
  41248. }
  41249. return {
  41250. loader: 'js',
  41251. contents: js,
  41252. };
  41253. });
  41254. // bare imports: record and externalize ----------------------------------
  41255. build.onResolve({
  41256. // avoid matching windows volume
  41257. filter: /^[\w@][^:]/,
  41258. }, async ({ path: id, importer, pluginData }) => {
  41259. if (moduleListContains(exclude, id)) {
  41260. return externalUnlessEntry({ path: id });
  41261. }
  41262. if (depImports[id]) {
  41263. return externalUnlessEntry({ path: id });
  41264. }
  41265. const resolved = await resolve(id, importer, {
  41266. custom: {
  41267. depScan: { loader: pluginData?.htmlType?.loader },
  41268. },
  41269. });
  41270. if (resolved) {
  41271. if (shouldExternalizeDep(resolved, id)) {
  41272. return externalUnlessEntry({ path: id });
  41273. }
  41274. if (isInNodeModules(resolved) || include?.includes(id)) {
  41275. // dependency or forced included, externalize and stop crawling
  41276. if (isOptimizable(resolved, config.optimizeDeps)) {
  41277. depImports[id] = resolved;
  41278. }
  41279. return externalUnlessEntry({ path: id });
  41280. }
  41281. else if (isScannable(resolved)) {
  41282. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  41283. // linked package, keep crawling
  41284. return {
  41285. path: path$o.resolve(resolved),
  41286. namespace,
  41287. };
  41288. }
  41289. else {
  41290. return externalUnlessEntry({ path: id });
  41291. }
  41292. }
  41293. else {
  41294. missing[id] = normalizePath$3(importer);
  41295. }
  41296. });
  41297. // Externalized file types -----------------------------------------------
  41298. // these are done on raw ids using esbuild's native regex filter so it
  41299. // should be faster than doing it in the catch-all via js
  41300. // they are done after the bare import resolve because a package name
  41301. // may end with these extensions
  41302. // css
  41303. build.onResolve({ filter: CSS_LANGS_RE }, externalUnlessEntry);
  41304. // json & wasm
  41305. build.onResolve({ filter: /\.(json|json5|wasm)$/ }, externalUnlessEntry);
  41306. // known asset types
  41307. build.onResolve({
  41308. filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`),
  41309. }, externalUnlessEntry);
  41310. // known vite query types: ?worker, ?raw
  41311. build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({
  41312. path,
  41313. external: true,
  41314. }));
  41315. // catch all -------------------------------------------------------------
  41316. build.onResolve({
  41317. filter: /.*/,
  41318. }, async ({ path: id, importer, pluginData }) => {
  41319. // use vite resolver to support urls and omitted extensions
  41320. const resolved = await resolve(id, importer, {
  41321. custom: {
  41322. depScan: { loader: pluginData?.htmlType?.loader },
  41323. },
  41324. });
  41325. if (resolved) {
  41326. if (shouldExternalizeDep(resolved, id) || !isScannable(resolved)) {
  41327. return externalUnlessEntry({ path: id });
  41328. }
  41329. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  41330. return {
  41331. path: path$o.resolve(cleanUrl(resolved)),
  41332. namespace,
  41333. };
  41334. }
  41335. else {
  41336. // resolve failed... probably unsupported type
  41337. return externalUnlessEntry({ path: id });
  41338. }
  41339. });
  41340. // for jsx/tsx, we need to access the content and check for
  41341. // presence of import.meta.glob, since it results in import relationships
  41342. // but isn't crawled by esbuild.
  41343. build.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => {
  41344. let ext = path$o.extname(id).slice(1);
  41345. if (ext === 'mjs')
  41346. ext = 'js';
  41347. let contents = await fsp.readFile(id, 'utf-8');
  41348. if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {
  41349. contents = config.esbuild.jsxInject + `\n` + contents;
  41350. }
  41351. const loader = config.optimizeDeps?.esbuildOptions?.loader?.[`.${ext}`] ||
  41352. ext;
  41353. if (contents.includes('import.meta.glob')) {
  41354. return {
  41355. loader: 'js',
  41356. contents: await doTransformGlobImport(contents, id, loader),
  41357. };
  41358. }
  41359. return {
  41360. loader,
  41361. contents,
  41362. };
  41363. });
  41364. },
  41365. };
  41366. }
  41367. /**
  41368. * when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
  41369. * unused to esbuild and dropped in the build output, which prevents
  41370. * esbuild from crawling further.
  41371. * the solution is to add `import 'x'` for every source to force
  41372. * esbuild to keep crawling due to potential side effects.
  41373. */
  41374. function extractImportPaths(code) {
  41375. // empty singleline & multiline comments to avoid matching comments
  41376. code = code
  41377. .replace(multilineCommentsRE$1, '/* */')
  41378. .replace(singlelineCommentsRE$1, '');
  41379. let js = '';
  41380. let m;
  41381. importsRE.lastIndex = 0;
  41382. while ((m = importsRE.exec(code)) != null) {
  41383. js += `\nimport ${m[1]}`;
  41384. }
  41385. return js;
  41386. }
  41387. function shouldExternalizeDep(resolvedId, rawId) {
  41388. // not a valid file path
  41389. if (!path$o.isAbsolute(resolvedId)) {
  41390. return true;
  41391. }
  41392. // virtual id
  41393. if (resolvedId === rawId || resolvedId.includes('\0')) {
  41394. return true;
  41395. }
  41396. return false;
  41397. }
  41398. function isScannable(id) {
  41399. // From Vite 5, all optimizeDeps.extensions are scannable. We hardcode .marko for 4.5.0 to avoid
  41400. // potential regressions. See https://github.com/vitejs/vite/pull/14543
  41401. return (JS_TYPES_RE.test(id) ||
  41402. htmlTypesRE.test(id) ||
  41403. path$o.extname(id) === '.marko');
  41404. }
  41405. // esbuild v0.18 only transforms decorators when `experimentalDecorators` is set to `true`.
  41406. // To preserve compat with the esbuild breaking change, we set `experimentalDecorators` to
  41407. // `true` by default if it's unset.
  41408. // TODO: Remove this in Vite 5 and check https://github.com/vitejs/vite/pull/13805#issuecomment-1633612320
  41409. function resolveTsconfigRaw(tsconfig, tsconfigRaw) {
  41410. return tsconfig || typeof tsconfigRaw === 'string'
  41411. ? tsconfigRaw
  41412. : {
  41413. ...tsconfigRaw,
  41414. compilerOptions: {
  41415. experimentalDecorators: true,
  41416. ...tsconfigRaw?.compilerOptions,
  41417. },
  41418. };
  41419. }
  41420. function createOptimizeDepsIncludeResolver(config, ssr) {
  41421. const resolve = config.createResolver({
  41422. asSrc: false,
  41423. scan: true,
  41424. ssrOptimizeCheck: ssr,
  41425. ssrConfig: config.ssr,
  41426. packageCache: new Map(),
  41427. });
  41428. return async (id) => {
  41429. const lastArrowIndex = id.lastIndexOf('>');
  41430. if (lastArrowIndex === -1) {
  41431. return await resolve(id, undefined, undefined, ssr);
  41432. }
  41433. // split nested selected id by last '>', for example:
  41434. // 'foo > bar > baz' => 'foo > bar' & 'baz'
  41435. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  41436. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  41437. const basedir = nestedResolveBasedir(nestedRoot, config.root, config.resolve.preserveSymlinks);
  41438. return await resolve(nestedPath, path$o.resolve(basedir, 'package.json'), undefined, ssr);
  41439. };
  41440. }
  41441. /**
  41442. * Expand the glob syntax in `optimizeDeps.include` to proper import paths
  41443. */
  41444. function expandGlobIds(id, config) {
  41445. const pkgName = getNpmPackageName(id);
  41446. if (!pkgName)
  41447. return [];
  41448. const pkgData = resolvePackageData(pkgName, config.root, config.resolve.preserveSymlinks, config.packageCache);
  41449. if (!pkgData)
  41450. return [];
  41451. const pattern = '.' + id.slice(pkgName.length);
  41452. const exports = pkgData.data.exports;
  41453. // if package has exports field, get all possible export paths and apply
  41454. // glob on them with micromatch
  41455. if (exports) {
  41456. if (typeof exports === 'string' || Array.isArray(exports)) {
  41457. return [pkgName];
  41458. }
  41459. const possibleExportPaths = [];
  41460. for (const key in exports) {
  41461. if (key.startsWith('.')) {
  41462. if (key.includes('*')) {
  41463. // "./glob/*": {
  41464. // "browser": "./dist/glob/*-browser/*.js", <-- get this one
  41465. // "default": "./dist/glob/*/*.js"
  41466. // }
  41467. // NOTE: theoretically the "default" condition could map to a different
  41468. // set of files, but that complicates the resolve logic, so we assume
  41469. // all conditions map to the same set of files, and get the first one.
  41470. const exportsValue = getFirstExportStringValue(exports[key]);
  41471. if (!exportsValue)
  41472. continue;
  41473. // "./dist/glob/*-browser/*.js" => "./dist/glob/**/*-browser/**/*.js"
  41474. // NOTE: in some cases, this could expand to consecutive /**/*/**/* etc
  41475. // but it's fine since fast-glob handles it the same.
  41476. const exportValuePattern = exportsValue.replace(/\*/g, '**/*');
  41477. // "./dist/glob/*-browser/*.js" => /dist\/glob\/(.*)-browser\/(.*)\.js/
  41478. const exportsValueGlobRe = new RegExp(exportsValue.split('*').map(escapeRegex).join('(.*)'));
  41479. possibleExportPaths.push(...glob
  41480. .sync(exportValuePattern, {
  41481. cwd: pkgData.dir,
  41482. ignore: ['node_modules'],
  41483. })
  41484. .map((filePath) => {
  41485. // "./glob/*": "./dist/glob/*-browser/*.js"
  41486. // `filePath`: "./dist/glob/foo-browser/foo.js"
  41487. // we need to revert the file path back to the export key by
  41488. // matching value regex and replacing the capture groups to the key
  41489. const matched = slash$1(filePath).match(exportsValueGlobRe);
  41490. // `matched`: [..., 'foo', 'foo']
  41491. if (matched) {
  41492. let allGlobSame = matched.length === 2;
  41493. // exports key can only have one *, so for >=2 matched groups,
  41494. // make sure they have the same value
  41495. if (!allGlobSame) {
  41496. // assume true, if one group is different, set false and break
  41497. allGlobSame = true;
  41498. for (let i = 2; i < matched.length; i++) {
  41499. if (matched[i] !== matched[i - 1]) {
  41500. allGlobSame = false;
  41501. break;
  41502. }
  41503. }
  41504. }
  41505. if (allGlobSame) {
  41506. return key.replace('*', matched[1]).slice(2);
  41507. }
  41508. }
  41509. return '';
  41510. })
  41511. .filter(Boolean));
  41512. }
  41513. else {
  41514. possibleExportPaths.push(key.slice(2));
  41515. }
  41516. }
  41517. }
  41518. const matched = micromatch$2(possibleExportPaths, pattern).map((match) => path$o.posix.join(pkgName, match));
  41519. matched.unshift(pkgName);
  41520. return matched;
  41521. }
  41522. else {
  41523. // for packages without exports, we can do a simple glob
  41524. const matched = glob
  41525. .sync(pattern, { cwd: pkgData.dir, ignore: ['node_modules'] })
  41526. .map((match) => path$o.posix.join(pkgName, slash$1(match)));
  41527. matched.unshift(pkgName);
  41528. return matched;
  41529. }
  41530. }
  41531. function getFirstExportStringValue(obj) {
  41532. if (typeof obj === 'string') {
  41533. return obj;
  41534. }
  41535. else if (Array.isArray(obj)) {
  41536. return obj[0];
  41537. }
  41538. else {
  41539. for (const key in obj) {
  41540. return getFirstExportStringValue(obj[key]);
  41541. }
  41542. }
  41543. }
  41544. /**
  41545. * Continuously resolve the basedir of packages separated by '>'
  41546. */
  41547. function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
  41548. const pkgs = id.split('>').map((pkg) => pkg.trim());
  41549. for (const pkg of pkgs) {
  41550. basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
  41551. }
  41552. return basedir;
  41553. }
  41554. const debug$8 = createDebugger('vite:deps');
  41555. /**
  41556. * The amount to wait for requests to register newly found dependencies before triggering
  41557. * a re-bundle + page reload
  41558. */
  41559. const debounceMs = 100;
  41560. const depsOptimizerMap = new WeakMap();
  41561. const devSsrDepsOptimizerMap = new WeakMap();
  41562. function getDepsOptimizer(config, ssr) {
  41563. // Workers compilation shares the DepsOptimizer from the main build
  41564. const isDevSsr = ssr && config.command !== 'build';
  41565. return (isDevSsr ? devSsrDepsOptimizerMap : depsOptimizerMap).get(config.mainConfig || config);
  41566. }
  41567. async function initDepsOptimizer(config, server) {
  41568. // Non Dev SSR Optimizer
  41569. const ssr = config.command === 'build' && !!config.build.ssr;
  41570. if (!getDepsOptimizer(config, ssr)) {
  41571. await createDepsOptimizer(config, server);
  41572. }
  41573. }
  41574. let creatingDevSsrOptimizer;
  41575. async function initDevSsrDepsOptimizer(config, server) {
  41576. if (getDepsOptimizer(config, true)) {
  41577. // ssr
  41578. return;
  41579. }
  41580. if (creatingDevSsrOptimizer) {
  41581. return creatingDevSsrOptimizer;
  41582. }
  41583. creatingDevSsrOptimizer = (async function () {
  41584. // Important: scanning needs to be done before starting the SSR dev optimizer
  41585. // If ssrLoadModule is called before server.listen(), the main deps optimizer
  41586. // will not be yet created
  41587. const ssr = false;
  41588. if (!getDepsOptimizer(config, ssr)) {
  41589. await initDepsOptimizer(config, server);
  41590. }
  41591. await getDepsOptimizer(config, ssr).scanProcessing;
  41592. await createDevSsrDepsOptimizer(config);
  41593. creatingDevSsrOptimizer = undefined;
  41594. })();
  41595. return await creatingDevSsrOptimizer;
  41596. }
  41597. async function createDepsOptimizer(config, server) {
  41598. const { logger } = config;
  41599. const isBuild = config.command === 'build';
  41600. const ssr = isBuild && !!config.build.ssr; // safe as Dev SSR don't use this optimizer
  41601. const sessionTimestamp = Date.now().toString();
  41602. const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr);
  41603. let debounceProcessingHandle;
  41604. let closed = false;
  41605. let metadata = cachedMetadata || initDepsOptimizerMetadata(config, ssr, sessionTimestamp);
  41606. const depsOptimizer = {
  41607. metadata,
  41608. registerMissingImport,
  41609. run: () => debouncedProcessing(0),
  41610. isOptimizedDepFile: createIsOptimizedDepFile(config),
  41611. isOptimizedDepUrl: createIsOptimizedDepUrl(config),
  41612. getOptimizedDepId: (depInfo) => isBuild ? depInfo.file : `${depInfo.file}?v=${depInfo.browserHash}`,
  41613. registerWorkersSource,
  41614. delayDepsOptimizerUntil,
  41615. resetRegisteredIds,
  41616. ensureFirstRun,
  41617. close,
  41618. options: getDepOptimizationConfig(config, ssr),
  41619. };
  41620. depsOptimizerMap.set(config, depsOptimizer);
  41621. let newDepsDiscovered = false;
  41622. let newDepsToLog = [];
  41623. let newDepsToLogHandle;
  41624. const logNewlyDiscoveredDeps = () => {
  41625. if (newDepsToLog.length) {
  41626. config.logger.info(colors$1.green(`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`), {
  41627. timestamp: true,
  41628. });
  41629. newDepsToLog = [];
  41630. }
  41631. };
  41632. let depOptimizationProcessing = newDepOptimizationProcessing();
  41633. let depOptimizationProcessingQueue = [];
  41634. const resolveEnqueuedProcessingPromises = () => {
  41635. // Resolve all the processings (including the ones which were delayed)
  41636. for (const processing of depOptimizationProcessingQueue) {
  41637. processing.resolve();
  41638. }
  41639. depOptimizationProcessingQueue = [];
  41640. };
  41641. let enqueuedRerun;
  41642. let currentlyProcessing = false;
  41643. let firstRunCalled = !!cachedMetadata;
  41644. // During build, we wait for every module to be scanned before resolving
  41645. // optimized deps loading for rollup on each rebuild. It will be recreated
  41646. // after each buildStart.
  41647. // During dev, if this is a cold run, we wait for static imports discovered
  41648. // from the first request before resolving to minimize full page reloads.
  41649. // On warm start or after the first optimization is run, we use a simpler
  41650. // debounce strategy each time a new dep is discovered.
  41651. let crawlEndFinder;
  41652. if (isBuild || !cachedMetadata) {
  41653. crawlEndFinder = setupOnCrawlEnd(onCrawlEnd);
  41654. }
  41655. let optimizationResult;
  41656. let discover;
  41657. async function close() {
  41658. closed = true;
  41659. crawlEndFinder?.cancel();
  41660. await Promise.allSettled([
  41661. discover?.cancel(),
  41662. depsOptimizer.scanProcessing,
  41663. optimizationResult?.cancel(),
  41664. ]);
  41665. }
  41666. if (!cachedMetadata) {
  41667. // Enter processing state until crawl of static imports ends
  41668. currentlyProcessing = true;
  41669. // Initialize discovered deps with manually added optimizeDeps.include info
  41670. const deps = {};
  41671. await addManuallyIncludedOptimizeDeps(deps, config, ssr);
  41672. const discovered = toDiscoveredDependencies(config, deps, ssr, sessionTimestamp);
  41673. for (const depInfo of Object.values(discovered)) {
  41674. addOptimizedDepInfo(metadata, 'discovered', {
  41675. ...depInfo,
  41676. processing: depOptimizationProcessing.promise,
  41677. });
  41678. newDepsDiscovered = true;
  41679. }
  41680. if (config.optimizeDeps.noDiscovery) {
  41681. // We don't need to scan for dependencies or wait for the static crawl to end
  41682. // Run the first optimization run immediately
  41683. runOptimizer();
  41684. }
  41685. else if (!isBuild) {
  41686. // Important, the scanner is dev only
  41687. depsOptimizer.scanProcessing = new Promise((resolve) => {
  41688. (async () => {
  41689. try {
  41690. debug$8?.(colors$1.green(`scanning for dependencies...`));
  41691. discover = discoverProjectDependencies(config);
  41692. const deps = await discover.result;
  41693. discover = undefined;
  41694. // Add these dependencies to the discovered list, as these are currently
  41695. // used by the preAliasPlugin to support aliased and optimized deps.
  41696. // This is also used by the CJS externalization heuristics in legacy mode
  41697. for (const id of Object.keys(deps)) {
  41698. if (!metadata.discovered[id]) {
  41699. addMissingDep(id, deps[id]);
  41700. }
  41701. }
  41702. const knownDeps = prepareKnownDeps();
  41703. // For dev, we run the scanner and the first optimization
  41704. // run on the background, but we wait until crawling has ended
  41705. // to decide if we send this result to the browser or we need to
  41706. // do another optimize step
  41707. optimizationResult = runOptimizeDeps(config, knownDeps);
  41708. }
  41709. catch (e) {
  41710. logger.error(e.stack || e.message);
  41711. }
  41712. finally {
  41713. resolve();
  41714. depsOptimizer.scanProcessing = undefined;
  41715. }
  41716. })();
  41717. });
  41718. }
  41719. }
  41720. function startNextDiscoveredBatch() {
  41721. newDepsDiscovered = false;
  41722. // Add the current depOptimizationProcessing to the queue, these
  41723. // promises are going to be resolved once a rerun is committed
  41724. depOptimizationProcessingQueue.push(depOptimizationProcessing);
  41725. // Create a new promise for the next rerun, discovered missing
  41726. // dependencies will be assigned this promise from this point
  41727. depOptimizationProcessing = newDepOptimizationProcessing();
  41728. }
  41729. function prepareKnownDeps() {
  41730. const knownDeps = {};
  41731. // Clone optimized info objects, fileHash, browserHash may be changed for them
  41732. for (const dep of Object.keys(metadata.optimized)) {
  41733. knownDeps[dep] = { ...metadata.optimized[dep] };
  41734. }
  41735. for (const dep of Object.keys(metadata.discovered)) {
  41736. // Clone the discovered info discarding its processing promise
  41737. const { processing, ...info } = metadata.discovered[dep];
  41738. knownDeps[dep] = info;
  41739. }
  41740. return knownDeps;
  41741. }
  41742. async function runOptimizer(preRunResult) {
  41743. // a successful completion of the optimizeDeps rerun will end up
  41744. // creating new bundled version of all current and discovered deps
  41745. // in the cache dir and a new metadata info object assigned
  41746. // to _metadata. A fullReload is only issued if the previous bundled
  41747. // dependencies have changed.
  41748. // if the rerun fails, _metadata remains untouched, current discovered
  41749. // deps are cleaned, and a fullReload is issued
  41750. // All deps, previous known and newly discovered are rebundled,
  41751. // respect insertion order to keep the metadata file stable
  41752. const isRerun = firstRunCalled;
  41753. firstRunCalled = true;
  41754. // Ensure that rerun is called sequentially
  41755. enqueuedRerun = undefined;
  41756. // Ensure that a rerun will not be issued for current discovered deps
  41757. if (debounceProcessingHandle)
  41758. clearTimeout(debounceProcessingHandle);
  41759. if (closed || Object.keys(metadata.discovered).length === 0) {
  41760. currentlyProcessing = false;
  41761. return;
  41762. }
  41763. currentlyProcessing = true;
  41764. try {
  41765. let processingResult;
  41766. if (preRunResult) {
  41767. processingResult = preRunResult;
  41768. }
  41769. else {
  41770. const knownDeps = prepareKnownDeps();
  41771. startNextDiscoveredBatch();
  41772. optimizationResult = runOptimizeDeps(config, knownDeps);
  41773. processingResult = await optimizationResult.result;
  41774. optimizationResult = undefined;
  41775. }
  41776. if (closed) {
  41777. currentlyProcessing = false;
  41778. processingResult.cancel();
  41779. resolveEnqueuedProcessingPromises();
  41780. return;
  41781. }
  41782. const newData = processingResult.metadata;
  41783. const needsInteropMismatch = findInteropMismatches(metadata.discovered, newData.optimized);
  41784. // After a re-optimization, if the internal bundled chunks change a full page reload
  41785. // is required. If the files are stable, we can avoid the reload that is expensive
  41786. // for large applications. Comparing their fileHash we can find out if it is safe to
  41787. // keep the current browser state.
  41788. const needsReload = needsInteropMismatch.length > 0 ||
  41789. metadata.hash !== newData.hash ||
  41790. Object.keys(metadata.optimized).some((dep) => {
  41791. return (metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash);
  41792. });
  41793. const commitProcessing = async () => {
  41794. await processingResult.commit();
  41795. // While optimizeDeps is running, new missing deps may be discovered,
  41796. // in which case they will keep being added to metadata.discovered
  41797. for (const id in metadata.discovered) {
  41798. if (!newData.optimized[id]) {
  41799. addOptimizedDepInfo(newData, 'discovered', metadata.discovered[id]);
  41800. }
  41801. }
  41802. // If we don't reload the page, we need to keep browserHash stable
  41803. if (!needsReload) {
  41804. newData.browserHash = metadata.browserHash;
  41805. for (const dep in newData.chunks) {
  41806. newData.chunks[dep].browserHash = metadata.browserHash;
  41807. }
  41808. for (const dep in newData.optimized) {
  41809. newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
  41810. }
  41811. }
  41812. // Commit hash and needsInterop changes to the discovered deps info
  41813. // object. Allow for code to await for the discovered processing promise
  41814. // and use the information in the same object
  41815. for (const o in newData.optimized) {
  41816. const discovered = metadata.discovered[o];
  41817. if (discovered) {
  41818. const optimized = newData.optimized[o];
  41819. discovered.browserHash = optimized.browserHash;
  41820. discovered.fileHash = optimized.fileHash;
  41821. discovered.needsInterop = optimized.needsInterop;
  41822. discovered.processing = undefined;
  41823. }
  41824. }
  41825. if (isRerun) {
  41826. newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
  41827. }
  41828. metadata = depsOptimizer.metadata = newData;
  41829. resolveEnqueuedProcessingPromises();
  41830. };
  41831. if (!needsReload) {
  41832. await commitProcessing();
  41833. if (!debug$8) {
  41834. if (newDepsToLogHandle)
  41835. clearTimeout(newDepsToLogHandle);
  41836. newDepsToLogHandle = setTimeout(() => {
  41837. newDepsToLogHandle = undefined;
  41838. logNewlyDiscoveredDeps();
  41839. }, 2 * debounceMs);
  41840. }
  41841. else {
  41842. debug$8(colors$1.green(`✨ ${!isRerun
  41843. ? `dependencies optimized`
  41844. : `optimized dependencies unchanged`}`));
  41845. }
  41846. }
  41847. else {
  41848. if (newDepsDiscovered) {
  41849. // There are newly discovered deps, and another rerun is about to be
  41850. // executed. Avoid the current full reload discarding this rerun result
  41851. // We don't resolve the processing promise, as they will be resolved
  41852. // once a rerun is committed
  41853. processingResult.cancel();
  41854. debug$8?.(colors$1.green(`✨ delaying reload as new dependencies have been found...`));
  41855. }
  41856. else {
  41857. await commitProcessing();
  41858. if (!debug$8) {
  41859. if (newDepsToLogHandle)
  41860. clearTimeout(newDepsToLogHandle);
  41861. newDepsToLogHandle = undefined;
  41862. logNewlyDiscoveredDeps();
  41863. }
  41864. logger.info(colors$1.green(`✨ optimized dependencies changed. reloading`), {
  41865. timestamp: true,
  41866. });
  41867. if (needsInteropMismatch.length > 0) {
  41868. config.logger.warn(`Mixed ESM and CJS detected in ${colors$1.yellow(needsInteropMismatch.join(', '))}, add ${needsInteropMismatch.length === 1 ? 'it' : 'them'} to optimizeDeps.needsInterop to speed up cold start`, {
  41869. timestamp: true,
  41870. });
  41871. }
  41872. fullReload();
  41873. }
  41874. }
  41875. }
  41876. catch (e) {
  41877. logger.error(colors$1.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e });
  41878. resolveEnqueuedProcessingPromises();
  41879. // Reset missing deps, let the server rediscover the dependencies
  41880. metadata.discovered = {};
  41881. }
  41882. currentlyProcessing = false;
  41883. // @ts-expect-error `enqueuedRerun` could exist because `debouncedProcessing` may run while awaited
  41884. enqueuedRerun?.();
  41885. }
  41886. function fullReload() {
  41887. if (server) {
  41888. // Cached transform results have stale imports (resolved to
  41889. // old locations) so they need to be invalidated before the page is
  41890. // reloaded.
  41891. server.moduleGraph.invalidateAll();
  41892. server.ws.send({
  41893. type: 'full-reload',
  41894. path: '*',
  41895. });
  41896. }
  41897. }
  41898. async function rerun() {
  41899. // debounce time to wait for new missing deps finished, issue a new
  41900. // optimization of deps (both old and newly found) once the previous
  41901. // optimizeDeps processing is finished
  41902. const deps = Object.keys(metadata.discovered);
  41903. const depsString = depsLogString(deps);
  41904. debug$8?.(colors$1.green(`new dependencies found: ${depsString}`));
  41905. runOptimizer();
  41906. }
  41907. function getDiscoveredBrowserHash(hash, deps, missing) {
  41908. return getHash(hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
  41909. }
  41910. function registerMissingImport(id, resolved) {
  41911. const optimized = metadata.optimized[id];
  41912. if (optimized) {
  41913. return optimized;
  41914. }
  41915. const chunk = metadata.chunks[id];
  41916. if (chunk) {
  41917. return chunk;
  41918. }
  41919. let missing = metadata.discovered[id];
  41920. if (missing) {
  41921. // We are already discover this dependency
  41922. // It will be processed in the next rerun call
  41923. return missing;
  41924. }
  41925. missing = addMissingDep(id, resolved);
  41926. // Until the first optimize run is called, avoid triggering processing
  41927. // We'll wait until the user codebase is eagerly processed by Vite so
  41928. // we can get a list of every missing dependency before giving to the
  41929. // browser a dependency that may be outdated, thus avoiding full page reloads
  41930. if (!crawlEndFinder) {
  41931. if (isBuild) {
  41932. logger.error('Vite Internal Error: Missing dependency found after crawling ended');
  41933. }
  41934. // Debounced rerun, let other missing dependencies be discovered before
  41935. // the running next optimizeDeps
  41936. debouncedProcessing();
  41937. }
  41938. // Return the path for the optimized bundle, this path is known before
  41939. // esbuild is run to generate the pre-bundle
  41940. return missing;
  41941. }
  41942. function addMissingDep(id, resolved) {
  41943. newDepsDiscovered = true;
  41944. return addOptimizedDepInfo(metadata, 'discovered', {
  41945. id,
  41946. file: getOptimizedDepPath(id, config, ssr),
  41947. src: resolved,
  41948. // Adding a browserHash to this missing dependency that is unique to
  41949. // the current state of known + missing deps. If its optimizeDeps run
  41950. // doesn't alter the bundled files of previous known dependencies,
  41951. // we don't need a full reload and this browserHash will be kept
  41952. browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
  41953. // loading of this pre-bundled dep needs to await for its processing
  41954. // promise to be resolved
  41955. processing: depOptimizationProcessing.promise,
  41956. exportsData: extractExportsData(resolved, config, ssr),
  41957. });
  41958. }
  41959. function debouncedProcessing(timeout = debounceMs) {
  41960. if (!newDepsDiscovered) {
  41961. return;
  41962. }
  41963. // Debounced rerun, let other missing dependencies be discovered before
  41964. // the running next optimizeDeps
  41965. enqueuedRerun = undefined;
  41966. if (debounceProcessingHandle)
  41967. clearTimeout(debounceProcessingHandle);
  41968. if (newDepsToLogHandle)
  41969. clearTimeout(newDepsToLogHandle);
  41970. newDepsToLogHandle = undefined;
  41971. debounceProcessingHandle = setTimeout(() => {
  41972. debounceProcessingHandle = undefined;
  41973. enqueuedRerun = rerun;
  41974. if (!currentlyProcessing) {
  41975. enqueuedRerun();
  41976. }
  41977. }, timeout);
  41978. }
  41979. // During dev, onCrawlEnd is called once when the server starts and all static
  41980. // imports after the first request have been crawled (dynamic imports may also
  41981. // be crawled if the browser requests them right away).
  41982. // During build, onCrawlEnd will be called once after each buildStart (so in
  41983. // watch mode it will be called after each rebuild has processed every module).
  41984. // All modules are transformed first in this case (both static and dynamic).
  41985. async function onCrawlEnd() {
  41986. // On build time, a missing dep appearing after onCrawlEnd is an internal error
  41987. // On dev, switch after this point to a simple debounce strategy
  41988. crawlEndFinder = undefined;
  41989. debug$8?.(colors$1.green(`✨ static imports crawl ended`));
  41990. if (closed) {
  41991. return;
  41992. }
  41993. // Await for the scan+optimize step running in the background
  41994. // It normally should be over by the time crawling of user code ended
  41995. await depsOptimizer.scanProcessing;
  41996. if (!isBuild && optimizationResult && !config.optimizeDeps.noDiscovery) {
  41997. const result = await optimizationResult.result;
  41998. optimizationResult = undefined;
  41999. currentlyProcessing = false;
  42000. const crawlDeps = Object.keys(metadata.discovered);
  42001. const scanDeps = Object.keys(result.metadata.optimized);
  42002. if (scanDeps.length === 0 && crawlDeps.length === 0) {
  42003. debug$8?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
  42004. result.cancel();
  42005. firstRunCalled = true;
  42006. return;
  42007. }
  42008. const needsInteropMismatch = findInteropMismatches(metadata.discovered, result.metadata.optimized);
  42009. const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
  42010. const outdatedResult = needsInteropMismatch.length > 0 || scannerMissedDeps;
  42011. if (outdatedResult) {
  42012. // Drop this scan result, and perform a new optimization to avoid a full reload
  42013. result.cancel();
  42014. // Add deps found by the scanner to the discovered deps while crawling
  42015. for (const dep of scanDeps) {
  42016. if (!crawlDeps.includes(dep)) {
  42017. addMissingDep(dep, result.metadata.optimized[dep].src);
  42018. }
  42019. }
  42020. if (scannerMissedDeps) {
  42021. debug$8?.(colors$1.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
  42022. }
  42023. debug$8?.(colors$1.green(`✨ re-running optimizer`));
  42024. debouncedProcessing(0);
  42025. }
  42026. else {
  42027. debug$8?.(colors$1.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
  42028. startNextDiscoveredBatch();
  42029. runOptimizer(result);
  42030. }
  42031. }
  42032. else {
  42033. const crawlDeps = Object.keys(metadata.discovered);
  42034. currentlyProcessing = false;
  42035. if (crawlDeps.length === 0) {
  42036. debug$8?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
  42037. firstRunCalled = true;
  42038. }
  42039. else {
  42040. // queue the first optimizer run
  42041. debouncedProcessing(0);
  42042. }
  42043. }
  42044. }
  42045. // Called during buildStart at build time, when build --watch is used.
  42046. function resetRegisteredIds() {
  42047. crawlEndFinder?.cancel();
  42048. crawlEndFinder = setupOnCrawlEnd(onCrawlEnd);
  42049. }
  42050. function registerWorkersSource(id) {
  42051. crawlEndFinder?.registerWorkersSource(id);
  42052. }
  42053. function delayDepsOptimizerUntil(id, done) {
  42054. if (crawlEndFinder && !depsOptimizer.isOptimizedDepFile(id)) {
  42055. crawlEndFinder.delayDepsOptimizerUntil(id, done);
  42056. }
  42057. }
  42058. function ensureFirstRun() {
  42059. crawlEndFinder?.ensureFirstRun();
  42060. }
  42061. }
  42062. const callCrawlEndIfIdleAfterMs = 50;
  42063. function setupOnCrawlEnd(onCrawlEnd) {
  42064. const registeredIds = new Set();
  42065. const seenIds = new Set();
  42066. const workersSources = new Set();
  42067. let timeoutHandle;
  42068. let cancelled = false;
  42069. function cancel() {
  42070. cancelled = true;
  42071. }
  42072. let crawlEndCalled = false;
  42073. function callOnCrawlEnd() {
  42074. if (!cancelled && !crawlEndCalled) {
  42075. crawlEndCalled = true;
  42076. onCrawlEnd();
  42077. }
  42078. }
  42079. // If all the inputs are dependencies, we aren't going to get any
  42080. // delayDepsOptimizerUntil(id) calls. We need to guard against this
  42081. // by forcing a rerun if no deps have been registered
  42082. let firstRunEnsured = false;
  42083. function ensureFirstRun() {
  42084. if (!firstRunEnsured && seenIds.size === 0) {
  42085. setTimeout(() => {
  42086. if (seenIds.size === 0) {
  42087. callOnCrawlEnd();
  42088. }
  42089. }, 200);
  42090. }
  42091. firstRunEnsured = true;
  42092. }
  42093. function registerWorkersSource(id) {
  42094. workersSources.add(id);
  42095. // Avoid waiting for this id, as it may be blocked by the rollup
  42096. // bundling process of the worker that also depends on the optimizer
  42097. registeredIds.delete(id);
  42098. checkIfCrawlEndAfterTimeout();
  42099. }
  42100. function delayDepsOptimizerUntil(id, done) {
  42101. if (!seenIds.has(id)) {
  42102. seenIds.add(id);
  42103. if (!workersSources.has(id)) {
  42104. registeredIds.add(id);
  42105. done()
  42106. .catch(() => { })
  42107. .finally(() => markIdAsDone(id));
  42108. }
  42109. }
  42110. }
  42111. function markIdAsDone(id) {
  42112. registeredIds.delete(id);
  42113. checkIfCrawlEndAfterTimeout();
  42114. }
  42115. function checkIfCrawlEndAfterTimeout() {
  42116. if (cancelled || registeredIds.size > 0)
  42117. return;
  42118. if (timeoutHandle)
  42119. clearTimeout(timeoutHandle);
  42120. timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
  42121. }
  42122. async function callOnCrawlEndWhenIdle() {
  42123. if (cancelled || registeredIds.size > 0)
  42124. return;
  42125. callOnCrawlEnd();
  42126. }
  42127. return {
  42128. ensureFirstRun,
  42129. registerWorkersSource,
  42130. delayDepsOptimizerUntil,
  42131. cancel,
  42132. };
  42133. }
  42134. async function createDevSsrDepsOptimizer(config) {
  42135. const metadata = await optimizeServerSsrDeps(config);
  42136. const depsOptimizer = {
  42137. metadata,
  42138. isOptimizedDepFile: createIsOptimizedDepFile(config),
  42139. isOptimizedDepUrl: createIsOptimizedDepUrl(config),
  42140. getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
  42141. registerMissingImport: () => {
  42142. throw new Error('Vite Internal Error: registerMissingImport is not supported in dev SSR');
  42143. },
  42144. // noop, there is no scanning during dev SSR
  42145. // the optimizer blocks the server start
  42146. run: () => { },
  42147. registerWorkersSource: (id) => { },
  42148. delayDepsOptimizerUntil: (id, done) => { },
  42149. resetRegisteredIds: () => { },
  42150. ensureFirstRun: () => { },
  42151. close: async () => { },
  42152. options: config.ssr.optimizeDeps,
  42153. };
  42154. devSsrDepsOptimizerMap.set(config, depsOptimizer);
  42155. }
  42156. function findInteropMismatches(discovered, optimized) {
  42157. const needsInteropMismatch = [];
  42158. for (const dep in discovered) {
  42159. const discoveredDepInfo = discovered[dep];
  42160. const depInfo = optimized[dep];
  42161. if (depInfo) {
  42162. if (discoveredDepInfo.needsInterop !== undefined &&
  42163. depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
  42164. // This only happens when a discovered dependency has mixed ESM and CJS syntax
  42165. // and it hasn't been manually added to optimizeDeps.needsInterop
  42166. needsInteropMismatch.push(dep);
  42167. debug$8?.(colors$1.cyan(`✨ needsInterop mismatch detected for ${dep}`));
  42168. }
  42169. }
  42170. }
  42171. return needsInteropMismatch;
  42172. }
  42173. const debug$7 = createDebugger('vite:deps');
  42174. const jsExtensionRE = /\.js$/i;
  42175. const jsMapExtensionRE = /\.js\.map$/i;
  42176. /**
  42177. * Scan and optimize dependencies within a project.
  42178. * Used by Vite CLI when running `vite optimize`.
  42179. */
  42180. async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
  42181. const log = asCommand ? config.logger.info : debug$7;
  42182. const ssr = config.command === 'build' && !!config.build.ssr;
  42183. const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
  42184. if (cachedMetadata) {
  42185. return cachedMetadata;
  42186. }
  42187. const deps = await discoverProjectDependencies(config).result;
  42188. const depsString = depsLogString(Object.keys(deps));
  42189. log?.(colors$1.green(`Optimizing dependencies:\n ${depsString}`));
  42190. await addManuallyIncludedOptimizeDeps(deps, config, ssr);
  42191. const depsInfo = toDiscoveredDependencies(config, deps, ssr);
  42192. const result = await runOptimizeDeps(config, depsInfo).result;
  42193. await result.commit();
  42194. return result.metadata;
  42195. }
  42196. async function optimizeServerSsrDeps(config) {
  42197. const ssr = true;
  42198. const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, config.optimizeDeps.force, false);
  42199. if (cachedMetadata) {
  42200. return cachedMetadata;
  42201. }
  42202. let alsoInclude;
  42203. let noExternalFilter;
  42204. const { exclude } = getDepOptimizationConfig(config, ssr);
  42205. const noExternal = config.ssr?.noExternal;
  42206. if (noExternal) {
  42207. alsoInclude = arraify(noExternal).filter((ne) => typeof ne === 'string');
  42208. noExternalFilter =
  42209. noExternal === true
  42210. ? (dep) => true
  42211. : createFilter$1(undefined, exclude, {
  42212. resolve: false,
  42213. });
  42214. }
  42215. const deps = {};
  42216. await addManuallyIncludedOptimizeDeps(deps, config, ssr, alsoInclude, noExternalFilter);
  42217. const depsInfo = toDiscoveredDependencies(config, deps, true);
  42218. const result = await runOptimizeDeps(config, depsInfo, true).result;
  42219. await result.commit();
  42220. return result.metadata;
  42221. }
  42222. function initDepsOptimizerMetadata(config, ssr, timestamp) {
  42223. const hash = getDepHash(config, ssr);
  42224. return {
  42225. hash,
  42226. browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
  42227. optimized: {},
  42228. chunks: {},
  42229. discovered: {},
  42230. depInfoList: [],
  42231. };
  42232. }
  42233. function addOptimizedDepInfo(metadata, type, depInfo) {
  42234. metadata[type][depInfo.id] = depInfo;
  42235. metadata.depInfoList.push(depInfo);
  42236. return depInfo;
  42237. }
  42238. let firstLoadCachedDepOptimizationMetadata = true;
  42239. /**
  42240. * Creates the initial dep optimization metadata, loading it from the deps cache
  42241. * if it exists and pre-bundling isn't forced
  42242. */
  42243. async function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
  42244. const log = asCommand ? config.logger.info : debug$7;
  42245. if (firstLoadCachedDepOptimizationMetadata) {
  42246. firstLoadCachedDepOptimizationMetadata = false;
  42247. // Fire up a clean up of stale processing deps dirs if older process exited early
  42248. setTimeout(() => cleanupDepsCacheStaleDirs(config), 0);
  42249. }
  42250. const depsCacheDir = getDepsCacheDir(config, ssr);
  42251. if (!force) {
  42252. let cachedMetadata;
  42253. try {
  42254. const cachedMetadataPath = path$o.join(depsCacheDir, '_metadata.json');
  42255. cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, 'utf-8'), depsCacheDir);
  42256. }
  42257. catch (e) { }
  42258. // hash is consistent, no need to re-bundle
  42259. if (cachedMetadata && cachedMetadata.hash === getDepHash(config, ssr)) {
  42260. log?.('Hash is consistent. Skipping. Use --force to override.');
  42261. // Nothing to commit or cancel as we are using the cache, we only
  42262. // need to resolve the processing promise so requests can move on
  42263. return cachedMetadata;
  42264. }
  42265. }
  42266. else {
  42267. config.logger.info('Forced re-optimization of dependencies');
  42268. }
  42269. // Start with a fresh cache
  42270. await fsp.rm(depsCacheDir, { recursive: true, force: true });
  42271. }
  42272. /**
  42273. * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
  42274. * find deps to pre-bundle and include user hard-coded dependencies
  42275. */
  42276. function discoverProjectDependencies(config) {
  42277. const { cancel, result } = scanImports(config);
  42278. return {
  42279. cancel,
  42280. result: result.then(({ deps, missing }) => {
  42281. const missingIds = Object.keys(missing);
  42282. if (missingIds.length) {
  42283. throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
  42284. .map((id) => `${colors$1.cyan(id)} ${colors$1.white(colors$1.dim(`(imported by ${missing[id]})`))}`)
  42285. .join(`\n `)}\n\nAre they installed?`);
  42286. }
  42287. return deps;
  42288. }),
  42289. };
  42290. }
  42291. function toDiscoveredDependencies(config, deps, ssr, timestamp) {
  42292. const browserHash = getOptimizedBrowserHash(getDepHash(config, ssr), deps, timestamp);
  42293. const discovered = {};
  42294. for (const id in deps) {
  42295. const src = deps[id];
  42296. discovered[id] = {
  42297. id,
  42298. file: getOptimizedDepPath(id, config, ssr),
  42299. src,
  42300. browserHash: browserHash,
  42301. exportsData: extractExportsData(src, config, ssr),
  42302. };
  42303. }
  42304. return discovered;
  42305. }
  42306. function depsLogString(qualifiedIds) {
  42307. return colors$1.yellow(qualifiedIds.join(`, `));
  42308. }
  42309. /**
  42310. * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
  42311. * the metadata and start the server without waiting for the optimizeDeps processing to be completed
  42312. */
  42313. function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command === 'build' &&
  42314. !!resolvedConfig.build.ssr) {
  42315. const optimizerContext = { cancelled: false };
  42316. const config = {
  42317. ...resolvedConfig,
  42318. command: 'build',
  42319. };
  42320. const depsCacheDir = getDepsCacheDir(resolvedConfig, ssr);
  42321. const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig, ssr);
  42322. // Create a temporal directory so we don't need to delete optimized deps
  42323. // until they have been processed. This also avoids leaving the deps cache
  42324. // directory in a corrupted state if there is an error
  42325. fs$l.mkdirSync(processingCacheDir, { recursive: true });
  42326. // a hint for Node.js
  42327. // all files in the cache directory should be recognized as ES modules
  42328. fs$l.writeFileSync(path$o.resolve(processingCacheDir, 'package.json'), `{\n "type": "module"\n}\n`);
  42329. const metadata = initDepsOptimizerMetadata(config, ssr);
  42330. metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
  42331. // We prebundle dependencies with esbuild and cache them, but there is no need
  42332. // to wait here. Code that needs to access the cached deps needs to await
  42333. // the optimizedDepInfo.processing promise for each dep
  42334. const qualifiedIds = Object.keys(depsInfo);
  42335. let cleaned = false;
  42336. let committed = false;
  42337. const cleanUp = () => {
  42338. // If commit was already called, ignore the clean up even if a cancel was requested
  42339. // This minimizes the chances of leaving the deps cache in a corrupted state
  42340. if (!cleaned && !committed) {
  42341. cleaned = true;
  42342. // No need to wait, we can clean up in the background because temp folders
  42343. // are unique per run
  42344. fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => {
  42345. // Ignore errors
  42346. });
  42347. }
  42348. };
  42349. const successfulResult = {
  42350. metadata,
  42351. cancel: cleanUp,
  42352. commit: async () => {
  42353. if (cleaned) {
  42354. throw new Error('Can not commit a Deps Optimization run as it was cancelled');
  42355. }
  42356. // Ignore clean up requests after this point so the temp folder isn't deleted before
  42357. // we finish commiting the new deps cache files to the deps folder
  42358. committed = true;
  42359. // Write metadata file, then commit the processing folder to the global deps cache
  42360. // Rewire the file paths from the temporal processing dir to the final deps cache dir
  42361. const dataPath = path$o.join(processingCacheDir, '_metadata.json');
  42362. fs$l.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
  42363. // In order to minimize the time where the deps folder isn't in a consistent state,
  42364. // we first rename the old depsCacheDir to a temporal path, then we rename the
  42365. // new processing cache dir to the depsCacheDir. In systems where doing so in sync
  42366. // is safe, we do an atomic operation (at least for this thread). For Windows, we
  42367. // found there are cases where the rename operation may finish before it's done
  42368. // so we do a graceful rename checking that the folder has been properly renamed.
  42369. // We found that the rename-rename (then delete the old folder in the background)
  42370. // is safer than a delete-rename operation.
  42371. const temporalPath = depsCacheDir + getTempSuffix();
  42372. const depsCacheDirPresent = fs$l.existsSync(depsCacheDir);
  42373. if (isWindows$4) {
  42374. if (depsCacheDirPresent)
  42375. await safeRename(depsCacheDir, temporalPath);
  42376. await safeRename(processingCacheDir, depsCacheDir);
  42377. }
  42378. else {
  42379. if (depsCacheDirPresent)
  42380. fs$l.renameSync(depsCacheDir, temporalPath);
  42381. fs$l.renameSync(processingCacheDir, depsCacheDir);
  42382. }
  42383. // Delete temporal path in the background
  42384. if (depsCacheDirPresent)
  42385. fsp.rm(temporalPath, { recursive: true, force: true });
  42386. },
  42387. };
  42388. if (!qualifiedIds.length) {
  42389. // No deps to optimize, we still commit the processing cache dir to remove
  42390. // the previous optimized deps if they exist, and let the next server start
  42391. // skip the scanner step if the lockfile hasn't changed
  42392. return {
  42393. cancel: async () => cleanUp(),
  42394. result: Promise.resolve(successfulResult),
  42395. };
  42396. }
  42397. const cancelledResult = {
  42398. metadata,
  42399. commit: async () => cleanUp(),
  42400. cancel: cleanUp,
  42401. };
  42402. const start = performance.now();
  42403. const preparedRun = prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext);
  42404. const runResult = preparedRun.then(({ context, idToExports }) => {
  42405. function disposeContext() {
  42406. return context?.dispose().catch((e) => {
  42407. config.logger.error('Failed to dispose esbuild context', { error: e });
  42408. });
  42409. }
  42410. if (!context || optimizerContext.cancelled) {
  42411. disposeContext();
  42412. return cancelledResult;
  42413. }
  42414. return context
  42415. .rebuild()
  42416. .then((result) => {
  42417. const meta = result.metafile;
  42418. // the paths in `meta.outputs` are relative to `process.cwd()`
  42419. const processingCacheDirOutputPath = path$o.relative(process.cwd(), processingCacheDir);
  42420. for (const id in depsInfo) {
  42421. const output = esbuildOutputFromId(meta.outputs, id, processingCacheDir);
  42422. const { exportsData, ...info } = depsInfo[id];
  42423. addOptimizedDepInfo(metadata, 'optimized', {
  42424. ...info,
  42425. // We only need to hash the output.imports in to check for stability, but adding the hash
  42426. // and file path gives us a unique hash that may be useful for other things in the future
  42427. fileHash: getHash(metadata.hash +
  42428. depsInfo[id].file +
  42429. JSON.stringify(output.imports)),
  42430. browserHash: metadata.browserHash,
  42431. // After bundling we have more information and can warn the user about legacy packages
  42432. // that require manual configuration
  42433. needsInterop: needsInterop(config, ssr, id, idToExports[id], output),
  42434. });
  42435. }
  42436. for (const o of Object.keys(meta.outputs)) {
  42437. if (!o.match(jsMapExtensionRE)) {
  42438. const id = path$o
  42439. .relative(processingCacheDirOutputPath, o)
  42440. .replace(jsExtensionRE, '');
  42441. const file = getOptimizedDepPath(id, resolvedConfig, ssr);
  42442. if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) {
  42443. addOptimizedDepInfo(metadata, 'chunks', {
  42444. id,
  42445. file,
  42446. needsInterop: false,
  42447. browserHash: metadata.browserHash,
  42448. });
  42449. }
  42450. }
  42451. }
  42452. debug$7?.(`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`);
  42453. return successfulResult;
  42454. })
  42455. .catch((e) => {
  42456. if (e.errors && e.message.includes('The build was canceled')) {
  42457. // esbuild logs an error when cancelling, but this is expected so
  42458. // return an empty result instead
  42459. return cancelledResult;
  42460. }
  42461. throw e;
  42462. })
  42463. .finally(() => {
  42464. return disposeContext();
  42465. });
  42466. });
  42467. runResult.catch(() => {
  42468. cleanUp();
  42469. });
  42470. return {
  42471. async cancel() {
  42472. optimizerContext.cancelled = true;
  42473. const { context } = await preparedRun;
  42474. await context?.cancel();
  42475. cleanUp();
  42476. },
  42477. result: runResult,
  42478. };
  42479. }
  42480. async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext) {
  42481. const isBuild = resolvedConfig.command === 'build';
  42482. const config = {
  42483. ...resolvedConfig,
  42484. command: 'build',
  42485. };
  42486. // esbuild generates nested directory output with lowest common ancestor base
  42487. // this is unpredictable and makes it difficult to analyze entry / output
  42488. // mapping. So what we do here is:
  42489. // 1. flatten all ids to eliminate slash
  42490. // 2. in the plugin, read the entry ourselves as virtual files to retain the
  42491. // path.
  42492. const flatIdDeps = {};
  42493. const idToExports = {};
  42494. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  42495. const { plugins: pluginsFromConfig = [], tsconfig, tsconfigRaw, ...esbuildOptions } = optimizeDeps?.esbuildOptions ?? {};
  42496. await Promise.all(Object.keys(depsInfo).map(async (id) => {
  42497. const src = depsInfo[id].src;
  42498. const exportsData = await (depsInfo[id].exportsData ??
  42499. extractExportsData(src, config, ssr));
  42500. if (exportsData.jsxLoader && !esbuildOptions.loader?.['.js']) {
  42501. // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
  42502. // This is useful for packages such as Gatsby.
  42503. esbuildOptions.loader = {
  42504. '.js': 'jsx',
  42505. ...esbuildOptions.loader,
  42506. };
  42507. }
  42508. const flatId = flattenId(id);
  42509. flatIdDeps[flatId] = src;
  42510. idToExports[id] = exportsData;
  42511. }));
  42512. if (optimizerContext.cancelled)
  42513. return { context: undefined, idToExports };
  42514. // esbuild automatically replaces process.env.NODE_ENV for platform 'browser'
  42515. // In lib mode, we need to keep process.env.NODE_ENV untouched, so to at build
  42516. // time we replace it by __vite_process_env_NODE_ENV. This placeholder will be
  42517. // later replaced by the define plugin
  42518. const define = {
  42519. 'process.env.NODE_ENV': isBuild
  42520. ? '__vite_process_env_NODE_ENV'
  42521. : JSON.stringify(process.env.NODE_ENV || config.mode),
  42522. };
  42523. const platform = ssr && config.ssr?.target !== 'webworker' ? 'node' : 'browser';
  42524. const external = [...(optimizeDeps?.exclude ?? [])];
  42525. if (isBuild) {
  42526. let rollupOptionsExternal = config?.build?.rollupOptions?.external;
  42527. if (rollupOptionsExternal) {
  42528. if (typeof rollupOptionsExternal === 'string') {
  42529. rollupOptionsExternal = [rollupOptionsExternal];
  42530. }
  42531. // TODO: decide whether to support RegExp and function options
  42532. // They're not supported yet because `optimizeDeps.exclude` currently only accepts strings
  42533. if (!Array.isArray(rollupOptionsExternal) ||
  42534. rollupOptionsExternal.some((ext) => typeof ext !== 'string')) {
  42535. throw new Error(`[vite] 'build.rollupOptions.external' can only be an array of strings or a string when using esbuild optimization at build time.`);
  42536. }
  42537. external.push(...rollupOptionsExternal);
  42538. }
  42539. }
  42540. const plugins = [...pluginsFromConfig];
  42541. if (external.length) {
  42542. plugins.push(esbuildCjsExternalPlugin(external, platform));
  42543. }
  42544. plugins.push(esbuildDepPlugin(flatIdDeps, external, config, ssr));
  42545. const context = await esbuild.context({
  42546. absWorkingDir: process.cwd(),
  42547. entryPoints: Object.keys(flatIdDeps),
  42548. bundle: true,
  42549. // We can't use platform 'neutral', as esbuild has custom handling
  42550. // when the platform is 'node' or 'browser' that can't be emulated
  42551. // by using mainFields and conditions
  42552. platform,
  42553. define,
  42554. format: 'esm',
  42555. // See https://github.com/evanw/esbuild/issues/1921#issuecomment-1152991694
  42556. banner: platform === 'node'
  42557. ? {
  42558. js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);`,
  42559. }
  42560. : undefined,
  42561. target: isBuild ? config.build.target || undefined : ESBUILD_MODULES_TARGET,
  42562. external,
  42563. logLevel: 'error',
  42564. splitting: true,
  42565. sourcemap: true,
  42566. outdir: processingCacheDir,
  42567. ignoreAnnotations: !isBuild,
  42568. metafile: true,
  42569. plugins,
  42570. charset: 'utf8',
  42571. tsconfig,
  42572. tsconfigRaw: resolveTsconfigRaw(tsconfig, tsconfigRaw),
  42573. ...esbuildOptions,
  42574. supported: {
  42575. 'dynamic-import': true,
  42576. 'import-meta': true,
  42577. ...esbuildOptions.supported,
  42578. },
  42579. });
  42580. return { context, idToExports };
  42581. }
  42582. async function findKnownImports(config, ssr) {
  42583. const { deps } = await scanImports(config).result;
  42584. await addManuallyIncludedOptimizeDeps(deps, config, ssr);
  42585. return Object.keys(deps);
  42586. }
  42587. async function addManuallyIncludedOptimizeDeps(deps, config, ssr, extra = [], filter) {
  42588. const { logger } = config;
  42589. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  42590. const optimizeDepsInclude = optimizeDeps?.include ?? [];
  42591. if (optimizeDepsInclude.length || extra.length) {
  42592. const unableToOptimize = (id, msg) => {
  42593. if (optimizeDepsInclude.includes(id)) {
  42594. logger.warn(`${msg}: ${colors$1.cyan(id)}, present in '${ssr ? 'ssr.' : ''}optimizeDeps.include'`);
  42595. }
  42596. };
  42597. const includes = [...optimizeDepsInclude, ...extra];
  42598. for (let i = 0; i < includes.length; i++) {
  42599. const id = includes[i];
  42600. if (glob.isDynamicPattern(id)) {
  42601. const globIds = expandGlobIds(id, config);
  42602. includes.splice(i, 1, ...globIds);
  42603. i += globIds.length - 1;
  42604. }
  42605. }
  42606. const resolve = createOptimizeDepsIncludeResolver(config, ssr);
  42607. for (const id of includes) {
  42608. // normalize 'foo >bar` as 'foo > bar' to prevent same id being added
  42609. // and for pretty printing
  42610. const normalizedId = normalizeId(id);
  42611. if (!deps[normalizedId] && filter?.(normalizedId) !== false) {
  42612. const entry = await resolve(id);
  42613. if (entry) {
  42614. if (isOptimizable(entry, optimizeDeps)) {
  42615. if (!entry.endsWith('?__vite_skip_optimization')) {
  42616. deps[normalizedId] = entry;
  42617. }
  42618. }
  42619. else {
  42620. unableToOptimize(id, 'Cannot optimize dependency');
  42621. }
  42622. }
  42623. else {
  42624. unableToOptimize(id, 'Failed to resolve dependency');
  42625. }
  42626. }
  42627. }
  42628. }
  42629. }
  42630. function newDepOptimizationProcessing() {
  42631. let resolve;
  42632. const promise = new Promise((_resolve) => {
  42633. resolve = _resolve;
  42634. });
  42635. return { promise, resolve: resolve };
  42636. }
  42637. // Convert to { id: src }
  42638. function depsFromOptimizedDepInfo(depsInfo) {
  42639. return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
  42640. }
  42641. function getOptimizedDepPath(id, config, ssr) {
  42642. return normalizePath$3(path$o.resolve(getDepsCacheDir(config, ssr), flattenId(id) + '.js'));
  42643. }
  42644. function getDepsCacheSuffix(config, ssr) {
  42645. let suffix = '';
  42646. if (config.command === 'build') {
  42647. // Differentiate build caches depending on outDir to allow parallel builds
  42648. const { outDir } = config.build;
  42649. const buildId = outDir.length > 8 || outDir.includes('/') ? getHash(outDir) : outDir;
  42650. suffix += `_build-${buildId}`;
  42651. }
  42652. if (ssr) {
  42653. suffix += '_ssr';
  42654. }
  42655. return suffix;
  42656. }
  42657. function getDepsCacheDir(config, ssr) {
  42658. return getDepsCacheDirPrefix(config) + getDepsCacheSuffix(config, ssr);
  42659. }
  42660. function getProcessingDepsCacheDir(config, ssr) {
  42661. return (getDepsCacheDirPrefix(config) +
  42662. getDepsCacheSuffix(config, ssr) +
  42663. getTempSuffix());
  42664. }
  42665. function getTempSuffix() {
  42666. return ('_temp_' +
  42667. getHash(`${process.pid}:${Date.now().toString()}:${Math.random()
  42668. .toString(16)
  42669. .slice(2)}`));
  42670. }
  42671. function getDepsCacheDirPrefix(config) {
  42672. return normalizePath$3(path$o.resolve(config.cacheDir, 'deps'));
  42673. }
  42674. function createIsOptimizedDepFile(config) {
  42675. const depsCacheDirPrefix = getDepsCacheDirPrefix(config);
  42676. return (id) => id.startsWith(depsCacheDirPrefix);
  42677. }
  42678. function createIsOptimizedDepUrl(config) {
  42679. const { root } = config;
  42680. const depsCacheDir = getDepsCacheDirPrefix(config);
  42681. // determine the url prefix of files inside cache directory
  42682. const depsCacheDirRelative = normalizePath$3(path$o.relative(root, depsCacheDir));
  42683. const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
  42684. ? // if the cache directory is outside root, the url prefix would be something
  42685. // like '/@fs/absolute/path/to/node_modules/.vite'
  42686. `/@fs/${removeLeadingSlash(normalizePath$3(depsCacheDir))}`
  42687. : // if the cache directory is inside root, the url prefix would be something
  42688. // like '/node_modules/.vite'
  42689. `/${depsCacheDirRelative}`;
  42690. return function isOptimizedDepUrl(url) {
  42691. return url.startsWith(depsCacheDirPrefix);
  42692. };
  42693. }
  42694. function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
  42695. const { hash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
  42696. // Paths can be absolute or relative to the deps cache dir where
  42697. // the _metadata.json is located
  42698. if (key === 'file' || key === 'src') {
  42699. return normalizePath$3(path$o.resolve(depsCacheDir, value));
  42700. }
  42701. return value;
  42702. });
  42703. if (!chunks ||
  42704. Object.values(optimized).some((depInfo) => !depInfo.fileHash)) {
  42705. // outdated _metadata.json version, ignore
  42706. return;
  42707. }
  42708. const metadata = {
  42709. hash,
  42710. browserHash,
  42711. optimized: {},
  42712. discovered: {},
  42713. chunks: {},
  42714. depInfoList: [],
  42715. };
  42716. for (const id of Object.keys(optimized)) {
  42717. addOptimizedDepInfo(metadata, 'optimized', {
  42718. ...optimized[id],
  42719. id,
  42720. browserHash,
  42721. });
  42722. }
  42723. for (const id of Object.keys(chunks)) {
  42724. addOptimizedDepInfo(metadata, 'chunks', {
  42725. ...chunks[id],
  42726. id,
  42727. browserHash,
  42728. needsInterop: false,
  42729. });
  42730. }
  42731. return metadata;
  42732. }
  42733. /**
  42734. * Stringify metadata for deps cache. Remove processing promises
  42735. * and individual dep info browserHash. Once the cache is reload
  42736. * the next time the server start we need to use the global
  42737. * browserHash to allow long term caching
  42738. */
  42739. function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
  42740. const { hash, browserHash, optimized, chunks } = metadata;
  42741. return JSON.stringify({
  42742. hash,
  42743. browserHash,
  42744. optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop }) => [
  42745. id,
  42746. {
  42747. src,
  42748. file,
  42749. fileHash,
  42750. needsInterop,
  42751. },
  42752. ])),
  42753. chunks: Object.fromEntries(Object.values(chunks).map(({ id, file }) => [id, { file }])),
  42754. }, (key, value) => {
  42755. // Paths can be absolute or relative to the deps cache dir where
  42756. // the _metadata.json is located
  42757. if (key === 'file' || key === 'src') {
  42758. return normalizePath$3(path$o.relative(depsCacheDir, value));
  42759. }
  42760. return value;
  42761. }, 2);
  42762. }
  42763. function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
  42764. const cwd = process.cwd();
  42765. const flatId = flattenId(id) + '.js';
  42766. const normalizedOutputPath = normalizePath$3(path$o.relative(cwd, path$o.join(cacheDirOutputPath, flatId)));
  42767. const output = outputs[normalizedOutputPath];
  42768. if (output) {
  42769. return output;
  42770. }
  42771. // If the root dir was symlinked, esbuild could return output keys as `../cwd/`
  42772. // Normalize keys to support this case too
  42773. for (const [key, value] of Object.entries(outputs)) {
  42774. if (normalizePath$3(path$o.relative(cwd, key)) === normalizedOutputPath) {
  42775. return value;
  42776. }
  42777. }
  42778. }
  42779. async function extractExportsData(filePath, config, ssr) {
  42780. await init;
  42781. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  42782. const esbuildOptions = optimizeDeps?.esbuildOptions ?? {};
  42783. if (optimizeDeps.extensions?.some((ext) => filePath.endsWith(ext))) {
  42784. // For custom supported extensions, build the entry file to transform it into JS,
  42785. // and then parse with es-module-lexer. Note that the `bundle` option is not `true`,
  42786. // so only the entry file is being transformed.
  42787. const result = await build$3({
  42788. ...esbuildOptions,
  42789. entryPoints: [filePath],
  42790. write: false,
  42791. format: 'esm',
  42792. });
  42793. const [imports, exports] = parse$e(result.outputFiles[0].text);
  42794. return {
  42795. hasImports: imports.length > 0,
  42796. exports: exports.map((e) => e.n),
  42797. };
  42798. }
  42799. let parseResult;
  42800. let usedJsxLoader = false;
  42801. const entryContent = await fsp.readFile(filePath, 'utf-8');
  42802. try {
  42803. parseResult = parse$e(entryContent);
  42804. }
  42805. catch {
  42806. const loader = esbuildOptions.loader?.[path$o.extname(filePath)] || 'jsx';
  42807. debug$7?.(`Unable to parse: ${filePath}.\n Trying again with a ${loader} transform.`);
  42808. const transformed = await transformWithEsbuild(entryContent, filePath, {
  42809. loader,
  42810. });
  42811. parseResult = parse$e(transformed.code);
  42812. usedJsxLoader = true;
  42813. }
  42814. const [imports, exports] = parseResult;
  42815. const exportsData = {
  42816. hasImports: imports.length > 0,
  42817. exports: exports.map((e) => e.n),
  42818. jsxLoader: usedJsxLoader,
  42819. };
  42820. return exportsData;
  42821. }
  42822. function needsInterop(config, ssr, id, exportsData, output) {
  42823. if (getDepOptimizationConfig(config, ssr)?.needsInterop?.includes(id)) {
  42824. return true;
  42825. }
  42826. const { hasImports, exports } = exportsData;
  42827. // entry has no ESM syntax - likely CJS or UMD
  42828. if (!exports.length && !hasImports) {
  42829. return true;
  42830. }
  42831. if (output) {
  42832. // if a peer dependency used require() on an ESM dependency, esbuild turns the
  42833. // ESM dependency's entry chunk into a single default export... detect
  42834. // such cases by checking exports mismatch, and force interop.
  42835. const generatedExports = output.exports;
  42836. if (!generatedExports ||
  42837. (isSingleDefaultExport(generatedExports) &&
  42838. !isSingleDefaultExport(exports))) {
  42839. return true;
  42840. }
  42841. }
  42842. return false;
  42843. }
  42844. function isSingleDefaultExport(exports) {
  42845. return exports.length === 1 && exports[0] === 'default';
  42846. }
  42847. const lockfileFormats = [
  42848. { name: 'package-lock.json', checkPatches: true, manager: 'npm' },
  42849. { name: 'yarn.lock', checkPatches: true, manager: 'yarn' },
  42850. { name: 'pnpm-lock.yaml', checkPatches: false, manager: 'pnpm' },
  42851. { name: 'bun.lockb', checkPatches: true, manager: 'bun' },
  42852. ].sort((_, { manager }) => {
  42853. return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
  42854. });
  42855. const lockfileNames = lockfileFormats.map((l) => l.name);
  42856. function getDepHash(config, ssr) {
  42857. const lockfilePath = lookupFile(config.root, lockfileNames);
  42858. let content = lockfilePath ? fs$l.readFileSync(lockfilePath, 'utf-8') : '';
  42859. if (lockfilePath) {
  42860. const lockfileName = path$o.basename(lockfilePath);
  42861. const { checkPatches } = lockfileFormats.find((f) => f.name === lockfileName);
  42862. if (checkPatches) {
  42863. // Default of https://github.com/ds300/patch-package
  42864. const fullPath = path$o.join(path$o.dirname(lockfilePath), 'patches');
  42865. const stat = tryStatSync(fullPath);
  42866. if (stat?.isDirectory()) {
  42867. content += stat.mtimeMs.toString();
  42868. }
  42869. }
  42870. }
  42871. // also take config into account
  42872. // only a subset of config options that can affect dep optimization
  42873. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  42874. content += JSON.stringify({
  42875. mode: process.env.NODE_ENV || config.mode,
  42876. root: config.root,
  42877. resolve: config.resolve,
  42878. buildTarget: config.build.target,
  42879. assetsInclude: config.assetsInclude,
  42880. plugins: config.plugins.map((p) => p.name),
  42881. optimizeDeps: {
  42882. include: optimizeDeps?.include,
  42883. exclude: optimizeDeps?.exclude,
  42884. esbuildOptions: {
  42885. ...optimizeDeps?.esbuildOptions,
  42886. plugins: optimizeDeps?.esbuildOptions?.plugins?.map((p) => p.name),
  42887. },
  42888. },
  42889. }, (_, value) => {
  42890. if (typeof value === 'function' || value instanceof RegExp) {
  42891. return value.toString();
  42892. }
  42893. return value;
  42894. });
  42895. return getHash(content);
  42896. }
  42897. function getOptimizedBrowserHash(hash, deps, timestamp = '') {
  42898. return getHash(hash + JSON.stringify(deps) + timestamp);
  42899. }
  42900. function optimizedDepInfoFromId(metadata, id) {
  42901. return (metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id]);
  42902. }
  42903. function optimizedDepInfoFromFile(metadata, file) {
  42904. return metadata.depInfoList.find((depInfo) => depInfo.file === file);
  42905. }
  42906. function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
  42907. for (const o of Object.keys(dependenciesInfo)) {
  42908. const info = dependenciesInfo[o];
  42909. if (callbackFn(info, o)) {
  42910. return info;
  42911. }
  42912. }
  42913. }
  42914. async function optimizedDepNeedsInterop(metadata, file, config, ssr) {
  42915. const depInfo = optimizedDepInfoFromFile(metadata, file);
  42916. if (depInfo?.src && depInfo.needsInterop === undefined) {
  42917. depInfo.exportsData ?? (depInfo.exportsData = extractExportsData(depInfo.src, config, ssr));
  42918. depInfo.needsInterop = needsInterop(config, ssr, depInfo.id, await depInfo.exportsData);
  42919. }
  42920. return depInfo?.needsInterop;
  42921. }
  42922. const MAX_TEMP_DIR_AGE_MS = 24 * 60 * 60 * 1000;
  42923. async function cleanupDepsCacheStaleDirs(config) {
  42924. try {
  42925. const cacheDir = path$o.resolve(config.cacheDir);
  42926. if (fs$l.existsSync(cacheDir)) {
  42927. const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
  42928. for (const dirent of dirents) {
  42929. if (dirent.isDirectory() && dirent.name.includes('_temp_')) {
  42930. const tempDirPath = path$o.resolve(config.cacheDir, dirent.name);
  42931. const stats = await fsp.stat(tempDirPath).catch((_) => null);
  42932. if (stats?.mtime &&
  42933. Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
  42934. await fsp.rm(tempDirPath, { recursive: true, force: true });
  42935. }
  42936. }
  42937. }
  42938. }
  42939. }
  42940. catch (err) {
  42941. config.logger.error(err);
  42942. }
  42943. }
  42944. // We found issues with renaming folders in some systems. This is a custom
  42945. // implementation for the optimizer. It isn't intended to be a general utility
  42946. // Based on node-graceful-fs
  42947. // The ISC License
  42948. // Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
  42949. // https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE
  42950. // On Windows, A/V software can lock the directory, causing this
  42951. // to fail with an EACCES or EPERM if the directory contains newly
  42952. // created files. The original tried for up to 60 seconds, we only
  42953. // wait for 5 seconds, as a longer time would be seen as an error
  42954. const GRACEFUL_RENAME_TIMEOUT = 5000;
  42955. const safeRename = promisify$4(function gracefulRename(from, to, cb) {
  42956. const start = Date.now();
  42957. let backoff = 0;
  42958. fs$l.rename(from, to, function CB(er) {
  42959. if (er &&
  42960. (er.code === 'EACCES' || er.code === 'EPERM') &&
  42961. Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
  42962. setTimeout(function () {
  42963. fs$l.stat(to, function (stater, st) {
  42964. if (stater && stater.code === 'ENOENT')
  42965. fs$l.rename(from, to, CB);
  42966. else
  42967. CB(er);
  42968. });
  42969. }, backoff);
  42970. if (backoff < 100)
  42971. backoff += 10;
  42972. return;
  42973. }
  42974. if (cb)
  42975. cb(er);
  42976. });
  42977. });
  42978. var index$1 = {
  42979. __proto__: null,
  42980. addManuallyIncludedOptimizeDeps: addManuallyIncludedOptimizeDeps,
  42981. addOptimizedDepInfo: addOptimizedDepInfo,
  42982. cleanupDepsCacheStaleDirs: cleanupDepsCacheStaleDirs,
  42983. createIsOptimizedDepFile: createIsOptimizedDepFile,
  42984. createIsOptimizedDepUrl: createIsOptimizedDepUrl,
  42985. depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
  42986. depsLogString: depsLogString,
  42987. discoverProjectDependencies: discoverProjectDependencies,
  42988. extractExportsData: extractExportsData,
  42989. findKnownImports: findKnownImports,
  42990. getDepHash: getDepHash,
  42991. getDepsCacheDir: getDepsCacheDir,
  42992. getDepsOptimizer: getDepsOptimizer,
  42993. getOptimizedDepPath: getOptimizedDepPath,
  42994. initDepsOptimizer: initDepsOptimizer,
  42995. initDepsOptimizerMetadata: initDepsOptimizerMetadata,
  42996. initDevSsrDepsOptimizer: initDevSsrDepsOptimizer,
  42997. loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
  42998. newDepOptimizationProcessing: newDepOptimizationProcessing,
  42999. optimizeDeps: optimizeDeps,
  43000. optimizeServerSsrDeps: optimizeServerSsrDeps,
  43001. optimizedDepInfoFromFile: optimizedDepInfoFromFile,
  43002. optimizedDepInfoFromId: optimizedDepInfoFromId,
  43003. optimizedDepNeedsInterop: optimizedDepNeedsInterop,
  43004. runOptimizeDeps: runOptimizeDeps,
  43005. toDiscoveredDependencies: toDiscoveredDependencies
  43006. };
  43007. /**
  43008. * A flag for injected helpers. This flag will be set to `false` if the output
  43009. * target is not native es - so that injected helper logic can be conditionally
  43010. * dropped.
  43011. */
  43012. const isModernFlag = `__VITE_IS_MODERN__`;
  43013. const preloadMethod = `__vitePreload`;
  43014. const preloadMarker = `__VITE_PRELOAD__`;
  43015. const preloadHelperId = '\0vite/preload-helper';
  43016. const preloadMarkerWithQuote = new RegExp(`['"]${preloadMarker}['"]`);
  43017. const dynamicImportPrefixRE = /import\s*\(/;
  43018. // TODO: abstract
  43019. const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
  43020. const optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/;
  43021. function toRelativePath(filename, importer) {
  43022. const relPath = path$o.relative(path$o.dirname(importer), filename);
  43023. return relPath[0] === '.' ? relPath : `./${relPath}`;
  43024. }
  43025. function indexOfMatchInSlice(str, reg, pos = 0) {
  43026. if (pos !== 0) {
  43027. str = str.slice(pos);
  43028. }
  43029. const matcher = str.match(reg);
  43030. return matcher?.index !== undefined ? matcher.index + pos : -1;
  43031. }
  43032. /**
  43033. * Helper for preloading CSS and direct imports of async chunks in parallel to
  43034. * the async chunk itself.
  43035. */
  43036. function detectScriptRel() {
  43037. const relList = typeof document !== 'undefined' && document.createElement('link').relList;
  43038. return relList && relList.supports && relList.supports('modulepreload')
  43039. ? 'modulepreload'
  43040. : 'preload';
  43041. }
  43042. function preload(baseModule, deps, importerUrl) {
  43043. // @ts-expect-error __VITE_IS_MODERN__ will be replaced with boolean later
  43044. if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
  43045. return baseModule();
  43046. }
  43047. const links = document.getElementsByTagName('link');
  43048. return Promise.all(deps.map((dep) => {
  43049. // @ts-expect-error assetsURL is declared before preload.toString()
  43050. dep = assetsURL(dep, importerUrl);
  43051. if (dep in seen)
  43052. return;
  43053. seen[dep] = true;
  43054. const isCss = dep.endsWith('.css');
  43055. const cssSelector = isCss ? '[rel="stylesheet"]' : '';
  43056. const isBaseRelative = !!importerUrl;
  43057. // check if the file is already preloaded by SSR markup
  43058. if (isBaseRelative) {
  43059. // When isBaseRelative is true then we have `importerUrl` and `dep` is
  43060. // already converted to an absolute URL by the `assetsURL` function
  43061. for (let i = links.length - 1; i >= 0; i--) {
  43062. const link = links[i];
  43063. // The `links[i].href` is an absolute URL thanks to browser doing the work
  43064. // for us. See https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:idl-domstring-5
  43065. if (link.href === dep && (!isCss || link.rel === 'stylesheet')) {
  43066. return;
  43067. }
  43068. }
  43069. }
  43070. else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
  43071. return;
  43072. }
  43073. const link = document.createElement('link');
  43074. link.rel = isCss ? 'stylesheet' : scriptRel;
  43075. if (!isCss) {
  43076. link.as = 'script';
  43077. link.crossOrigin = '';
  43078. }
  43079. link.href = dep;
  43080. document.head.appendChild(link);
  43081. if (isCss) {
  43082. return new Promise((res, rej) => {
  43083. link.addEventListener('load', res);
  43084. link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)));
  43085. });
  43086. }
  43087. }))
  43088. .then(() => baseModule())
  43089. .catch((err) => {
  43090. const e = new Event('vite:preloadError', { cancelable: true });
  43091. // @ts-expect-error custom payload
  43092. e.payload = err;
  43093. window.dispatchEvent(e);
  43094. if (!e.defaultPrevented) {
  43095. throw err;
  43096. }
  43097. });
  43098. }
  43099. /**
  43100. * Build only. During serve this is performed as part of ./importAnalysis.
  43101. */
  43102. function buildImportAnalysisPlugin(config) {
  43103. const ssr = !!config.build.ssr;
  43104. const isWorker = config.isWorker;
  43105. const insertPreload = !(ssr || !!config.build.lib || isWorker);
  43106. const resolveModulePreloadDependencies = config.build.modulePreload && config.build.modulePreload.resolveDependencies;
  43107. const renderBuiltUrl = config.experimental.renderBuiltUrl;
  43108. const customModulePreloadPaths = !!(resolveModulePreloadDependencies || renderBuiltUrl);
  43109. const isRelativeBase = config.base === './' || config.base === '';
  43110. const optimizeModulePreloadRelativePaths = isRelativeBase && !customModulePreloadPaths;
  43111. const { modulePreload } = config.build;
  43112. const scriptRel = modulePreload && modulePreload.polyfill
  43113. ? `'modulepreload'`
  43114. : `(${detectScriptRel.toString()})()`;
  43115. // There are three different cases for the preload list format in __vitePreload
  43116. //
  43117. // __vitePreload(() => import(asyncChunk), [ ...deps... ])
  43118. //
  43119. // This is maintained to keep backwards compatibility as some users developed plugins
  43120. // using regex over this list to workaround the fact that module preload wasn't
  43121. // configurable.
  43122. const assetsURL = customModulePreloadPaths
  43123. ? // If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used
  43124. // the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)`
  43125. // a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized.
  43126. `function(dep, importerUrl) { return dep[0] === '.' ? new URL(dep, importerUrl).href : dep }`
  43127. : optimizeModulePreloadRelativePaths
  43128. ? // If there isn't custom resolvers affecting the deps list, deps in the list are relative
  43129. // to the current chunk and are resolved to absolute URL by the __vitePreload helper itself.
  43130. // The importerUrl is passed as third parameter to __vitePreload in this case
  43131. `function(dep, importerUrl) { return new URL(dep, importerUrl).href }`
  43132. : // If the base isn't relative, then the deps are relative to the projects `outDir` and the base
  43133. // is appended inside __vitePreload too.
  43134. `function(dep) { return ${JSON.stringify(config.base)}+dep }`;
  43135. const preloadCode = `const scriptRel = ${scriptRel};const assetsURL = ${assetsURL};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
  43136. return {
  43137. name: 'vite:build-import-analysis',
  43138. resolveId(id) {
  43139. if (id === preloadHelperId) {
  43140. return id;
  43141. }
  43142. },
  43143. load(id) {
  43144. if (id === preloadHelperId) {
  43145. return preloadCode;
  43146. }
  43147. },
  43148. async transform(source, importer) {
  43149. if (isInNodeModules(importer) && !dynamicImportPrefixRE.test(source)) {
  43150. return;
  43151. }
  43152. await init;
  43153. let imports = [];
  43154. try {
  43155. imports = parse$e(source)[0];
  43156. }
  43157. catch (e) {
  43158. this.error(e, e.idx);
  43159. }
  43160. if (!imports.length) {
  43161. return null;
  43162. }
  43163. const { root } = config;
  43164. const depsOptimizer = getDepsOptimizer(config, ssr);
  43165. const normalizeUrl = async (url, pos) => {
  43166. let importerFile = importer;
  43167. const optimizeDeps = getDepOptimizationConfig(config, ssr);
  43168. if (moduleListContains(optimizeDeps?.exclude, url)) {
  43169. if (depsOptimizer) {
  43170. await depsOptimizer.scanProcessing;
  43171. // if the dependency encountered in the optimized file was excluded from the optimization
  43172. // the dependency needs to be resolved starting from the original source location of the optimized file
  43173. // because starting from node_modules/.vite will not find the dependency if it was not hoisted
  43174. // (that is, if it is under node_modules directory in the package source of the optimized file)
  43175. for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
  43176. if (!optimizedModule.src)
  43177. continue; // Ignore chunks
  43178. if (optimizedModule.file === importer) {
  43179. importerFile = optimizedModule.src;
  43180. }
  43181. }
  43182. }
  43183. }
  43184. const resolved = await this.resolve(url, importerFile);
  43185. if (!resolved) {
  43186. // in ssr, we should let node handle the missing modules
  43187. if (ssr) {
  43188. return [url, url];
  43189. }
  43190. return this.error(`Failed to resolve import "${url}" from "${path$o.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
  43191. }
  43192. // normalize all imports into resolved URLs
  43193. // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
  43194. if (resolved.id.startsWith(withTrailingSlash(root))) {
  43195. // in root: infer short absolute path from root
  43196. url = resolved.id.slice(root.length);
  43197. }
  43198. else {
  43199. url = resolved.id;
  43200. }
  43201. if (isExternalUrl(url)) {
  43202. return [url, url];
  43203. }
  43204. return [url, resolved.id];
  43205. };
  43206. let s;
  43207. const str = () => s || (s = new MagicString(source));
  43208. let needPreloadHelper = false;
  43209. for (let index = 0; index < imports.length; index++) {
  43210. const { s: start, e: end, ss: expStart, se: expEnd, n: specifier, d: dynamicIndex, a: assertIndex, } = imports[index];
  43211. const isDynamicImport = dynamicIndex > -1;
  43212. // strip import assertions as we can process them ourselves
  43213. if (!isDynamicImport && assertIndex > -1) {
  43214. str().remove(end + 1, expEnd);
  43215. }
  43216. if (isDynamicImport && insertPreload) {
  43217. needPreloadHelper = true;
  43218. str().prependLeft(expStart, `${preloadMethod}(() => `);
  43219. str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0${optimizeModulePreloadRelativePaths || customModulePreloadPaths
  43220. ? ',import.meta.url'
  43221. : ''})`);
  43222. }
  43223. // static import or valid string in dynamic import
  43224. // If resolvable, let's resolve it
  43225. if (depsOptimizer && specifier) {
  43226. // skip external / data uri
  43227. if (isExternalUrl(specifier) || isDataUrl(specifier)) {
  43228. continue;
  43229. }
  43230. // normalize
  43231. const [url, resolvedId] = await normalizeUrl(specifier, start);
  43232. if (url !== specifier) {
  43233. if (depsOptimizer.isOptimizedDepFile(resolvedId) &&
  43234. !resolvedId.match(optimizedDepChunkRE)) {
  43235. const file = cleanUrl(resolvedId); // Remove ?v={hash}
  43236. const needsInterop = await optimizedDepNeedsInterop(depsOptimizer.metadata, file, config, ssr);
  43237. let rewriteDone = false;
  43238. if (needsInterop === undefined) {
  43239. // Non-entry dynamic imports from dependencies will reach here as there isn't
  43240. // optimize info for them, but they don't need es interop. If the request isn't
  43241. // a dynamic import, then it is an internal Vite error
  43242. if (!file.match(optimizedDepDynamicRE)) {
  43243. config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
  43244. }
  43245. }
  43246. else if (needsInterop) {
  43247. // config.logger.info(`${url} needs interop`)
  43248. interopNamedImports(str(), imports[index], url, index, importer, config);
  43249. rewriteDone = true;
  43250. }
  43251. if (!rewriteDone) {
  43252. const rewrittenUrl = JSON.stringify(file);
  43253. const s = isDynamicImport ? start : start - 1;
  43254. const e = isDynamicImport ? end : end + 1;
  43255. str().update(s, e, rewrittenUrl);
  43256. }
  43257. }
  43258. }
  43259. }
  43260. // Differentiate CSS imports that use the default export from those that
  43261. // do not by injecting a ?used query - this allows us to avoid including
  43262. // the CSS string when unnecessary (esbuild has trouble tree-shaking
  43263. // them)
  43264. if (specifier &&
  43265. isCSSRequest(specifier) &&
  43266. // always inject ?used query when it is a dynamic import
  43267. // because there is no way to check whether the default export is used
  43268. (source.slice(expStart, start).includes('from') || isDynamicImport) &&
  43269. // already has ?used query (by import.meta.glob)
  43270. !specifier.match(/\?used(&|$)/) &&
  43271. // don't append ?used when SPECIAL_QUERY_RE exists
  43272. !specifier.match(SPECIAL_QUERY_RE) &&
  43273. // edge case for package names ending with .css (e.g normalize.css)
  43274. !(bareImportRE.test(specifier) && !specifier.includes('/'))) {
  43275. const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`);
  43276. str().update(start, end, isDynamicImport ? `'${url}'` : url);
  43277. }
  43278. }
  43279. if (needPreloadHelper &&
  43280. insertPreload &&
  43281. !source.includes(`const ${preloadMethod} =`)) {
  43282. str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
  43283. }
  43284. if (s) {
  43285. return {
  43286. code: s.toString(),
  43287. map: config.build.sourcemap
  43288. ? s.generateMap({ hires: 'boundary' })
  43289. : null,
  43290. };
  43291. }
  43292. },
  43293. renderChunk(code, _, { format }) {
  43294. // make sure we only perform the preload logic in modern builds.
  43295. if (code.indexOf(isModernFlag) > -1) {
  43296. const re = new RegExp(isModernFlag, 'g');
  43297. const isModern = String(format === 'es');
  43298. if (config.build.sourcemap) {
  43299. const s = new MagicString(code);
  43300. let match;
  43301. while ((match = re.exec(code))) {
  43302. s.update(match.index, match.index + isModernFlag.length, isModern);
  43303. }
  43304. return {
  43305. code: s.toString(),
  43306. map: s.generateMap({ hires: 'boundary' }),
  43307. };
  43308. }
  43309. else {
  43310. return code.replace(re, isModern);
  43311. }
  43312. }
  43313. return null;
  43314. },
  43315. generateBundle({ format }, bundle) {
  43316. if (format !== 'es' || ssr || isWorker) {
  43317. return;
  43318. }
  43319. for (const file in bundle) {
  43320. const chunk = bundle[file];
  43321. // can't use chunk.dynamicImports.length here since some modules e.g.
  43322. // dynamic import to constant json may get inlined.
  43323. if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
  43324. const code = chunk.code;
  43325. let imports;
  43326. try {
  43327. imports = parse$e(code)[0].filter((i) => i.d > -1);
  43328. }
  43329. catch (e) {
  43330. const loc = numberToPos(code, e.idx);
  43331. this.error({
  43332. name: e.name,
  43333. message: e.message,
  43334. stack: e.stack,
  43335. cause: e.cause,
  43336. pos: e.idx,
  43337. loc: { ...loc, file: chunk.fileName },
  43338. frame: generateCodeFrame(code, loc),
  43339. });
  43340. }
  43341. const s = new MagicString(code);
  43342. const rewroteMarkerStartPos = new Set(); // position of the leading double quote
  43343. if (imports.length) {
  43344. for (let index = 0; index < imports.length; index++) {
  43345. // To handle escape sequences in specifier strings, the .n field will be provided where possible.
  43346. const { n: name, s: start, e: end, ss: expStart, se: expEnd, } = imports[index];
  43347. // check the chunk being imported
  43348. let url = name;
  43349. if (!url) {
  43350. const rawUrl = code.slice(start, end);
  43351. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"`)
  43352. url = rawUrl.slice(1, -1);
  43353. }
  43354. const deps = new Set();
  43355. let hasRemovedPureCssChunk = false;
  43356. let normalizedFile = undefined;
  43357. if (url) {
  43358. normalizedFile = path$o.posix.join(path$o.posix.dirname(chunk.fileName), url);
  43359. const ownerFilename = chunk.fileName;
  43360. // literal import - trace direct imports and add to deps
  43361. const analyzed = new Set();
  43362. const addDeps = (filename) => {
  43363. if (filename === ownerFilename)
  43364. return;
  43365. if (analyzed.has(filename))
  43366. return;
  43367. analyzed.add(filename);
  43368. const chunk = bundle[filename];
  43369. if (chunk) {
  43370. deps.add(chunk.fileName);
  43371. chunk.imports.forEach(addDeps);
  43372. // Ensure that the css imported by current chunk is loaded after the dependencies.
  43373. // So the style of current chunk won't be overwritten unexpectedly.
  43374. chunk.viteMetadata.importedCss.forEach((file) => {
  43375. deps.add(file);
  43376. });
  43377. }
  43378. else {
  43379. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  43380. const chunk = removedPureCssFiles.get(filename);
  43381. if (chunk) {
  43382. if (chunk.viteMetadata.importedCss.size) {
  43383. chunk.viteMetadata.importedCss.forEach((file) => {
  43384. deps.add(file);
  43385. });
  43386. hasRemovedPureCssChunk = true;
  43387. }
  43388. s.update(expStart, expEnd, 'Promise.resolve({})');
  43389. }
  43390. }
  43391. };
  43392. addDeps(normalizedFile);
  43393. }
  43394. let markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote, end);
  43395. // fix issue #3051
  43396. if (markerStartPos === -1 && imports.length === 1) {
  43397. markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote);
  43398. }
  43399. if (markerStartPos > 0) {
  43400. // the dep list includes the main chunk, so only need to reload when there are actual other deps.
  43401. const depsArray = deps.size > 1 ||
  43402. // main chunk is removed
  43403. (hasRemovedPureCssChunk && deps.size > 0)
  43404. ? modulePreload === false
  43405. ? // CSS deps use the same mechanism as module preloads, so even if disabled,
  43406. // we still need to pass these deps to the preload helper in dynamic imports.
  43407. [...deps].filter((d) => d.endsWith('.css'))
  43408. : [...deps]
  43409. : [];
  43410. let renderedDeps;
  43411. if (normalizedFile && customModulePreloadPaths) {
  43412. const { modulePreload } = config.build;
  43413. const resolveDependencies = modulePreload
  43414. ? modulePreload.resolveDependencies
  43415. : undefined;
  43416. let resolvedDeps;
  43417. if (resolveDependencies) {
  43418. // We can't let the user remove css deps as these aren't really preloads, they are just using
  43419. // the same mechanism as module preloads for this chunk
  43420. const cssDeps = [];
  43421. const otherDeps = [];
  43422. for (const dep of depsArray) {
  43423. (dep.endsWith('.css') ? cssDeps : otherDeps).push(dep);
  43424. }
  43425. resolvedDeps = [
  43426. ...resolveDependencies(normalizedFile, otherDeps, {
  43427. hostId: file,
  43428. hostType: 'js',
  43429. }),
  43430. ...cssDeps,
  43431. ];
  43432. }
  43433. else {
  43434. resolvedDeps = depsArray;
  43435. }
  43436. renderedDeps = resolvedDeps.map((dep) => {
  43437. const replacement = toOutputFilePathInJS(dep, 'asset', chunk.fileName, 'js', config, toRelativePath);
  43438. const replacementString = typeof replacement === 'string'
  43439. ? JSON.stringify(replacement)
  43440. : replacement.runtime;
  43441. return replacementString;
  43442. });
  43443. }
  43444. else {
  43445. renderedDeps = depsArray.map((d) =>
  43446. // Don't include the assets dir if the default asset file names
  43447. // are used, the path will be reconstructed by the import preload helper
  43448. JSON.stringify(optimizeModulePreloadRelativePaths
  43449. ? toRelativePath(d, file)
  43450. : d));
  43451. }
  43452. s.update(markerStartPos, markerStartPos + preloadMarker.length + 2, `[${renderedDeps.join(',')}]`);
  43453. rewroteMarkerStartPos.add(markerStartPos);
  43454. }
  43455. }
  43456. }
  43457. // there may still be markers due to inlined dynamic imports, remove
  43458. // all the markers regardless
  43459. let markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote);
  43460. while (markerStartPos >= 0) {
  43461. if (!rewroteMarkerStartPos.has(markerStartPos)) {
  43462. s.update(markerStartPos, markerStartPos + preloadMarker.length + 2, 'void 0');
  43463. }
  43464. markerStartPos = indexOfMatchInSlice(code, preloadMarkerWithQuote, markerStartPos + preloadMarker.length + 2);
  43465. }
  43466. if (s.hasChanged()) {
  43467. chunk.code = s.toString();
  43468. if (config.build.sourcemap && chunk.map) {
  43469. const nextMap = s.generateMap({
  43470. source: chunk.fileName,
  43471. hires: 'boundary',
  43472. });
  43473. const map = combineSourcemaps(chunk.fileName, [
  43474. nextMap,
  43475. chunk.map,
  43476. ]);
  43477. map.toUrl = () => genSourceMapUrl(map);
  43478. chunk.map = map;
  43479. if (config.build.sourcemap === 'inline') {
  43480. chunk.code = chunk.code.replace(convertSourceMap.mapFileCommentRegex, '');
  43481. chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  43482. }
  43483. else if (config.build.sourcemap) {
  43484. const mapAsset = bundle[chunk.fileName + '.map'];
  43485. if (mapAsset && mapAsset.type === 'asset') {
  43486. mapAsset.source = map.toString();
  43487. }
  43488. }
  43489. }
  43490. }
  43491. }
  43492. }
  43493. },
  43494. };
  43495. }
  43496. function ssrManifestPlugin(config) {
  43497. // module id => preload assets mapping
  43498. const ssrManifest = {};
  43499. const base = config.base; // TODO:base
  43500. return {
  43501. name: 'vite:ssr-manifest',
  43502. generateBundle(_options, bundle) {
  43503. for (const file in bundle) {
  43504. const chunk = bundle[file];
  43505. if (chunk.type === 'chunk') {
  43506. for (const id in chunk.modules) {
  43507. const normalizedId = normalizePath$3(relative$2(config.root, id));
  43508. const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
  43509. if (!chunk.isEntry) {
  43510. mappedChunks.push(joinUrlSegments(base, chunk.fileName));
  43511. // <link> tags for entry chunks are already generated in static HTML,
  43512. // so we only need to record info for non-entry chunks.
  43513. chunk.viteMetadata.importedCss.forEach((file) => {
  43514. mappedChunks.push(joinUrlSegments(base, file));
  43515. });
  43516. }
  43517. chunk.viteMetadata.importedAssets.forEach((file) => {
  43518. mappedChunks.push(joinUrlSegments(base, file));
  43519. });
  43520. }
  43521. if (chunk.code.includes(preloadMethod)) {
  43522. // generate css deps map
  43523. const code = chunk.code;
  43524. let imports;
  43525. try {
  43526. imports = parse$e(code)[0].filter((i) => i.n && i.d > -1);
  43527. }
  43528. catch (e) {
  43529. const loc = numberToPos(code, e.idx);
  43530. this.error({
  43531. name: e.name,
  43532. message: e.message,
  43533. stack: e.stack,
  43534. cause: e.cause,
  43535. pos: e.idx,
  43536. loc: { ...loc, file: chunk.fileName },
  43537. frame: generateCodeFrame(code, loc),
  43538. });
  43539. }
  43540. if (imports.length) {
  43541. for (let index = 0; index < imports.length; index++) {
  43542. const { s: start, e: end, n: name } = imports[index];
  43543. // check the chunk being imported
  43544. const url = code.slice(start, end);
  43545. const deps = [];
  43546. const ownerFilename = chunk.fileName;
  43547. // literal import - trace direct imports and add to deps
  43548. const analyzed = new Set();
  43549. const addDeps = (filename) => {
  43550. if (filename === ownerFilename)
  43551. return;
  43552. if (analyzed.has(filename))
  43553. return;
  43554. analyzed.add(filename);
  43555. const chunk = bundle[filename];
  43556. if (chunk) {
  43557. chunk.viteMetadata.importedCss.forEach((file) => {
  43558. deps.push(joinUrlSegments(base, file)); // TODO:base
  43559. });
  43560. chunk.imports.forEach(addDeps);
  43561. }
  43562. };
  43563. const normalizedFile = normalizePath$3(join$2(dirname$2(chunk.fileName), url.slice(1, -1)));
  43564. addDeps(normalizedFile);
  43565. ssrManifest[basename$2(name)] = deps;
  43566. }
  43567. }
  43568. }
  43569. }
  43570. }
  43571. this.emitFile({
  43572. fileName: typeof config.build.ssrManifest === 'string'
  43573. ? config.build.ssrManifest
  43574. : 'ssr-manifest.json',
  43575. type: 'asset',
  43576. source: jsonStableStringify$1(ssrManifest, { space: 2 }),
  43577. });
  43578. },
  43579. };
  43580. }
  43581. /**
  43582. * A plugin to provide build load fallback for arbitrary request with queries.
  43583. */
  43584. function loadFallbackPlugin() {
  43585. return {
  43586. name: 'vite:load-fallback',
  43587. async load(id) {
  43588. try {
  43589. // if we don't add `await` here, we couldn't catch the error in readFile
  43590. return await fsp.readFile(cleanUrl(id), 'utf-8');
  43591. }
  43592. catch (e) {
  43593. return fsp.readFile(id, 'utf-8');
  43594. }
  43595. },
  43596. };
  43597. }
  43598. function resolveChokidarOptions(config, options) {
  43599. const { ignored = [], ...otherOptions } = options ?? {};
  43600. const resolvedWatchOptions = {
  43601. ignored: [
  43602. '**/.git/**',
  43603. '**/node_modules/**',
  43604. '**/test-results/**',
  43605. glob.escapePath(config.cacheDir) + '/**',
  43606. ...(Array.isArray(ignored) ? ignored : [ignored]),
  43607. ],
  43608. ignoreInitial: true,
  43609. ignorePermissionErrors: true,
  43610. ...otherOptions,
  43611. };
  43612. return resolvedWatchOptions;
  43613. }
  43614. /**
  43615. * make sure systemjs register wrap to had complete parameters in system format
  43616. */
  43617. function completeSystemWrapPlugin() {
  43618. const SystemJSWrapRE = /System.register\(.*(\(exports\)|\(\))/g;
  43619. return {
  43620. name: 'vite:force-systemjs-wrap-complete',
  43621. renderChunk(code, chunk, opts) {
  43622. if (opts.format === 'system') {
  43623. return {
  43624. code: code.replace(SystemJSWrapRE, (s, s1) => s.replace(s1, '(exports, module)')),
  43625. map: null,
  43626. };
  43627. }
  43628. },
  43629. };
  43630. }
  43631. /*!
  43632. * etag
  43633. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  43634. * MIT Licensed
  43635. */
  43636. /**
  43637. * Module exports.
  43638. * @public
  43639. */
  43640. var etag_1 = etag;
  43641. /**
  43642. * Module dependencies.
  43643. * @private
  43644. */
  43645. var crypto = require$$3$1;
  43646. var Stats = require$$0__default.Stats;
  43647. /**
  43648. * Module variables.
  43649. * @private
  43650. */
  43651. var toString = Object.prototype.toString;
  43652. /**
  43653. * Generate an entity tag.
  43654. *
  43655. * @param {Buffer|string} entity
  43656. * @return {string}
  43657. * @private
  43658. */
  43659. function entitytag (entity) {
  43660. if (entity.length === 0) {
  43661. // fast-path empty
  43662. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  43663. }
  43664. // compute hash of entity
  43665. var hash = crypto
  43666. .createHash('sha1')
  43667. .update(entity, 'utf8')
  43668. .digest('base64')
  43669. .substring(0, 27);
  43670. // compute length of entity
  43671. var len = typeof entity === 'string'
  43672. ? Buffer.byteLength(entity, 'utf8')
  43673. : entity.length;
  43674. return '"' + len.toString(16) + '-' + hash + '"'
  43675. }
  43676. /**
  43677. * Create a simple ETag.
  43678. *
  43679. * @param {string|Buffer|Stats} entity
  43680. * @param {object} [options]
  43681. * @param {boolean} [options.weak]
  43682. * @return {String}
  43683. * @public
  43684. */
  43685. function etag (entity, options) {
  43686. if (entity == null) {
  43687. throw new TypeError('argument entity is required')
  43688. }
  43689. // support fs.Stats object
  43690. var isStats = isstats(entity);
  43691. var weak = options && typeof options.weak === 'boolean'
  43692. ? options.weak
  43693. : isStats;
  43694. // validate argument
  43695. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  43696. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  43697. }
  43698. // generate entity tag
  43699. var tag = isStats
  43700. ? stattag(entity)
  43701. : entitytag(entity);
  43702. return weak
  43703. ? 'W/' + tag
  43704. : tag
  43705. }
  43706. /**
  43707. * Determine if object is a Stats object.
  43708. *
  43709. * @param {object} obj
  43710. * @return {boolean}
  43711. * @api private
  43712. */
  43713. function isstats (obj) {
  43714. // genuine fs.Stats
  43715. if (typeof Stats === 'function' && obj instanceof Stats) {
  43716. return true
  43717. }
  43718. // quack quack
  43719. return obj && typeof obj === 'object' &&
  43720. 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
  43721. 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
  43722. 'ino' in obj && typeof obj.ino === 'number' &&
  43723. 'size' in obj && typeof obj.size === 'number'
  43724. }
  43725. /**
  43726. * Generate a tag for a stat.
  43727. *
  43728. * @param {object} stat
  43729. * @return {string}
  43730. * @private
  43731. */
  43732. function stattag (stat) {
  43733. var mtime = stat.mtime.getTime().toString(16);
  43734. var size = stat.size.toString(16);
  43735. return '"' + size + '-' + mtime + '"'
  43736. }
  43737. var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
  43738. const alias = {
  43739. js: 'application/javascript',
  43740. css: 'text/css',
  43741. html: 'text/html',
  43742. json: 'application/json',
  43743. };
  43744. function send$2(req, res, content, type, options) {
  43745. const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options;
  43746. if (res.writableEnded) {
  43747. return;
  43748. }
  43749. if (req.headers['if-none-match'] === etag) {
  43750. res.statusCode = 304;
  43751. res.end();
  43752. return;
  43753. }
  43754. res.setHeader('Content-Type', alias[type] || type);
  43755. res.setHeader('Cache-Control', cacheControl);
  43756. res.setHeader('Etag', etag);
  43757. if (headers) {
  43758. for (const name in headers) {
  43759. res.setHeader(name, headers[name]);
  43760. }
  43761. }
  43762. // inject source map reference
  43763. if (map && map.mappings) {
  43764. if (type === 'js' || type === 'css') {
  43765. content = getCodeWithSourcemap(type, content.toString(), map);
  43766. }
  43767. }
  43768. res.statusCode = 200;
  43769. res.end(content);
  43770. return;
  43771. }
  43772. function totalist(dir, callback, pre='') {
  43773. dir = resolve$3('.', dir);
  43774. let arr = readdirSync(dir);
  43775. let i=0, abs, stats;
  43776. for (; i < arr.length; i++) {
  43777. abs = join$1(dir, arr[i]);
  43778. stats = statSync$1(abs);
  43779. stats.isDirectory()
  43780. ? totalist(abs, callback, join$1(pre, arr[i]))
  43781. : callback(join$1(pre, arr[i]), abs, stats);
  43782. }
  43783. }
  43784. /**
  43785. * @typedef ParsedURL
  43786. * @type {import('.').ParsedURL}
  43787. */
  43788. /**
  43789. * @typedef Request
  43790. * @property {string} url
  43791. * @property {ParsedURL} _parsedUrl
  43792. */
  43793. /**
  43794. * @param {Request} req
  43795. * @returns {ParsedURL|void}
  43796. */
  43797. function parse$8(req) {
  43798. let raw = req.url;
  43799. if (raw == null) return;
  43800. let prev = req._parsedUrl;
  43801. if (prev && prev.raw === raw) return prev;
  43802. let pathname=raw, search='', query;
  43803. if (raw.length > 1) {
  43804. let idx = raw.indexOf('?', 1);
  43805. if (idx !== -1) {
  43806. search = raw.substring(idx);
  43807. pathname = raw.substring(0, idx);
  43808. if (search.length > 1) {
  43809. query = qs.parse(search.substring(1));
  43810. }
  43811. }
  43812. }
  43813. return req._parsedUrl = { pathname, search, query, raw };
  43814. }
  43815. const noop$2 = () => {};
  43816. function isMatch(uri, arr) {
  43817. for (let i=0; i < arr.length; i++) {
  43818. if (arr[i].test(uri)) return true;
  43819. }
  43820. }
  43821. function toAssume(uri, extns) {
  43822. let i=0, x, len=uri.length - 1;
  43823. if (uri.charCodeAt(len) === 47) {
  43824. uri = uri.substring(0, len);
  43825. }
  43826. let arr=[], tmp=`${uri}/index`;
  43827. for (; i < extns.length; i++) {
  43828. x = extns[i] ? `.${extns[i]}` : '';
  43829. if (uri) arr.push(uri + x);
  43830. arr.push(tmp + x);
  43831. }
  43832. return arr;
  43833. }
  43834. function viaCache(cache, uri, extns) {
  43835. let i=0, data, arr=toAssume(uri, extns);
  43836. for (; i < arr.length; i++) {
  43837. if (data = cache[arr[i]]) return data;
  43838. }
  43839. }
  43840. function viaLocal(dir, isEtag, uri, extns, shouldServe) {
  43841. let i=0, arr=toAssume(uri, extns);
  43842. let abs, stats, name, headers;
  43843. for (; i < arr.length; i++) {
  43844. abs = normalize(join$1(dir, name=arr[i]));
  43845. if (abs.startsWith(dir) && require$$0$2.existsSync(abs)) {
  43846. stats = require$$0$2.statSync(abs);
  43847. if (stats.isDirectory()) continue;
  43848. if (shouldServe && !shouldServe(abs)) continue;
  43849. headers = toHeaders(name, stats, isEtag);
  43850. headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
  43851. return { abs, stats, headers };
  43852. }
  43853. }
  43854. }
  43855. function is404(req, res) {
  43856. return (res.statusCode=404,res.end());
  43857. }
  43858. function send$1(req, res, file, stats, headers) {
  43859. let code=200, tmp, opts={};
  43860. headers = { ...headers };
  43861. for (let key in headers) {
  43862. tmp = res.getHeader(key);
  43863. if (tmp) headers[key] = tmp;
  43864. }
  43865. if (tmp = res.getHeader('content-type')) {
  43866. headers['Content-Type'] = tmp;
  43867. }
  43868. if (req.headers.range) {
  43869. code = 206;
  43870. let [x, y] = req.headers.range.replace('bytes=', '').split('-');
  43871. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  43872. let start = opts.start = parseInt(x, 10) || 0;
  43873. if (end >= stats.size) {
  43874. end = stats.size - 1;
  43875. }
  43876. if (start >= stats.size) {
  43877. res.setHeader('Content-Range', `bytes */${stats.size}`);
  43878. res.statusCode = 416;
  43879. return res.end();
  43880. }
  43881. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  43882. headers['Content-Length'] = (end - start + 1);
  43883. headers['Accept-Ranges'] = 'bytes';
  43884. }
  43885. res.writeHead(code, headers);
  43886. require$$0$2.createReadStream(file, opts).pipe(res);
  43887. }
  43888. const ENCODING = {
  43889. '.br': 'br',
  43890. '.gz': 'gzip',
  43891. };
  43892. function toHeaders(name, stats, isEtag) {
  43893. let enc = ENCODING[name.slice(-3)];
  43894. let ctype = lookup(name.slice(0, enc && -3)) || '';
  43895. if (ctype === 'text/html') ctype += ';charset=utf-8';
  43896. let headers = {
  43897. 'Content-Length': stats.size,
  43898. 'Content-Type': ctype,
  43899. 'Last-Modified': stats.mtime.toUTCString(),
  43900. };
  43901. if (enc) headers['Content-Encoding'] = enc;
  43902. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  43903. return headers;
  43904. }
  43905. function sirv (dir, opts={}) {
  43906. dir = resolve$3(dir || '.');
  43907. let isNotFound = opts.onNoMatch || is404;
  43908. let setHeaders = opts.setHeaders || noop$2;
  43909. let extensions = opts.extensions || ['html', 'htm'];
  43910. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  43911. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  43912. const FILES = {};
  43913. let fallback = '/';
  43914. let isEtag = !!opts.etag;
  43915. let isSPA = !!opts.single;
  43916. if (typeof opts.single === 'string') {
  43917. let idx = opts.single.lastIndexOf('.');
  43918. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  43919. }
  43920. let ignores = [];
  43921. if (opts.ignores !== false) {
  43922. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  43923. if (opts.dotfiles) ignores.push(/\/\.\w/);
  43924. else ignores.push(/\/\.well-known/);
  43925. [].concat(opts.ignores || []).forEach(x => {
  43926. ignores.push(new RegExp(x, 'i'));
  43927. });
  43928. }
  43929. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  43930. if (cc && opts.immutable) cc += ',immutable';
  43931. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  43932. if (!opts.dev) {
  43933. totalist(dir, (name, abs, stats) => {
  43934. if (/\.well-known[\\+\/]/.test(name)) ; // keep
  43935. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  43936. let headers = toHeaders(name, stats, isEtag);
  43937. if (cc) headers['Cache-Control'] = cc;
  43938. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  43939. });
  43940. }
  43941. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  43942. return function (req, res, next) {
  43943. let extns = [''];
  43944. let pathname = parse$8(req).pathname;
  43945. let val = req.headers['accept-encoding'] || '';
  43946. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  43947. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  43948. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  43949. if (pathname.indexOf('%') !== -1) {
  43950. try { pathname = decodeURI(pathname); }
  43951. catch (err) { /* malform uri */ }
  43952. }
  43953. let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
  43954. if (!data) return next ? next() : isNotFound(req, res);
  43955. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  43956. res.writeHead(304);
  43957. return res.end();
  43958. }
  43959. if (gzips || brots) {
  43960. res.setHeader('Vary', 'Accept-Encoding');
  43961. }
  43962. setHeaders(res, pathname, data.stats);
  43963. send$1(req, res, data.abs, data.stats, data.headers);
  43964. };
  43965. }
  43966. /*!
  43967. * escape-html
  43968. * Copyright(c) 2012-2013 TJ Holowaychuk
  43969. * Copyright(c) 2015 Andreas Lubbe
  43970. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  43971. * MIT Licensed
  43972. */
  43973. /**
  43974. * Module variables.
  43975. * @private
  43976. */
  43977. var matchHtmlRegExp = /["'&<>]/;
  43978. /**
  43979. * Module exports.
  43980. * @public
  43981. */
  43982. var escapeHtml_1 = escapeHtml$1;
  43983. /**
  43984. * Escape special characters in the given string of html.
  43985. *
  43986. * @param {string} string The string to escape for inserting into HTML
  43987. * @return {string}
  43988. * @public
  43989. */
  43990. function escapeHtml$1(string) {
  43991. var str = '' + string;
  43992. var match = matchHtmlRegExp.exec(str);
  43993. if (!match) {
  43994. return str;
  43995. }
  43996. var escape;
  43997. var html = '';
  43998. var index = 0;
  43999. var lastIndex = 0;
  44000. for (index = match.index; index < str.length; index++) {
  44001. switch (str.charCodeAt(index)) {
  44002. case 34: // "
  44003. escape = '&quot;';
  44004. break;
  44005. case 38: // &
  44006. escape = '&amp;';
  44007. break;
  44008. case 39: // '
  44009. escape = '&#39;';
  44010. break;
  44011. case 60: // <
  44012. escape = '&lt;';
  44013. break;
  44014. case 62: // >
  44015. escape = '&gt;';
  44016. break;
  44017. default:
  44018. continue;
  44019. }
  44020. if (lastIndex !== index) {
  44021. html += str.substring(lastIndex, index);
  44022. }
  44023. lastIndex = index + 1;
  44024. html += escape;
  44025. }
  44026. return lastIndex !== index
  44027. ? html + str.substring(lastIndex, index)
  44028. : html;
  44029. }
  44030. var escapeHtml$2 = /*@__PURE__*/getDefaultExportFromCjs(escapeHtml_1);
  44031. const knownJavascriptExtensionRE = /\.[tj]sx?$/;
  44032. const ERR_DENIED_FILE = 'ERR_DENIED_FILE';
  44033. const sirvOptions = ({ server, headers, shouldServe, disableFsServeCheck, }) => {
  44034. return {
  44035. dev: true,
  44036. etag: true,
  44037. extensions: [],
  44038. setHeaders(res, pathname) {
  44039. // Matches js, jsx, ts, tsx.
  44040. // The reason this is done, is that the .ts file extension is reserved
  44041. // for the MIME type video/mp2t. In almost all cases, we can expect
  44042. // these files to be TypeScript files, and for Vite to serve them with
  44043. // this Content-Type.
  44044. if (knownJavascriptExtensionRE.test(pathname)) {
  44045. res.setHeader('Content-Type', 'application/javascript');
  44046. }
  44047. if (headers) {
  44048. for (const name in headers) {
  44049. res.setHeader(name, headers[name]);
  44050. }
  44051. }
  44052. },
  44053. shouldServe: disableFsServeCheck
  44054. ? shouldServe
  44055. : (filePath) => {
  44056. const servingAccessResult = checkLoadingAccess(server, filePath);
  44057. if (servingAccessResult === 'denied') {
  44058. const error = new Error('denied access');
  44059. error.code = ERR_DENIED_FILE;
  44060. error.path = filePath;
  44061. throw error;
  44062. }
  44063. if (servingAccessResult === 'fallback') {
  44064. return false;
  44065. }
  44066. if (shouldServe) {
  44067. return shouldServe(filePath);
  44068. }
  44069. return true;
  44070. },
  44071. };
  44072. };
  44073. function servePublicMiddleware(dir, server, headers) {
  44074. const serve = sirv(dir, sirvOptions({
  44075. server,
  44076. headers,
  44077. shouldServe: (filePath) => shouldServeFile(filePath, dir),
  44078. disableFsServeCheck: true,
  44079. }));
  44080. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  44081. return function viteServePublicMiddleware(req, res, next) {
  44082. // skip import request and internal requests `/@fs/ /@vite-client` etc...
  44083. if (isImportRequest(req.url) || isInternalRequest(req.url)) {
  44084. return next();
  44085. }
  44086. serve(req, res, next);
  44087. };
  44088. }
  44089. function serveStaticMiddleware(dir, server) {
  44090. const serve = sirv(dir, sirvOptions({
  44091. server,
  44092. headers: server.config.server.headers,
  44093. }));
  44094. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  44095. return function viteServeStaticMiddleware(req, res, next) {
  44096. // only serve the file if it's not an html request or ends with `/`
  44097. // so that html requests can fallthrough to our html middleware for
  44098. // special processing
  44099. // also skip internal requests `/@fs/ /@vite-client` etc...
  44100. const cleanedUrl = cleanUrl(req.url);
  44101. if (cleanedUrl[cleanedUrl.length - 1] === '/' ||
  44102. path$o.extname(cleanedUrl) === '.html' ||
  44103. isInternalRequest(req.url)) {
  44104. return next();
  44105. }
  44106. const url = new URL(req.url.replace(/^\/{2,}/, '/'), 'http://example.com');
  44107. const pathname = decodeURI(url.pathname);
  44108. // apply aliases to static requests as well
  44109. let redirectedPathname;
  44110. for (const { find, replacement } of server.config.resolve.alias) {
  44111. const matches = typeof find === 'string'
  44112. ? pathname.startsWith(find)
  44113. : find.test(pathname);
  44114. if (matches) {
  44115. redirectedPathname = pathname.replace(find, replacement);
  44116. break;
  44117. }
  44118. }
  44119. if (redirectedPathname) {
  44120. // dir is pre-normalized to posix style
  44121. if (redirectedPathname.startsWith(withTrailingSlash(dir))) {
  44122. redirectedPathname = redirectedPathname.slice(dir.length);
  44123. }
  44124. }
  44125. const resolvedPathname = redirectedPathname || pathname;
  44126. path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
  44127. if (redirectedPathname) {
  44128. url.pathname = encodeURI(redirectedPathname);
  44129. req.url = url.href.slice(url.origin.length);
  44130. }
  44131. try {
  44132. serve(req, res, next);
  44133. }
  44134. catch (e) {
  44135. if (e && 'code' in e && e.code === ERR_DENIED_FILE) {
  44136. respondWithAccessDenied(e.path, server, res);
  44137. return;
  44138. }
  44139. throw e;
  44140. }
  44141. };
  44142. }
  44143. function serveRawFsMiddleware(server) {
  44144. const serveFromRoot = sirv('/', sirvOptions({
  44145. server,
  44146. headers: server.config.server.headers,
  44147. }));
  44148. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  44149. return function viteServeRawFsMiddleware(req, res, next) {
  44150. const url = new URL(req.url.replace(/^\/{2,}/, '/'), 'http://example.com');
  44151. // In some cases (e.g. linked monorepos) files outside of root will
  44152. // reference assets that are also out of served root. In such cases
  44153. // the paths are rewritten to `/@fs/` prefixed paths and must be served by
  44154. // searching based from fs root.
  44155. if (url.pathname.startsWith(FS_PREFIX)) {
  44156. const pathname = decodeURI(url.pathname);
  44157. let newPathname = pathname.slice(FS_PREFIX.length);
  44158. if (isWindows$4)
  44159. newPathname = newPathname.replace(/^[A-Z]:/i, '');
  44160. url.pathname = encodeURI(newPathname);
  44161. req.url = url.href.slice(url.origin.length);
  44162. try {
  44163. serveFromRoot(req, res, next);
  44164. }
  44165. catch (e) {
  44166. if (e && 'code' in e && e.code === ERR_DENIED_FILE) {
  44167. respondWithAccessDenied(e.path, server, res);
  44168. return;
  44169. }
  44170. throw e;
  44171. }
  44172. }
  44173. else {
  44174. next();
  44175. }
  44176. };
  44177. }
  44178. /**
  44179. * Check if the url is allowed to be served, via the `server.fs` config.
  44180. * @deprecated Use the `isFileLoadingAllowed` function instead.
  44181. */
  44182. function isFileServingAllowed(url, server) {
  44183. if (!server.config.server.fs.strict)
  44184. return true;
  44185. const filePath = fsPathFromUrl(url);
  44186. return isFileLoadingAllowed(server, filePath);
  44187. }
  44188. function isUriInFilePath(uri, filePath) {
  44189. return isSameFileUri(uri, filePath) || isParentDirectory(uri, filePath);
  44190. }
  44191. function isFileLoadingAllowed(server, filePath) {
  44192. const { fs } = server.config.server;
  44193. if (!fs.strict)
  44194. return true;
  44195. if (server._fsDenyGlob(filePath))
  44196. return false;
  44197. if (server.moduleGraph.safeModulesPath.has(filePath))
  44198. return true;
  44199. if (fs.allow.some((uri) => isUriInFilePath(uri, filePath)))
  44200. return true;
  44201. return false;
  44202. }
  44203. function checkLoadingAccess(server, path) {
  44204. if (isFileLoadingAllowed(server, slash$1(path))) {
  44205. return 'allowed';
  44206. }
  44207. if (isFileReadable(path)) {
  44208. return 'denied';
  44209. }
  44210. // if the file doesn't exist, we shouldn't restrict this path as it can
  44211. // be an API call. Middlewares would issue a 404 if the file isn't handled
  44212. return 'fallback';
  44213. }
  44214. function checkServingAccess(url, server) {
  44215. if (isFileServingAllowed(url, server)) {
  44216. return 'allowed';
  44217. }
  44218. if (isFileReadable(cleanUrl(url))) {
  44219. return 'denied';
  44220. }
  44221. // if the file doesn't exist, we shouldn't restrict this path as it can
  44222. // be an API call. Middlewares would issue a 404 if the file isn't handled
  44223. return 'fallback';
  44224. }
  44225. function respondWithAccessDenied(url, server, res) {
  44226. const urlMessage = `The request url "${url}" is outside of Vite serving allow list.`;
  44227. const hintMessage = `
  44228. ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
  44229. Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
  44230. server.config.logger.error(urlMessage);
  44231. server.config.logger.warnOnce(hintMessage + '\n');
  44232. res.statusCode = 403;
  44233. res.write(renderRestrictedErrorHTML(urlMessage + '\n' + hintMessage));
  44234. res.end();
  44235. }
  44236. function renderRestrictedErrorHTML(msg) {
  44237. // to have syntax highlighting and autocompletion in IDE
  44238. const html = String.raw;
  44239. return html `
  44240. <body>
  44241. <h1>403 Restricted</h1>
  44242. <p>${escapeHtml$2(msg).replace(/\n/g, '<br/>')}</p>
  44243. <style>
  44244. body {
  44245. padding: 1em 2em;
  44246. }
  44247. </style>
  44248. </body>
  44249. `;
  44250. }
  44251. function resolveBuildOptions(raw, logger, root) {
  44252. const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload;
  44253. if (raw) {
  44254. const { polyfillModulePreload, ...rest } = raw;
  44255. raw = rest;
  44256. if (deprecatedPolyfillModulePreload !== undefined) {
  44257. logger.warn('polyfillModulePreload is deprecated. Use modulePreload.polyfill instead.');
  44258. }
  44259. if (deprecatedPolyfillModulePreload === false &&
  44260. raw.modulePreload === undefined) {
  44261. raw.modulePreload = { polyfill: false };
  44262. }
  44263. }
  44264. const modulePreload = raw?.modulePreload;
  44265. const defaultModulePreload = {
  44266. polyfill: true,
  44267. };
  44268. const defaultBuildOptions = {
  44269. outDir: 'dist',
  44270. assetsDir: 'assets',
  44271. assetsInlineLimit: 4096,
  44272. cssCodeSplit: !raw?.lib,
  44273. sourcemap: false,
  44274. rollupOptions: {},
  44275. minify: raw?.ssr ? false : 'esbuild',
  44276. terserOptions: {},
  44277. write: true,
  44278. emptyOutDir: null,
  44279. copyPublicDir: true,
  44280. manifest: false,
  44281. lib: false,
  44282. ssr: false,
  44283. ssrManifest: false,
  44284. ssrEmitAssets: false,
  44285. reportCompressedSize: true,
  44286. chunkSizeWarningLimit: 500,
  44287. watch: null,
  44288. };
  44289. const userBuildOptions = raw
  44290. ? mergeConfig(defaultBuildOptions, raw)
  44291. : defaultBuildOptions;
  44292. // @ts-expect-error Fallback options instead of merging
  44293. const resolved = {
  44294. target: 'modules',
  44295. cssTarget: false,
  44296. ...userBuildOptions,
  44297. commonjsOptions: {
  44298. include: [/node_modules/],
  44299. extensions: ['.js', '.cjs'],
  44300. ...userBuildOptions.commonjsOptions,
  44301. },
  44302. dynamicImportVarsOptions: {
  44303. warnOnError: true,
  44304. exclude: [/node_modules/],
  44305. ...userBuildOptions.dynamicImportVarsOptions,
  44306. },
  44307. // Resolve to false | object
  44308. modulePreload: modulePreload === false
  44309. ? false
  44310. : typeof modulePreload === 'object'
  44311. ? {
  44312. ...defaultModulePreload,
  44313. ...modulePreload,
  44314. }
  44315. : defaultModulePreload,
  44316. };
  44317. // handle special build targets
  44318. if (resolved.target === 'modules') {
  44319. resolved.target = ESBUILD_MODULES_TARGET;
  44320. }
  44321. else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
  44322. try {
  44323. const terserPackageJsonPath = requireResolveFromRootWithFallback(root, 'terser/package.json');
  44324. const terserPackageJson = JSON.parse(fs$l.readFileSync(terserPackageJsonPath, 'utf-8'));
  44325. const v = terserPackageJson.version.split('.');
  44326. if (v[0] === '5' && v[1] < 16) {
  44327. // esnext + terser 5.16<: limit to es2021 so it can be minified by terser
  44328. resolved.target = 'es2021';
  44329. }
  44330. }
  44331. catch { }
  44332. }
  44333. if (!resolved.cssTarget) {
  44334. resolved.cssTarget = resolved.target;
  44335. }
  44336. // normalize false string into actual false
  44337. if (resolved.minify === 'false') {
  44338. resolved.minify = false;
  44339. }
  44340. if (resolved.minify === true) {
  44341. resolved.minify = 'esbuild';
  44342. }
  44343. if (resolved.cssMinify == null) {
  44344. resolved.cssMinify = !!resolved.minify;
  44345. }
  44346. return resolved;
  44347. }
  44348. async function resolveBuildPlugins(config) {
  44349. const options = config.build;
  44350. const { commonjsOptions } = options;
  44351. const usePluginCommonjs = !Array.isArray(commonjsOptions?.include) ||
  44352. commonjsOptions?.include.length !== 0;
  44353. const rollupOptionsPlugins = options.rollupOptions.plugins;
  44354. return {
  44355. pre: [
  44356. completeSystemWrapPlugin(),
  44357. ...(options.watch ? [ensureWatchPlugin()] : []),
  44358. ...(usePluginCommonjs ? [commonjs(options.commonjsOptions)] : []),
  44359. dataURIPlugin(),
  44360. ...(await asyncFlatten(Array.isArray(rollupOptionsPlugins)
  44361. ? rollupOptionsPlugins
  44362. : [rollupOptionsPlugins])).filter(Boolean),
  44363. ...(config.isWorker ? [webWorkerPostPlugin()] : []),
  44364. ],
  44365. post: [
  44366. buildImportAnalysisPlugin(config),
  44367. ...(config.esbuild !== false ? [buildEsbuildPlugin(config)] : []),
  44368. ...(options.minify ? [terserPlugin(config)] : []),
  44369. ...(!config.isWorker
  44370. ? [
  44371. ...(options.manifest ? [manifestPlugin(config)] : []),
  44372. ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
  44373. buildReporterPlugin(config),
  44374. ]
  44375. : []),
  44376. loadFallbackPlugin(),
  44377. ],
  44378. };
  44379. }
  44380. /**
  44381. * Bundles the app for production.
  44382. * Returns a Promise containing the build result.
  44383. */
  44384. async function build(inlineConfig = {}) {
  44385. const config = await resolveConfig(inlineConfig, 'build', 'production', 'production');
  44386. const options = config.build;
  44387. const ssr = !!options.ssr;
  44388. const libOptions = options.lib;
  44389. config.logger.info(colors$1.cyan(`vite v${VERSION$1} ${colors$1.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
  44390. const resolve = (p) => path$o.resolve(config.root, p);
  44391. const input = libOptions
  44392. ? options.rollupOptions?.input ||
  44393. (typeof libOptions.entry === 'string'
  44394. ? resolve(libOptions.entry)
  44395. : Array.isArray(libOptions.entry)
  44396. ? libOptions.entry.map(resolve)
  44397. : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [
  44398. alias,
  44399. resolve(file),
  44400. ])))
  44401. : typeof options.ssr === 'string'
  44402. ? resolve(options.ssr)
  44403. : options.rollupOptions?.input || resolve('index.html');
  44404. if (ssr && typeof input === 'string' && input.endsWith('.html')) {
  44405. throw new Error(`rollupOptions.input should not be an html file when building for SSR. ` +
  44406. `Please specify a dedicated SSR entry.`);
  44407. }
  44408. const outDir = resolve(options.outDir);
  44409. // inject ssr arg to plugin load/transform hooks
  44410. const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins);
  44411. const userExternal = options.rollupOptions?.external;
  44412. let external = userExternal;
  44413. // In CJS, we can pass the externals to rollup as is. In ESM, we need to
  44414. // do it in the resolve plugin so we can add the resolved extension for
  44415. // deep node_modules imports
  44416. if (ssr && config.legacy?.buildSsrCjsExternalHeuristics) {
  44417. external = await cjsSsrResolveExternal(config, userExternal);
  44418. }
  44419. if (isDepsOptimizerEnabled(config, ssr)) {
  44420. await initDepsOptimizer(config);
  44421. }
  44422. const rollupOptions = {
  44423. context: 'globalThis',
  44424. preserveEntrySignatures: ssr
  44425. ? 'allow-extension'
  44426. : libOptions
  44427. ? 'strict'
  44428. : false,
  44429. cache: config.build.watch ? undefined : false,
  44430. ...options.rollupOptions,
  44431. input,
  44432. plugins,
  44433. external,
  44434. onwarn(warning, warn) {
  44435. onRollupWarning(warning, warn, config);
  44436. },
  44437. };
  44438. const outputBuildError = (e) => {
  44439. let msg = colors$1.red((e.plugin ? `[${e.plugin}] ` : '') + e.message);
  44440. if (e.id) {
  44441. msg += `\nfile: ${colors$1.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ''))}`;
  44442. }
  44443. if (e.frame) {
  44444. msg += `\n` + colors$1.yellow(e.frame);
  44445. }
  44446. config.logger.error(msg, { error: e });
  44447. };
  44448. let bundle;
  44449. try {
  44450. const buildOutputOptions = (output = {}) => {
  44451. // @ts-expect-error See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618
  44452. if (output.output) {
  44453. config.logger.warn(`You've set "rollupOptions.output.output" in your config. ` +
  44454. `This is deprecated and will override all Vite.js default output options. ` +
  44455. `Please use "rollupOptions.output" instead.`);
  44456. }
  44457. const ssrNodeBuild = ssr && config.ssr.target === 'node';
  44458. const ssrWorkerBuild = ssr && config.ssr.target === 'webworker';
  44459. const cjsSsrBuild = ssr && config.ssr.format === 'cjs';
  44460. const format = output.format || (cjsSsrBuild ? 'cjs' : 'es');
  44461. const jsExt = ssrNodeBuild || libOptions
  44462. ? resolveOutputJsExtension(format, findNearestPackageData(config.root, config.packageCache)?.data
  44463. .type)
  44464. : 'js';
  44465. return {
  44466. dir: outDir,
  44467. // Default format is 'es' for regular and for SSR builds
  44468. format,
  44469. exports: cjsSsrBuild ? 'named' : 'auto',
  44470. sourcemap: options.sourcemap,
  44471. name: libOptions ? libOptions.name : undefined,
  44472. // es2015 enables `generatedCode.symbols`
  44473. // - #764 add `Symbol.toStringTag` when build es module into cjs chunk
  44474. // - #1048 add `Symbol.toStringTag` for module default export
  44475. generatedCode: 'es2015',
  44476. entryFileNames: ssr
  44477. ? `[name].${jsExt}`
  44478. : libOptions
  44479. ? ({ name }) => resolveLibFilename(libOptions, format, name, config.root, jsExt, config.packageCache)
  44480. : path$o.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  44481. chunkFileNames: libOptions
  44482. ? `[name]-[hash].${jsExt}`
  44483. : path$o.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
  44484. assetFileNames: libOptions
  44485. ? `[name].[ext]`
  44486. : path$o.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
  44487. inlineDynamicImports: output.format === 'umd' ||
  44488. output.format === 'iife' ||
  44489. (ssrWorkerBuild &&
  44490. (typeof input === 'string' || Object.keys(input).length === 1)),
  44491. ...output,
  44492. };
  44493. };
  44494. // resolve lib mode outputs
  44495. const outputs = resolveBuildOutputs(options.rollupOptions?.output, libOptions, config.logger);
  44496. const normalizedOutputs = [];
  44497. if (Array.isArray(outputs)) {
  44498. for (const resolvedOutput of outputs) {
  44499. normalizedOutputs.push(buildOutputOptions(resolvedOutput));
  44500. }
  44501. }
  44502. else {
  44503. normalizedOutputs.push(buildOutputOptions(outputs));
  44504. }
  44505. const outDirs = normalizedOutputs.map(({ dir }) => resolve(dir));
  44506. // watch file changes with rollup
  44507. if (config.build.watch) {
  44508. config.logger.info(colors$1.cyan(`\nwatching for file changes...`));
  44509. const resolvedChokidarOptions = resolveChokidarOptions(config, config.build.watch.chokidar);
  44510. const { watch } = await import('rollup');
  44511. const watcher = watch({
  44512. ...rollupOptions,
  44513. output: normalizedOutputs,
  44514. watch: {
  44515. ...config.build.watch,
  44516. chokidar: resolvedChokidarOptions,
  44517. },
  44518. });
  44519. watcher.on('event', (event) => {
  44520. if (event.code === 'BUNDLE_START') {
  44521. config.logger.info(colors$1.cyan(`\nbuild started...`));
  44522. if (options.write) {
  44523. prepareOutDir(outDirs, options.emptyOutDir, config);
  44524. }
  44525. }
  44526. else if (event.code === 'BUNDLE_END') {
  44527. event.result.close();
  44528. config.logger.info(colors$1.cyan(`built in ${event.duration}ms.`));
  44529. }
  44530. else if (event.code === 'ERROR') {
  44531. outputBuildError(event.error);
  44532. }
  44533. });
  44534. return watcher;
  44535. }
  44536. // write or generate files with rollup
  44537. const { rollup } = await import('rollup');
  44538. bundle = await rollup(rollupOptions);
  44539. if (options.write) {
  44540. prepareOutDir(outDirs, options.emptyOutDir, config);
  44541. }
  44542. const res = [];
  44543. for (const output of normalizedOutputs) {
  44544. res.push(await bundle[options.write ? 'write' : 'generate'](output));
  44545. }
  44546. return Array.isArray(outputs) ? res : res[0];
  44547. }
  44548. catch (e) {
  44549. outputBuildError(e);
  44550. throw e;
  44551. }
  44552. finally {
  44553. if (bundle)
  44554. await bundle.close();
  44555. }
  44556. }
  44557. function prepareOutDir(outDirs, emptyOutDir, config) {
  44558. const nonDuplicateDirs = new Set(outDirs);
  44559. let outside = false;
  44560. if (emptyOutDir == null) {
  44561. for (const outDir of nonDuplicateDirs) {
  44562. if (fs$l.existsSync(outDir) &&
  44563. !normalizePath$3(outDir).startsWith(withTrailingSlash(config.root))) {
  44564. // warn if outDir is outside of root
  44565. config.logger.warn(colors$1.yellow(`\n${colors$1.bold(`(!)`)} outDir ${colors$1.white(colors$1.dim(outDir))} is not inside project root and will not be emptied.\n` +
  44566. `Use --emptyOutDir to override.\n`));
  44567. outside = true;
  44568. break;
  44569. }
  44570. }
  44571. }
  44572. for (const outDir of nonDuplicateDirs) {
  44573. if (!outside && emptyOutDir !== false && fs$l.existsSync(outDir)) {
  44574. // skip those other outDirs which are nested in current outDir
  44575. const skipDirs = outDirs
  44576. .map((dir) => {
  44577. const relative = path$o.relative(outDir, dir);
  44578. if (relative &&
  44579. !relative.startsWith('..') &&
  44580. !path$o.isAbsolute(relative)) {
  44581. return relative;
  44582. }
  44583. return '';
  44584. })
  44585. .filter(Boolean);
  44586. emptyDir(outDir, [...skipDirs, '.git']);
  44587. }
  44588. if (config.build.copyPublicDir &&
  44589. config.publicDir &&
  44590. fs$l.existsSync(config.publicDir)) {
  44591. if (!areSeparateFolders(outDir, config.publicDir)) {
  44592. config.logger.warn(colors$1.yellow(`\n${colors$1.bold(`(!)`)} The public directory feature may not work correctly. outDir ${colors$1.white(colors$1.dim(outDir))} and publicDir ${colors$1.white(colors$1.dim(config.publicDir))} are not separate folders.\n`));
  44593. }
  44594. copyDir(config.publicDir, outDir);
  44595. }
  44596. }
  44597. }
  44598. function getPkgName(name) {
  44599. return name?.[0] === '@' ? name.split('/')[1] : name;
  44600. }
  44601. function resolveOutputJsExtension(format, type = 'commonjs') {
  44602. if (type === 'module') {
  44603. return format === 'cjs' || format === 'umd' ? 'cjs' : 'js';
  44604. }
  44605. else {
  44606. return format === 'es' ? 'mjs' : 'js';
  44607. }
  44608. }
  44609. function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
  44610. if (typeof libOptions.fileName === 'function') {
  44611. return libOptions.fileName(format, entryName);
  44612. }
  44613. const packageJson = findNearestPackageData(root, packageCache)?.data;
  44614. const name = libOptions.fileName ||
  44615. (packageJson && typeof libOptions.entry === 'string'
  44616. ? getPkgName(packageJson.name)
  44617. : entryName);
  44618. if (!name)
  44619. throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
  44620. extension ?? (extension = resolveOutputJsExtension(format, packageJson?.type));
  44621. if (format === 'cjs' || format === 'es') {
  44622. return `${name}.${extension}`;
  44623. }
  44624. return `${name}.${format}.${extension}`;
  44625. }
  44626. function resolveBuildOutputs(outputs, libOptions, logger) {
  44627. if (libOptions) {
  44628. const libHasMultipleEntries = typeof libOptions.entry !== 'string' &&
  44629. Object.values(libOptions.entry).length > 1;
  44630. const libFormats = libOptions.formats ||
  44631. (libHasMultipleEntries ? ['es', 'cjs'] : ['es', 'umd']);
  44632. if (!Array.isArray(outputs)) {
  44633. if (libFormats.includes('umd') || libFormats.includes('iife')) {
  44634. if (libHasMultipleEntries) {
  44635. throw new Error('Multiple entry points are not supported when output formats include "umd" or "iife".');
  44636. }
  44637. if (!libOptions.name) {
  44638. throw new Error('Option "build.lib.name" is required when output formats include "umd" or "iife".');
  44639. }
  44640. }
  44641. return libFormats.map((format) => ({ ...outputs, format }));
  44642. }
  44643. // By this point, we know "outputs" is an Array.
  44644. if (libOptions.formats) {
  44645. logger.warn(colors$1.yellow('"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.'));
  44646. }
  44647. outputs.forEach((output) => {
  44648. if (['umd', 'iife'].includes(output.format) && !output.name) {
  44649. throw new Error('Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".');
  44650. }
  44651. });
  44652. }
  44653. return outputs;
  44654. }
  44655. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  44656. const dynamicImportWarningIgnoreList = [
  44657. `Unsupported expression`,
  44658. `statically analyzed`,
  44659. ];
  44660. function onRollupWarning(warning, warn, config) {
  44661. const viteWarn = (warnLog) => {
  44662. let warning;
  44663. if (typeof warnLog === 'function') {
  44664. warning = warnLog();
  44665. }
  44666. else {
  44667. warning = warnLog;
  44668. }
  44669. if (typeof warning === 'object') {
  44670. if (warning.code === 'UNRESOLVED_IMPORT') {
  44671. const id = warning.id;
  44672. const exporter = warning.exporter;
  44673. // throw unless it's commonjs external...
  44674. if (!id || !/\?commonjs-external$/.test(id)) {
  44675. throw new Error(`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".\n` +
  44676. `This is most likely unintended because it can break your application at runtime.\n` +
  44677. `If you do want to externalize this module explicitly add it to\n` +
  44678. `\`build.rollupOptions.external\``);
  44679. }
  44680. }
  44681. if (warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
  44682. dynamicImportWarningIgnoreList.some((msg) =>
  44683. // @ts-expect-error warning is RollupLog
  44684. warning.message.includes(msg))) {
  44685. return;
  44686. }
  44687. if (warningIgnoreList.includes(warning.code)) {
  44688. return;
  44689. }
  44690. if (warning.code === 'PLUGIN_WARNING') {
  44691. config.logger.warn(`${colors$1.bold(colors$1.yellow(`[plugin:${warning.plugin}]`))} ${colors$1.yellow(warning.message)}`);
  44692. return;
  44693. }
  44694. }
  44695. warn(warnLog);
  44696. };
  44697. const tty = process.stdout.isTTY && !process.env.CI;
  44698. if (tty) {
  44699. process.stdout.clearLine(0);
  44700. process.stdout.cursorTo(0);
  44701. }
  44702. const userOnWarn = config.build.rollupOptions?.onwarn;
  44703. if (userOnWarn) {
  44704. userOnWarn(warning, viteWarn);
  44705. }
  44706. else {
  44707. viteWarn(warning);
  44708. }
  44709. }
  44710. async function cjsSsrResolveExternal(config, user) {
  44711. // see if we have cached deps data available
  44712. let knownImports;
  44713. const dataPath = path$o.join(getDepsCacheDir(config, false), '_metadata.json');
  44714. try {
  44715. const data = JSON.parse(fs$l.readFileSync(dataPath, 'utf-8'));
  44716. knownImports = Object.keys(data.optimized);
  44717. }
  44718. catch (e) { }
  44719. if (!knownImports) {
  44720. // no dev deps optimization data, do a fresh scan
  44721. knownImports = await findKnownImports(config, false); // needs to use non-ssr
  44722. }
  44723. const ssrExternals = cjsSsrResolveExternals(config, knownImports);
  44724. return (id, parentId, isResolved) => {
  44725. const isExternal = cjsShouldExternalizeForSSR(id, ssrExternals);
  44726. if (isExternal) {
  44727. return true;
  44728. }
  44729. if (user) {
  44730. return resolveUserExternal(user, id, parentId, isResolved);
  44731. }
  44732. };
  44733. }
  44734. function resolveUserExternal(user, id, parentId, isResolved) {
  44735. if (typeof user === 'function') {
  44736. return user(id, parentId, isResolved);
  44737. }
  44738. else if (Array.isArray(user)) {
  44739. return user.some((test) => isExternal(id, test));
  44740. }
  44741. else {
  44742. return isExternal(id, user);
  44743. }
  44744. }
  44745. function isExternal(id, test) {
  44746. if (typeof test === 'string') {
  44747. return id === test;
  44748. }
  44749. else {
  44750. return test.test(id);
  44751. }
  44752. }
  44753. function injectSsrFlagToHooks(plugin) {
  44754. const { resolveId, load, transform } = plugin;
  44755. return {
  44756. ...plugin,
  44757. resolveId: wrapSsrResolveId(resolveId),
  44758. load: wrapSsrLoad(load),
  44759. transform: wrapSsrTransform(transform),
  44760. };
  44761. }
  44762. function wrapSsrResolveId(hook) {
  44763. if (!hook)
  44764. return;
  44765. const fn = 'handler' in hook ? hook.handler : hook;
  44766. const handler = function (id, importer, options) {
  44767. return fn.call(this, id, importer, injectSsrFlag(options));
  44768. };
  44769. if ('handler' in hook) {
  44770. return {
  44771. ...hook,
  44772. handler,
  44773. };
  44774. }
  44775. else {
  44776. return handler;
  44777. }
  44778. }
  44779. function wrapSsrLoad(hook) {
  44780. if (!hook)
  44781. return;
  44782. const fn = 'handler' in hook ? hook.handler : hook;
  44783. const handler = function (id, ...args) {
  44784. // @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
  44785. return fn.call(this, id, injectSsrFlag(args[0]));
  44786. };
  44787. if ('handler' in hook) {
  44788. return {
  44789. ...hook,
  44790. handler,
  44791. };
  44792. }
  44793. else {
  44794. return handler;
  44795. }
  44796. }
  44797. function wrapSsrTransform(hook) {
  44798. if (!hook)
  44799. return;
  44800. const fn = 'handler' in hook ? hook.handler : hook;
  44801. const handler = function (code, importer, ...args) {
  44802. // @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
  44803. return fn.call(this, code, importer, injectSsrFlag(args[0]));
  44804. };
  44805. if ('handler' in hook) {
  44806. return {
  44807. ...hook,
  44808. handler,
  44809. };
  44810. }
  44811. else {
  44812. return handler;
  44813. }
  44814. }
  44815. function injectSsrFlag(options) {
  44816. return { ...(options ?? {}), ssr: true };
  44817. }
  44818. /*
  44819. The following functions are copied from rollup
  44820. https://github.com/rollup/rollup/blob/0bcf0a672ac087ff2eb88fbba45ec62389a4f45f/src/ast/nodes/MetaProperty.ts#L145-L193
  44821. https://github.com/rollup/rollup
  44822. The MIT License (MIT)
  44823. Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors)
  44824. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  44825. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  44826. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  44827. */
  44828. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  44829. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  44830. const backSlashRegEx = /\\/g;
  44831. function escapeId(id) {
  44832. if (!needsEscapeRegEx.test(id))
  44833. return id;
  44834. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  44835. }
  44836. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  44837. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  44838. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  44839. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  44840. const relativeUrlMechanisms = {
  44841. amd: (relativePath) => {
  44842. if (relativePath[0] !== '.')
  44843. relativePath = './' + relativePath;
  44844. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  44845. },
  44846. cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  44847. es: (relativePath) => getResolveUrl(`'${relativePath}', import.meta.url`),
  44848. iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
  44849. // NOTE: make sure rollup generate `module` params
  44850. system: (relativePath) => getResolveUrl(`'${relativePath}', module.meta.url`),
  44851. umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`,
  44852. };
  44853. /* end of copy */
  44854. const customRelativeUrlMechanisms = {
  44855. ...relativeUrlMechanisms,
  44856. 'worker-iife': (relativePath) => getResolveUrl(`'${relativePath}', self.location.href`),
  44857. };
  44858. function toOutputFilePathInJS(filename, type, hostId, hostType, config, toRelative) {
  44859. const { renderBuiltUrl } = config.experimental;
  44860. let relative = config.base === '' || config.base === './';
  44861. if (renderBuiltUrl) {
  44862. const result = renderBuiltUrl(filename, {
  44863. hostId,
  44864. hostType,
  44865. type,
  44866. ssr: !!config.build.ssr,
  44867. });
  44868. if (typeof result === 'object') {
  44869. if (result.runtime) {
  44870. return { runtime: result.runtime };
  44871. }
  44872. if (typeof result.relative === 'boolean') {
  44873. relative = result.relative;
  44874. }
  44875. }
  44876. else if (result) {
  44877. return result;
  44878. }
  44879. }
  44880. if (relative && !config.build.ssr) {
  44881. return toRelative(filename, hostId);
  44882. }
  44883. return joinUrlSegments(config.base, filename);
  44884. }
  44885. function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
  44886. const formatLong = isWorker && format === 'iife' ? 'worker-iife' : format;
  44887. const toRelativePath = customRelativeUrlMechanisms[formatLong];
  44888. return (filename, importer) => ({
  44889. runtime: toRelativePath(path$o.posix.relative(path$o.dirname(importer), filename)),
  44890. });
  44891. }
  44892. function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
  44893. const { renderBuiltUrl } = config.experimental;
  44894. let relative = config.base === '' || config.base === './';
  44895. if (renderBuiltUrl) {
  44896. const result = renderBuiltUrl(filename, {
  44897. hostId,
  44898. hostType,
  44899. type,
  44900. ssr: !!config.build.ssr,
  44901. });
  44902. if (typeof result === 'object') {
  44903. if (result.runtime) {
  44904. throw new Error(`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`);
  44905. }
  44906. if (typeof result.relative === 'boolean') {
  44907. relative = result.relative;
  44908. }
  44909. }
  44910. else if (result) {
  44911. return result;
  44912. }
  44913. }
  44914. if (relative && !config.build.ssr) {
  44915. return toRelative(filename, hostId);
  44916. }
  44917. else {
  44918. return joinUrlSegments(config.base, filename);
  44919. }
  44920. }
  44921. const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
  44922. const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
  44923. function areSeparateFolders(a, b) {
  44924. const na = normalizePath$3(a);
  44925. const nb = normalizePath$3(b);
  44926. return (na !== nb &&
  44927. !na.startsWith(withTrailingSlash(nb)) &&
  44928. !nb.startsWith(withTrailingSlash(na)));
  44929. }
  44930. var build$1 = {
  44931. __proto__: null,
  44932. build: build,
  44933. createToImportMetaURLBasedRelativeRuntime: createToImportMetaURLBasedRelativeRuntime,
  44934. onRollupWarning: onRollupWarning,
  44935. resolveBuildOptions: resolveBuildOptions,
  44936. resolveBuildOutputs: resolveBuildOutputs,
  44937. resolveBuildPlugins: resolveBuildPlugins,
  44938. resolveLibFilename: resolveLibFilename,
  44939. resolveUserExternal: resolveUserExternal,
  44940. toOutputFilePathInCss: toOutputFilePathInCss,
  44941. toOutputFilePathInHtml: toOutputFilePathInHtml,
  44942. toOutputFilePathInJS: toOutputFilePathInJS,
  44943. toOutputFilePathWithoutRuntime: toOutputFilePathWithoutRuntime
  44944. };
  44945. var src = {exports: {}};
  44946. var browser = {exports: {}};
  44947. var debug$6 = {exports: {}};
  44948. /**
  44949. * Helpers.
  44950. */
  44951. var ms;
  44952. var hasRequiredMs;
  44953. function requireMs () {
  44954. if (hasRequiredMs) return ms;
  44955. hasRequiredMs = 1;
  44956. var s = 1000;
  44957. var m = s * 60;
  44958. var h = m * 60;
  44959. var d = h * 24;
  44960. var y = d * 365.25;
  44961. /**
  44962. * Parse or format the given `val`.
  44963. *
  44964. * Options:
  44965. *
  44966. * - `long` verbose formatting [false]
  44967. *
  44968. * @param {String|Number} val
  44969. * @param {Object} [options]
  44970. * @throws {Error} throw an error if val is not a non-empty string or a number
  44971. * @return {String|Number}
  44972. * @api public
  44973. */
  44974. ms = function(val, options) {
  44975. options = options || {};
  44976. var type = typeof val;
  44977. if (type === 'string' && val.length > 0) {
  44978. return parse(val);
  44979. } else if (type === 'number' && isNaN(val) === false) {
  44980. return options.long ? fmtLong(val) : fmtShort(val);
  44981. }
  44982. throw new Error(
  44983. 'val is not a non-empty string or a valid number. val=' +
  44984. JSON.stringify(val)
  44985. );
  44986. };
  44987. /**
  44988. * Parse the given `str` and return milliseconds.
  44989. *
  44990. * @param {String} str
  44991. * @return {Number}
  44992. * @api private
  44993. */
  44994. function parse(str) {
  44995. str = String(str);
  44996. if (str.length > 100) {
  44997. return;
  44998. }
  44999. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  45000. str
  45001. );
  45002. if (!match) {
  45003. return;
  45004. }
  45005. var n = parseFloat(match[1]);
  45006. var type = (match[2] || 'ms').toLowerCase();
  45007. switch (type) {
  45008. case 'years':
  45009. case 'year':
  45010. case 'yrs':
  45011. case 'yr':
  45012. case 'y':
  45013. return n * y;
  45014. case 'days':
  45015. case 'day':
  45016. case 'd':
  45017. return n * d;
  45018. case 'hours':
  45019. case 'hour':
  45020. case 'hrs':
  45021. case 'hr':
  45022. case 'h':
  45023. return n * h;
  45024. case 'minutes':
  45025. case 'minute':
  45026. case 'mins':
  45027. case 'min':
  45028. case 'm':
  45029. return n * m;
  45030. case 'seconds':
  45031. case 'second':
  45032. case 'secs':
  45033. case 'sec':
  45034. case 's':
  45035. return n * s;
  45036. case 'milliseconds':
  45037. case 'millisecond':
  45038. case 'msecs':
  45039. case 'msec':
  45040. case 'ms':
  45041. return n;
  45042. default:
  45043. return undefined;
  45044. }
  45045. }
  45046. /**
  45047. * Short format for `ms`.
  45048. *
  45049. * @param {Number} ms
  45050. * @return {String}
  45051. * @api private
  45052. */
  45053. function fmtShort(ms) {
  45054. if (ms >= d) {
  45055. return Math.round(ms / d) + 'd';
  45056. }
  45057. if (ms >= h) {
  45058. return Math.round(ms / h) + 'h';
  45059. }
  45060. if (ms >= m) {
  45061. return Math.round(ms / m) + 'm';
  45062. }
  45063. if (ms >= s) {
  45064. return Math.round(ms / s) + 's';
  45065. }
  45066. return ms + 'ms';
  45067. }
  45068. /**
  45069. * Long format for `ms`.
  45070. *
  45071. * @param {Number} ms
  45072. * @return {String}
  45073. * @api private
  45074. */
  45075. function fmtLong(ms) {
  45076. return plural(ms, d, 'day') ||
  45077. plural(ms, h, 'hour') ||
  45078. plural(ms, m, 'minute') ||
  45079. plural(ms, s, 'second') ||
  45080. ms + ' ms';
  45081. }
  45082. /**
  45083. * Pluralization helper.
  45084. */
  45085. function plural(ms, n, name) {
  45086. if (ms < n) {
  45087. return;
  45088. }
  45089. if (ms < n * 1.5) {
  45090. return Math.floor(ms / n) + ' ' + name;
  45091. }
  45092. return Math.ceil(ms / n) + ' ' + name + 's';
  45093. }
  45094. return ms;
  45095. }
  45096. var hasRequiredDebug;
  45097. function requireDebug () {
  45098. if (hasRequiredDebug) return debug$6.exports;
  45099. hasRequiredDebug = 1;
  45100. (function (module, exports) {
  45101. /**
  45102. * This is the common logic for both the Node.js and web browser
  45103. * implementations of `debug()`.
  45104. *
  45105. * Expose `debug()` as the module.
  45106. */
  45107. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  45108. exports.coerce = coerce;
  45109. exports.disable = disable;
  45110. exports.enable = enable;
  45111. exports.enabled = enabled;
  45112. exports.humanize = requireMs();
  45113. /**
  45114. * The currently active debug mode names, and names to skip.
  45115. */
  45116. exports.names = [];
  45117. exports.skips = [];
  45118. /**
  45119. * Map of special "%n" handling functions, for the debug "format" argument.
  45120. *
  45121. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  45122. */
  45123. exports.formatters = {};
  45124. /**
  45125. * Previous log timestamp.
  45126. */
  45127. var prevTime;
  45128. /**
  45129. * Select a color.
  45130. * @param {String} namespace
  45131. * @return {Number}
  45132. * @api private
  45133. */
  45134. function selectColor(namespace) {
  45135. var hash = 0, i;
  45136. for (i in namespace) {
  45137. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  45138. hash |= 0; // Convert to 32bit integer
  45139. }
  45140. return exports.colors[Math.abs(hash) % exports.colors.length];
  45141. }
  45142. /**
  45143. * Create a debugger with the given `namespace`.
  45144. *
  45145. * @param {String} namespace
  45146. * @return {Function}
  45147. * @api public
  45148. */
  45149. function createDebug(namespace) {
  45150. function debug() {
  45151. // disabled?
  45152. if (!debug.enabled) return;
  45153. var self = debug;
  45154. // set `diff` timestamp
  45155. var curr = +new Date();
  45156. var ms = curr - (prevTime || curr);
  45157. self.diff = ms;
  45158. self.prev = prevTime;
  45159. self.curr = curr;
  45160. prevTime = curr;
  45161. // turn the `arguments` into a proper Array
  45162. var args = new Array(arguments.length);
  45163. for (var i = 0; i < args.length; i++) {
  45164. args[i] = arguments[i];
  45165. }
  45166. args[0] = exports.coerce(args[0]);
  45167. if ('string' !== typeof args[0]) {
  45168. // anything else let's inspect with %O
  45169. args.unshift('%O');
  45170. }
  45171. // apply any `formatters` transformations
  45172. var index = 0;
  45173. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  45174. // if we encounter an escaped % then don't increase the array index
  45175. if (match === '%%') return match;
  45176. index++;
  45177. var formatter = exports.formatters[format];
  45178. if ('function' === typeof formatter) {
  45179. var val = args[index];
  45180. match = formatter.call(self, val);
  45181. // now we need to remove `args[index]` since it's inlined in the `format`
  45182. args.splice(index, 1);
  45183. index--;
  45184. }
  45185. return match;
  45186. });
  45187. // apply env-specific formatting (colors, etc.)
  45188. exports.formatArgs.call(self, args);
  45189. var logFn = debug.log || exports.log || console.log.bind(console);
  45190. logFn.apply(self, args);
  45191. }
  45192. debug.namespace = namespace;
  45193. debug.enabled = exports.enabled(namespace);
  45194. debug.useColors = exports.useColors();
  45195. debug.color = selectColor(namespace);
  45196. // env-specific initialization logic for debug instances
  45197. if ('function' === typeof exports.init) {
  45198. exports.init(debug);
  45199. }
  45200. return debug;
  45201. }
  45202. /**
  45203. * Enables a debug mode by namespaces. This can include modes
  45204. * separated by a colon and wildcards.
  45205. *
  45206. * @param {String} namespaces
  45207. * @api public
  45208. */
  45209. function enable(namespaces) {
  45210. exports.save(namespaces);
  45211. exports.names = [];
  45212. exports.skips = [];
  45213. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  45214. var len = split.length;
  45215. for (var i = 0; i < len; i++) {
  45216. if (!split[i]) continue; // ignore empty strings
  45217. namespaces = split[i].replace(/\*/g, '.*?');
  45218. if (namespaces[0] === '-') {
  45219. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  45220. } else {
  45221. exports.names.push(new RegExp('^' + namespaces + '$'));
  45222. }
  45223. }
  45224. }
  45225. /**
  45226. * Disable debug output.
  45227. *
  45228. * @api public
  45229. */
  45230. function disable() {
  45231. exports.enable('');
  45232. }
  45233. /**
  45234. * Returns true if the given mode name is enabled, false otherwise.
  45235. *
  45236. * @param {String} name
  45237. * @return {Boolean}
  45238. * @api public
  45239. */
  45240. function enabled(name) {
  45241. var i, len;
  45242. for (i = 0, len = exports.skips.length; i < len; i++) {
  45243. if (exports.skips[i].test(name)) {
  45244. return false;
  45245. }
  45246. }
  45247. for (i = 0, len = exports.names.length; i < len; i++) {
  45248. if (exports.names[i].test(name)) {
  45249. return true;
  45250. }
  45251. }
  45252. return false;
  45253. }
  45254. /**
  45255. * Coerce `val`.
  45256. *
  45257. * @param {Mixed} val
  45258. * @return {Mixed}
  45259. * @api private
  45260. */
  45261. function coerce(val) {
  45262. if (val instanceof Error) return val.stack || val.message;
  45263. return val;
  45264. }
  45265. } (debug$6, debug$6.exports));
  45266. return debug$6.exports;
  45267. }
  45268. /**
  45269. * This is the web browser implementation of `debug()`.
  45270. *
  45271. * Expose `debug()` as the module.
  45272. */
  45273. var hasRequiredBrowser;
  45274. function requireBrowser () {
  45275. if (hasRequiredBrowser) return browser.exports;
  45276. hasRequiredBrowser = 1;
  45277. (function (module, exports) {
  45278. exports = module.exports = requireDebug();
  45279. exports.log = log;
  45280. exports.formatArgs = formatArgs;
  45281. exports.save = save;
  45282. exports.load = load;
  45283. exports.useColors = useColors;
  45284. exports.storage = 'undefined' != typeof chrome
  45285. && 'undefined' != typeof chrome.storage
  45286. ? chrome.storage.local
  45287. : localstorage();
  45288. /**
  45289. * Colors.
  45290. */
  45291. exports.colors = [
  45292. 'lightseagreen',
  45293. 'forestgreen',
  45294. 'goldenrod',
  45295. 'dodgerblue',
  45296. 'darkorchid',
  45297. 'crimson'
  45298. ];
  45299. /**
  45300. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  45301. * and the Firebug extension (any Firefox version) are known
  45302. * to support "%c" CSS customizations.
  45303. *
  45304. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  45305. */
  45306. function useColors() {
  45307. // NB: In an Electron preload script, document will be defined but not fully
  45308. // initialized. Since we know we're in Chrome, we'll just detect this case
  45309. // explicitly
  45310. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  45311. return true;
  45312. }
  45313. // is webkit? http://stackoverflow.com/a/16459606/376773
  45314. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  45315. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  45316. // is firebug? http://stackoverflow.com/a/398120/376773
  45317. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  45318. // is firefox >= v31?
  45319. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  45320. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  45321. // double check webkit in userAgent just in case we are in a worker
  45322. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  45323. }
  45324. /**
  45325. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  45326. */
  45327. exports.formatters.j = function(v) {
  45328. try {
  45329. return JSON.stringify(v);
  45330. } catch (err) {
  45331. return '[UnexpectedJSONParseError]: ' + err.message;
  45332. }
  45333. };
  45334. /**
  45335. * Colorize log arguments if enabled.
  45336. *
  45337. * @api public
  45338. */
  45339. function formatArgs(args) {
  45340. var useColors = this.useColors;
  45341. args[0] = (useColors ? '%c' : '')
  45342. + this.namespace
  45343. + (useColors ? ' %c' : ' ')
  45344. + args[0]
  45345. + (useColors ? '%c ' : ' ')
  45346. + '+' + exports.humanize(this.diff);
  45347. if (!useColors) return;
  45348. var c = 'color: ' + this.color;
  45349. args.splice(1, 0, c, 'color: inherit');
  45350. // the final "%c" is somewhat tricky, because there could be other
  45351. // arguments passed either before or after the %c, so we need to
  45352. // figure out the correct index to insert the CSS into
  45353. var index = 0;
  45354. var lastC = 0;
  45355. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  45356. if ('%%' === match) return;
  45357. index++;
  45358. if ('%c' === match) {
  45359. // we only are interested in the *last* %c
  45360. // (the user may have provided their own)
  45361. lastC = index;
  45362. }
  45363. });
  45364. args.splice(lastC, 0, c);
  45365. }
  45366. /**
  45367. * Invokes `console.log()` when available.
  45368. * No-op when `console.log` is not a "function".
  45369. *
  45370. * @api public
  45371. */
  45372. function log() {
  45373. // this hackery is required for IE8/9, where
  45374. // the `console.log` function doesn't have 'apply'
  45375. return 'object' === typeof console
  45376. && console.log
  45377. && Function.prototype.apply.call(console.log, console, arguments);
  45378. }
  45379. /**
  45380. * Save `namespaces`.
  45381. *
  45382. * @param {String} namespaces
  45383. * @api private
  45384. */
  45385. function save(namespaces) {
  45386. try {
  45387. if (null == namespaces) {
  45388. exports.storage.removeItem('debug');
  45389. } else {
  45390. exports.storage.debug = namespaces;
  45391. }
  45392. } catch(e) {}
  45393. }
  45394. /**
  45395. * Load `namespaces`.
  45396. *
  45397. * @return {String} returns the previously persisted debug modes
  45398. * @api private
  45399. */
  45400. function load() {
  45401. var r;
  45402. try {
  45403. r = exports.storage.debug;
  45404. } catch(e) {}
  45405. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  45406. if (!r && typeof process !== 'undefined' && 'env' in process) {
  45407. r = process.env.DEBUG;
  45408. }
  45409. return r;
  45410. }
  45411. /**
  45412. * Enable namespaces listed in `localStorage.debug` initially.
  45413. */
  45414. exports.enable(load());
  45415. /**
  45416. * Localstorage attempts to return the localstorage.
  45417. *
  45418. * This is necessary because safari throws
  45419. * when a user disables cookies/localstorage
  45420. * and you attempt to access it.
  45421. *
  45422. * @return {LocalStorage}
  45423. * @api private
  45424. */
  45425. function localstorage() {
  45426. try {
  45427. return window.localStorage;
  45428. } catch (e) {}
  45429. }
  45430. } (browser, browser.exports));
  45431. return browser.exports;
  45432. }
  45433. var node = {exports: {}};
  45434. /**
  45435. * Module dependencies.
  45436. */
  45437. var hasRequiredNode;
  45438. function requireNode () {
  45439. if (hasRequiredNode) return node.exports;
  45440. hasRequiredNode = 1;
  45441. (function (module, exports) {
  45442. var tty = require$$0$3;
  45443. var util = require$$0$6;
  45444. /**
  45445. * This is the Node.js implementation of `debug()`.
  45446. *
  45447. * Expose `debug()` as the module.
  45448. */
  45449. exports = module.exports = requireDebug();
  45450. exports.init = init;
  45451. exports.log = log;
  45452. exports.formatArgs = formatArgs;
  45453. exports.save = save;
  45454. exports.load = load;
  45455. exports.useColors = useColors;
  45456. /**
  45457. * Colors.
  45458. */
  45459. exports.colors = [6, 2, 3, 4, 5, 1];
  45460. /**
  45461. * Build up the default `inspectOpts` object from the environment variables.
  45462. *
  45463. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  45464. */
  45465. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  45466. return /^debug_/i.test(key);
  45467. }).reduce(function (obj, key) {
  45468. // camel-case
  45469. var prop = key
  45470. .substring(6)
  45471. .toLowerCase()
  45472. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  45473. // coerce string value into JS value
  45474. var val = process.env[key];
  45475. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  45476. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  45477. else if (val === 'null') val = null;
  45478. else val = Number(val);
  45479. obj[prop] = val;
  45480. return obj;
  45481. }, {});
  45482. /**
  45483. * The file descriptor to write the `debug()` calls to.
  45484. * Set the `DEBUG_FD` env variable to override with another value. i.e.:
  45485. *
  45486. * $ DEBUG_FD=3 node script.js 3>debug.log
  45487. */
  45488. var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
  45489. if (1 !== fd && 2 !== fd) {
  45490. util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
  45491. }
  45492. var stream = 1 === fd ? process.stdout :
  45493. 2 === fd ? process.stderr :
  45494. createWritableStdioStream(fd);
  45495. /**
  45496. * Is stdout a TTY? Colored output is enabled when `true`.
  45497. */
  45498. function useColors() {
  45499. return 'colors' in exports.inspectOpts
  45500. ? Boolean(exports.inspectOpts.colors)
  45501. : tty.isatty(fd);
  45502. }
  45503. /**
  45504. * Map %o to `util.inspect()`, all on a single line.
  45505. */
  45506. exports.formatters.o = function(v) {
  45507. this.inspectOpts.colors = this.useColors;
  45508. return util.inspect(v, this.inspectOpts)
  45509. .split('\n').map(function(str) {
  45510. return str.trim()
  45511. }).join(' ');
  45512. };
  45513. /**
  45514. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  45515. */
  45516. exports.formatters.O = function(v) {
  45517. this.inspectOpts.colors = this.useColors;
  45518. return util.inspect(v, this.inspectOpts);
  45519. };
  45520. /**
  45521. * Adds ANSI color escape codes if enabled.
  45522. *
  45523. * @api public
  45524. */
  45525. function formatArgs(args) {
  45526. var name = this.namespace;
  45527. var useColors = this.useColors;
  45528. if (useColors) {
  45529. var c = this.color;
  45530. var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
  45531. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  45532. args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  45533. } else {
  45534. args[0] = new Date().toUTCString()
  45535. + ' ' + name + ' ' + args[0];
  45536. }
  45537. }
  45538. /**
  45539. * Invokes `util.format()` with the specified arguments and writes to `stream`.
  45540. */
  45541. function log() {
  45542. return stream.write(util.format.apply(util, arguments) + '\n');
  45543. }
  45544. /**
  45545. * Save `namespaces`.
  45546. *
  45547. * @param {String} namespaces
  45548. * @api private
  45549. */
  45550. function save(namespaces) {
  45551. if (null == namespaces) {
  45552. // If you set a process.env field to null or undefined, it gets cast to the
  45553. // string 'null' or 'undefined'. Just delete instead.
  45554. delete process.env.DEBUG;
  45555. } else {
  45556. process.env.DEBUG = namespaces;
  45557. }
  45558. }
  45559. /**
  45560. * Load `namespaces`.
  45561. *
  45562. * @return {String} returns the previously persisted debug modes
  45563. * @api private
  45564. */
  45565. function load() {
  45566. return process.env.DEBUG;
  45567. }
  45568. /**
  45569. * Copied from `node/src/node.js`.
  45570. *
  45571. * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
  45572. * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
  45573. */
  45574. function createWritableStdioStream (fd) {
  45575. var stream;
  45576. var tty_wrap = process.binding('tty_wrap');
  45577. // Note stream._type is used for test-module-load-list.js
  45578. switch (tty_wrap.guessHandleType(fd)) {
  45579. case 'TTY':
  45580. stream = new tty.WriteStream(fd);
  45581. stream._type = 'tty';
  45582. // Hack to have stream not keep the event loop alive.
  45583. // See https://github.com/joyent/node/issues/1726
  45584. if (stream._handle && stream._handle.unref) {
  45585. stream._handle.unref();
  45586. }
  45587. break;
  45588. case 'FILE':
  45589. var fs = require$$0__default;
  45590. stream = new fs.SyncWriteStream(fd, { autoClose: false });
  45591. stream._type = 'fs';
  45592. break;
  45593. case 'PIPE':
  45594. case 'TCP':
  45595. var net = require$$3$2;
  45596. stream = new net.Socket({
  45597. fd: fd,
  45598. readable: false,
  45599. writable: true
  45600. });
  45601. // FIXME Should probably have an option in net.Socket to create a
  45602. // stream from an existing fd which is writable only. But for now
  45603. // we'll just add this hack and set the `readable` member to false.
  45604. // Test: ./node test/fixtures/echo.js < /etc/passwd
  45605. stream.readable = false;
  45606. stream.read = null;
  45607. stream._type = 'pipe';
  45608. // FIXME Hack to have stream not keep the event loop alive.
  45609. // See https://github.com/joyent/node/issues/1726
  45610. if (stream._handle && stream._handle.unref) {
  45611. stream._handle.unref();
  45612. }
  45613. break;
  45614. default:
  45615. // Probably an error on in uv_guess_handle()
  45616. throw new Error('Implement me. Unknown stream file type!');
  45617. }
  45618. // For supporting legacy API we put the FD here.
  45619. stream.fd = fd;
  45620. stream._isStdio = true;
  45621. return stream;
  45622. }
  45623. /**
  45624. * Init logic for `debug` instances.
  45625. *
  45626. * Create a new `inspectOpts` object in case `useColors` is set
  45627. * differently for a particular `debug` instance.
  45628. */
  45629. function init (debug) {
  45630. debug.inspectOpts = {};
  45631. var keys = Object.keys(exports.inspectOpts);
  45632. for (var i = 0; i < keys.length; i++) {
  45633. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  45634. }
  45635. }
  45636. /**
  45637. * Enable namespaces listed in `process.env.DEBUG` initially.
  45638. */
  45639. exports.enable(load());
  45640. } (node, node.exports));
  45641. return node.exports;
  45642. }
  45643. /**
  45644. * Detect Electron renderer process, which is node, but we should
  45645. * treat as a browser.
  45646. */
  45647. if (typeof process !== 'undefined' && process.type === 'renderer') {
  45648. src.exports = requireBrowser();
  45649. } else {
  45650. src.exports = requireNode();
  45651. }
  45652. var srcExports = src.exports;
  45653. /*!
  45654. * encodeurl
  45655. * Copyright(c) 2016 Douglas Christopher Wilson
  45656. * MIT Licensed
  45657. */
  45658. /**
  45659. * Module exports.
  45660. * @public
  45661. */
  45662. var encodeurl = encodeUrl$1;
  45663. /**
  45664. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  45665. * and including invalid escape sequences.
  45666. * @private
  45667. */
  45668. var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
  45669. /**
  45670. * RegExp to match unmatched surrogate pair.
  45671. * @private
  45672. */
  45673. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  45674. /**
  45675. * String to replace unmatched surrogate pair with.
  45676. * @private
  45677. */
  45678. var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2';
  45679. /**
  45680. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  45681. *
  45682. * This function will take an already-encoded URL and encode all the non-URL
  45683. * code points. This function will not encode the "%" character unless it is
  45684. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  45685. * be encoded as `%25foo`).
  45686. *
  45687. * This encode is meant to be "safe" and does not throw errors. It will try as
  45688. * hard as it can to properly encode the given URL, including replacing any raw,
  45689. * unpaired surrogate pairs with the Unicode replacement character prior to
  45690. * encoding.
  45691. *
  45692. * @param {string} url
  45693. * @return {string}
  45694. * @public
  45695. */
  45696. function encodeUrl$1 (url) {
  45697. return String(url)
  45698. .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
  45699. .replace(ENCODE_CHARS_REGEXP, encodeURI)
  45700. }
  45701. var onFinished$2 = {exports: {}};
  45702. /*!
  45703. * ee-first
  45704. * Copyright(c) 2014 Jonathan Ong
  45705. * MIT Licensed
  45706. */
  45707. /**
  45708. * Module exports.
  45709. * @public
  45710. */
  45711. var eeFirst = first$1;
  45712. /**
  45713. * Get the first event in a set of event emitters and event pairs.
  45714. *
  45715. * @param {array} stuff
  45716. * @param {function} done
  45717. * @public
  45718. */
  45719. function first$1(stuff, done) {
  45720. if (!Array.isArray(stuff))
  45721. throw new TypeError('arg must be an array of [ee, events...] arrays')
  45722. var cleanups = [];
  45723. for (var i = 0; i < stuff.length; i++) {
  45724. var arr = stuff[i];
  45725. if (!Array.isArray(arr) || arr.length < 2)
  45726. throw new TypeError('each array member must be [ee, events...]')
  45727. var ee = arr[0];
  45728. for (var j = 1; j < arr.length; j++) {
  45729. var event = arr[j];
  45730. var fn = listener(event, callback);
  45731. // listen to the event
  45732. ee.on(event, fn);
  45733. // push this listener to the list of cleanups
  45734. cleanups.push({
  45735. ee: ee,
  45736. event: event,
  45737. fn: fn,
  45738. });
  45739. }
  45740. }
  45741. function callback() {
  45742. cleanup();
  45743. done.apply(null, arguments);
  45744. }
  45745. function cleanup() {
  45746. var x;
  45747. for (var i = 0; i < cleanups.length; i++) {
  45748. x = cleanups[i];
  45749. x.ee.removeListener(x.event, x.fn);
  45750. }
  45751. }
  45752. function thunk(fn) {
  45753. done = fn;
  45754. }
  45755. thunk.cancel = cleanup;
  45756. return thunk
  45757. }
  45758. /**
  45759. * Create the event listener.
  45760. * @private
  45761. */
  45762. function listener(event, done) {
  45763. return function onevent(arg1) {
  45764. var args = new Array(arguments.length);
  45765. var ee = this;
  45766. var err = event === 'error'
  45767. ? arg1
  45768. : null;
  45769. // copy args to prevent arguments escaping scope
  45770. for (var i = 0; i < args.length; i++) {
  45771. args[i] = arguments[i];
  45772. }
  45773. done(err, ee, event, args);
  45774. }
  45775. }
  45776. /*!
  45777. * on-finished
  45778. * Copyright(c) 2013 Jonathan Ong
  45779. * Copyright(c) 2014 Douglas Christopher Wilson
  45780. * MIT Licensed
  45781. */
  45782. /**
  45783. * Module exports.
  45784. * @public
  45785. */
  45786. onFinished$2.exports = onFinished$1;
  45787. onFinished$2.exports.isFinished = isFinished$1;
  45788. /**
  45789. * Module dependencies.
  45790. * @private
  45791. */
  45792. var first = eeFirst;
  45793. /**
  45794. * Variables.
  45795. * @private
  45796. */
  45797. /* istanbul ignore next */
  45798. var defer$2 = typeof setImmediate === 'function'
  45799. ? setImmediate
  45800. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  45801. /**
  45802. * Invoke callback when the response has finished, useful for
  45803. * cleaning up resources afterwards.
  45804. *
  45805. * @param {object} msg
  45806. * @param {function} listener
  45807. * @return {object}
  45808. * @public
  45809. */
  45810. function onFinished$1(msg, listener) {
  45811. if (isFinished$1(msg) !== false) {
  45812. defer$2(listener, null, msg);
  45813. return msg
  45814. }
  45815. // attach the listener to the message
  45816. attachListener(msg, listener);
  45817. return msg
  45818. }
  45819. /**
  45820. * Determine if message is already finished.
  45821. *
  45822. * @param {object} msg
  45823. * @return {boolean}
  45824. * @public
  45825. */
  45826. function isFinished$1(msg) {
  45827. var socket = msg.socket;
  45828. if (typeof msg.finished === 'boolean') {
  45829. // OutgoingMessage
  45830. return Boolean(msg.finished || (socket && !socket.writable))
  45831. }
  45832. if (typeof msg.complete === 'boolean') {
  45833. // IncomingMessage
  45834. return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
  45835. }
  45836. // don't know
  45837. return undefined
  45838. }
  45839. /**
  45840. * Attach a finished listener to the message.
  45841. *
  45842. * @param {object} msg
  45843. * @param {function} callback
  45844. * @private
  45845. */
  45846. function attachFinishedListener(msg, callback) {
  45847. var eeMsg;
  45848. var eeSocket;
  45849. var finished = false;
  45850. function onFinish(error) {
  45851. eeMsg.cancel();
  45852. eeSocket.cancel();
  45853. finished = true;
  45854. callback(error);
  45855. }
  45856. // finished on first message event
  45857. eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);
  45858. function onSocket(socket) {
  45859. // remove listener
  45860. msg.removeListener('socket', onSocket);
  45861. if (finished) return
  45862. if (eeMsg !== eeSocket) return
  45863. // finished on first socket event
  45864. eeSocket = first([[socket, 'error', 'close']], onFinish);
  45865. }
  45866. if (msg.socket) {
  45867. // socket already assigned
  45868. onSocket(msg.socket);
  45869. return
  45870. }
  45871. // wait for socket to be assigned
  45872. msg.on('socket', onSocket);
  45873. if (msg.socket === undefined) {
  45874. // node.js 0.8 patch
  45875. patchAssignSocket(msg, onSocket);
  45876. }
  45877. }
  45878. /**
  45879. * Attach the listener to the message.
  45880. *
  45881. * @param {object} msg
  45882. * @return {function}
  45883. * @private
  45884. */
  45885. function attachListener(msg, listener) {
  45886. var attached = msg.__onFinished;
  45887. // create a private single listener with queue
  45888. if (!attached || !attached.queue) {
  45889. attached = msg.__onFinished = createListener(msg);
  45890. attachFinishedListener(msg, attached);
  45891. }
  45892. attached.queue.push(listener);
  45893. }
  45894. /**
  45895. * Create listener on message.
  45896. *
  45897. * @param {object} msg
  45898. * @return {function}
  45899. * @private
  45900. */
  45901. function createListener(msg) {
  45902. function listener(err) {
  45903. if (msg.__onFinished === listener) msg.__onFinished = null;
  45904. if (!listener.queue) return
  45905. var queue = listener.queue;
  45906. listener.queue = null;
  45907. for (var i = 0; i < queue.length; i++) {
  45908. queue[i](err, msg);
  45909. }
  45910. }
  45911. listener.queue = [];
  45912. return listener
  45913. }
  45914. /**
  45915. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  45916. *
  45917. * @param {ServerResponse} res
  45918. * @param {function} callback
  45919. * @private
  45920. */
  45921. function patchAssignSocket(res, callback) {
  45922. var assignSocket = res.assignSocket;
  45923. if (typeof assignSocket !== 'function') return
  45924. // res.on('socket', callback) is broken in 0.8
  45925. res.assignSocket = function _assignSocket(socket) {
  45926. assignSocket.call(this, socket);
  45927. callback(socket);
  45928. };
  45929. }
  45930. var onFinishedExports = onFinished$2.exports;
  45931. var parseurl$1 = {exports: {}};
  45932. /*!
  45933. * parseurl
  45934. * Copyright(c) 2014 Jonathan Ong
  45935. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  45936. * MIT Licensed
  45937. */
  45938. /**
  45939. * Module dependencies.
  45940. * @private
  45941. */
  45942. var url$3 = require$$0$9;
  45943. var parse$7 = url$3.parse;
  45944. var Url = url$3.Url;
  45945. /**
  45946. * Module exports.
  45947. * @public
  45948. */
  45949. parseurl$1.exports = parseurl;
  45950. parseurl$1.exports.original = originalurl;
  45951. /**
  45952. * Parse the `req` url with memoization.
  45953. *
  45954. * @param {ServerRequest} req
  45955. * @return {Object}
  45956. * @public
  45957. */
  45958. function parseurl (req) {
  45959. var url = req.url;
  45960. if (url === undefined) {
  45961. // URL is undefined
  45962. return undefined
  45963. }
  45964. var parsed = req._parsedUrl;
  45965. if (fresh(url, parsed)) {
  45966. // Return cached URL parse
  45967. return parsed
  45968. }
  45969. // Parse the URL
  45970. parsed = fastparse(url);
  45971. parsed._raw = url;
  45972. return (req._parsedUrl = parsed)
  45973. }
  45974. /**
  45975. * Parse the `req` original url with fallback and memoization.
  45976. *
  45977. * @param {ServerRequest} req
  45978. * @return {Object}
  45979. * @public
  45980. */
  45981. function originalurl (req) {
  45982. var url = req.originalUrl;
  45983. if (typeof url !== 'string') {
  45984. // Fallback
  45985. return parseurl(req)
  45986. }
  45987. var parsed = req._parsedOriginalUrl;
  45988. if (fresh(url, parsed)) {
  45989. // Return cached URL parse
  45990. return parsed
  45991. }
  45992. // Parse the URL
  45993. parsed = fastparse(url);
  45994. parsed._raw = url;
  45995. return (req._parsedOriginalUrl = parsed)
  45996. }
  45997. /**
  45998. * Parse the `str` url with fast-path short-cut.
  45999. *
  46000. * @param {string} str
  46001. * @return {Object}
  46002. * @private
  46003. */
  46004. function fastparse (str) {
  46005. if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
  46006. return parse$7(str)
  46007. }
  46008. var pathname = str;
  46009. var query = null;
  46010. var search = null;
  46011. // This takes the regexp from https://github.com/joyent/node/pull/7878
  46012. // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
  46013. // And unrolls it into a for loop
  46014. for (var i = 1; i < str.length; i++) {
  46015. switch (str.charCodeAt(i)) {
  46016. case 0x3f: /* ? */
  46017. if (search === null) {
  46018. pathname = str.substring(0, i);
  46019. query = str.substring(i + 1);
  46020. search = str.substring(i);
  46021. }
  46022. break
  46023. case 0x09: /* \t */
  46024. case 0x0a: /* \n */
  46025. case 0x0c: /* \f */
  46026. case 0x0d: /* \r */
  46027. case 0x20: /* */
  46028. case 0x23: /* # */
  46029. case 0xa0:
  46030. case 0xfeff:
  46031. return parse$7(str)
  46032. }
  46033. }
  46034. var url = Url !== undefined
  46035. ? new Url()
  46036. : {};
  46037. url.path = str;
  46038. url.href = str;
  46039. url.pathname = pathname;
  46040. if (search !== null) {
  46041. url.query = query;
  46042. url.search = search;
  46043. }
  46044. return url
  46045. }
  46046. /**
  46047. * Determine if parsed is still fresh for url.
  46048. *
  46049. * @param {string} url
  46050. * @param {object} parsedUrl
  46051. * @return {boolean}
  46052. * @private
  46053. */
  46054. function fresh (url, parsedUrl) {
  46055. return typeof parsedUrl === 'object' &&
  46056. parsedUrl !== null &&
  46057. (Url === undefined || parsedUrl instanceof Url) &&
  46058. parsedUrl._raw === url
  46059. }
  46060. var parseurlExports = parseurl$1.exports;
  46061. var require$$0$1 = {
  46062. "100": "Continue",
  46063. "101": "Switching Protocols",
  46064. "102": "Processing",
  46065. "103": "Early Hints",
  46066. "200": "OK",
  46067. "201": "Created",
  46068. "202": "Accepted",
  46069. "203": "Non-Authoritative Information",
  46070. "204": "No Content",
  46071. "205": "Reset Content",
  46072. "206": "Partial Content",
  46073. "207": "Multi-Status",
  46074. "208": "Already Reported",
  46075. "226": "IM Used",
  46076. "300": "Multiple Choices",
  46077. "301": "Moved Permanently",
  46078. "302": "Found",
  46079. "303": "See Other",
  46080. "304": "Not Modified",
  46081. "305": "Use Proxy",
  46082. "306": "(Unused)",
  46083. "307": "Temporary Redirect",
  46084. "308": "Permanent Redirect",
  46085. "400": "Bad Request",
  46086. "401": "Unauthorized",
  46087. "402": "Payment Required",
  46088. "403": "Forbidden",
  46089. "404": "Not Found",
  46090. "405": "Method Not Allowed",
  46091. "406": "Not Acceptable",
  46092. "407": "Proxy Authentication Required",
  46093. "408": "Request Timeout",
  46094. "409": "Conflict",
  46095. "410": "Gone",
  46096. "411": "Length Required",
  46097. "412": "Precondition Failed",
  46098. "413": "Payload Too Large",
  46099. "414": "URI Too Long",
  46100. "415": "Unsupported Media Type",
  46101. "416": "Range Not Satisfiable",
  46102. "417": "Expectation Failed",
  46103. "418": "I'm a teapot",
  46104. "421": "Misdirected Request",
  46105. "422": "Unprocessable Entity",
  46106. "423": "Locked",
  46107. "424": "Failed Dependency",
  46108. "425": "Unordered Collection",
  46109. "426": "Upgrade Required",
  46110. "428": "Precondition Required",
  46111. "429": "Too Many Requests",
  46112. "431": "Request Header Fields Too Large",
  46113. "451": "Unavailable For Legal Reasons",
  46114. "500": "Internal Server Error",
  46115. "501": "Not Implemented",
  46116. "502": "Bad Gateway",
  46117. "503": "Service Unavailable",
  46118. "504": "Gateway Timeout",
  46119. "505": "HTTP Version Not Supported",
  46120. "506": "Variant Also Negotiates",
  46121. "507": "Insufficient Storage",
  46122. "508": "Loop Detected",
  46123. "509": "Bandwidth Limit Exceeded",
  46124. "510": "Not Extended",
  46125. "511": "Network Authentication Required"
  46126. };
  46127. /*!
  46128. * statuses
  46129. * Copyright(c) 2014 Jonathan Ong
  46130. * Copyright(c) 2016 Douglas Christopher Wilson
  46131. * MIT Licensed
  46132. */
  46133. /**
  46134. * Module dependencies.
  46135. * @private
  46136. */
  46137. var codes = require$$0$1;
  46138. /**
  46139. * Module exports.
  46140. * @public
  46141. */
  46142. var statuses$1 = status;
  46143. // status code to message map
  46144. status.STATUS_CODES = codes;
  46145. // array of status codes
  46146. status.codes = populateStatusesMap(status, codes);
  46147. // status codes for redirects
  46148. status.redirect = {
  46149. 300: true,
  46150. 301: true,
  46151. 302: true,
  46152. 303: true,
  46153. 305: true,
  46154. 307: true,
  46155. 308: true
  46156. };
  46157. // status codes for empty bodies
  46158. status.empty = {
  46159. 204: true,
  46160. 205: true,
  46161. 304: true
  46162. };
  46163. // status codes for when you should retry the request
  46164. status.retry = {
  46165. 502: true,
  46166. 503: true,
  46167. 504: true
  46168. };
  46169. /**
  46170. * Populate the statuses map for given codes.
  46171. * @private
  46172. */
  46173. function populateStatusesMap (statuses, codes) {
  46174. var arr = [];
  46175. Object.keys(codes).forEach(function forEachCode (code) {
  46176. var message = codes[code];
  46177. var status = Number(code);
  46178. // Populate properties
  46179. statuses[status] = message;
  46180. statuses[message] = status;
  46181. statuses[message.toLowerCase()] = status;
  46182. // Add to array
  46183. arr.push(status);
  46184. });
  46185. return arr
  46186. }
  46187. /**
  46188. * Get the status code.
  46189. *
  46190. * Given a number, this will throw if it is not a known status
  46191. * code, otherwise the code will be returned. Given a string,
  46192. * the string will be parsed for a number and return the code
  46193. * if valid, otherwise will lookup the code assuming this is
  46194. * the status message.
  46195. *
  46196. * @param {string|number} code
  46197. * @returns {number}
  46198. * @public
  46199. */
  46200. function status (code) {
  46201. if (typeof code === 'number') {
  46202. if (!status[code]) throw new Error('invalid status code: ' + code)
  46203. return code
  46204. }
  46205. if (typeof code !== 'string') {
  46206. throw new TypeError('code must be a number or string')
  46207. }
  46208. // '403'
  46209. var n = parseInt(code, 10);
  46210. if (!isNaN(n)) {
  46211. if (!status[n]) throw new Error('invalid status code: ' + n)
  46212. return n
  46213. }
  46214. n = status[code.toLowerCase()];
  46215. if (!n) throw new Error('invalid status message: "' + code + '"')
  46216. return n
  46217. }
  46218. /*!
  46219. * unpipe
  46220. * Copyright(c) 2015 Douglas Christopher Wilson
  46221. * MIT Licensed
  46222. */
  46223. /**
  46224. * Module exports.
  46225. * @public
  46226. */
  46227. var unpipe_1 = unpipe$1;
  46228. /**
  46229. * Determine if there are Node.js pipe-like data listeners.
  46230. * @private
  46231. */
  46232. function hasPipeDataListeners(stream) {
  46233. var listeners = stream.listeners('data');
  46234. for (var i = 0; i < listeners.length; i++) {
  46235. if (listeners[i].name === 'ondata') {
  46236. return true
  46237. }
  46238. }
  46239. return false
  46240. }
  46241. /**
  46242. * Unpipe a stream from all destinations.
  46243. *
  46244. * @param {object} stream
  46245. * @public
  46246. */
  46247. function unpipe$1(stream) {
  46248. if (!stream) {
  46249. throw new TypeError('argument stream is required')
  46250. }
  46251. if (typeof stream.unpipe === 'function') {
  46252. // new-style
  46253. stream.unpipe();
  46254. return
  46255. }
  46256. // Node.js 0.8 hack
  46257. if (!hasPipeDataListeners(stream)) {
  46258. return
  46259. }
  46260. var listener;
  46261. var listeners = stream.listeners('close');
  46262. for (var i = 0; i < listeners.length; i++) {
  46263. listener = listeners[i];
  46264. if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
  46265. continue
  46266. }
  46267. // invoke the listener
  46268. listener.call(stream);
  46269. }
  46270. }
  46271. /*!
  46272. * finalhandler
  46273. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  46274. * MIT Licensed
  46275. */
  46276. /**
  46277. * Module dependencies.
  46278. * @private
  46279. */
  46280. var debug$5 = srcExports('finalhandler');
  46281. var encodeUrl = encodeurl;
  46282. var escapeHtml = escapeHtml_1;
  46283. var onFinished = onFinishedExports;
  46284. var parseUrl$1 = parseurlExports;
  46285. var statuses = statuses$1;
  46286. var unpipe = unpipe_1;
  46287. /**
  46288. * Module variables.
  46289. * @private
  46290. */
  46291. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  46292. var NEWLINE_REGEXP = /\n/g;
  46293. /* istanbul ignore next */
  46294. var defer$1 = typeof setImmediate === 'function'
  46295. ? setImmediate
  46296. : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };
  46297. var isFinished = onFinished.isFinished;
  46298. /**
  46299. * Create a minimal HTML document.
  46300. *
  46301. * @param {string} message
  46302. * @private
  46303. */
  46304. function createHtmlDocument (message) {
  46305. var body = escapeHtml(message)
  46306. .replace(NEWLINE_REGEXP, '<br>')
  46307. .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;');
  46308. return '<!DOCTYPE html>\n' +
  46309. '<html lang="en">\n' +
  46310. '<head>\n' +
  46311. '<meta charset="utf-8">\n' +
  46312. '<title>Error</title>\n' +
  46313. '</head>\n' +
  46314. '<body>\n' +
  46315. '<pre>' + body + '</pre>\n' +
  46316. '</body>\n' +
  46317. '</html>\n'
  46318. }
  46319. /**
  46320. * Module exports.
  46321. * @public
  46322. */
  46323. var finalhandler_1 = finalhandler$1;
  46324. /**
  46325. * Create a function to handle the final response.
  46326. *
  46327. * @param {Request} req
  46328. * @param {Response} res
  46329. * @param {Object} [options]
  46330. * @return {Function}
  46331. * @public
  46332. */
  46333. function finalhandler$1 (req, res, options) {
  46334. var opts = options || {};
  46335. // get environment
  46336. var env = opts.env || process.env.NODE_ENV || 'development';
  46337. // get error callback
  46338. var onerror = opts.onerror;
  46339. return function (err) {
  46340. var headers;
  46341. var msg;
  46342. var status;
  46343. // ignore 404 on in-flight response
  46344. if (!err && headersSent(res)) {
  46345. debug$5('cannot 404 after headers sent');
  46346. return
  46347. }
  46348. // unhandled error
  46349. if (err) {
  46350. // respect status code from error
  46351. status = getErrorStatusCode(err);
  46352. if (status === undefined) {
  46353. // fallback to status code on response
  46354. status = getResponseStatusCode(res);
  46355. } else {
  46356. // respect headers from error
  46357. headers = getErrorHeaders(err);
  46358. }
  46359. // get error message
  46360. msg = getErrorMessage(err, status, env);
  46361. } else {
  46362. // not found
  46363. status = 404;
  46364. msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req));
  46365. }
  46366. debug$5('default %s', status);
  46367. // schedule onerror callback
  46368. if (err && onerror) {
  46369. defer$1(onerror, err, req, res);
  46370. }
  46371. // cannot actually respond
  46372. if (headersSent(res)) {
  46373. debug$5('cannot %d after headers sent', status);
  46374. req.socket.destroy();
  46375. return
  46376. }
  46377. // send response
  46378. send(req, res, status, headers, msg);
  46379. }
  46380. }
  46381. /**
  46382. * Get headers from Error object.
  46383. *
  46384. * @param {Error} err
  46385. * @return {object}
  46386. * @private
  46387. */
  46388. function getErrorHeaders (err) {
  46389. if (!err.headers || typeof err.headers !== 'object') {
  46390. return undefined
  46391. }
  46392. var headers = Object.create(null);
  46393. var keys = Object.keys(err.headers);
  46394. for (var i = 0; i < keys.length; i++) {
  46395. var key = keys[i];
  46396. headers[key] = err.headers[key];
  46397. }
  46398. return headers
  46399. }
  46400. /**
  46401. * Get message from Error object, fallback to status message.
  46402. *
  46403. * @param {Error} err
  46404. * @param {number} status
  46405. * @param {string} env
  46406. * @return {string}
  46407. * @private
  46408. */
  46409. function getErrorMessage (err, status, env) {
  46410. var msg;
  46411. if (env !== 'production') {
  46412. // use err.stack, which typically includes err.message
  46413. msg = err.stack;
  46414. // fallback to err.toString() when possible
  46415. if (!msg && typeof err.toString === 'function') {
  46416. msg = err.toString();
  46417. }
  46418. }
  46419. return msg || statuses[status]
  46420. }
  46421. /**
  46422. * Get status code from Error object.
  46423. *
  46424. * @param {Error} err
  46425. * @return {number}
  46426. * @private
  46427. */
  46428. function getErrorStatusCode (err) {
  46429. // check err.status
  46430. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  46431. return err.status
  46432. }
  46433. // check err.statusCode
  46434. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  46435. return err.statusCode
  46436. }
  46437. return undefined
  46438. }
  46439. /**
  46440. * Get resource name for the request.
  46441. *
  46442. * This is typically just the original pathname of the request
  46443. * but will fallback to "resource" is that cannot be determined.
  46444. *
  46445. * @param {IncomingMessage} req
  46446. * @return {string}
  46447. * @private
  46448. */
  46449. function getResourceName (req) {
  46450. try {
  46451. return parseUrl$1.original(req).pathname
  46452. } catch (e) {
  46453. return 'resource'
  46454. }
  46455. }
  46456. /**
  46457. * Get status code from response.
  46458. *
  46459. * @param {OutgoingMessage} res
  46460. * @return {number}
  46461. * @private
  46462. */
  46463. function getResponseStatusCode (res) {
  46464. var status = res.statusCode;
  46465. // default status code to 500 if outside valid range
  46466. if (typeof status !== 'number' || status < 400 || status > 599) {
  46467. status = 500;
  46468. }
  46469. return status
  46470. }
  46471. /**
  46472. * Determine if the response headers have been sent.
  46473. *
  46474. * @param {object} res
  46475. * @returns {boolean}
  46476. * @private
  46477. */
  46478. function headersSent (res) {
  46479. return typeof res.headersSent !== 'boolean'
  46480. ? Boolean(res._header)
  46481. : res.headersSent
  46482. }
  46483. /**
  46484. * Send response.
  46485. *
  46486. * @param {IncomingMessage} req
  46487. * @param {OutgoingMessage} res
  46488. * @param {number} status
  46489. * @param {object} headers
  46490. * @param {string} message
  46491. * @private
  46492. */
  46493. function send (req, res, status, headers, message) {
  46494. function write () {
  46495. // response body
  46496. var body = createHtmlDocument(message);
  46497. // response status
  46498. res.statusCode = status;
  46499. res.statusMessage = statuses[status];
  46500. // response headers
  46501. setHeaders(res, headers);
  46502. // security headers
  46503. res.setHeader('Content-Security-Policy', "default-src 'none'");
  46504. res.setHeader('X-Content-Type-Options', 'nosniff');
  46505. // standard headers
  46506. res.setHeader('Content-Type', 'text/html; charset=utf-8');
  46507. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  46508. if (req.method === 'HEAD') {
  46509. res.end();
  46510. return
  46511. }
  46512. res.end(body, 'utf8');
  46513. }
  46514. if (isFinished(req)) {
  46515. write();
  46516. return
  46517. }
  46518. // unpipe everything from the request
  46519. unpipe(req);
  46520. // flush the request
  46521. onFinished(req, write);
  46522. req.resume();
  46523. }
  46524. /**
  46525. * Set response headers from an object.
  46526. *
  46527. * @param {OutgoingMessage} res
  46528. * @param {object} headers
  46529. * @private
  46530. */
  46531. function setHeaders (res, headers) {
  46532. if (!headers) {
  46533. return
  46534. }
  46535. var keys = Object.keys(headers);
  46536. for (var i = 0; i < keys.length; i++) {
  46537. var key = keys[i];
  46538. res.setHeader(key, headers[key]);
  46539. }
  46540. }
  46541. var utilsMerge = {exports: {}};
  46542. /**
  46543. * Merge object b with object a.
  46544. *
  46545. * var a = { foo: 'bar' }
  46546. * , b = { bar: 'baz' };
  46547. *
  46548. * merge(a, b);
  46549. * // => { foo: 'bar', bar: 'baz' }
  46550. *
  46551. * @param {Object} a
  46552. * @param {Object} b
  46553. * @return {Object}
  46554. * @api public
  46555. */
  46556. (function (module, exports) {
  46557. module.exports = function(a, b){
  46558. if (a && b) {
  46559. for (var key in b) {
  46560. a[key] = b[key];
  46561. }
  46562. }
  46563. return a;
  46564. };
  46565. } (utilsMerge));
  46566. var utilsMergeExports = utilsMerge.exports;
  46567. /*!
  46568. * connect
  46569. * Copyright(c) 2010 Sencha Inc.
  46570. * Copyright(c) 2011 TJ Holowaychuk
  46571. * Copyright(c) 2015 Douglas Christopher Wilson
  46572. * MIT Licensed
  46573. */
  46574. /**
  46575. * Module dependencies.
  46576. * @private
  46577. */
  46578. var debug$4 = srcExports('connect:dispatcher');
  46579. var EventEmitter$3 = require$$0$5.EventEmitter;
  46580. var finalhandler = finalhandler_1;
  46581. var http$4 = require$$1$1;
  46582. var merge = utilsMergeExports;
  46583. var parseUrl = parseurlExports;
  46584. /**
  46585. * Module exports.
  46586. * @public
  46587. */
  46588. var connect = createServer$1;
  46589. /**
  46590. * Module variables.
  46591. * @private
  46592. */
  46593. var env = process.env.NODE_ENV || 'development';
  46594. var proto = {};
  46595. /* istanbul ignore next */
  46596. var defer = typeof setImmediate === 'function'
  46597. ? setImmediate
  46598. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  46599. /**
  46600. * Create a new connect server.
  46601. *
  46602. * @return {function}
  46603. * @public
  46604. */
  46605. function createServer$1() {
  46606. function app(req, res, next){ app.handle(req, res, next); }
  46607. merge(app, proto);
  46608. merge(app, EventEmitter$3.prototype);
  46609. app.route = '/';
  46610. app.stack = [];
  46611. return app;
  46612. }
  46613. /**
  46614. * Utilize the given middleware `handle` to the given `route`,
  46615. * defaulting to _/_. This "route" is the mount-point for the
  46616. * middleware, when given a value other than _/_ the middleware
  46617. * is only effective when that segment is present in the request's
  46618. * pathname.
  46619. *
  46620. * For example if we were to mount a function at _/admin_, it would
  46621. * be invoked on _/admin_, and _/admin/settings_, however it would
  46622. * not be invoked for _/_, or _/posts_.
  46623. *
  46624. * @param {String|Function|Server} route, callback or server
  46625. * @param {Function|Server} callback or server
  46626. * @return {Server} for chaining
  46627. * @public
  46628. */
  46629. proto.use = function use(route, fn) {
  46630. var handle = fn;
  46631. var path = route;
  46632. // default route to '/'
  46633. if (typeof route !== 'string') {
  46634. handle = route;
  46635. path = '/';
  46636. }
  46637. // wrap sub-apps
  46638. if (typeof handle.handle === 'function') {
  46639. var server = handle;
  46640. server.route = path;
  46641. handle = function (req, res, next) {
  46642. server.handle(req, res, next);
  46643. };
  46644. }
  46645. // wrap vanilla http.Servers
  46646. if (handle instanceof http$4.Server) {
  46647. handle = handle.listeners('request')[0];
  46648. }
  46649. // strip trailing slash
  46650. if (path[path.length - 1] === '/') {
  46651. path = path.slice(0, -1);
  46652. }
  46653. // add the middleware
  46654. debug$4('use %s %s', path || '/', handle.name || 'anonymous');
  46655. this.stack.push({ route: path, handle: handle });
  46656. return this;
  46657. };
  46658. /**
  46659. * Handle server requests, punting them down
  46660. * the middleware stack.
  46661. *
  46662. * @private
  46663. */
  46664. proto.handle = function handle(req, res, out) {
  46665. var index = 0;
  46666. var protohost = getProtohost(req.url) || '';
  46667. var removed = '';
  46668. var slashAdded = false;
  46669. var stack = this.stack;
  46670. // final function handler
  46671. var done = out || finalhandler(req, res, {
  46672. env: env,
  46673. onerror: logerror
  46674. });
  46675. // store the original URL
  46676. req.originalUrl = req.originalUrl || req.url;
  46677. function next(err) {
  46678. if (slashAdded) {
  46679. req.url = req.url.substr(1);
  46680. slashAdded = false;
  46681. }
  46682. if (removed.length !== 0) {
  46683. req.url = protohost + removed + req.url.substr(protohost.length);
  46684. removed = '';
  46685. }
  46686. // next callback
  46687. var layer = stack[index++];
  46688. // all done
  46689. if (!layer) {
  46690. defer(done, err);
  46691. return;
  46692. }
  46693. // route data
  46694. var path = parseUrl(req).pathname || '/';
  46695. var route = layer.route;
  46696. // skip this layer if the route doesn't match
  46697. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
  46698. return next(err);
  46699. }
  46700. // skip if route match does not border "/", ".", or end
  46701. var c = path.length > route.length && path[route.length];
  46702. if (c && c !== '/' && c !== '.') {
  46703. return next(err);
  46704. }
  46705. // trim off the part of the url that matches the route
  46706. if (route.length !== 0 && route !== '/') {
  46707. removed = route;
  46708. req.url = protohost + req.url.substr(protohost.length + removed.length);
  46709. // ensure leading slash
  46710. if (!protohost && req.url[0] !== '/') {
  46711. req.url = '/' + req.url;
  46712. slashAdded = true;
  46713. }
  46714. }
  46715. // call the layer handle
  46716. call(layer.handle, route, err, req, res, next);
  46717. }
  46718. next();
  46719. };
  46720. /**
  46721. * Listen for connections.
  46722. *
  46723. * This method takes the same arguments
  46724. * as node's `http.Server#listen()`.
  46725. *
  46726. * HTTP and HTTPS:
  46727. *
  46728. * If you run your application both as HTTP
  46729. * and HTTPS you may wrap them individually,
  46730. * since your Connect "server" is really just
  46731. * a JavaScript `Function`.
  46732. *
  46733. * var connect = require('connect')
  46734. * , http = require('http')
  46735. * , https = require('https');
  46736. *
  46737. * var app = connect();
  46738. *
  46739. * http.createServer(app).listen(80);
  46740. * https.createServer(options, app).listen(443);
  46741. *
  46742. * @return {http.Server}
  46743. * @api public
  46744. */
  46745. proto.listen = function listen() {
  46746. var server = http$4.createServer(this);
  46747. return server.listen.apply(server, arguments);
  46748. };
  46749. /**
  46750. * Invoke a route handle.
  46751. * @private
  46752. */
  46753. function call(handle, route, err, req, res, next) {
  46754. var arity = handle.length;
  46755. var error = err;
  46756. var hasError = Boolean(err);
  46757. debug$4('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
  46758. try {
  46759. if (hasError && arity === 4) {
  46760. // error-handling middleware
  46761. handle(err, req, res, next);
  46762. return;
  46763. } else if (!hasError && arity < 4) {
  46764. // request-handling middleware
  46765. handle(req, res, next);
  46766. return;
  46767. }
  46768. } catch (e) {
  46769. // replace the error
  46770. error = e;
  46771. }
  46772. // continue
  46773. next(error);
  46774. }
  46775. /**
  46776. * Log error using console.error.
  46777. *
  46778. * @param {Error} err
  46779. * @private
  46780. */
  46781. function logerror(err) {
  46782. if (env !== 'test') console.error(err.stack || err.toString());
  46783. }
  46784. /**
  46785. * Get get protocol + host for a URL.
  46786. *
  46787. * @param {string} url
  46788. * @private
  46789. */
  46790. function getProtohost(url) {
  46791. if (url.length === 0 || url[0] === '/') {
  46792. return undefined;
  46793. }
  46794. var fqdnIndex = url.indexOf('://');
  46795. return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1
  46796. ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
  46797. : undefined;
  46798. }
  46799. var connect$1 = /*@__PURE__*/getDefaultExportFromCjs(connect);
  46800. var lib$1 = {exports: {}};
  46801. /*
  46802. object-assign
  46803. (c) Sindre Sorhus
  46804. @license MIT
  46805. */
  46806. /* eslint-disable no-unused-vars */
  46807. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  46808. var hasOwnProperty = Object.prototype.hasOwnProperty;
  46809. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  46810. function toObject(val) {
  46811. if (val === null || val === undefined) {
  46812. throw new TypeError('Object.assign cannot be called with null or undefined');
  46813. }
  46814. return Object(val);
  46815. }
  46816. function shouldUseNative() {
  46817. try {
  46818. if (!Object.assign) {
  46819. return false;
  46820. }
  46821. // Detect buggy property enumeration order in older V8 versions.
  46822. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  46823. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  46824. test1[5] = 'de';
  46825. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  46826. return false;
  46827. }
  46828. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  46829. var test2 = {};
  46830. for (var i = 0; i < 10; i++) {
  46831. test2['_' + String.fromCharCode(i)] = i;
  46832. }
  46833. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  46834. return test2[n];
  46835. });
  46836. if (order2.join('') !== '0123456789') {
  46837. return false;
  46838. }
  46839. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  46840. var test3 = {};
  46841. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  46842. test3[letter] = letter;
  46843. });
  46844. if (Object.keys(Object.assign({}, test3)).join('') !==
  46845. 'abcdefghijklmnopqrst') {
  46846. return false;
  46847. }
  46848. return true;
  46849. } catch (err) {
  46850. // We don't expect any of the above to throw, but better to be safe.
  46851. return false;
  46852. }
  46853. }
  46854. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  46855. var from;
  46856. var to = toObject(target);
  46857. var symbols;
  46858. for (var s = 1; s < arguments.length; s++) {
  46859. from = Object(arguments[s]);
  46860. for (var key in from) {
  46861. if (hasOwnProperty.call(from, key)) {
  46862. to[key] = from[key];
  46863. }
  46864. }
  46865. if (getOwnPropertySymbols) {
  46866. symbols = getOwnPropertySymbols(from);
  46867. for (var i = 0; i < symbols.length; i++) {
  46868. if (propIsEnumerable.call(from, symbols[i])) {
  46869. to[symbols[i]] = from[symbols[i]];
  46870. }
  46871. }
  46872. }
  46873. }
  46874. return to;
  46875. };
  46876. var vary$1 = {exports: {}};
  46877. /*!
  46878. * vary
  46879. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  46880. * MIT Licensed
  46881. */
  46882. /**
  46883. * Module exports.
  46884. */
  46885. vary$1.exports = vary;
  46886. vary$1.exports.append = append;
  46887. /**
  46888. * RegExp to match field-name in RFC 7230 sec 3.2
  46889. *
  46890. * field-name = token
  46891. * token = 1*tchar
  46892. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  46893. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  46894. * / DIGIT / ALPHA
  46895. * ; any VCHAR, except delimiters
  46896. */
  46897. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  46898. /**
  46899. * Append a field to a vary header.
  46900. *
  46901. * @param {String} header
  46902. * @param {String|Array} field
  46903. * @return {String}
  46904. * @public
  46905. */
  46906. function append (header, field) {
  46907. if (typeof header !== 'string') {
  46908. throw new TypeError('header argument is required')
  46909. }
  46910. if (!field) {
  46911. throw new TypeError('field argument is required')
  46912. }
  46913. // get fields array
  46914. var fields = !Array.isArray(field)
  46915. ? parse$6(String(field))
  46916. : field;
  46917. // assert on invalid field names
  46918. for (var j = 0; j < fields.length; j++) {
  46919. if (!FIELD_NAME_REGEXP.test(fields[j])) {
  46920. throw new TypeError('field argument contains an invalid header name')
  46921. }
  46922. }
  46923. // existing, unspecified vary
  46924. if (header === '*') {
  46925. return header
  46926. }
  46927. // enumerate current values
  46928. var val = header;
  46929. var vals = parse$6(header.toLowerCase());
  46930. // unspecified vary
  46931. if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
  46932. return '*'
  46933. }
  46934. for (var i = 0; i < fields.length; i++) {
  46935. var fld = fields[i].toLowerCase();
  46936. // append value (case-preserving)
  46937. if (vals.indexOf(fld) === -1) {
  46938. vals.push(fld);
  46939. val = val
  46940. ? val + ', ' + fields[i]
  46941. : fields[i];
  46942. }
  46943. }
  46944. return val
  46945. }
  46946. /**
  46947. * Parse a vary header into an array.
  46948. *
  46949. * @param {String} header
  46950. * @return {Array}
  46951. * @private
  46952. */
  46953. function parse$6 (header) {
  46954. var end = 0;
  46955. var list = [];
  46956. var start = 0;
  46957. // gather tokens
  46958. for (var i = 0, len = header.length; i < len; i++) {
  46959. switch (header.charCodeAt(i)) {
  46960. case 0x20: /* */
  46961. if (start === end) {
  46962. start = end = i + 1;
  46963. }
  46964. break
  46965. case 0x2c: /* , */
  46966. list.push(header.substring(start, end));
  46967. start = end = i + 1;
  46968. break
  46969. default:
  46970. end = i + 1;
  46971. break
  46972. }
  46973. }
  46974. // final token
  46975. list.push(header.substring(start, end));
  46976. return list
  46977. }
  46978. /**
  46979. * Mark that a request is varied on a header field.
  46980. *
  46981. * @param {Object} res
  46982. * @param {String|Array} field
  46983. * @public
  46984. */
  46985. function vary (res, field) {
  46986. if (!res || !res.getHeader || !res.setHeader) {
  46987. // quack quack
  46988. throw new TypeError('res argument is required')
  46989. }
  46990. // get existing header
  46991. var val = res.getHeader('Vary') || '';
  46992. var header = Array.isArray(val)
  46993. ? val.join(', ')
  46994. : String(val);
  46995. // set new header
  46996. if ((val = append(header, field))) {
  46997. res.setHeader('Vary', val);
  46998. }
  46999. }
  47000. var varyExports = vary$1.exports;
  47001. (function () {
  47002. var assign = objectAssign;
  47003. var vary = varyExports;
  47004. var defaults = {
  47005. origin: '*',
  47006. methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  47007. preflightContinue: false,
  47008. optionsSuccessStatus: 204
  47009. };
  47010. function isString(s) {
  47011. return typeof s === 'string' || s instanceof String;
  47012. }
  47013. function isOriginAllowed(origin, allowedOrigin) {
  47014. if (Array.isArray(allowedOrigin)) {
  47015. for (var i = 0; i < allowedOrigin.length; ++i) {
  47016. if (isOriginAllowed(origin, allowedOrigin[i])) {
  47017. return true;
  47018. }
  47019. }
  47020. return false;
  47021. } else if (isString(allowedOrigin)) {
  47022. return origin === allowedOrigin;
  47023. } else if (allowedOrigin instanceof RegExp) {
  47024. return allowedOrigin.test(origin);
  47025. } else {
  47026. return !!allowedOrigin;
  47027. }
  47028. }
  47029. function configureOrigin(options, req) {
  47030. var requestOrigin = req.headers.origin,
  47031. headers = [],
  47032. isAllowed;
  47033. if (!options.origin || options.origin === '*') {
  47034. // allow any origin
  47035. headers.push([{
  47036. key: 'Access-Control-Allow-Origin',
  47037. value: '*'
  47038. }]);
  47039. } else if (isString(options.origin)) {
  47040. // fixed origin
  47041. headers.push([{
  47042. key: 'Access-Control-Allow-Origin',
  47043. value: options.origin
  47044. }]);
  47045. headers.push([{
  47046. key: 'Vary',
  47047. value: 'Origin'
  47048. }]);
  47049. } else {
  47050. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  47051. // reflect origin
  47052. headers.push([{
  47053. key: 'Access-Control-Allow-Origin',
  47054. value: isAllowed ? requestOrigin : false
  47055. }]);
  47056. headers.push([{
  47057. key: 'Vary',
  47058. value: 'Origin'
  47059. }]);
  47060. }
  47061. return headers;
  47062. }
  47063. function configureMethods(options) {
  47064. var methods = options.methods;
  47065. if (methods.join) {
  47066. methods = options.methods.join(','); // .methods is an array, so turn it into a string
  47067. }
  47068. return {
  47069. key: 'Access-Control-Allow-Methods',
  47070. value: methods
  47071. };
  47072. }
  47073. function configureCredentials(options) {
  47074. if (options.credentials === true) {
  47075. return {
  47076. key: 'Access-Control-Allow-Credentials',
  47077. value: 'true'
  47078. };
  47079. }
  47080. return null;
  47081. }
  47082. function configureAllowedHeaders(options, req) {
  47083. var allowedHeaders = options.allowedHeaders || options.headers;
  47084. var headers = [];
  47085. if (!allowedHeaders) {
  47086. allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
  47087. headers.push([{
  47088. key: 'Vary',
  47089. value: 'Access-Control-Request-Headers'
  47090. }]);
  47091. } else if (allowedHeaders.join) {
  47092. allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
  47093. }
  47094. if (allowedHeaders && allowedHeaders.length) {
  47095. headers.push([{
  47096. key: 'Access-Control-Allow-Headers',
  47097. value: allowedHeaders
  47098. }]);
  47099. }
  47100. return headers;
  47101. }
  47102. function configureExposedHeaders(options) {
  47103. var headers = options.exposedHeaders;
  47104. if (!headers) {
  47105. return null;
  47106. } else if (headers.join) {
  47107. headers = headers.join(','); // .headers is an array, so turn it into a string
  47108. }
  47109. if (headers && headers.length) {
  47110. return {
  47111. key: 'Access-Control-Expose-Headers',
  47112. value: headers
  47113. };
  47114. }
  47115. return null;
  47116. }
  47117. function configureMaxAge(options) {
  47118. var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
  47119. if (maxAge && maxAge.length) {
  47120. return {
  47121. key: 'Access-Control-Max-Age',
  47122. value: maxAge
  47123. };
  47124. }
  47125. return null;
  47126. }
  47127. function applyHeaders(headers, res) {
  47128. for (var i = 0, n = headers.length; i < n; i++) {
  47129. var header = headers[i];
  47130. if (header) {
  47131. if (Array.isArray(header)) {
  47132. applyHeaders(header, res);
  47133. } else if (header.key === 'Vary' && header.value) {
  47134. vary(res, header.value);
  47135. } else if (header.value) {
  47136. res.setHeader(header.key, header.value);
  47137. }
  47138. }
  47139. }
  47140. }
  47141. function cors(options, req, res, next) {
  47142. var headers = [],
  47143. method = req.method && req.method.toUpperCase && req.method.toUpperCase();
  47144. if (method === 'OPTIONS') {
  47145. // preflight
  47146. headers.push(configureOrigin(options, req));
  47147. headers.push(configureCredentials(options));
  47148. headers.push(configureMethods(options));
  47149. headers.push(configureAllowedHeaders(options, req));
  47150. headers.push(configureMaxAge(options));
  47151. headers.push(configureExposedHeaders(options));
  47152. applyHeaders(headers, res);
  47153. if (options.preflightContinue) {
  47154. next();
  47155. } else {
  47156. // Safari (and potentially other browsers) need content-length 0,
  47157. // for 204 or they just hang waiting for a body
  47158. res.statusCode = options.optionsSuccessStatus;
  47159. res.setHeader('Content-Length', '0');
  47160. res.end();
  47161. }
  47162. } else {
  47163. // actual response
  47164. headers.push(configureOrigin(options, req));
  47165. headers.push(configureCredentials(options));
  47166. headers.push(configureExposedHeaders(options));
  47167. applyHeaders(headers, res);
  47168. next();
  47169. }
  47170. }
  47171. function middlewareWrapper(o) {
  47172. // if options are static (either via defaults or custom options passed in), wrap in a function
  47173. var optionsCallback = null;
  47174. if (typeof o === 'function') {
  47175. optionsCallback = o;
  47176. } else {
  47177. optionsCallback = function (req, cb) {
  47178. cb(null, o);
  47179. };
  47180. }
  47181. return function corsMiddleware(req, res, next) {
  47182. optionsCallback(req, function (err, options) {
  47183. if (err) {
  47184. next(err);
  47185. } else {
  47186. var corsOptions = assign({}, defaults, options);
  47187. var originCallback = null;
  47188. if (corsOptions.origin && typeof corsOptions.origin === 'function') {
  47189. originCallback = corsOptions.origin;
  47190. } else if (corsOptions.origin) {
  47191. originCallback = function (origin, cb) {
  47192. cb(null, corsOptions.origin);
  47193. };
  47194. }
  47195. if (originCallback) {
  47196. originCallback(req.headers.origin, function (err2, origin) {
  47197. if (err2 || !origin) {
  47198. next(err2);
  47199. } else {
  47200. corsOptions.origin = origin;
  47201. cors(corsOptions, req, res, next);
  47202. }
  47203. });
  47204. } else {
  47205. next();
  47206. }
  47207. }
  47208. });
  47209. };
  47210. }
  47211. // can pass either an options hash, an options delegate, or nothing
  47212. lib$1.exports = middlewareWrapper;
  47213. }());
  47214. var libExports$1 = lib$1.exports;
  47215. var corsMiddleware = /*@__PURE__*/getDefaultExportFromCjs(libExports$1);
  47216. var chokidar = {};
  47217. const fs$8 = require$$0__default;
  47218. const { Readable } = require$$0$7;
  47219. const sysPath$3 = require$$0$4;
  47220. const { promisify: promisify$3 } = require$$0$6;
  47221. const picomatch$1 = picomatch$3;
  47222. const readdir$1 = promisify$3(fs$8.readdir);
  47223. const stat$3 = promisify$3(fs$8.stat);
  47224. const lstat$2 = promisify$3(fs$8.lstat);
  47225. const realpath$1 = promisify$3(fs$8.realpath);
  47226. /**
  47227. * @typedef {Object} EntryInfo
  47228. * @property {String} path
  47229. * @property {String} fullPath
  47230. * @property {fs.Stats=} stats
  47231. * @property {fs.Dirent=} dirent
  47232. * @property {String} basename
  47233. */
  47234. const BANG$2 = '!';
  47235. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  47236. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  47237. const FILE_TYPE = 'files';
  47238. const DIR_TYPE = 'directories';
  47239. const FILE_DIR_TYPE = 'files_directories';
  47240. const EVERYTHING_TYPE = 'all';
  47241. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  47242. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  47243. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  47244. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  47245. const normalizeFilter = filter => {
  47246. if (filter === undefined) return;
  47247. if (typeof filter === 'function') return filter;
  47248. if (typeof filter === 'string') {
  47249. const glob = picomatch$1(filter.trim());
  47250. return entry => glob(entry.basename);
  47251. }
  47252. if (Array.isArray(filter)) {
  47253. const positive = [];
  47254. const negative = [];
  47255. for (const item of filter) {
  47256. const trimmed = item.trim();
  47257. if (trimmed.charAt(0) === BANG$2) {
  47258. negative.push(picomatch$1(trimmed.slice(1)));
  47259. } else {
  47260. positive.push(picomatch$1(trimmed));
  47261. }
  47262. }
  47263. if (negative.length > 0) {
  47264. if (positive.length > 0) {
  47265. return entry =>
  47266. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  47267. }
  47268. return entry => !negative.some(f => f(entry.basename));
  47269. }
  47270. return entry => positive.some(f => f(entry.basename));
  47271. }
  47272. };
  47273. class ReaddirpStream extends Readable {
  47274. static get defaultOptions() {
  47275. return {
  47276. root: '.',
  47277. /* eslint-disable no-unused-vars */
  47278. fileFilter: (path) => true,
  47279. directoryFilter: (path) => true,
  47280. /* eslint-enable no-unused-vars */
  47281. type: FILE_TYPE,
  47282. lstat: false,
  47283. depth: 2147483648,
  47284. alwaysStat: false
  47285. };
  47286. }
  47287. constructor(options = {}) {
  47288. super({
  47289. objectMode: true,
  47290. autoDestroy: true,
  47291. highWaterMark: options.highWaterMark || 4096
  47292. });
  47293. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  47294. const { root, type } = opts;
  47295. this._fileFilter = normalizeFilter(opts.fileFilter);
  47296. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  47297. const statMethod = opts.lstat ? lstat$2 : stat$3;
  47298. // Use bigint stats if it's windows and stat() supports options (node 10+).
  47299. if (wantBigintFsStats) {
  47300. this._stat = path => statMethod(path, { bigint: true });
  47301. } else {
  47302. this._stat = statMethod;
  47303. }
  47304. this._maxDepth = opts.depth;
  47305. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  47306. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  47307. this._wantsEverything = type === EVERYTHING_TYPE;
  47308. this._root = sysPath$3.resolve(root);
  47309. this._isDirent = ('Dirent' in fs$8) && !opts.alwaysStat;
  47310. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  47311. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  47312. // Launch stream with one parent, the root dir.
  47313. this.parents = [this._exploreDir(root, 1)];
  47314. this.reading = false;
  47315. this.parent = undefined;
  47316. }
  47317. async _read(batch) {
  47318. if (this.reading) return;
  47319. this.reading = true;
  47320. try {
  47321. while (!this.destroyed && batch > 0) {
  47322. const { path, depth, files = [] } = this.parent || {};
  47323. if (files.length > 0) {
  47324. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  47325. for (const entry of await Promise.all(slice)) {
  47326. if (this.destroyed) return;
  47327. const entryType = await this._getEntryType(entry);
  47328. if (entryType === 'directory' && this._directoryFilter(entry)) {
  47329. if (depth <= this._maxDepth) {
  47330. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  47331. }
  47332. if (this._wantsDir) {
  47333. this.push(entry);
  47334. batch--;
  47335. }
  47336. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  47337. if (this._wantsFile) {
  47338. this.push(entry);
  47339. batch--;
  47340. }
  47341. }
  47342. }
  47343. } else {
  47344. const parent = this.parents.pop();
  47345. if (!parent) {
  47346. this.push(null);
  47347. break;
  47348. }
  47349. this.parent = await parent;
  47350. if (this.destroyed) return;
  47351. }
  47352. }
  47353. } catch (error) {
  47354. this.destroy(error);
  47355. } finally {
  47356. this.reading = false;
  47357. }
  47358. }
  47359. async _exploreDir(path, depth) {
  47360. let files;
  47361. try {
  47362. files = await readdir$1(path, this._rdOptions);
  47363. } catch (error) {
  47364. this._onError(error);
  47365. }
  47366. return { files, depth, path };
  47367. }
  47368. async _formatEntry(dirent, path) {
  47369. let entry;
  47370. try {
  47371. const basename = this._isDirent ? dirent.name : dirent;
  47372. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  47373. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  47374. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  47375. } catch (err) {
  47376. this._onError(err);
  47377. }
  47378. return entry;
  47379. }
  47380. _onError(err) {
  47381. if (isNormalFlowError(err) && !this.destroyed) {
  47382. this.emit('warn', err);
  47383. } else {
  47384. this.destroy(err);
  47385. }
  47386. }
  47387. async _getEntryType(entry) {
  47388. // entry may be undefined, because a warning or an error were emitted
  47389. // and the statsProp is undefined
  47390. const stats = entry && entry[this._statsProp];
  47391. if (!stats) {
  47392. return;
  47393. }
  47394. if (stats.isFile()) {
  47395. return 'file';
  47396. }
  47397. if (stats.isDirectory()) {
  47398. return 'directory';
  47399. }
  47400. if (stats && stats.isSymbolicLink()) {
  47401. const full = entry.fullPath;
  47402. try {
  47403. const entryRealPath = await realpath$1(full);
  47404. const entryRealPathStats = await lstat$2(entryRealPath);
  47405. if (entryRealPathStats.isFile()) {
  47406. return 'file';
  47407. }
  47408. if (entryRealPathStats.isDirectory()) {
  47409. const len = entryRealPath.length;
  47410. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  47411. const recursiveError = new Error(
  47412. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  47413. );
  47414. recursiveError.code = RECURSIVE_ERROR_CODE;
  47415. return this._onError(recursiveError);
  47416. }
  47417. return 'directory';
  47418. }
  47419. } catch (error) {
  47420. this._onError(error);
  47421. }
  47422. }
  47423. }
  47424. _includeAsFile(entry) {
  47425. const stats = entry && entry[this._statsProp];
  47426. return stats && this._wantsEverything && !stats.isDirectory();
  47427. }
  47428. }
  47429. /**
  47430. * @typedef {Object} ReaddirpArguments
  47431. * @property {Function=} fileFilter
  47432. * @property {Function=} directoryFilter
  47433. * @property {String=} type
  47434. * @property {Number=} depth
  47435. * @property {String=} root
  47436. * @property {Boolean=} lstat
  47437. * @property {Boolean=} bigint
  47438. */
  47439. /**
  47440. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  47441. * @param {String} root Root directory
  47442. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  47443. */
  47444. const readdirp$1 = (root, options = {}) => {
  47445. let type = options.entryType || options.type;
  47446. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  47447. if (type) options.type = type;
  47448. if (!root) {
  47449. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  47450. } else if (typeof root !== 'string') {
  47451. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  47452. } else if (type && !ALL_TYPES.includes(type)) {
  47453. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  47454. }
  47455. options.root = root;
  47456. return new ReaddirpStream(options);
  47457. };
  47458. const readdirpPromise = (root, options = {}) => {
  47459. return new Promise((resolve, reject) => {
  47460. const files = [];
  47461. readdirp$1(root, options)
  47462. .on('data', entry => files.push(entry))
  47463. .on('end', () => resolve(files))
  47464. .on('error', error => reject(error));
  47465. });
  47466. };
  47467. readdirp$1.promise = readdirpPromise;
  47468. readdirp$1.ReaddirpStream = ReaddirpStream;
  47469. readdirp$1.default = readdirp$1;
  47470. var readdirp_1 = readdirp$1;
  47471. var anymatch$2 = {exports: {}};
  47472. /*!
  47473. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  47474. *
  47475. * Copyright (c) 2014-2018, Jon Schlinkert.
  47476. * Released under the MIT License.
  47477. */
  47478. var normalizePath$2 = function(path, stripTrailing) {
  47479. if (typeof path !== 'string') {
  47480. throw new TypeError('expected path to be a string');
  47481. }
  47482. if (path === '\\' || path === '/') return '/';
  47483. var len = path.length;
  47484. if (len <= 1) return path;
  47485. // ensure that win32 namespaces has two leading slashes, so that the path is
  47486. // handled properly by the win32 version of path.parse() after being normalized
  47487. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  47488. var prefix = '';
  47489. if (len > 4 && path[3] === '\\') {
  47490. var ch = path[2];
  47491. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  47492. path = path.slice(2);
  47493. prefix = '//';
  47494. }
  47495. }
  47496. var segs = path.split(/[/\\]+/);
  47497. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  47498. segs.pop();
  47499. }
  47500. return prefix + segs.join('/');
  47501. };
  47502. var anymatch_1 = anymatch$2.exports;
  47503. Object.defineProperty(anymatch_1, "__esModule", { value: true });
  47504. const picomatch = picomatch$3;
  47505. const normalizePath$1 = normalizePath$2;
  47506. /**
  47507. * @typedef {(testString: string) => boolean} AnymatchFn
  47508. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  47509. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  47510. */
  47511. const BANG$1 = '!';
  47512. const DEFAULT_OPTIONS = {returnIndex: false};
  47513. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  47514. /**
  47515. * @param {AnymatchPattern} matcher
  47516. * @param {object} options
  47517. * @returns {AnymatchFn}
  47518. */
  47519. const createPattern = (matcher, options) => {
  47520. if (typeof matcher === 'function') {
  47521. return matcher;
  47522. }
  47523. if (typeof matcher === 'string') {
  47524. const glob = picomatch(matcher, options);
  47525. return (string) => matcher === string || glob(string);
  47526. }
  47527. if (matcher instanceof RegExp) {
  47528. return (string) => matcher.test(string);
  47529. }
  47530. return (string) => false;
  47531. };
  47532. /**
  47533. * @param {Array<Function>} patterns
  47534. * @param {Array<Function>} negPatterns
  47535. * @param {String|Array} args
  47536. * @param {Boolean} returnIndex
  47537. * @returns {boolean|number}
  47538. */
  47539. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  47540. const isList = Array.isArray(args);
  47541. const _path = isList ? args[0] : args;
  47542. if (!isList && typeof _path !== 'string') {
  47543. throw new TypeError('anymatch: second argument must be a string: got ' +
  47544. Object.prototype.toString.call(_path))
  47545. }
  47546. const path = normalizePath$1(_path);
  47547. for (let index = 0; index < negPatterns.length; index++) {
  47548. const nglob = negPatterns[index];
  47549. if (nglob(path)) {
  47550. return returnIndex ? -1 : false;
  47551. }
  47552. }
  47553. const applied = isList && [path].concat(args.slice(1));
  47554. for (let index = 0; index < patterns.length; index++) {
  47555. const pattern = patterns[index];
  47556. if (isList ? pattern(...applied) : pattern(path)) {
  47557. return returnIndex ? index : true;
  47558. }
  47559. }
  47560. return returnIndex ? -1 : false;
  47561. };
  47562. /**
  47563. * @param {AnymatchMatcher} matchers
  47564. * @param {Array|string} testString
  47565. * @param {object} options
  47566. * @returns {boolean|number|Function}
  47567. */
  47568. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  47569. if (matchers == null) {
  47570. throw new TypeError('anymatch: specify first argument');
  47571. }
  47572. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  47573. const returnIndex = opts.returnIndex || false;
  47574. // Early cache for matchers.
  47575. const mtchers = arrify$1(matchers);
  47576. const negatedGlobs = mtchers
  47577. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  47578. .map(item => item.slice(1))
  47579. .map(item => picomatch(item, opts));
  47580. const patterns = mtchers
  47581. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  47582. .map(matcher => createPattern(matcher, opts));
  47583. if (testString == null) {
  47584. return (testString, ri = false) => {
  47585. const returnIndex = typeof ri === 'boolean' ? ri : false;
  47586. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  47587. }
  47588. }
  47589. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  47590. };
  47591. anymatch$1.default = anymatch$1;
  47592. anymatch$2.exports = anymatch$1;
  47593. var anymatchExports = anymatch$2.exports;
  47594. var require$$0 = [
  47595. "3dm",
  47596. "3ds",
  47597. "3g2",
  47598. "3gp",
  47599. "7z",
  47600. "a",
  47601. "aac",
  47602. "adp",
  47603. "ai",
  47604. "aif",
  47605. "aiff",
  47606. "alz",
  47607. "ape",
  47608. "apk",
  47609. "appimage",
  47610. "ar",
  47611. "arj",
  47612. "asf",
  47613. "au",
  47614. "avi",
  47615. "bak",
  47616. "baml",
  47617. "bh",
  47618. "bin",
  47619. "bk",
  47620. "bmp",
  47621. "btif",
  47622. "bz2",
  47623. "bzip2",
  47624. "cab",
  47625. "caf",
  47626. "cgm",
  47627. "class",
  47628. "cmx",
  47629. "cpio",
  47630. "cr2",
  47631. "cur",
  47632. "dat",
  47633. "dcm",
  47634. "deb",
  47635. "dex",
  47636. "djvu",
  47637. "dll",
  47638. "dmg",
  47639. "dng",
  47640. "doc",
  47641. "docm",
  47642. "docx",
  47643. "dot",
  47644. "dotm",
  47645. "dra",
  47646. "DS_Store",
  47647. "dsk",
  47648. "dts",
  47649. "dtshd",
  47650. "dvb",
  47651. "dwg",
  47652. "dxf",
  47653. "ecelp4800",
  47654. "ecelp7470",
  47655. "ecelp9600",
  47656. "egg",
  47657. "eol",
  47658. "eot",
  47659. "epub",
  47660. "exe",
  47661. "f4v",
  47662. "fbs",
  47663. "fh",
  47664. "fla",
  47665. "flac",
  47666. "flatpak",
  47667. "fli",
  47668. "flv",
  47669. "fpx",
  47670. "fst",
  47671. "fvt",
  47672. "g3",
  47673. "gh",
  47674. "gif",
  47675. "graffle",
  47676. "gz",
  47677. "gzip",
  47678. "h261",
  47679. "h263",
  47680. "h264",
  47681. "icns",
  47682. "ico",
  47683. "ief",
  47684. "img",
  47685. "ipa",
  47686. "iso",
  47687. "jar",
  47688. "jpeg",
  47689. "jpg",
  47690. "jpgv",
  47691. "jpm",
  47692. "jxr",
  47693. "key",
  47694. "ktx",
  47695. "lha",
  47696. "lib",
  47697. "lvp",
  47698. "lz",
  47699. "lzh",
  47700. "lzma",
  47701. "lzo",
  47702. "m3u",
  47703. "m4a",
  47704. "m4v",
  47705. "mar",
  47706. "mdi",
  47707. "mht",
  47708. "mid",
  47709. "midi",
  47710. "mj2",
  47711. "mka",
  47712. "mkv",
  47713. "mmr",
  47714. "mng",
  47715. "mobi",
  47716. "mov",
  47717. "movie",
  47718. "mp3",
  47719. "mp4",
  47720. "mp4a",
  47721. "mpeg",
  47722. "mpg",
  47723. "mpga",
  47724. "mxu",
  47725. "nef",
  47726. "npx",
  47727. "numbers",
  47728. "nupkg",
  47729. "o",
  47730. "odp",
  47731. "ods",
  47732. "odt",
  47733. "oga",
  47734. "ogg",
  47735. "ogv",
  47736. "otf",
  47737. "ott",
  47738. "pages",
  47739. "pbm",
  47740. "pcx",
  47741. "pdb",
  47742. "pdf",
  47743. "pea",
  47744. "pgm",
  47745. "pic",
  47746. "png",
  47747. "pnm",
  47748. "pot",
  47749. "potm",
  47750. "potx",
  47751. "ppa",
  47752. "ppam",
  47753. "ppm",
  47754. "pps",
  47755. "ppsm",
  47756. "ppsx",
  47757. "ppt",
  47758. "pptm",
  47759. "pptx",
  47760. "psd",
  47761. "pya",
  47762. "pyc",
  47763. "pyo",
  47764. "pyv",
  47765. "qt",
  47766. "rar",
  47767. "ras",
  47768. "raw",
  47769. "resources",
  47770. "rgb",
  47771. "rip",
  47772. "rlc",
  47773. "rmf",
  47774. "rmvb",
  47775. "rpm",
  47776. "rtf",
  47777. "rz",
  47778. "s3m",
  47779. "s7z",
  47780. "scpt",
  47781. "sgi",
  47782. "shar",
  47783. "snap",
  47784. "sil",
  47785. "sketch",
  47786. "slk",
  47787. "smv",
  47788. "snk",
  47789. "so",
  47790. "stl",
  47791. "suo",
  47792. "sub",
  47793. "swf",
  47794. "tar",
  47795. "tbz",
  47796. "tbz2",
  47797. "tga",
  47798. "tgz",
  47799. "thmx",
  47800. "tif",
  47801. "tiff",
  47802. "tlz",
  47803. "ttc",
  47804. "ttf",
  47805. "txz",
  47806. "udf",
  47807. "uvh",
  47808. "uvi",
  47809. "uvm",
  47810. "uvp",
  47811. "uvs",
  47812. "uvu",
  47813. "viv",
  47814. "vob",
  47815. "war",
  47816. "wav",
  47817. "wax",
  47818. "wbmp",
  47819. "wdp",
  47820. "weba",
  47821. "webm",
  47822. "webp",
  47823. "whl",
  47824. "wim",
  47825. "wm",
  47826. "wma",
  47827. "wmv",
  47828. "wmx",
  47829. "woff",
  47830. "woff2",
  47831. "wrm",
  47832. "wvx",
  47833. "xbm",
  47834. "xif",
  47835. "xla",
  47836. "xlam",
  47837. "xls",
  47838. "xlsb",
  47839. "xlsm",
  47840. "xlsx",
  47841. "xlt",
  47842. "xltm",
  47843. "xltx",
  47844. "xm",
  47845. "xmind",
  47846. "xpi",
  47847. "xpm",
  47848. "xwd",
  47849. "xz",
  47850. "z",
  47851. "zip",
  47852. "zipx"
  47853. ];
  47854. var binaryExtensions$1 = require$$0;
  47855. const path$8 = require$$0$4;
  47856. const binaryExtensions = binaryExtensions$1;
  47857. const extensions = new Set(binaryExtensions);
  47858. var isBinaryPath$1 = filePath => extensions.has(path$8.extname(filePath).slice(1).toLowerCase());
  47859. var constants$1 = {};
  47860. (function (exports) {
  47861. const {sep} = require$$0$4;
  47862. const {platform} = process;
  47863. const os = require$$2;
  47864. exports.EV_ALL = 'all';
  47865. exports.EV_READY = 'ready';
  47866. exports.EV_ADD = 'add';
  47867. exports.EV_CHANGE = 'change';
  47868. exports.EV_ADD_DIR = 'addDir';
  47869. exports.EV_UNLINK = 'unlink';
  47870. exports.EV_UNLINK_DIR = 'unlinkDir';
  47871. exports.EV_RAW = 'raw';
  47872. exports.EV_ERROR = 'error';
  47873. exports.STR_DATA = 'data';
  47874. exports.STR_END = 'end';
  47875. exports.STR_CLOSE = 'close';
  47876. exports.FSEVENT_CREATED = 'created';
  47877. exports.FSEVENT_MODIFIED = 'modified';
  47878. exports.FSEVENT_DELETED = 'deleted';
  47879. exports.FSEVENT_MOVED = 'moved';
  47880. exports.FSEVENT_CLONED = 'cloned';
  47881. exports.FSEVENT_UNKNOWN = 'unknown';
  47882. exports.FSEVENT_TYPE_FILE = 'file';
  47883. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  47884. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  47885. exports.KEY_LISTENERS = 'listeners';
  47886. exports.KEY_ERR = 'errHandlers';
  47887. exports.KEY_RAW = 'rawEmitters';
  47888. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  47889. exports.DOT_SLASH = `.${sep}`;
  47890. exports.BACK_SLASH_RE = /\\/g;
  47891. exports.DOUBLE_SLASH_RE = /\/\//;
  47892. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  47893. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  47894. exports.REPLACER_RE = /^\.[/\\]/;
  47895. exports.SLASH = '/';
  47896. exports.SLASH_SLASH = '//';
  47897. exports.BRACE_START = '{';
  47898. exports.BANG = '!';
  47899. exports.ONE_DOT = '.';
  47900. exports.TWO_DOTS = '..';
  47901. exports.STAR = '*';
  47902. exports.GLOBSTAR = '**';
  47903. exports.ROOT_GLOBSTAR = '/**/*';
  47904. exports.SLASH_GLOBSTAR = '/**';
  47905. exports.DIR_SUFFIX = 'Dir';
  47906. exports.ANYMATCH_OPTS = {dot: true};
  47907. exports.STRING_TYPE = 'string';
  47908. exports.FUNCTION_TYPE = 'function';
  47909. exports.EMPTY_STR = '';
  47910. exports.EMPTY_FN = () => {};
  47911. exports.IDENTITY_FN = val => val;
  47912. exports.isWindows = platform === 'win32';
  47913. exports.isMacos = platform === 'darwin';
  47914. exports.isLinux = platform === 'linux';
  47915. exports.isIBMi = os.type() === 'OS400';
  47916. } (constants$1));
  47917. const fs$7 = require$$0__default;
  47918. const sysPath$2 = require$$0$4;
  47919. const { promisify: promisify$2 } = require$$0$6;
  47920. const isBinaryPath = isBinaryPath$1;
  47921. const {
  47922. isWindows: isWindows$2,
  47923. isLinux,
  47924. EMPTY_FN: EMPTY_FN$2,
  47925. EMPTY_STR: EMPTY_STR$1,
  47926. KEY_LISTENERS,
  47927. KEY_ERR,
  47928. KEY_RAW,
  47929. HANDLER_KEYS,
  47930. EV_CHANGE: EV_CHANGE$2,
  47931. EV_ADD: EV_ADD$2,
  47932. EV_ADD_DIR: EV_ADD_DIR$2,
  47933. EV_ERROR: EV_ERROR$2,
  47934. STR_DATA: STR_DATA$1,
  47935. STR_END: STR_END$2,
  47936. BRACE_START: BRACE_START$1,
  47937. STAR
  47938. } = constants$1;
  47939. const THROTTLE_MODE_WATCH = 'watch';
  47940. const open$2 = promisify$2(fs$7.open);
  47941. const stat$2 = promisify$2(fs$7.stat);
  47942. const lstat$1 = promisify$2(fs$7.lstat);
  47943. const close = promisify$2(fs$7.close);
  47944. const fsrealpath = promisify$2(fs$7.realpath);
  47945. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  47946. // TODO: emit errors properly. Example: EMFILE on Macos.
  47947. const foreach = (val, fn) => {
  47948. if (val instanceof Set) {
  47949. val.forEach(fn);
  47950. } else {
  47951. fn(val);
  47952. }
  47953. };
  47954. const addAndConvert = (main, prop, item) => {
  47955. let container = main[prop];
  47956. if (!(container instanceof Set)) {
  47957. main[prop] = container = new Set([container]);
  47958. }
  47959. container.add(item);
  47960. };
  47961. const clearItem = cont => key => {
  47962. const set = cont[key];
  47963. if (set instanceof Set) {
  47964. set.clear();
  47965. } else {
  47966. delete cont[key];
  47967. }
  47968. };
  47969. const delFromSet = (main, prop, item) => {
  47970. const container = main[prop];
  47971. if (container instanceof Set) {
  47972. container.delete(item);
  47973. } else if (container === item) {
  47974. delete main[prop];
  47975. }
  47976. };
  47977. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  47978. /**
  47979. * @typedef {String} Path
  47980. */
  47981. // fs_watch helpers
  47982. // object to hold per-process fs_watch instances
  47983. // (may be shared across chokidar FSWatcher instances)
  47984. /**
  47985. * @typedef {Object} FsWatchContainer
  47986. * @property {Set} listeners
  47987. * @property {Set} errHandlers
  47988. * @property {Set} rawEmitters
  47989. * @property {fs.FSWatcher=} watcher
  47990. * @property {Boolean=} watcherUnusable
  47991. */
  47992. /**
  47993. * @type {Map<String,FsWatchContainer>}
  47994. */
  47995. const FsWatchInstances = new Map();
  47996. /**
  47997. * Instantiates the fs_watch interface
  47998. * @param {String} path to be watched
  47999. * @param {Object} options to be passed to fs_watch
  48000. * @param {Function} listener main event handler
  48001. * @param {Function} errHandler emits info about errors
  48002. * @param {Function} emitRaw emits raw event data
  48003. * @returns {fs.FSWatcher} new fsevents instance
  48004. */
  48005. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  48006. const handleEvent = (rawEvent, evPath) => {
  48007. listener(path);
  48008. emitRaw(rawEvent, evPath, {watchedPath: path});
  48009. // emit based on events occurring for files from a directory's watcher in
  48010. // case the file's watcher misses it (and rely on throttling to de-dupe)
  48011. if (evPath && path !== evPath) {
  48012. fsWatchBroadcast(
  48013. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  48014. );
  48015. }
  48016. };
  48017. try {
  48018. return fs$7.watch(path, options, handleEvent);
  48019. } catch (error) {
  48020. errHandler(error);
  48021. }
  48022. }
  48023. /**
  48024. * Helper for passing fs_watch event data to a collection of listeners
  48025. * @param {Path} fullPath absolute path bound to fs_watch instance
  48026. * @param {String} type listener type
  48027. * @param {*=} val1 arguments to be passed to listeners
  48028. * @param {*=} val2
  48029. * @param {*=} val3
  48030. */
  48031. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  48032. const cont = FsWatchInstances.get(fullPath);
  48033. if (!cont) return;
  48034. foreach(cont[type], (listener) => {
  48035. listener(val1, val2, val3);
  48036. });
  48037. };
  48038. /**
  48039. * Instantiates the fs_watch interface or binds listeners
  48040. * to an existing one covering the same file system entry
  48041. * @param {String} path
  48042. * @param {String} fullPath absolute path
  48043. * @param {Object} options to be passed to fs_watch
  48044. * @param {Object} handlers container for event listener functions
  48045. */
  48046. const setFsWatchListener = (path, fullPath, options, handlers) => {
  48047. const {listener, errHandler, rawEmitter} = handlers;
  48048. let cont = FsWatchInstances.get(fullPath);
  48049. /** @type {fs.FSWatcher=} */
  48050. let watcher;
  48051. if (!options.persistent) {
  48052. watcher = createFsWatchInstance(
  48053. path, options, listener, errHandler, rawEmitter
  48054. );
  48055. return watcher.close.bind(watcher);
  48056. }
  48057. if (cont) {
  48058. addAndConvert(cont, KEY_LISTENERS, listener);
  48059. addAndConvert(cont, KEY_ERR, errHandler);
  48060. addAndConvert(cont, KEY_RAW, rawEmitter);
  48061. } else {
  48062. watcher = createFsWatchInstance(
  48063. path,
  48064. options,
  48065. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  48066. errHandler, // no need to use broadcast here
  48067. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  48068. );
  48069. if (!watcher) return;
  48070. watcher.on(EV_ERROR$2, async (error) => {
  48071. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  48072. cont.watcherUnusable = true; // documented since Node 10.4.1
  48073. // Workaround for https://github.com/joyent/node/issues/4337
  48074. if (isWindows$2 && error.code === 'EPERM') {
  48075. try {
  48076. const fd = await open$2(path, 'r');
  48077. await close(fd);
  48078. broadcastErr(error);
  48079. } catch (err) {}
  48080. } else {
  48081. broadcastErr(error);
  48082. }
  48083. });
  48084. cont = {
  48085. listeners: listener,
  48086. errHandlers: errHandler,
  48087. rawEmitters: rawEmitter,
  48088. watcher
  48089. };
  48090. FsWatchInstances.set(fullPath, cont);
  48091. }
  48092. // const index = cont.listeners.indexOf(listener);
  48093. // removes this instance's listeners and closes the underlying fs_watch
  48094. // instance if there are no more listeners left
  48095. return () => {
  48096. delFromSet(cont, KEY_LISTENERS, listener);
  48097. delFromSet(cont, KEY_ERR, errHandler);
  48098. delFromSet(cont, KEY_RAW, rawEmitter);
  48099. if (isEmptySet(cont.listeners)) {
  48100. // Check to protect against issue gh-730.
  48101. // if (cont.watcherUnusable) {
  48102. cont.watcher.close();
  48103. // }
  48104. FsWatchInstances.delete(fullPath);
  48105. HANDLER_KEYS.forEach(clearItem(cont));
  48106. cont.watcher = undefined;
  48107. Object.freeze(cont);
  48108. }
  48109. };
  48110. };
  48111. // fs_watchFile helpers
  48112. // object to hold per-process fs_watchFile instances
  48113. // (may be shared across chokidar FSWatcher instances)
  48114. const FsWatchFileInstances = new Map();
  48115. /**
  48116. * Instantiates the fs_watchFile interface or binds listeners
  48117. * to an existing one covering the same file system entry
  48118. * @param {String} path to be watched
  48119. * @param {String} fullPath absolute path
  48120. * @param {Object} options options to be passed to fs_watchFile
  48121. * @param {Object} handlers container for event listener functions
  48122. * @returns {Function} closer
  48123. */
  48124. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  48125. const {listener, rawEmitter} = handlers;
  48126. let cont = FsWatchFileInstances.get(fullPath);
  48127. const copts = cont && cont.options;
  48128. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  48129. fs$7.unwatchFile(fullPath);
  48130. cont = undefined;
  48131. }
  48132. /* eslint-enable no-unused-vars, prefer-destructuring */
  48133. if (cont) {
  48134. addAndConvert(cont, KEY_LISTENERS, listener);
  48135. addAndConvert(cont, KEY_RAW, rawEmitter);
  48136. } else {
  48137. // TODO
  48138. // listeners.add(listener);
  48139. // rawEmitters.add(rawEmitter);
  48140. cont = {
  48141. listeners: listener,
  48142. rawEmitters: rawEmitter,
  48143. options,
  48144. watcher: fs$7.watchFile(fullPath, options, (curr, prev) => {
  48145. foreach(cont.rawEmitters, (rawEmitter) => {
  48146. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  48147. });
  48148. const currmtime = curr.mtimeMs;
  48149. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  48150. foreach(cont.listeners, (listener) => listener(path, curr));
  48151. }
  48152. })
  48153. };
  48154. FsWatchFileInstances.set(fullPath, cont);
  48155. }
  48156. // const index = cont.listeners.indexOf(listener);
  48157. // Removes this instance's listeners and closes the underlying fs_watchFile
  48158. // instance if there are no more listeners left.
  48159. return () => {
  48160. delFromSet(cont, KEY_LISTENERS, listener);
  48161. delFromSet(cont, KEY_RAW, rawEmitter);
  48162. if (isEmptySet(cont.listeners)) {
  48163. FsWatchFileInstances.delete(fullPath);
  48164. fs$7.unwatchFile(fullPath);
  48165. cont.options = cont.watcher = undefined;
  48166. Object.freeze(cont);
  48167. }
  48168. };
  48169. };
  48170. /**
  48171. * @mixin
  48172. */
  48173. let NodeFsHandler$1 = class NodeFsHandler {
  48174. /**
  48175. * @param {import("../index").FSWatcher} fsW
  48176. */
  48177. constructor(fsW) {
  48178. this.fsw = fsW;
  48179. this._boundHandleError = (error) => fsW._handleError(error);
  48180. }
  48181. /**
  48182. * Watch file for changes with fs_watchFile or fs_watch.
  48183. * @param {String} path to file or dir
  48184. * @param {Function} listener on fs change
  48185. * @returns {Function} closer for the watcher instance
  48186. */
  48187. _watchWithNodeFs(path, listener) {
  48188. const opts = this.fsw.options;
  48189. const directory = sysPath$2.dirname(path);
  48190. const basename = sysPath$2.basename(path);
  48191. const parent = this.fsw._getWatchedDir(directory);
  48192. parent.add(basename);
  48193. const absolutePath = sysPath$2.resolve(path);
  48194. const options = {persistent: opts.persistent};
  48195. if (!listener) listener = EMPTY_FN$2;
  48196. let closer;
  48197. if (opts.usePolling) {
  48198. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  48199. opts.binaryInterval : opts.interval;
  48200. closer = setFsWatchFileListener(path, absolutePath, options, {
  48201. listener,
  48202. rawEmitter: this.fsw._emitRaw
  48203. });
  48204. } else {
  48205. closer = setFsWatchListener(path, absolutePath, options, {
  48206. listener,
  48207. errHandler: this._boundHandleError,
  48208. rawEmitter: this.fsw._emitRaw
  48209. });
  48210. }
  48211. return closer;
  48212. }
  48213. /**
  48214. * Watch a file and emit add event if warranted.
  48215. * @param {Path} file Path
  48216. * @param {fs.Stats} stats result of fs_stat
  48217. * @param {Boolean} initialAdd was the file added at watch instantiation?
  48218. * @returns {Function} closer for the watcher instance
  48219. */
  48220. _handleFile(file, stats, initialAdd) {
  48221. if (this.fsw.closed) {
  48222. return;
  48223. }
  48224. const dirname = sysPath$2.dirname(file);
  48225. const basename = sysPath$2.basename(file);
  48226. const parent = this.fsw._getWatchedDir(dirname);
  48227. // stats is always present
  48228. let prevStats = stats;
  48229. // if the file is already being watched, do nothing
  48230. if (parent.has(basename)) return;
  48231. const listener = async (path, newStats) => {
  48232. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  48233. if (!newStats || newStats.mtimeMs === 0) {
  48234. try {
  48235. const newStats = await stat$2(file);
  48236. if (this.fsw.closed) return;
  48237. // Check that change event was not fired because of changed only accessTime.
  48238. const at = newStats.atimeMs;
  48239. const mt = newStats.mtimeMs;
  48240. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  48241. this.fsw._emit(EV_CHANGE$2, file, newStats);
  48242. }
  48243. if (isLinux && prevStats.ino !== newStats.ino) {
  48244. this.fsw._closeFile(path);
  48245. prevStats = newStats;
  48246. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  48247. } else {
  48248. prevStats = newStats;
  48249. }
  48250. } catch (error) {
  48251. // Fix issues where mtime is null but file is still present
  48252. this.fsw._remove(dirname, basename);
  48253. }
  48254. // add is about to be emitted if file not already tracked in parent
  48255. } else if (parent.has(basename)) {
  48256. // Check that change event was not fired because of changed only accessTime.
  48257. const at = newStats.atimeMs;
  48258. const mt = newStats.mtimeMs;
  48259. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  48260. this.fsw._emit(EV_CHANGE$2, file, newStats);
  48261. }
  48262. prevStats = newStats;
  48263. }
  48264. };
  48265. // kick off the watcher
  48266. const closer = this._watchWithNodeFs(file, listener);
  48267. // emit an add event if we're supposed to
  48268. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  48269. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  48270. this.fsw._emit(EV_ADD$2, file, stats);
  48271. }
  48272. return closer;
  48273. }
  48274. /**
  48275. * Handle symlinks encountered while reading a dir.
  48276. * @param {Object} entry returned by readdirp
  48277. * @param {String} directory path of dir being read
  48278. * @param {String} path of this item
  48279. * @param {String} item basename of this item
  48280. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  48281. */
  48282. async _handleSymlink(entry, directory, path, item) {
  48283. if (this.fsw.closed) {
  48284. return;
  48285. }
  48286. const full = entry.fullPath;
  48287. const dir = this.fsw._getWatchedDir(directory);
  48288. if (!this.fsw.options.followSymlinks) {
  48289. // watch symlink directly (don't follow) and detect changes
  48290. this.fsw._incrReadyCount();
  48291. let linkPath;
  48292. try {
  48293. linkPath = await fsrealpath(path);
  48294. } catch (e) {
  48295. this.fsw._emitReady();
  48296. return true;
  48297. }
  48298. if (this.fsw.closed) return;
  48299. if (dir.has(item)) {
  48300. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  48301. this.fsw._symlinkPaths.set(full, linkPath);
  48302. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  48303. }
  48304. } else {
  48305. dir.add(item);
  48306. this.fsw._symlinkPaths.set(full, linkPath);
  48307. this.fsw._emit(EV_ADD$2, path, entry.stats);
  48308. }
  48309. this.fsw._emitReady();
  48310. return true;
  48311. }
  48312. // don't follow the same symlink more than once
  48313. if (this.fsw._symlinkPaths.has(full)) {
  48314. return true;
  48315. }
  48316. this.fsw._symlinkPaths.set(full, true);
  48317. }
  48318. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  48319. // Normalize the directory name on Windows
  48320. directory = sysPath$2.join(directory, EMPTY_STR$1);
  48321. if (!wh.hasGlob) {
  48322. throttler = this.fsw._throttle('readdir', directory, 1000);
  48323. if (!throttler) return;
  48324. }
  48325. const previous = this.fsw._getWatchedDir(wh.path);
  48326. const current = new Set();
  48327. let stream = this.fsw._readdirp(directory, {
  48328. fileFilter: entry => wh.filterPath(entry),
  48329. directoryFilter: entry => wh.filterDir(entry),
  48330. depth: 0
  48331. }).on(STR_DATA$1, async (entry) => {
  48332. if (this.fsw.closed) {
  48333. stream = undefined;
  48334. return;
  48335. }
  48336. const item = entry.path;
  48337. let path = sysPath$2.join(directory, item);
  48338. current.add(item);
  48339. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  48340. return;
  48341. }
  48342. if (this.fsw.closed) {
  48343. stream = undefined;
  48344. return;
  48345. }
  48346. // Files that present in current directory snapshot
  48347. // but absent in previous are added to watch list and
  48348. // emit `add` event.
  48349. if (item === target || !target && !previous.has(item)) {
  48350. this.fsw._incrReadyCount();
  48351. // ensure relativeness of path is preserved in case of watcher reuse
  48352. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  48353. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  48354. }
  48355. }).on(EV_ERROR$2, this._boundHandleError);
  48356. return new Promise(resolve =>
  48357. stream.once(STR_END$2, () => {
  48358. if (this.fsw.closed) {
  48359. stream = undefined;
  48360. return;
  48361. }
  48362. const wasThrottled = throttler ? throttler.clear() : false;
  48363. resolve();
  48364. // Files that absent in current directory snapshot
  48365. // but present in previous emit `remove` event
  48366. // and are removed from @watched[directory].
  48367. previous.getChildren().filter((item) => {
  48368. return item !== directory &&
  48369. !current.has(item) &&
  48370. // in case of intersecting globs;
  48371. // a path may have been filtered out of this readdir, but
  48372. // shouldn't be removed because it matches a different glob
  48373. (!wh.hasGlob || wh.filterPath({
  48374. fullPath: sysPath$2.resolve(directory, item)
  48375. }));
  48376. }).forEach((item) => {
  48377. this.fsw._remove(directory, item);
  48378. });
  48379. stream = undefined;
  48380. // one more time for any missed in case changes came in extremely quickly
  48381. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  48382. })
  48383. );
  48384. }
  48385. /**
  48386. * Read directory to add / remove files from `@watched` list and re-read it on change.
  48387. * @param {String} dir fs path
  48388. * @param {fs.Stats} stats
  48389. * @param {Boolean} initialAdd
  48390. * @param {Number} depth relative to user-supplied path
  48391. * @param {String} target child path targeted for watch
  48392. * @param {Object} wh Common watch helpers for this path
  48393. * @param {String} realpath
  48394. * @returns {Promise<Function>} closer for the watcher instance.
  48395. */
  48396. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  48397. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  48398. const tracked = parentDir.has(sysPath$2.basename(dir));
  48399. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  48400. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  48401. }
  48402. // ensure dir is tracked (harmless if redundant)
  48403. parentDir.add(sysPath$2.basename(dir));
  48404. this.fsw._getWatchedDir(dir);
  48405. let throttler;
  48406. let closer;
  48407. const oDepth = this.fsw.options.depth;
  48408. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  48409. if (!target) {
  48410. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  48411. if (this.fsw.closed) return;
  48412. }
  48413. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  48414. // if current directory is removed, do nothing
  48415. if (stats && stats.mtimeMs === 0) return;
  48416. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  48417. });
  48418. }
  48419. return closer;
  48420. }
  48421. /**
  48422. * Handle added file, directory, or glob pattern.
  48423. * Delegates call to _handleFile / _handleDir after checks.
  48424. * @param {String} path to file or ir
  48425. * @param {Boolean} initialAdd was the file added at watch instantiation?
  48426. * @param {Object} priorWh depth relative to user-supplied path
  48427. * @param {Number} depth Child path actually targeted for watch
  48428. * @param {String=} target Child path actually targeted for watch
  48429. * @returns {Promise}
  48430. */
  48431. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  48432. const ready = this.fsw._emitReady;
  48433. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  48434. ready();
  48435. return false;
  48436. }
  48437. const wh = this.fsw._getWatchHelpers(path, depth);
  48438. if (!wh.hasGlob && priorWh) {
  48439. wh.hasGlob = priorWh.hasGlob;
  48440. wh.globFilter = priorWh.globFilter;
  48441. wh.filterPath = entry => priorWh.filterPath(entry);
  48442. wh.filterDir = entry => priorWh.filterDir(entry);
  48443. }
  48444. // evaluate what is at the path we're being asked to watch
  48445. try {
  48446. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  48447. if (this.fsw.closed) return;
  48448. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  48449. ready();
  48450. return false;
  48451. }
  48452. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  48453. let closer;
  48454. if (stats.isDirectory()) {
  48455. const absPath = sysPath$2.resolve(path);
  48456. const targetPath = follow ? await fsrealpath(path) : path;
  48457. if (this.fsw.closed) return;
  48458. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  48459. if (this.fsw.closed) return;
  48460. // preserve this symlink's target path
  48461. if (absPath !== targetPath && targetPath !== undefined) {
  48462. this.fsw._symlinkPaths.set(absPath, targetPath);
  48463. }
  48464. } else if (stats.isSymbolicLink()) {
  48465. const targetPath = follow ? await fsrealpath(path) : path;
  48466. if (this.fsw.closed) return;
  48467. const parent = sysPath$2.dirname(wh.watchPath);
  48468. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  48469. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  48470. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  48471. if (this.fsw.closed) return;
  48472. // preserve this symlink's target path
  48473. if (targetPath !== undefined) {
  48474. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  48475. }
  48476. } else {
  48477. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  48478. }
  48479. ready();
  48480. this.fsw._addPathCloser(path, closer);
  48481. return false;
  48482. } catch (error) {
  48483. if (this.fsw._handleError(error)) {
  48484. ready();
  48485. return path;
  48486. }
  48487. }
  48488. }
  48489. };
  48490. var nodefsHandler = NodeFsHandler$1;
  48491. var fseventsHandler = {exports: {}};
  48492. const fs$6 = require$$0__default;
  48493. const sysPath$1 = require$$0$4;
  48494. const { promisify: promisify$1 } = require$$0$6;
  48495. let fsevents;
  48496. try {
  48497. fsevents = __require('fsevents');
  48498. } catch (error) {
  48499. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  48500. }
  48501. if (fsevents) {
  48502. // TODO: real check
  48503. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  48504. if (mtch && mtch[1] && mtch[2]) {
  48505. const maj = Number.parseInt(mtch[1], 10);
  48506. const min = Number.parseInt(mtch[2], 10);
  48507. if (maj === 8 && min < 16) {
  48508. fsevents = undefined;
  48509. }
  48510. }
  48511. }
  48512. const {
  48513. EV_ADD: EV_ADD$1,
  48514. EV_CHANGE: EV_CHANGE$1,
  48515. EV_ADD_DIR: EV_ADD_DIR$1,
  48516. EV_UNLINK: EV_UNLINK$1,
  48517. EV_ERROR: EV_ERROR$1,
  48518. STR_DATA,
  48519. STR_END: STR_END$1,
  48520. FSEVENT_CREATED,
  48521. FSEVENT_MODIFIED,
  48522. FSEVENT_DELETED,
  48523. FSEVENT_MOVED,
  48524. // FSEVENT_CLONED,
  48525. FSEVENT_UNKNOWN,
  48526. FSEVENT_TYPE_FILE,
  48527. FSEVENT_TYPE_DIRECTORY,
  48528. FSEVENT_TYPE_SYMLINK,
  48529. ROOT_GLOBSTAR,
  48530. DIR_SUFFIX,
  48531. DOT_SLASH,
  48532. FUNCTION_TYPE: FUNCTION_TYPE$1,
  48533. EMPTY_FN: EMPTY_FN$1,
  48534. IDENTITY_FN
  48535. } = constants$1;
  48536. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  48537. const stat$1 = promisify$1(fs$6.stat);
  48538. const lstat = promisify$1(fs$6.lstat);
  48539. const realpath = promisify$1(fs$6.realpath);
  48540. const statMethods = { stat: stat$1, lstat };
  48541. /**
  48542. * @typedef {String} Path
  48543. */
  48544. /**
  48545. * @typedef {Object} FsEventsWatchContainer
  48546. * @property {Set<Function>} listeners
  48547. * @property {Function} rawEmitter
  48548. * @property {{stop: Function}} watcher
  48549. */
  48550. // fsevents instance helper functions
  48551. /**
  48552. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  48553. * @type {Map<Path,FsEventsWatchContainer>}
  48554. */
  48555. const FSEventsWatchers = new Map();
  48556. // Threshold of duplicate path prefixes at which to start
  48557. // consolidating going forward
  48558. const consolidateThreshhold = 10;
  48559. const wrongEventFlags = new Set([
  48560. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  48561. ]);
  48562. /**
  48563. * Instantiates the fsevents interface
  48564. * @param {Path} path path to be watched
  48565. * @param {Function} callback called when fsevents is bound and ready
  48566. * @returns {{stop: Function}} new fsevents instance
  48567. */
  48568. const createFSEventsInstance = (path, callback) => {
  48569. const stop = fsevents.watch(path, callback);
  48570. return {stop};
  48571. };
  48572. /**
  48573. * Instantiates the fsevents interface or binds listeners to an existing one covering
  48574. * the same file tree.
  48575. * @param {Path} path - to be watched
  48576. * @param {Path} realPath - real path for symlinks
  48577. * @param {Function} listener - called when fsevents emits events
  48578. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  48579. * @returns {Function} closer
  48580. */
  48581. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  48582. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  48583. const parentPath = sysPath$1.dirname(watchPath);
  48584. let cont = FSEventsWatchers.get(watchPath);
  48585. // If we've accumulated a substantial number of paths that
  48586. // could have been consolidated by watching one directory
  48587. // above the current one, create a watcher on the parent
  48588. // path instead, so that we do consolidate going forward.
  48589. if (couldConsolidate(parentPath)) {
  48590. watchPath = parentPath;
  48591. }
  48592. const resolvedPath = sysPath$1.resolve(path);
  48593. const hasSymlink = resolvedPath !== realPath;
  48594. const filteredListener = (fullPath, flags, info) => {
  48595. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  48596. if (
  48597. fullPath === resolvedPath ||
  48598. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  48599. ) listener(fullPath, flags, info);
  48600. };
  48601. // check if there is already a watcher on a parent path
  48602. // modifies `watchPath` to the parent path when it finds a match
  48603. let watchedParent = false;
  48604. for (const watchedPath of FSEventsWatchers.keys()) {
  48605. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  48606. watchPath = watchedPath;
  48607. cont = FSEventsWatchers.get(watchPath);
  48608. watchedParent = true;
  48609. break;
  48610. }
  48611. }
  48612. if (cont || watchedParent) {
  48613. cont.listeners.add(filteredListener);
  48614. } else {
  48615. cont = {
  48616. listeners: new Set([filteredListener]),
  48617. rawEmitter,
  48618. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  48619. if (!cont.listeners.size) return;
  48620. const info = fsevents.getInfo(fullPath, flags);
  48621. cont.listeners.forEach(list => {
  48622. list(fullPath, flags, info);
  48623. });
  48624. cont.rawEmitter(info.event, fullPath, info);
  48625. })
  48626. };
  48627. FSEventsWatchers.set(watchPath, cont);
  48628. }
  48629. // removes this instance's listeners and closes the underlying fsevents
  48630. // instance if there are no more listeners left
  48631. return () => {
  48632. const lst = cont.listeners;
  48633. lst.delete(filteredListener);
  48634. if (!lst.size) {
  48635. FSEventsWatchers.delete(watchPath);
  48636. if (cont.watcher) return cont.watcher.stop().then(() => {
  48637. cont.rawEmitter = cont.watcher = undefined;
  48638. Object.freeze(cont);
  48639. });
  48640. }
  48641. };
  48642. }
  48643. // Decide whether or not we should start a new higher-level
  48644. // parent watcher
  48645. const couldConsolidate = (path) => {
  48646. let count = 0;
  48647. for (const watchPath of FSEventsWatchers.keys()) {
  48648. if (watchPath.indexOf(path) === 0) {
  48649. count++;
  48650. if (count >= consolidateThreshhold) {
  48651. return true;
  48652. }
  48653. }
  48654. }
  48655. return false;
  48656. };
  48657. // returns boolean indicating whether fsevents can be used
  48658. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  48659. // determines subdirectory traversal levels from root to path
  48660. const calcDepth = (path, root) => {
  48661. let i = 0;
  48662. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  48663. return i;
  48664. };
  48665. // returns boolean indicating whether the fsevents' event info has the same type
  48666. // as the one returned by fs.stat
  48667. const sameTypes = (info, stats) => (
  48668. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  48669. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  48670. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  48671. );
  48672. /**
  48673. * @mixin
  48674. */
  48675. let FsEventsHandler$1 = class FsEventsHandler {
  48676. /**
  48677. * @param {import('../index').FSWatcher} fsw
  48678. */
  48679. constructor(fsw) {
  48680. this.fsw = fsw;
  48681. }
  48682. checkIgnored(path, stats) {
  48683. const ipaths = this.fsw._ignoredPaths;
  48684. if (this.fsw._isIgnored(path, stats)) {
  48685. ipaths.add(path);
  48686. if (stats && stats.isDirectory()) {
  48687. ipaths.add(path + ROOT_GLOBSTAR);
  48688. }
  48689. return true;
  48690. }
  48691. ipaths.delete(path);
  48692. ipaths.delete(path + ROOT_GLOBSTAR);
  48693. }
  48694. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  48695. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  48696. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48697. }
  48698. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  48699. try {
  48700. const stats = await stat$1(path);
  48701. if (this.fsw.closed) return;
  48702. if (sameTypes(info, stats)) {
  48703. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48704. } else {
  48705. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48706. }
  48707. } catch (error) {
  48708. if (error.code === 'EACCES') {
  48709. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48710. } else {
  48711. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48712. }
  48713. }
  48714. }
  48715. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  48716. if (this.fsw.closed || this.checkIgnored(path)) return;
  48717. if (event === EV_UNLINK$1) {
  48718. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  48719. // suppress unlink events on never before seen files
  48720. if (isDirectory || watchedDir.has(item)) {
  48721. this.fsw._remove(parent, item, isDirectory);
  48722. }
  48723. } else {
  48724. if (event === EV_ADD$1) {
  48725. // track new directories
  48726. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  48727. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  48728. // push symlinks back to the top of the stack to get handled
  48729. const curDepth = opts.depth === undefined ?
  48730. undefined : calcDepth(fullPath, realPath) + 1;
  48731. return this._addToFsEvents(path, false, true, curDepth);
  48732. }
  48733. // track new paths
  48734. // (other than symlinks being followed, which will be tracked soon)
  48735. this.fsw._getWatchedDir(parent).add(item);
  48736. }
  48737. /**
  48738. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  48739. */
  48740. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  48741. this.fsw._emit(eventName, path);
  48742. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  48743. }
  48744. }
  48745. /**
  48746. * Handle symlinks encountered during directory scan
  48747. * @param {String} watchPath - file/dir path to be watched with fsevents
  48748. * @param {String} realPath - real path (in case of symlinks)
  48749. * @param {Function} transform - path transformer
  48750. * @param {Function} globFilter - path filter in case a glob pattern was provided
  48751. * @returns {Function} closer for the watcher instance
  48752. */
  48753. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  48754. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  48755. const opts = this.fsw.options;
  48756. const watchCallback = async (fullPath, flags, info) => {
  48757. // PATCH: bypass the callback for better perf when fullPath hit the ignored file list
  48758. if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
  48759. if (
  48760. opts.depth !== undefined &&
  48761. calcDepth(fullPath, realPath) > opts.depth
  48762. ) return;
  48763. const path = transform(sysPath$1.join(
  48764. watchPath, sysPath$1.relative(watchPath, fullPath)
  48765. ));
  48766. if (globFilter && !globFilter(path)) return;
  48767. // ensure directories are tracked
  48768. const parent = sysPath$1.dirname(path);
  48769. const item = sysPath$1.basename(path);
  48770. const watchedDir = this.fsw._getWatchedDir(
  48771. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  48772. );
  48773. // correct for wrong events emitted
  48774. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  48775. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  48776. let stats;
  48777. try {
  48778. stats = await stat$1(path);
  48779. } catch (error) {}
  48780. if (this.fsw.closed) return;
  48781. if (this.checkIgnored(path, stats)) return;
  48782. if (sameTypes(info, stats)) {
  48783. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48784. } else {
  48785. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48786. }
  48787. } else {
  48788. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48789. }
  48790. } else {
  48791. switch (info.event) {
  48792. case FSEVENT_CREATED:
  48793. case FSEVENT_MODIFIED:
  48794. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48795. case FSEVENT_DELETED:
  48796. case FSEVENT_MOVED:
  48797. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  48798. }
  48799. }
  48800. };
  48801. const closer = setFSEventsListener(
  48802. watchPath,
  48803. realPath,
  48804. watchCallback,
  48805. this.fsw._emitRaw
  48806. );
  48807. this.fsw._emitReady();
  48808. return closer;
  48809. }
  48810. /**
  48811. * Handle symlinks encountered during directory scan
  48812. * @param {String} linkPath path to symlink
  48813. * @param {String} fullPath absolute path to the symlink
  48814. * @param {Function} transform pre-existing path transformer
  48815. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  48816. * @returns {Promise<void>}
  48817. */
  48818. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  48819. // don't follow the same symlink more than once
  48820. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  48821. this.fsw._symlinkPaths.set(fullPath, true);
  48822. this.fsw._incrReadyCount();
  48823. try {
  48824. const linkTarget = await realpath(linkPath);
  48825. if (this.fsw.closed) return;
  48826. if (this.fsw._isIgnored(linkTarget)) {
  48827. return this.fsw._emitReady();
  48828. }
  48829. this.fsw._incrReadyCount();
  48830. // add the linkTarget for watching with a wrapper for transform
  48831. // that causes emitted paths to incorporate the link's path
  48832. this._addToFsEvents(linkTarget || linkPath, (path) => {
  48833. let aliasedPath = linkPath;
  48834. if (linkTarget && linkTarget !== DOT_SLASH) {
  48835. aliasedPath = path.replace(linkTarget, linkPath);
  48836. } else if (path !== DOT_SLASH) {
  48837. aliasedPath = sysPath$1.join(linkPath, path);
  48838. }
  48839. return transform(aliasedPath);
  48840. }, false, curDepth);
  48841. } catch(error) {
  48842. if (this.fsw._handleError(error)) {
  48843. return this.fsw._emitReady();
  48844. }
  48845. }
  48846. }
  48847. /**
  48848. *
  48849. * @param {Path} newPath
  48850. * @param {fs.Stats} stats
  48851. */
  48852. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  48853. const pp = processPath(newPath);
  48854. const isDir = stats.isDirectory();
  48855. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  48856. const base = sysPath$1.basename(pp);
  48857. // ensure empty dirs get tracked
  48858. if (isDir) this.fsw._getWatchedDir(pp);
  48859. if (dirObj.has(base)) return;
  48860. dirObj.add(base);
  48861. if (!opts.ignoreInitial || forceAdd === true) {
  48862. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  48863. }
  48864. }
  48865. initWatch(realPath, path, wh, processPath) {
  48866. if (this.fsw.closed) return;
  48867. const closer = this._watchWithFsEvents(
  48868. wh.watchPath,
  48869. sysPath$1.resolve(realPath || wh.watchPath),
  48870. processPath,
  48871. wh.globFilter
  48872. );
  48873. this.fsw._addPathCloser(path, closer);
  48874. }
  48875. /**
  48876. * Handle added path with fsevents
  48877. * @param {String} path file/dir path or glob pattern
  48878. * @param {Function|Boolean=} transform converts working path to what the user expects
  48879. * @param {Boolean=} forceAdd ensure add is emitted
  48880. * @param {Number=} priorDepth Level of subdirectories already traversed.
  48881. * @returns {Promise<void>}
  48882. */
  48883. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  48884. if (this.fsw.closed) {
  48885. return;
  48886. }
  48887. const opts = this.fsw.options;
  48888. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  48889. const wh = this.fsw._getWatchHelpers(path);
  48890. // evaluate what is at the path we're being asked to watch
  48891. try {
  48892. const stats = await statMethods[wh.statMethod](wh.watchPath);
  48893. if (this.fsw.closed) return;
  48894. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  48895. throw null;
  48896. }
  48897. if (stats.isDirectory()) {
  48898. // emit addDir unless this is a glob parent
  48899. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  48900. // don't recurse further if it would exceed depth setting
  48901. if (priorDepth && priorDepth > opts.depth) return;
  48902. // scan the contents of the dir
  48903. this.fsw._readdirp(wh.watchPath, {
  48904. fileFilter: entry => wh.filterPath(entry),
  48905. directoryFilter: entry => wh.filterDir(entry),
  48906. ...Depth(opts.depth - (priorDepth || 0))
  48907. }).on(STR_DATA, (entry) => {
  48908. // need to check filterPath on dirs b/c filterDir is less restrictive
  48909. if (this.fsw.closed) {
  48910. return;
  48911. }
  48912. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  48913. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  48914. const {fullPath} = entry;
  48915. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  48916. // preserve the current depth here since it can't be derived from
  48917. // real paths past the symlink
  48918. const curDepth = opts.depth === undefined ?
  48919. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  48920. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  48921. } else {
  48922. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  48923. }
  48924. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  48925. this.fsw._emitReady();
  48926. });
  48927. } else {
  48928. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  48929. this.fsw._emitReady();
  48930. }
  48931. } catch (error) {
  48932. if (!error || this.fsw._handleError(error)) {
  48933. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  48934. this.fsw._emitReady();
  48935. this.fsw._emitReady();
  48936. }
  48937. }
  48938. if (opts.persistent && forceAdd !== true) {
  48939. if (typeof transform === FUNCTION_TYPE$1) {
  48940. // realpath has already been resolved
  48941. this.initWatch(undefined, path, wh, processPath);
  48942. } else {
  48943. let realPath;
  48944. try {
  48945. realPath = await realpath(wh.watchPath);
  48946. } catch (e) {}
  48947. this.initWatch(realPath, path, wh, processPath);
  48948. }
  48949. }
  48950. }
  48951. };
  48952. fseventsHandler.exports = FsEventsHandler$1;
  48953. fseventsHandler.exports.canUse = canUse;
  48954. var fseventsHandlerExports = fseventsHandler.exports;
  48955. const { EventEmitter: EventEmitter$2 } = require$$0$5;
  48956. const fs$5 = require$$0__default;
  48957. const sysPath = require$$0$4;
  48958. const { promisify } = require$$0$6;
  48959. const readdirp = readdirp_1;
  48960. const anymatch = anymatchExports.default;
  48961. const globParent = globParent$2;
  48962. const isGlob = isGlob$2;
  48963. const braces = braces_1;
  48964. const normalizePath = normalizePath$2;
  48965. const NodeFsHandler = nodefsHandler;
  48966. const FsEventsHandler = fseventsHandlerExports;
  48967. const {
  48968. EV_ALL,
  48969. EV_READY,
  48970. EV_ADD,
  48971. EV_CHANGE,
  48972. EV_UNLINK,
  48973. EV_ADD_DIR,
  48974. EV_UNLINK_DIR,
  48975. EV_RAW,
  48976. EV_ERROR,
  48977. STR_CLOSE,
  48978. STR_END,
  48979. BACK_SLASH_RE,
  48980. DOUBLE_SLASH_RE,
  48981. SLASH_OR_BACK_SLASH_RE,
  48982. DOT_RE,
  48983. REPLACER_RE,
  48984. SLASH,
  48985. SLASH_SLASH,
  48986. BRACE_START,
  48987. BANG,
  48988. ONE_DOT,
  48989. TWO_DOTS,
  48990. GLOBSTAR,
  48991. SLASH_GLOBSTAR,
  48992. ANYMATCH_OPTS,
  48993. STRING_TYPE,
  48994. FUNCTION_TYPE,
  48995. EMPTY_STR,
  48996. EMPTY_FN,
  48997. isWindows: isWindows$1,
  48998. isMacos,
  48999. isIBMi
  49000. } = constants$1;
  49001. const stat = promisify(fs$5.stat);
  49002. const readdir = promisify(fs$5.readdir);
  49003. /**
  49004. * @typedef {String} Path
  49005. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  49006. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  49007. */
  49008. /**
  49009. *
  49010. * @typedef {Object} WatchHelpers
  49011. * @property {Boolean} followSymlinks
  49012. * @property {'stat'|'lstat'} statMethod
  49013. * @property {Path} path
  49014. * @property {Path} watchPath
  49015. * @property {Function} entryPath
  49016. * @property {Boolean} hasGlob
  49017. * @property {Object} globFilter
  49018. * @property {Function} filterPath
  49019. * @property {Function} filterDir
  49020. */
  49021. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  49022. const flatten = (list, result = []) => {
  49023. list.forEach(item => {
  49024. if (Array.isArray(item)) {
  49025. flatten(item, result);
  49026. } else {
  49027. result.push(item);
  49028. }
  49029. });
  49030. return result;
  49031. };
  49032. const unifyPaths = (paths_) => {
  49033. /**
  49034. * @type {Array<String>}
  49035. */
  49036. const paths = flatten(arrify(paths_));
  49037. if (!paths.every(p => typeof p === STRING_TYPE)) {
  49038. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  49039. }
  49040. return paths.map(normalizePathToUnix);
  49041. };
  49042. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  49043. // because "//StoragePC/DrivePool/Movies" is a valid network path
  49044. const toUnix = (string) => {
  49045. let str = string.replace(BACK_SLASH_RE, SLASH);
  49046. let prepend = false;
  49047. if (str.startsWith(SLASH_SLASH)) {
  49048. prepend = true;
  49049. }
  49050. while (str.match(DOUBLE_SLASH_RE)) {
  49051. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  49052. }
  49053. if (prepend) {
  49054. str = SLASH + str;
  49055. }
  49056. return str;
  49057. };
  49058. // Our version of upath.normalize
  49059. // TODO: this is not equal to path-normalize module - investigate why
  49060. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  49061. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  49062. if (typeof path !== STRING_TYPE) return path;
  49063. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  49064. };
  49065. const getAbsolutePath = (path, cwd) => {
  49066. if (sysPath.isAbsolute(path)) {
  49067. return path;
  49068. }
  49069. if (path.startsWith(BANG)) {
  49070. return BANG + sysPath.join(cwd, path.slice(1));
  49071. }
  49072. return sysPath.join(cwd, path);
  49073. };
  49074. const undef = (opts, key) => opts[key] === undefined;
  49075. /**
  49076. * Directory entry.
  49077. * @property {Path} path
  49078. * @property {Set<Path>} items
  49079. */
  49080. class DirEntry {
  49081. /**
  49082. * @param {Path} dir
  49083. * @param {Function} removeWatcher
  49084. */
  49085. constructor(dir, removeWatcher) {
  49086. this.path = dir;
  49087. this._removeWatcher = removeWatcher;
  49088. /** @type {Set<Path>} */
  49089. this.items = new Set();
  49090. }
  49091. add(item) {
  49092. const {items} = this;
  49093. if (!items) return;
  49094. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  49095. }
  49096. async remove(item) {
  49097. const {items} = this;
  49098. if (!items) return;
  49099. items.delete(item);
  49100. if (items.size > 0) return;
  49101. const dir = this.path;
  49102. try {
  49103. await readdir(dir);
  49104. } catch (err) {
  49105. if (this._removeWatcher) {
  49106. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  49107. }
  49108. }
  49109. }
  49110. has(item) {
  49111. const {items} = this;
  49112. if (!items) return;
  49113. return items.has(item);
  49114. }
  49115. /**
  49116. * @returns {Array<String>}
  49117. */
  49118. getChildren() {
  49119. const {items} = this;
  49120. if (!items) return;
  49121. return [...items.values()];
  49122. }
  49123. dispose() {
  49124. this.items.clear();
  49125. delete this.path;
  49126. delete this._removeWatcher;
  49127. delete this.items;
  49128. Object.freeze(this);
  49129. }
  49130. }
  49131. const STAT_METHOD_F = 'stat';
  49132. const STAT_METHOD_L = 'lstat';
  49133. class WatchHelper {
  49134. constructor(path, watchPath, follow, fsw) {
  49135. this.fsw = fsw;
  49136. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  49137. this.watchPath = watchPath;
  49138. this.fullWatchPath = sysPath.resolve(watchPath);
  49139. this.hasGlob = watchPath !== path;
  49140. /** @type {object|boolean} */
  49141. if (path === EMPTY_STR) this.hasGlob = false;
  49142. this.globSymlink = this.hasGlob && follow ? undefined : false;
  49143. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  49144. this.dirParts = this.getDirParts(path);
  49145. this.dirParts.forEach((parts) => {
  49146. if (parts.length > 1) parts.pop();
  49147. });
  49148. this.followSymlinks = follow;
  49149. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  49150. }
  49151. checkGlobSymlink(entry) {
  49152. // only need to resolve once
  49153. // first entry should always have entry.parentDir === EMPTY_STR
  49154. if (this.globSymlink === undefined) {
  49155. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  49156. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  49157. }
  49158. if (this.globSymlink) {
  49159. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  49160. }
  49161. return entry.fullPath;
  49162. }
  49163. entryPath(entry) {
  49164. return sysPath.join(this.watchPath,
  49165. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  49166. );
  49167. }
  49168. filterPath(entry) {
  49169. const {stats} = entry;
  49170. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  49171. const resolvedPath = this.entryPath(entry);
  49172. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  49173. this.globFilter(resolvedPath) : true;
  49174. return matchesGlob &&
  49175. this.fsw._isntIgnored(resolvedPath, stats) &&
  49176. this.fsw._hasReadPermissions(stats);
  49177. }
  49178. getDirParts(path) {
  49179. if (!this.hasGlob) return [];
  49180. const parts = [];
  49181. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  49182. expandedPath.forEach((path) => {
  49183. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  49184. });
  49185. return parts;
  49186. }
  49187. filterDir(entry) {
  49188. if (this.hasGlob) {
  49189. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  49190. let globstar = false;
  49191. this.unmatchedGlob = !this.dirParts.some((parts) => {
  49192. return parts.every((part, i) => {
  49193. if (part === GLOBSTAR) globstar = true;
  49194. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  49195. });
  49196. });
  49197. }
  49198. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  49199. }
  49200. }
  49201. /**
  49202. * Watches files & directories for changes. Emitted events:
  49203. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  49204. *
  49205. * new FSWatcher()
  49206. * .add(directories)
  49207. * .on('add', path => log('File', path, 'was added'))
  49208. */
  49209. class FSWatcher extends EventEmitter$2 {
  49210. // Not indenting methods for history sake; for now.
  49211. constructor(_opts) {
  49212. super();
  49213. const opts = {};
  49214. if (_opts) Object.assign(opts, _opts); // for frozen objects
  49215. /** @type {Map<String, DirEntry>} */
  49216. this._watched = new Map();
  49217. /** @type {Map<String, Array>} */
  49218. this._closers = new Map();
  49219. /** @type {Set<String>} */
  49220. this._ignoredPaths = new Set();
  49221. /** @type {Map<ThrottleType, Map>} */
  49222. this._throttled = new Map();
  49223. /** @type {Map<Path, String|Boolean>} */
  49224. this._symlinkPaths = new Map();
  49225. this._streams = new Set();
  49226. this.closed = false;
  49227. // Set up default options.
  49228. if (undef(opts, 'persistent')) opts.persistent = true;
  49229. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  49230. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  49231. if (undef(opts, 'interval')) opts.interval = 100;
  49232. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  49233. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  49234. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  49235. // Enable fsevents on OS X when polling isn't explicitly enabled.
  49236. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  49237. // If we can't use fsevents, ensure the options reflect it's disabled.
  49238. const canUseFsEvents = FsEventsHandler.canUse();
  49239. if (!canUseFsEvents) opts.useFsEvents = false;
  49240. // Use polling on Mac if not using fsevents.
  49241. // Other platforms use non-polling fs_watch.
  49242. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  49243. opts.usePolling = isMacos;
  49244. }
  49245. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  49246. if(isIBMi) {
  49247. opts.usePolling = true;
  49248. }
  49249. // Global override (useful for end-developers that need to force polling for all
  49250. // instances of chokidar, regardless of usage/dependency depth)
  49251. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  49252. if (envPoll !== undefined) {
  49253. const envLower = envPoll.toLowerCase();
  49254. if (envLower === 'false' || envLower === '0') {
  49255. opts.usePolling = false;
  49256. } else if (envLower === 'true' || envLower === '1') {
  49257. opts.usePolling = true;
  49258. } else {
  49259. opts.usePolling = !!envLower;
  49260. }
  49261. }
  49262. const envInterval = process.env.CHOKIDAR_INTERVAL;
  49263. if (envInterval) {
  49264. opts.interval = Number.parseInt(envInterval, 10);
  49265. }
  49266. // Editor atomic write normalization enabled by default with fs.watch
  49267. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  49268. if (opts.atomic) this._pendingUnlinks = new Map();
  49269. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  49270. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  49271. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  49272. const awf = opts.awaitWriteFinish;
  49273. if (awf) {
  49274. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  49275. if (!awf.pollInterval) awf.pollInterval = 100;
  49276. this._pendingWrites = new Map();
  49277. }
  49278. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  49279. let readyCalls = 0;
  49280. this._emitReady = () => {
  49281. readyCalls++;
  49282. if (readyCalls >= this._readyCount) {
  49283. this._emitReady = EMPTY_FN;
  49284. this._readyEmitted = true;
  49285. // use process.nextTick to allow time for listener to be bound
  49286. process.nextTick(() => this.emit(EV_READY));
  49287. }
  49288. };
  49289. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  49290. this._readyEmitted = false;
  49291. this.options = opts;
  49292. // Initialize with proper watcher.
  49293. if (opts.useFsEvents) {
  49294. this._fsEventsHandler = new FsEventsHandler(this);
  49295. } else {
  49296. this._nodeFsHandler = new NodeFsHandler(this);
  49297. }
  49298. // You’re frozen when your heart’s not open.
  49299. Object.freeze(opts);
  49300. }
  49301. // Public methods
  49302. /**
  49303. * Adds paths to be watched on an existing FSWatcher instance
  49304. * @param {Path|Array<Path>} paths_
  49305. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  49306. * @param {Boolean=} _internal private; indicates a non-user add
  49307. * @returns {FSWatcher} for chaining
  49308. */
  49309. add(paths_, _origAdd, _internal) {
  49310. const {cwd, disableGlobbing} = this.options;
  49311. this.closed = false;
  49312. let paths = unifyPaths(paths_);
  49313. if (cwd) {
  49314. paths = paths.map((path) => {
  49315. const absPath = getAbsolutePath(path, cwd);
  49316. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  49317. if (disableGlobbing || !isGlob(path)) {
  49318. return absPath;
  49319. }
  49320. return normalizePath(absPath);
  49321. });
  49322. }
  49323. // set aside negated glob strings
  49324. paths = paths.filter((path) => {
  49325. if (path.startsWith(BANG)) {
  49326. this._ignoredPaths.add(path.slice(1));
  49327. return false;
  49328. }
  49329. // if a path is being added that was previously ignored, stop ignoring it
  49330. this._ignoredPaths.delete(path);
  49331. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  49332. // reset the cached userIgnored anymatch fn
  49333. // to make ignoredPaths changes effective
  49334. this._userIgnored = undefined;
  49335. return true;
  49336. });
  49337. if (this.options.useFsEvents && this._fsEventsHandler) {
  49338. if (!this._readyCount) this._readyCount = paths.length;
  49339. if (this.options.persistent) this._readyCount *= 2;
  49340. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  49341. } else {
  49342. if (!this._readyCount) this._readyCount = 0;
  49343. this._readyCount += paths.length;
  49344. Promise.all(
  49345. paths.map(async path => {
  49346. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  49347. if (res) this._emitReady();
  49348. return res;
  49349. })
  49350. ).then(results => {
  49351. if (this.closed) return;
  49352. results.filter(item => item).forEach(item => {
  49353. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  49354. });
  49355. });
  49356. }
  49357. return this;
  49358. }
  49359. /**
  49360. * Close watchers or start ignoring events from specified paths.
  49361. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  49362. * @returns {FSWatcher} for chaining
  49363. */
  49364. unwatch(paths_) {
  49365. if (this.closed) return this;
  49366. const paths = unifyPaths(paths_);
  49367. const {cwd} = this.options;
  49368. paths.forEach((path) => {
  49369. // convert to absolute path unless relative path already matches
  49370. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  49371. if (cwd) path = sysPath.join(cwd, path);
  49372. path = sysPath.resolve(path);
  49373. }
  49374. this._closePath(path);
  49375. this._ignoredPaths.add(path);
  49376. if (this._watched.has(path)) {
  49377. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  49378. }
  49379. // reset the cached userIgnored anymatch fn
  49380. // to make ignoredPaths changes effective
  49381. this._userIgnored = undefined;
  49382. });
  49383. return this;
  49384. }
  49385. /**
  49386. * Close watchers and remove all listeners from watched paths.
  49387. * @returns {Promise<void>}.
  49388. */
  49389. close() {
  49390. if (this.closed) return this._closePromise;
  49391. this.closed = true;
  49392. // Memory management.
  49393. this.removeAllListeners();
  49394. const closers = [];
  49395. this._closers.forEach(closerList => closerList.forEach(closer => {
  49396. const promise = closer();
  49397. if (promise instanceof Promise) closers.push(promise);
  49398. }));
  49399. this._streams.forEach(stream => stream.destroy());
  49400. this._userIgnored = undefined;
  49401. this._readyCount = 0;
  49402. this._readyEmitted = false;
  49403. this._watched.forEach(dirent => dirent.dispose());
  49404. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  49405. this[`_${key}`].clear();
  49406. });
  49407. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  49408. return this._closePromise;
  49409. }
  49410. /**
  49411. * Expose list of watched paths
  49412. * @returns {Object} for chaining
  49413. */
  49414. getWatched() {
  49415. const watchList = {};
  49416. this._watched.forEach((entry, dir) => {
  49417. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  49418. watchList[key || ONE_DOT] = entry.getChildren().sort();
  49419. });
  49420. return watchList;
  49421. }
  49422. emitWithAll(event, args) {
  49423. this.emit(...args);
  49424. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  49425. }
  49426. // Common helpers
  49427. // --------------
  49428. /**
  49429. * Normalize and emit events.
  49430. * Calling _emit DOES NOT MEAN emit() would be called!
  49431. * @param {EventName} event Type of event
  49432. * @param {Path} path File or directory path
  49433. * @param {*=} val1 arguments to be passed with event
  49434. * @param {*=} val2
  49435. * @param {*=} val3
  49436. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  49437. */
  49438. async _emit(event, path, val1, val2, val3) {
  49439. if (this.closed) return;
  49440. const opts = this.options;
  49441. if (isWindows$1) path = sysPath.normalize(path);
  49442. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  49443. /** @type Array<any> */
  49444. const args = [event, path];
  49445. if (val3 !== undefined) args.push(val1, val2, val3);
  49446. else if (val2 !== undefined) args.push(val1, val2);
  49447. else if (val1 !== undefined) args.push(val1);
  49448. const awf = opts.awaitWriteFinish;
  49449. let pw;
  49450. if (awf && (pw = this._pendingWrites.get(path))) {
  49451. pw.lastChange = new Date();
  49452. return this;
  49453. }
  49454. if (opts.atomic) {
  49455. if (event === EV_UNLINK) {
  49456. this._pendingUnlinks.set(path, args);
  49457. setTimeout(() => {
  49458. this._pendingUnlinks.forEach((entry, path) => {
  49459. this.emit(...entry);
  49460. this.emit(EV_ALL, ...entry);
  49461. this._pendingUnlinks.delete(path);
  49462. });
  49463. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  49464. return this;
  49465. }
  49466. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  49467. event = args[0] = EV_CHANGE;
  49468. this._pendingUnlinks.delete(path);
  49469. }
  49470. }
  49471. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  49472. const awfEmit = (err, stats) => {
  49473. if (err) {
  49474. event = args[0] = EV_ERROR;
  49475. args[1] = err;
  49476. this.emitWithAll(event, args);
  49477. } else if (stats) {
  49478. // if stats doesn't exist the file must have been deleted
  49479. if (args.length > 2) {
  49480. args[2] = stats;
  49481. } else {
  49482. args.push(stats);
  49483. }
  49484. this.emitWithAll(event, args);
  49485. }
  49486. };
  49487. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  49488. return this;
  49489. }
  49490. if (event === EV_CHANGE) {
  49491. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  49492. if (isThrottled) return this;
  49493. }
  49494. if (opts.alwaysStat && val1 === undefined &&
  49495. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  49496. ) {
  49497. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  49498. let stats;
  49499. try {
  49500. stats = await stat(fullPath);
  49501. } catch (err) {}
  49502. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  49503. if (!stats || this.closed) return;
  49504. args.push(stats);
  49505. }
  49506. this.emitWithAll(event, args);
  49507. return this;
  49508. }
  49509. /**
  49510. * Common handler for errors
  49511. * @param {Error} error
  49512. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  49513. */
  49514. _handleError(error) {
  49515. const code = error && error.code;
  49516. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  49517. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  49518. ) {
  49519. this.emit(EV_ERROR, error);
  49520. }
  49521. return error || this.closed;
  49522. }
  49523. /**
  49524. * Helper utility for throttling
  49525. * @param {ThrottleType} actionType type being throttled
  49526. * @param {Path} path being acted upon
  49527. * @param {Number} timeout duration of time to suppress duplicate actions
  49528. * @returns {Object|false} tracking object or false if action should be suppressed
  49529. */
  49530. _throttle(actionType, path, timeout) {
  49531. if (!this._throttled.has(actionType)) {
  49532. this._throttled.set(actionType, new Map());
  49533. }
  49534. /** @type {Map<Path, Object>} */
  49535. const action = this._throttled.get(actionType);
  49536. /** @type {Object} */
  49537. const actionPath = action.get(path);
  49538. if (actionPath) {
  49539. actionPath.count++;
  49540. return false;
  49541. }
  49542. let timeoutObject;
  49543. const clear = () => {
  49544. const item = action.get(path);
  49545. const count = item ? item.count : 0;
  49546. action.delete(path);
  49547. clearTimeout(timeoutObject);
  49548. if (item) clearTimeout(item.timeoutObject);
  49549. return count;
  49550. };
  49551. timeoutObject = setTimeout(clear, timeout);
  49552. const thr = {timeoutObject, clear, count: 0};
  49553. action.set(path, thr);
  49554. return thr;
  49555. }
  49556. _incrReadyCount() {
  49557. return this._readyCount++;
  49558. }
  49559. /**
  49560. * Awaits write operation to finish.
  49561. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  49562. * @param {Path} path being acted upon
  49563. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  49564. * @param {EventName} event
  49565. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  49566. */
  49567. _awaitWriteFinish(path, threshold, event, awfEmit) {
  49568. let timeoutHandler;
  49569. let fullPath = path;
  49570. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  49571. fullPath = sysPath.join(this.options.cwd, path);
  49572. }
  49573. const now = new Date();
  49574. const awaitWriteFinish = (prevStat) => {
  49575. fs$5.stat(fullPath, (err, curStat) => {
  49576. if (err || !this._pendingWrites.has(path)) {
  49577. if (err && err.code !== 'ENOENT') awfEmit(err);
  49578. return;
  49579. }
  49580. const now = Number(new Date());
  49581. if (prevStat && curStat.size !== prevStat.size) {
  49582. this._pendingWrites.get(path).lastChange = now;
  49583. }
  49584. const pw = this._pendingWrites.get(path);
  49585. const df = now - pw.lastChange;
  49586. if (df >= threshold) {
  49587. this._pendingWrites.delete(path);
  49588. awfEmit(undefined, curStat);
  49589. } else {
  49590. timeoutHandler = setTimeout(
  49591. awaitWriteFinish,
  49592. this.options.awaitWriteFinish.pollInterval,
  49593. curStat
  49594. );
  49595. }
  49596. });
  49597. };
  49598. if (!this._pendingWrites.has(path)) {
  49599. this._pendingWrites.set(path, {
  49600. lastChange: now,
  49601. cancelWait: () => {
  49602. this._pendingWrites.delete(path);
  49603. clearTimeout(timeoutHandler);
  49604. return event;
  49605. }
  49606. });
  49607. timeoutHandler = setTimeout(
  49608. awaitWriteFinish,
  49609. this.options.awaitWriteFinish.pollInterval
  49610. );
  49611. }
  49612. }
  49613. _getGlobIgnored() {
  49614. return [...this._ignoredPaths.values()];
  49615. }
  49616. /**
  49617. * Determines whether user has asked to ignore this path.
  49618. * @param {Path} path filepath or dir
  49619. * @param {fs.Stats=} stats result of fs.stat
  49620. * @returns {Boolean}
  49621. */
  49622. _isIgnored(path, stats) {
  49623. if (this.options.atomic && DOT_RE.test(path)) return true;
  49624. if (!this._userIgnored) {
  49625. const {cwd} = this.options;
  49626. const ign = this.options.ignored;
  49627. const ignored = ign && ign.map(normalizeIgnored(cwd));
  49628. const paths = arrify(ignored)
  49629. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  49630. .map((path) => path + SLASH_GLOBSTAR);
  49631. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  49632. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  49633. }
  49634. return this._userIgnored([path, stats]);
  49635. }
  49636. _isntIgnored(path, stat) {
  49637. return !this._isIgnored(path, stat);
  49638. }
  49639. /**
  49640. * Provides a set of common helpers and properties relating to symlink and glob handling.
  49641. * @param {Path} path file, directory, or glob pattern being watched
  49642. * @param {Number=} depth at any depth > 0, this isn't a glob
  49643. * @returns {WatchHelper} object containing helpers for this path
  49644. */
  49645. _getWatchHelpers(path, depth) {
  49646. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  49647. const follow = this.options.followSymlinks;
  49648. return new WatchHelper(path, watchPath, follow, this);
  49649. }
  49650. // Directory helpers
  49651. // -----------------
  49652. /**
  49653. * Provides directory tracking objects
  49654. * @param {String} directory path of the directory
  49655. * @returns {DirEntry} the directory's tracking object
  49656. */
  49657. _getWatchedDir(directory) {
  49658. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  49659. const dir = sysPath.resolve(directory);
  49660. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  49661. return this._watched.get(dir);
  49662. }
  49663. // File helpers
  49664. // ------------
  49665. /**
  49666. * Check for read permissions.
  49667. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  49668. * @param {fs.Stats} stats - object, result of fs_stat
  49669. * @returns {Boolean} indicates whether the file can be read
  49670. */
  49671. _hasReadPermissions(stats) {
  49672. if (this.options.ignorePermissionErrors) return true;
  49673. // stats.mode may be bigint
  49674. const md = stats && Number.parseInt(stats.mode, 10);
  49675. const st = md & 0o777;
  49676. const it = Number.parseInt(st.toString(8)[0], 10);
  49677. return Boolean(4 & it);
  49678. }
  49679. /**
  49680. * Handles emitting unlink events for
  49681. * files and directories, and via recursion, for
  49682. * files and directories within directories that are unlinked
  49683. * @param {String} directory within which the following item is located
  49684. * @param {String} item base path of item/directory
  49685. * @returns {void}
  49686. */
  49687. _remove(directory, item, isDirectory) {
  49688. // if what is being deleted is a directory, get that directory's paths
  49689. // for recursive deleting and cleaning of watched object
  49690. // if it is not a directory, nestedDirectoryChildren will be empty array
  49691. const path = sysPath.join(directory, item);
  49692. const fullPath = sysPath.resolve(path);
  49693. isDirectory = isDirectory != null
  49694. ? isDirectory
  49695. : this._watched.has(path) || this._watched.has(fullPath);
  49696. // prevent duplicate handling in case of arriving here nearly simultaneously
  49697. // via multiple paths (such as _handleFile and _handleDir)
  49698. if (!this._throttle('remove', path, 100)) return;
  49699. // if the only watched file is removed, watch for its return
  49700. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  49701. this.add(directory, item, true);
  49702. }
  49703. // This will create a new entry in the watched object in either case
  49704. // so we got to do the directory check beforehand
  49705. const wp = this._getWatchedDir(path);
  49706. const nestedDirectoryChildren = wp.getChildren();
  49707. // Recursively remove children directories / files.
  49708. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  49709. // Check if item was on the watched list and remove it
  49710. const parent = this._getWatchedDir(directory);
  49711. const wasTracked = parent.has(item);
  49712. parent.remove(item);
  49713. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  49714. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  49715. // but never removed from the map in case the path was deleted.
  49716. // This leads to an incorrect state if the path was recreated:
  49717. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  49718. if (this._symlinkPaths.has(fullPath)) {
  49719. this._symlinkPaths.delete(fullPath);
  49720. }
  49721. // If we wait for this file to be fully written, cancel the wait.
  49722. let relPath = path;
  49723. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  49724. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  49725. const event = this._pendingWrites.get(relPath).cancelWait();
  49726. if (event === EV_ADD) return;
  49727. }
  49728. // The Entry will either be a directory that just got removed
  49729. // or a bogus entry to a file, in either case we have to remove it
  49730. this._watched.delete(path);
  49731. this._watched.delete(fullPath);
  49732. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  49733. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  49734. // Avoid conflicts if we later create another file with the same name
  49735. if (!this.options.useFsEvents) {
  49736. this._closePath(path);
  49737. }
  49738. }
  49739. /**
  49740. * Closes all watchers for a path
  49741. * @param {Path} path
  49742. */
  49743. _closePath(path) {
  49744. this._closeFile(path);
  49745. const dir = sysPath.dirname(path);
  49746. this._getWatchedDir(dir).remove(sysPath.basename(path));
  49747. }
  49748. /**
  49749. * Closes only file-specific watchers
  49750. * @param {Path} path
  49751. */
  49752. _closeFile(path) {
  49753. const closers = this._closers.get(path);
  49754. if (!closers) return;
  49755. closers.forEach(closer => closer());
  49756. this._closers.delete(path);
  49757. }
  49758. /**
  49759. *
  49760. * @param {Path} path
  49761. * @param {Function} closer
  49762. */
  49763. _addPathCloser(path, closer) {
  49764. if (!closer) return;
  49765. let list = this._closers.get(path);
  49766. if (!list) {
  49767. list = [];
  49768. this._closers.set(path, list);
  49769. }
  49770. list.push(closer);
  49771. }
  49772. _readdirp(root, opts) {
  49773. if (this.closed) return;
  49774. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  49775. let stream = readdirp(root, options);
  49776. this._streams.add(stream);
  49777. stream.once(STR_CLOSE, () => {
  49778. stream = undefined;
  49779. });
  49780. stream.once(STR_END, () => {
  49781. if (stream) {
  49782. this._streams.delete(stream);
  49783. stream = undefined;
  49784. }
  49785. });
  49786. return stream;
  49787. }
  49788. }
  49789. // Export FSWatcher class
  49790. chokidar.FSWatcher = FSWatcher;
  49791. /**
  49792. * Instantiates watcher with paths to be tracked.
  49793. * @param {String|Array<String>} paths file/directory paths and/or globs
  49794. * @param {Object=} options chokidar opts
  49795. * @returns an instance of FSWatcher for chaining.
  49796. */
  49797. const watch = (paths, options) => {
  49798. const watcher = new FSWatcher(options);
  49799. watcher.add(paths);
  49800. return watcher;
  49801. };
  49802. chokidar.watch = watch;
  49803. var shellQuote$1 = {};
  49804. shellQuote$1.quote = function (xs) {
  49805. return xs.map(function (s) {
  49806. if (s && typeof s === 'object') {
  49807. return s.op.replace(/(.)/g, '\\$1');
  49808. }
  49809. else if (/["\s]/.test(s) && !/'/.test(s)) {
  49810. return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
  49811. }
  49812. else if (/["'\s]/.test(s)) {
  49813. return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
  49814. }
  49815. else {
  49816. return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2');
  49817. }
  49818. }).join(' ');
  49819. };
  49820. // '<(' is process substitution operator and
  49821. // can be parsed the same as control operator
  49822. var CONTROL = '(?:' + [
  49823. '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]'
  49824. ].join('|') + ')';
  49825. var META = '|&;()<> \\t';
  49826. var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+';
  49827. var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
  49828. var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
  49829. var TOKEN = '';
  49830. for (var i = 0; i < 4; i++) {
  49831. TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
  49832. }
  49833. shellQuote$1.parse = function (s, env, opts) {
  49834. var mapped = parse$5(s, env, opts);
  49835. if (typeof env !== 'function') return mapped;
  49836. return mapped.reduce(function (acc, s) {
  49837. if (typeof s === 'object') return acc.concat(s);
  49838. var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
  49839. if (xs.length === 1) return acc.concat(xs[0]);
  49840. return acc.concat(xs.filter(Boolean).map(function (x) {
  49841. if (RegExp('^' + TOKEN).test(x)) {
  49842. return JSON.parse(x.split(TOKEN)[1]);
  49843. }
  49844. else return x;
  49845. }));
  49846. }, []);
  49847. };
  49848. function parse$5 (s, env, opts) {
  49849. var chunker = new RegExp([
  49850. '(' + CONTROL + ')', // control chars
  49851. '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
  49852. ].join('|'), 'g');
  49853. var match = s.match(chunker).filter(Boolean);
  49854. var commented = false;
  49855. if (!match) return [];
  49856. if (!env) env = {};
  49857. if (!opts) opts = {};
  49858. return match.map(function (s, j) {
  49859. if (commented) {
  49860. return;
  49861. }
  49862. if (RegExp('^' + CONTROL + '$').test(s)) {
  49863. return { op: s };
  49864. }
  49865. // Hand-written scanner/parser for Bash quoting rules:
  49866. //
  49867. // 1. inside single quotes, all characters are printed literally.
  49868. // 2. inside double quotes, all characters are printed literally
  49869. // except variables prefixed by '$' and backslashes followed by
  49870. // either a double quote or another backslash.
  49871. // 3. outside of any quotes, backslashes are treated as escape
  49872. // characters and not printed (unless they are themselves escaped)
  49873. // 4. quote context can switch mid-token if there is no whitespace
  49874. // between the two quote contexts (e.g. all'one'"token" parses as
  49875. // "allonetoken")
  49876. var SQ = "'";
  49877. var DQ = '"';
  49878. var DS = '$';
  49879. var BS = opts.escape || '\\';
  49880. var quote = false;
  49881. var esc = false;
  49882. var out = '';
  49883. var isGlob = false;
  49884. for (var i = 0, len = s.length; i < len; i++) {
  49885. var c = s.charAt(i);
  49886. isGlob = isGlob || (!quote && (c === '*' || c === '?'));
  49887. if (esc) {
  49888. out += c;
  49889. esc = false;
  49890. }
  49891. else if (quote) {
  49892. if (c === quote) {
  49893. quote = false;
  49894. }
  49895. else if (quote == SQ) {
  49896. out += c;
  49897. }
  49898. else { // Double quote
  49899. if (c === BS) {
  49900. i += 1;
  49901. c = s.charAt(i);
  49902. if (c === DQ || c === BS || c === DS) {
  49903. out += c;
  49904. } else {
  49905. out += BS + c;
  49906. }
  49907. }
  49908. else if (c === DS) {
  49909. out += parseEnvVar();
  49910. }
  49911. else {
  49912. out += c;
  49913. }
  49914. }
  49915. }
  49916. else if (c === DQ || c === SQ) {
  49917. quote = c;
  49918. }
  49919. else if (RegExp('^' + CONTROL + '$').test(c)) {
  49920. return { op: s };
  49921. }
  49922. else if (RegExp('^#$').test(c)) {
  49923. commented = true;
  49924. if (out.length){
  49925. return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  49926. }
  49927. return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  49928. }
  49929. else if (c === BS) {
  49930. esc = true;
  49931. }
  49932. else if (c === DS) {
  49933. out += parseEnvVar();
  49934. }
  49935. else out += c;
  49936. }
  49937. if (isGlob) return {op: 'glob', pattern: out};
  49938. return out;
  49939. function parseEnvVar() {
  49940. i += 1;
  49941. var varend, varname;
  49942. //debugger
  49943. if (s.charAt(i) === '{') {
  49944. i += 1;
  49945. if (s.charAt(i) === '}') {
  49946. throw new Error("Bad substitution: " + s.substr(i - 2, 3));
  49947. }
  49948. varend = s.indexOf('}', i);
  49949. if (varend < 0) {
  49950. throw new Error("Bad substitution: " + s.substr(i));
  49951. }
  49952. varname = s.substr(i, varend - i);
  49953. i = varend;
  49954. }
  49955. else if (/[*@#?$!_\-]/.test(s.charAt(i))) {
  49956. varname = s.charAt(i);
  49957. i += 1;
  49958. }
  49959. else {
  49960. varend = s.substr(i).match(/[^\w\d_]/);
  49961. if (!varend) {
  49962. varname = s.substr(i);
  49963. i = s.length;
  49964. } else {
  49965. varname = s.substr(i, varend.index);
  49966. i += varend.index - 1;
  49967. }
  49968. }
  49969. return getVar(null, '', varname);
  49970. }
  49971. })
  49972. // finalize parsed aruments
  49973. .reduce(function(prev, arg){
  49974. if (arg === undefined){
  49975. return prev;
  49976. }
  49977. return prev.concat(arg);
  49978. },[]);
  49979. function getVar (_, pre, key) {
  49980. var r = typeof env === 'function' ? env(key) : env[key];
  49981. if (r === undefined && key != '')
  49982. r = '';
  49983. else if (r === undefined)
  49984. r = '$';
  49985. if (typeof r === 'object') {
  49986. return pre + TOKEN + JSON.stringify(r) + TOKEN;
  49987. }
  49988. else return pre + r;
  49989. }
  49990. }
  49991. var osx = {
  49992. '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
  49993. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
  49994. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
  49995. '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
  49996. '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
  49997. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  49998. '/Applications/Sublime Text.app/Contents/MacOS/sublime_text':
  49999. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  50000. '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
  50001. '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
  50002. '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
  50003. '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
  50004. '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
  50005. '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
  50006. 'code-insiders',
  50007. '/Applications/VSCodium.app/Contents/MacOS/Electron': 'codium',
  50008. '/Applications/AppCode.app/Contents/MacOS/appcode':
  50009. '/Applications/AppCode.app/Contents/MacOS/appcode',
  50010. '/Applications/CLion.app/Contents/MacOS/clion':
  50011. '/Applications/CLion.app/Contents/MacOS/clion',
  50012. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
  50013. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
  50014. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
  50015. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
  50016. '/Applications/PyCharm.app/Contents/MacOS/pycharm':
  50017. '/Applications/PyCharm.app/Contents/MacOS/pycharm',
  50018. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
  50019. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
  50020. '/Applications/RubyMine.app/Contents/MacOS/rubymine':
  50021. '/Applications/RubyMine.app/Contents/MacOS/rubymine',
  50022. '/Applications/WebStorm.app/Contents/MacOS/webstorm':
  50023. '/Applications/WebStorm.app/Contents/MacOS/webstorm',
  50024. '/Applications/MacVim.app/Contents/MacOS/MacVim': 'mvim',
  50025. '/Applications/GoLand.app/Contents/MacOS/goland':
  50026. '/Applications/GoLand.app/Contents/MacOS/goland',
  50027. '/Applications/Rider.app/Contents/MacOS/rider':
  50028. '/Applications/Rider.app/Contents/MacOS/rider'
  50029. };
  50030. var linux = {
  50031. atom: 'atom',
  50032. Brackets: 'brackets',
  50033. code: 'code',
  50034. 'code-insiders': 'code-insiders',
  50035. codium: 'codium',
  50036. vscodium: 'vscodium',
  50037. emacs: 'emacs',
  50038. gvim: 'gvim',
  50039. 'idea.sh': 'idea',
  50040. 'phpstorm.sh': 'phpstorm',
  50041. 'pycharm.sh': 'pycharm',
  50042. 'rubymine.sh': 'rubymine',
  50043. sublime_text: 'subl',
  50044. vim: 'vim',
  50045. 'webstorm.sh': 'webstorm',
  50046. 'goland.sh': 'goland',
  50047. 'rider.sh': 'rider'
  50048. };
  50049. var windows$1 = [
  50050. 'Brackets.exe',
  50051. 'Code.exe',
  50052. 'Code - Insiders.exe',
  50053. 'VSCodium.exe',
  50054. 'atom.exe',
  50055. 'sublime_text.exe',
  50056. 'notepad++.exe',
  50057. 'clion.exe',
  50058. 'clion64.exe',
  50059. 'idea.exe',
  50060. 'idea64.exe',
  50061. 'phpstorm.exe',
  50062. 'phpstorm64.exe',
  50063. 'pycharm.exe',
  50064. 'pycharm64.exe',
  50065. 'rubymine.exe',
  50066. 'rubymine64.exe',
  50067. 'webstorm.exe',
  50068. 'webstorm64.exe',
  50069. 'goland.exe',
  50070. 'goland64.exe',
  50071. 'rider.exe',
  50072. 'rider64.exe'
  50073. ];
  50074. const path$7 = require$$0$4;
  50075. const shellQuote = shellQuote$1;
  50076. const childProcess$2 = require$$2$1;
  50077. // Map from full process name to binary that starts the process
  50078. // We can't just re-use full process name, because it will spawn a new instance
  50079. // of the app every time
  50080. const COMMON_EDITORS_OSX = osx;
  50081. const COMMON_EDITORS_LINUX = linux;
  50082. const COMMON_EDITORS_WIN = windows$1;
  50083. var guess = function guessEditor (specifiedEditor) {
  50084. if (specifiedEditor) {
  50085. return shellQuote.parse(specifiedEditor)
  50086. }
  50087. if (process.env.LAUNCH_EDITOR) {
  50088. return [process.env.LAUNCH_EDITOR]
  50089. }
  50090. if (process.versions.webcontainer) {
  50091. return [process.env.EDITOR || 'code']
  50092. }
  50093. // We can find out which editor is currently running by:
  50094. // `ps x` on macOS and Linux
  50095. // `Get-Process` on Windows
  50096. try {
  50097. if (process.platform === 'darwin') {
  50098. const output = childProcess$2
  50099. .execSync('ps x -o comm=', {
  50100. stdio: ['pipe', 'pipe', 'ignore']
  50101. })
  50102. .toString();
  50103. const processNames = Object.keys(COMMON_EDITORS_OSX);
  50104. const processList = output.split('\n');
  50105. for (let i = 0; i < processNames.length; i++) {
  50106. const processName = processNames[i];
  50107. // Find editor by exact match.
  50108. if (output.indexOf(processName) !== -1) {
  50109. return [COMMON_EDITORS_OSX[processName]]
  50110. }
  50111. const processNameWithoutApplications = processName.replace('/Applications', '');
  50112. // Find editor installation not in /Applications.
  50113. if (output.indexOf(processNameWithoutApplications) !== -1) {
  50114. // Use the CLI command if one is specified
  50115. if (processName !== COMMON_EDITORS_OSX[processName]) {
  50116. return [COMMON_EDITORS_OSX[processName]]
  50117. }
  50118. // Use a partial match to find the running process path. If one is found, use the
  50119. // existing path since it can be running from anywhere.
  50120. const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
  50121. if (runningProcess !== undefined) {
  50122. return [runningProcess]
  50123. }
  50124. }
  50125. }
  50126. } else if (process.platform === 'win32') {
  50127. const output = childProcess$2
  50128. .execSync(
  50129. 'powershell -NoProfile -Command "Get-CimInstance -Query \\"select executablepath from win32_process where executablepath is not null\\" | % { $_.ExecutablePath }"',
  50130. {
  50131. stdio: ['pipe', 'pipe', 'ignore']
  50132. }
  50133. )
  50134. .toString();
  50135. const runningProcesses = output.split('\r\n');
  50136. for (let i = 0; i < runningProcesses.length; i++) {
  50137. const fullProcessPath = runningProcesses[i].trim();
  50138. const shortProcessName = path$7.basename(fullProcessPath);
  50139. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
  50140. return [fullProcessPath]
  50141. }
  50142. }
  50143. } else if (process.platform === 'linux') {
  50144. // --no-heading No header line
  50145. // x List all processes owned by you
  50146. // -o comm Need only names column
  50147. const output = childProcess$2
  50148. .execSync('ps x --no-heading -o comm --sort=comm', {
  50149. stdio: ['pipe', 'pipe', 'ignore']
  50150. })
  50151. .toString();
  50152. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  50153. for (let i = 0; i < processNames.length; i++) {
  50154. const processName = processNames[i];
  50155. if (output.indexOf(processName) !== -1) {
  50156. return [COMMON_EDITORS_LINUX[processName]]
  50157. }
  50158. }
  50159. }
  50160. } catch (error) {
  50161. // Ignore...
  50162. }
  50163. // Last resort, use old skool env vars
  50164. if (process.env.VISUAL) {
  50165. return [process.env.VISUAL]
  50166. } else if (process.env.EDITOR) {
  50167. return [process.env.EDITOR]
  50168. }
  50169. return [null]
  50170. };
  50171. const path$6 = require$$0$4;
  50172. // normalize file/line numbers into command line args for specific editors
  50173. var getArgs = function getArgumentsForPosition (
  50174. editor,
  50175. fileName,
  50176. lineNumber,
  50177. columnNumber = 1
  50178. ) {
  50179. const editorBasename = path$6.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
  50180. switch (editorBasename) {
  50181. case 'atom':
  50182. case 'Atom':
  50183. case 'Atom Beta':
  50184. case 'subl':
  50185. case 'sublime':
  50186. case 'sublime_text':
  50187. case 'wstorm':
  50188. case 'charm':
  50189. return [`${fileName}:${lineNumber}:${columnNumber}`]
  50190. case 'notepad++':
  50191. return ['-n' + lineNumber, '-c' + columnNumber, fileName]
  50192. case 'vim':
  50193. case 'mvim':
  50194. return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]
  50195. case 'joe':
  50196. case 'gvim':
  50197. return ['+' + `${lineNumber}`, fileName]
  50198. case 'emacs':
  50199. case 'emacsclient':
  50200. return [`+${lineNumber}:${columnNumber}`, fileName]
  50201. case 'rmate':
  50202. case 'mate':
  50203. case 'mine':
  50204. return ['--line', lineNumber, fileName]
  50205. case 'code':
  50206. case 'Code':
  50207. case 'code-insiders':
  50208. case 'Code - Insiders':
  50209. case 'codium':
  50210. case 'vscodium':
  50211. case 'VSCodium':
  50212. return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]
  50213. case 'appcode':
  50214. case 'clion':
  50215. case 'clion64':
  50216. case 'idea':
  50217. case 'idea64':
  50218. case 'phpstorm':
  50219. case 'phpstorm64':
  50220. case 'pycharm':
  50221. case 'pycharm64':
  50222. case 'rubymine':
  50223. case 'rubymine64':
  50224. case 'webstorm':
  50225. case 'webstorm64':
  50226. case 'goland':
  50227. case 'goland64':
  50228. case 'rider':
  50229. case 'rider64':
  50230. return ['--line', lineNumber, '--column', columnNumber, fileName]
  50231. }
  50232. if (process.env.LAUNCH_EDITOR) {
  50233. return [fileName, lineNumber, columnNumber]
  50234. }
  50235. // For all others, drop the lineNumber until we have
  50236. // a mapping above, since providing the lineNumber incorrectly
  50237. // can result in errors or confusing behavior.
  50238. return [fileName]
  50239. };
  50240. /**
  50241. * Copyright (c) 2015-present, Facebook, Inc.
  50242. *
  50243. * This source code is licensed under the MIT license found in the
  50244. * LICENSE file at
  50245. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  50246. *
  50247. * Modified by Yuxi Evan You
  50248. */
  50249. const fs$4 = require$$0__default;
  50250. const os$1 = require$$2;
  50251. const path$5 = require$$0$4;
  50252. const colors = picocolorsExports;
  50253. const childProcess$1 = require$$2$1;
  50254. const guessEditor = guess;
  50255. const getArgumentsForPosition = getArgs;
  50256. function wrapErrorCallback (cb) {
  50257. return (fileName, errorMessage) => {
  50258. console.log();
  50259. console.log(
  50260. colors.red('Could not open ' + path$5.basename(fileName) + ' in the editor.')
  50261. );
  50262. if (errorMessage) {
  50263. if (errorMessage[errorMessage.length - 1] !== '.') {
  50264. errorMessage += '.';
  50265. }
  50266. console.log(
  50267. colors.red('The editor process exited with an error: ' + errorMessage)
  50268. );
  50269. }
  50270. console.log();
  50271. if (cb) cb(fileName, errorMessage);
  50272. }
  50273. }
  50274. function isTerminalEditor (editor) {
  50275. switch (editor) {
  50276. case 'vim':
  50277. case 'emacs':
  50278. case 'nano':
  50279. return true
  50280. }
  50281. return false
  50282. }
  50283. const positionRE = /:(\d+)(:(\d+))?$/;
  50284. function parseFile (file) {
  50285. const fileName = file.replace(positionRE, '');
  50286. const match = file.match(positionRE);
  50287. const lineNumber = match && match[1];
  50288. const columnNumber = match && match[3];
  50289. return {
  50290. fileName,
  50291. lineNumber,
  50292. columnNumber
  50293. }
  50294. }
  50295. let _childProcess = null;
  50296. function launchEditor (file, specifiedEditor, onErrorCallback) {
  50297. const parsed = parseFile(file);
  50298. let { fileName } = parsed;
  50299. const { lineNumber, columnNumber } = parsed;
  50300. if (!fs$4.existsSync(fileName)) {
  50301. return
  50302. }
  50303. if (typeof specifiedEditor === 'function') {
  50304. onErrorCallback = specifiedEditor;
  50305. specifiedEditor = undefined;
  50306. }
  50307. onErrorCallback = wrapErrorCallback(onErrorCallback);
  50308. const [editor, ...args] = guessEditor(specifiedEditor);
  50309. if (!editor) {
  50310. onErrorCallback(fileName, null);
  50311. return
  50312. }
  50313. if (
  50314. process.platform === 'linux' &&
  50315. fileName.startsWith('/mnt/') &&
  50316. /Microsoft/i.test(os$1.release())
  50317. ) {
  50318. // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
  50319. // that the file exists on the Windows file system.
  50320. // `os.release()` is "4.4.0-43-Microsoft" in the current release
  50321. // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
  50322. // When a Windows editor is specified, interop functionality can
  50323. // handle the path translation, but only if a relative path is used.
  50324. fileName = path$5.relative('', fileName);
  50325. }
  50326. if (lineNumber) {
  50327. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  50328. args.push.apply(args, extraArgs);
  50329. } else {
  50330. args.push(fileName);
  50331. }
  50332. if (_childProcess && isTerminalEditor(editor)) {
  50333. // There's an existing editor process already and it's attached
  50334. // to the terminal, so go kill it. Otherwise two separate editor
  50335. // instances attach to the stdin/stdout which gets confusing.
  50336. _childProcess.kill('SIGKILL');
  50337. }
  50338. if (process.platform === 'win32') {
  50339. // On Windows, launch the editor in a shell because spawn can only
  50340. // launch .exe files.
  50341. _childProcess = childProcess$1.spawn(
  50342. 'cmd.exe',
  50343. ['/C', editor].concat(args),
  50344. { stdio: 'inherit' }
  50345. );
  50346. } else {
  50347. _childProcess = childProcess$1.spawn(editor, args, { stdio: 'inherit' });
  50348. }
  50349. _childProcess.on('exit', function (errorCode) {
  50350. _childProcess = null;
  50351. if (errorCode) {
  50352. onErrorCallback(fileName, '(code ' + errorCode + ')');
  50353. }
  50354. });
  50355. _childProcess.on('error', function (error) {
  50356. onErrorCallback(fileName, error.message);
  50357. });
  50358. }
  50359. var launchEditor_1 = launchEditor;
  50360. const url$2 = require$$0$9;
  50361. const path$4 = require$$0$4;
  50362. const launch = launchEditor_1;
  50363. var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
  50364. if (typeof specifiedEditor === 'function') {
  50365. onErrorCallback = specifiedEditor;
  50366. specifiedEditor = undefined;
  50367. }
  50368. if (typeof srcRoot === 'function') {
  50369. onErrorCallback = srcRoot;
  50370. srcRoot = undefined;
  50371. }
  50372. srcRoot = srcRoot || process.cwd();
  50373. return function launchEditorMiddleware (req, res, next) {
  50374. const { file } = url$2.parse(req.url, true).query || {};
  50375. if (!file) {
  50376. res.statusCode = 500;
  50377. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  50378. } else {
  50379. launch(path$4.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  50380. res.end();
  50381. }
  50382. }
  50383. };
  50384. var launchEditorMiddleware$1 = /*@__PURE__*/getDefaultExportFromCjs(launchEditorMiddleware);
  50385. async function resolveHttpServer({ proxy }, app, httpsOptions) {
  50386. if (!httpsOptions) {
  50387. const { createServer } = await import('node:http');
  50388. return createServer(app);
  50389. }
  50390. // #484 fallback to http1 when proxy is needed.
  50391. if (proxy) {
  50392. const { createServer } = await import('node:https');
  50393. return createServer(httpsOptions, app);
  50394. }
  50395. else {
  50396. const { createSecureServer } = await import('node:http2');
  50397. return createSecureServer({
  50398. // Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
  50399. // errors on large numbers of requests
  50400. maxSessionMemory: 1000,
  50401. ...httpsOptions,
  50402. allowHTTP1: true,
  50403. },
  50404. // @ts-expect-error TODO: is this correct?
  50405. app);
  50406. }
  50407. }
  50408. async function resolveHttpsConfig(https) {
  50409. if (!https)
  50410. return undefined;
  50411. if (!isObject$2(https))
  50412. return {};
  50413. const [ca, cert, key, pfx] = await Promise.all([
  50414. readFileIfExists(https.ca),
  50415. readFileIfExists(https.cert),
  50416. readFileIfExists(https.key),
  50417. readFileIfExists(https.pfx),
  50418. ]);
  50419. return { ...https, ca, cert, key, pfx };
  50420. }
  50421. async function readFileIfExists(value) {
  50422. if (typeof value === 'string') {
  50423. return fsp.readFile(path$o.resolve(value)).catch(() => value);
  50424. }
  50425. return value;
  50426. }
  50427. async function httpServerStart(httpServer, serverOptions) {
  50428. let { port, strictPort, host, logger } = serverOptions;
  50429. return new Promise((resolve, reject) => {
  50430. const onError = (e) => {
  50431. if (e.code === 'EADDRINUSE') {
  50432. if (strictPort) {
  50433. httpServer.removeListener('error', onError);
  50434. reject(new Error(`Port ${port} is already in use`));
  50435. }
  50436. else {
  50437. logger.info(`Port ${port} is in use, trying another one...`);
  50438. httpServer.listen(++port, host);
  50439. }
  50440. }
  50441. else {
  50442. httpServer.removeListener('error', onError);
  50443. reject(e);
  50444. }
  50445. };
  50446. httpServer.on('error', onError);
  50447. httpServer.listen(port, host, () => {
  50448. httpServer.removeListener('error', onError);
  50449. resolve(port);
  50450. });
  50451. });
  50452. }
  50453. function setClientErrorHandler(server, logger) {
  50454. server.on('clientError', (err, socket) => {
  50455. let msg = '400 Bad Request';
  50456. if (err.code === 'HPE_HEADER_OVERFLOW') {
  50457. msg = '431 Request Header Fields Too Large';
  50458. logger.warn(colors$1.yellow('Server responded with status code 431. ' +
  50459. 'See https://vitejs.dev/guide/troubleshooting.html#_431-request-header-fields-too-large.'));
  50460. }
  50461. if (err.code === 'ECONNRESET' || !socket.writable) {
  50462. return;
  50463. }
  50464. socket.end(`HTTP/1.1 ${msg}\r\n\r\n`);
  50465. });
  50466. }
  50467. const ERR_LOAD_URL = 'ERR_LOAD_URL';
  50468. const ERR_LOAD_PUBLIC_URL = 'ERR_LOAD_PUBLIC_URL';
  50469. const ERR_DENIED_ID = 'ERR_DENIED_ID';
  50470. const debugLoad = createDebugger('vite:load');
  50471. const debugTransform = createDebugger('vite:transform');
  50472. const debugCache$1 = createDebugger('vite:cache');
  50473. function transformRequest(url, server, options = {}) {
  50474. if (server._restartPromise && !options.ssr)
  50475. throwClosedServerError();
  50476. const cacheKey = (options.ssr ? 'ssr:' : options.html ? 'html:' : '') + url;
  50477. // This module may get invalidated while we are processing it. For example
  50478. // when a full page reload is needed after the re-processing of pre-bundled
  50479. // dependencies when a missing dep is discovered. We save the current time
  50480. // to compare it to the last invalidation performed to know if we should
  50481. // cache the result of the transformation or we should discard it as stale.
  50482. //
  50483. // A module can be invalidated due to:
  50484. // 1. A full reload because of pre-bundling newly discovered deps
  50485. // 2. A full reload after a config change
  50486. // 3. The file that generated the module changed
  50487. // 4. Invalidation for a virtual module
  50488. //
  50489. // For 1 and 2, a new request for this module will be issued after
  50490. // the invalidation as part of the browser reloading the page. For 3 and 4
  50491. // there may not be a new request right away because of HMR handling.
  50492. // In all cases, the next time this module is requested, it should be
  50493. // re-processed.
  50494. //
  50495. // We save the timestamp when we start processing and compare it with the
  50496. // last time this module is invalidated
  50497. const timestamp = Date.now();
  50498. const pending = server._pendingRequests.get(cacheKey);
  50499. if (pending) {
  50500. return server.moduleGraph
  50501. .getModuleByUrl(removeTimestampQuery(url), options.ssr)
  50502. .then((module) => {
  50503. if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
  50504. // The pending request is still valid, we can safely reuse its result
  50505. return pending.request;
  50506. }
  50507. else {
  50508. // Request 1 for module A (pending.timestamp)
  50509. // Invalidate module A (module.lastInvalidationTimestamp)
  50510. // Request 2 for module A (timestamp)
  50511. // First request has been invalidated, abort it to clear the cache,
  50512. // then perform a new doTransform.
  50513. pending.abort();
  50514. return transformRequest(url, server, options);
  50515. }
  50516. });
  50517. }
  50518. const request = doTransform(url, server, options, timestamp);
  50519. // Avoid clearing the cache of future requests if aborted
  50520. let cleared = false;
  50521. const clearCache = () => {
  50522. if (!cleared) {
  50523. server._pendingRequests.delete(cacheKey);
  50524. cleared = true;
  50525. }
  50526. };
  50527. // Cache the request and clear it once processing is done
  50528. server._pendingRequests.set(cacheKey, {
  50529. request,
  50530. timestamp,
  50531. abort: clearCache,
  50532. });
  50533. return request.finally(clearCache);
  50534. }
  50535. async function doTransform(url, server, options, timestamp) {
  50536. url = removeTimestampQuery(url);
  50537. const { config, pluginContainer } = server;
  50538. const prettyUrl = debugCache$1 ? prettifyUrl(url, config.root) : '';
  50539. const ssr = !!options.ssr;
  50540. const module = await server.moduleGraph.getModuleByUrl(url, ssr);
  50541. // check if we have a fresh cache
  50542. const cached = module && (ssr ? module.ssrTransformResult : module.transformResult);
  50543. if (cached) {
  50544. // TODO: check if the module is "partially invalidated" - i.e. an import
  50545. // down the chain has been fully invalidated, but this current module's
  50546. // content has not changed.
  50547. // in this case, we can reuse its previous cached result and only update
  50548. // its import timestamps.
  50549. debugCache$1?.(`[memory] ${prettyUrl}`);
  50550. return cached;
  50551. }
  50552. const resolved = module
  50553. ? undefined
  50554. : (await pluginContainer.resolveId(url, undefined, { ssr })) ?? undefined;
  50555. // resolve
  50556. const id = module?.id ?? resolved?.id ?? url;
  50557. const result = loadAndTransform(id, url, server, options, timestamp, module, resolved);
  50558. getDepsOptimizer(config, ssr)?.delayDepsOptimizerUntil(id, () => result);
  50559. return result;
  50560. }
  50561. async function loadAndTransform(id, url, server, options, timestamp, mod, resolved) {
  50562. const { config, pluginContainer, moduleGraph, watcher } = server;
  50563. const { root, logger } = config;
  50564. const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : '';
  50565. const ssr = !!options.ssr;
  50566. const file = cleanUrl(id);
  50567. if (options.allowId && !options.allowId(id)) {
  50568. const err = new Error(`Denied ID ${id}`);
  50569. err.code = ERR_DENIED_ID;
  50570. throw err;
  50571. }
  50572. let code = null;
  50573. let map = null;
  50574. // load
  50575. const loadStart = debugLoad ? performance.now() : 0;
  50576. const loadResult = await pluginContainer.load(id, { ssr });
  50577. if (loadResult == null) {
  50578. // if this is an html request and there is no load result, skip ahead to
  50579. // SPA fallback.
  50580. if (options.html && !id.endsWith('.html')) {
  50581. return null;
  50582. }
  50583. // try fallback loading it from fs as string
  50584. // if the file is a binary, there should be a plugin that already loaded it
  50585. // as string
  50586. // only try the fallback if access is allowed, skip for out of root url
  50587. // like /service-worker.js or /api/users
  50588. if (options.ssr || isFileServingAllowed(file, server)) {
  50589. try {
  50590. code = await fsp.readFile(file, 'utf-8');
  50591. debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  50592. }
  50593. catch (e) {
  50594. if (e.code !== 'ENOENT') {
  50595. if (e.code === 'EISDIR') {
  50596. e.message = `${e.message} ${file}`;
  50597. }
  50598. throw e;
  50599. }
  50600. }
  50601. }
  50602. if (code) {
  50603. try {
  50604. map = (convertSourceMap.fromSource(code) ||
  50605. (await convertSourceMap.fromMapFileSource(code, createConvertSourceMapReadMap(file))))?.toObject();
  50606. code = code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer);
  50607. }
  50608. catch (e) {
  50609. logger.warn(`Failed to load source map for ${url}.`, {
  50610. timestamp: true,
  50611. });
  50612. }
  50613. }
  50614. }
  50615. else {
  50616. debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  50617. if (isObject$2(loadResult)) {
  50618. code = loadResult.code;
  50619. map = loadResult.map;
  50620. }
  50621. else {
  50622. code = loadResult;
  50623. }
  50624. }
  50625. if (code == null) {
  50626. const isPublicFile = checkPublicFile(url, config);
  50627. const msg = isPublicFile
  50628. ? `This file is in /public and will be copied as-is during build without ` +
  50629. `going through the plugin transforms, and therefore should not be ` +
  50630. `imported from source code. It can only be referenced via HTML tags.`
  50631. : `Does the file exist?`;
  50632. const importerMod = server.moduleGraph.idToModuleMap
  50633. .get(id)
  50634. ?.importers.values()
  50635. .next().value;
  50636. const importer = importerMod?.file || importerMod?.url;
  50637. const err = new Error(`Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ''}. ${msg}`);
  50638. err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
  50639. throw err;
  50640. }
  50641. if (server._restartPromise && !ssr)
  50642. throwClosedServerError();
  50643. // ensure module in graph after successful load
  50644. mod ?? (mod = await moduleGraph._ensureEntryFromUrl(url, ssr, undefined, resolved));
  50645. ensureWatchedFile(watcher, mod.file, root);
  50646. // transform
  50647. const transformStart = debugTransform ? performance.now() : 0;
  50648. const transformResult = await pluginContainer.transform(code, id, {
  50649. inMap: map,
  50650. ssr,
  50651. });
  50652. const originalCode = code;
  50653. if (transformResult == null ||
  50654. (isObject$2(transformResult) && transformResult.code == null)) {
  50655. // no transform applied, keep code as-is
  50656. debugTransform?.(timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`));
  50657. }
  50658. else {
  50659. debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
  50660. code = transformResult.code;
  50661. map = transformResult.map;
  50662. }
  50663. if (map && mod.file) {
  50664. map = (typeof map === 'string' ? JSON.parse(map) : map);
  50665. if (map.mappings) {
  50666. await injectSourcesContent(map, mod.file, logger);
  50667. }
  50668. const sourcemapPath = `${mod.file}.map`;
  50669. applySourcemapIgnoreList(map, sourcemapPath, config.server.sourcemapIgnoreList, logger);
  50670. if (path$o.isAbsolute(mod.file)) {
  50671. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  50672. const sourcePath = map.sources[sourcesIndex];
  50673. if (sourcePath) {
  50674. // Rewrite sources to relative paths to give debuggers the chance
  50675. // to resolve and display them in a meaningful way (rather than
  50676. // with absolute paths).
  50677. if (path$o.isAbsolute(sourcePath)) {
  50678. map.sources[sourcesIndex] = path$o.relative(path$o.dirname(mod.file), sourcePath);
  50679. }
  50680. }
  50681. }
  50682. }
  50683. }
  50684. if (server._restartPromise && !ssr)
  50685. throwClosedServerError();
  50686. const result = ssr && !server.config.experimental.skipSsrTransform
  50687. ? await server.ssrTransform(code, map, url, originalCode)
  50688. : {
  50689. code,
  50690. map,
  50691. etag: getEtag(code, { weak: true }),
  50692. };
  50693. // Only cache the result if the module wasn't invalidated while it was
  50694. // being processed, so it is re-processed next time if it is stale
  50695. if (timestamp > mod.lastInvalidationTimestamp) {
  50696. if (ssr)
  50697. mod.ssrTransformResult = result;
  50698. else
  50699. mod.transformResult = result;
  50700. }
  50701. return result;
  50702. }
  50703. function createConvertSourceMapReadMap(originalFileName) {
  50704. return (filename) => {
  50705. return fsp.readFile(path$o.resolve(path$o.dirname(originalFileName), filename), 'utf-8');
  50706. };
  50707. }
  50708. /**
  50709. * @typedef { import('estree').Node} Node
  50710. * @typedef {{
  50711. * skip: () => void;
  50712. * remove: () => void;
  50713. * replace: (node: Node) => void;
  50714. * }} WalkerContext
  50715. */
  50716. class WalkerBase {
  50717. constructor() {
  50718. /** @type {boolean} */
  50719. this.should_skip = false;
  50720. /** @type {boolean} */
  50721. this.should_remove = false;
  50722. /** @type {Node | null} */
  50723. this.replacement = null;
  50724. /** @type {WalkerContext} */
  50725. this.context = {
  50726. skip: () => (this.should_skip = true),
  50727. remove: () => (this.should_remove = true),
  50728. replace: (node) => (this.replacement = node)
  50729. };
  50730. }
  50731. /**
  50732. * @template {Node} Parent
  50733. * @param {Parent | null | undefined} parent
  50734. * @param {keyof Parent | null | undefined} prop
  50735. * @param {number | null | undefined} index
  50736. * @param {Node} node
  50737. */
  50738. replace(parent, prop, index, node) {
  50739. if (parent && prop) {
  50740. if (index != null) {
  50741. /** @type {Array<Node>} */ (parent[prop])[index] = node;
  50742. } else {
  50743. /** @type {Node} */ (parent[prop]) = node;
  50744. }
  50745. }
  50746. }
  50747. /**
  50748. * @template {Node} Parent
  50749. * @param {Parent | null | undefined} parent
  50750. * @param {keyof Parent | null | undefined} prop
  50751. * @param {number | null | undefined} index
  50752. */
  50753. remove(parent, prop, index) {
  50754. if (parent && prop) {
  50755. if (index !== null && index !== undefined) {
  50756. /** @type {Array<Node>} */ (parent[prop]).splice(index, 1);
  50757. } else {
  50758. delete parent[prop];
  50759. }
  50760. }
  50761. }
  50762. }
  50763. /**
  50764. * @typedef { import('estree').Node} Node
  50765. * @typedef { import('./walker.js').WalkerContext} WalkerContext
  50766. * @typedef {(
  50767. * this: WalkerContext,
  50768. * node: Node,
  50769. * parent: Node | null,
  50770. * key: string | number | symbol | null | undefined,
  50771. * index: number | null | undefined
  50772. * ) => void} SyncHandler
  50773. */
  50774. class SyncWalker extends WalkerBase {
  50775. /**
  50776. *
  50777. * @param {SyncHandler} [enter]
  50778. * @param {SyncHandler} [leave]
  50779. */
  50780. constructor(enter, leave) {
  50781. super();
  50782. /** @type {boolean} */
  50783. this.should_skip = false;
  50784. /** @type {boolean} */
  50785. this.should_remove = false;
  50786. /** @type {Node | null} */
  50787. this.replacement = null;
  50788. /** @type {WalkerContext} */
  50789. this.context = {
  50790. skip: () => (this.should_skip = true),
  50791. remove: () => (this.should_remove = true),
  50792. replace: (node) => (this.replacement = node)
  50793. };
  50794. /** @type {SyncHandler | undefined} */
  50795. this.enter = enter;
  50796. /** @type {SyncHandler | undefined} */
  50797. this.leave = leave;
  50798. }
  50799. /**
  50800. * @template {Node} Parent
  50801. * @param {Node} node
  50802. * @param {Parent | null} parent
  50803. * @param {keyof Parent} [prop]
  50804. * @param {number | null} [index]
  50805. * @returns {Node | null}
  50806. */
  50807. visit(node, parent, prop, index) {
  50808. if (node) {
  50809. if (this.enter) {
  50810. const _should_skip = this.should_skip;
  50811. const _should_remove = this.should_remove;
  50812. const _replacement = this.replacement;
  50813. this.should_skip = false;
  50814. this.should_remove = false;
  50815. this.replacement = null;
  50816. this.enter.call(this.context, node, parent, prop, index);
  50817. if (this.replacement) {
  50818. node = this.replacement;
  50819. this.replace(parent, prop, index, node);
  50820. }
  50821. if (this.should_remove) {
  50822. this.remove(parent, prop, index);
  50823. }
  50824. const skipped = this.should_skip;
  50825. const removed = this.should_remove;
  50826. this.should_skip = _should_skip;
  50827. this.should_remove = _should_remove;
  50828. this.replacement = _replacement;
  50829. if (skipped) return node;
  50830. if (removed) return null;
  50831. }
  50832. /** @type {keyof Node} */
  50833. let key;
  50834. for (key in node) {
  50835. /** @type {unknown} */
  50836. const value = node[key];
  50837. if (value && typeof value === 'object') {
  50838. if (Array.isArray(value)) {
  50839. const nodes = /** @type {Array<unknown>} */ (value);
  50840. for (let i = 0; i < nodes.length; i += 1) {
  50841. const item = nodes[i];
  50842. if (isNode(item)) {
  50843. if (!this.visit(item, node, key, i)) {
  50844. // removed
  50845. i--;
  50846. }
  50847. }
  50848. }
  50849. } else if (isNode(value)) {
  50850. this.visit(value, node, key, null);
  50851. }
  50852. }
  50853. }
  50854. if (this.leave) {
  50855. const _replacement = this.replacement;
  50856. const _should_remove = this.should_remove;
  50857. this.replacement = null;
  50858. this.should_remove = false;
  50859. this.leave.call(this.context, node, parent, prop, index);
  50860. if (this.replacement) {
  50861. node = this.replacement;
  50862. this.replace(parent, prop, index, node);
  50863. }
  50864. if (this.should_remove) {
  50865. this.remove(parent, prop, index);
  50866. }
  50867. const removed = this.should_remove;
  50868. this.replacement = _replacement;
  50869. this.should_remove = _should_remove;
  50870. if (removed) return null;
  50871. }
  50872. }
  50873. return node;
  50874. }
  50875. }
  50876. /**
  50877. * Ducktype a node.
  50878. *
  50879. * @param {unknown} value
  50880. * @returns {value is Node}
  50881. */
  50882. function isNode(value) {
  50883. return (
  50884. value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
  50885. );
  50886. }
  50887. /**
  50888. * @typedef {import('estree').Node} Node
  50889. * @typedef {import('./sync.js').SyncHandler} SyncHandler
  50890. * @typedef {import('./async.js').AsyncHandler} AsyncHandler
  50891. */
  50892. /**
  50893. * @param {Node} ast
  50894. * @param {{
  50895. * enter?: SyncHandler
  50896. * leave?: SyncHandler
  50897. * }} walker
  50898. * @returns {Node | null}
  50899. */
  50900. function walk$1(ast, { enter, leave }) {
  50901. const instance = new SyncWalker(enter, leave);
  50902. return instance.visit(ast, null);
  50903. }
  50904. /**
  50905. * @param {import('estree').Node} param
  50906. * @returns {string[]}
  50907. */
  50908. function extract_names(param) {
  50909. return extract_identifiers(param).map(node => node.name);
  50910. }
  50911. /**
  50912. * @param {import('estree').Node} param
  50913. * @param {import('estree').Identifier[]} nodes
  50914. * @returns {import('estree').Identifier[]}
  50915. */
  50916. function extract_identifiers(param, nodes = []) {
  50917. switch (param.type) {
  50918. case 'Identifier':
  50919. nodes.push(param);
  50920. break;
  50921. case 'MemberExpression':
  50922. let object = param;
  50923. while (object.type === 'MemberExpression') {
  50924. object = /** @type {any} */ (object.object);
  50925. }
  50926. nodes.push(/** @type {any} */ (object));
  50927. break;
  50928. case 'ObjectPattern':
  50929. /** @param {import('estree').Property | import('estree').RestElement} prop */
  50930. const handle_prop = (prop) => {
  50931. if (prop.type === 'RestElement') {
  50932. extract_identifiers(prop.argument, nodes);
  50933. } else {
  50934. extract_identifiers(prop.value, nodes);
  50935. }
  50936. };
  50937. param.properties.forEach(handle_prop);
  50938. break;
  50939. case 'ArrayPattern':
  50940. /** @param {import('estree').Node} element */
  50941. const handle_element = (element) => {
  50942. if (element) extract_identifiers(element, nodes);
  50943. };
  50944. param.elements.forEach((element) => {
  50945. if (element) {
  50946. handle_element(element);
  50947. }
  50948. });
  50949. break;
  50950. case 'RestElement':
  50951. extract_identifiers(param.argument, nodes);
  50952. break;
  50953. case 'AssignmentPattern':
  50954. extract_identifiers(param.left, nodes);
  50955. break;
  50956. }
  50957. return nodes;
  50958. }
  50959. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  50960. const ssrImportKey = `__vite_ssr_import__`;
  50961. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  50962. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  50963. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  50964. const hashbangRE = /^#!.*\n/;
  50965. async function ssrTransform(code, inMap, url, originalCode, options) {
  50966. if (options?.json?.stringify && isJSONRequest(url)) {
  50967. return ssrTransformJSON(code, inMap);
  50968. }
  50969. return ssrTransformScript(code, inMap, url, originalCode);
  50970. }
  50971. async function ssrTransformJSON(code, inMap) {
  50972. return {
  50973. code: code.replace('export default', `${ssrModuleExportsKey}.default =`),
  50974. map: inMap,
  50975. deps: [],
  50976. dynamicDeps: [],
  50977. };
  50978. }
  50979. async function ssrTransformScript(code, inMap, url, originalCode) {
  50980. const s = new MagicString(code);
  50981. let ast;
  50982. try {
  50983. ast = parser.parse(code, {
  50984. sourceType: 'module',
  50985. ecmaVersion: 'latest',
  50986. locations: true,
  50987. allowHashBang: true,
  50988. });
  50989. }
  50990. catch (err) {
  50991. if (!err.loc || !err.loc.line)
  50992. throw err;
  50993. const line = err.loc.line;
  50994. throw new Error(`Parse failure: ${err.message}\nAt file: ${url}\nContents of line ${line}: ${code.split('\n')[line - 1]}`);
  50995. }
  50996. let uid = 0;
  50997. const deps = new Set();
  50998. const dynamicDeps = new Set();
  50999. const idToImportMap = new Map();
  51000. const declaredConst = new Set();
  51001. // hoist at the start of the file, after the hashbang
  51002. const hoistIndex = code.match(hashbangRE)?.[0].length ?? 0;
  51003. function defineImport(source) {
  51004. deps.add(source);
  51005. const importId = `__vite_ssr_import_${uid++}__`;
  51006. // There will be an error if the module is called before it is imported,
  51007. // so the module import statement is hoisted to the top
  51008. s.appendLeft(hoistIndex, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`);
  51009. return importId;
  51010. }
  51011. function defineExport(position, name, local = name) {
  51012. s.appendLeft(position, `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` +
  51013. `{ enumerable: true, configurable: true, get(){ return ${local} }});`);
  51014. }
  51015. // 1. check all import statements and record id -> importName map
  51016. for (const node of ast.body) {
  51017. // import foo from 'foo' --> foo -> __import_foo__.default
  51018. // import { baz } from 'foo' --> baz -> __import_foo__.baz
  51019. // import * as ok from 'foo' --> ok -> __import_foo__
  51020. if (node.type === 'ImportDeclaration') {
  51021. const importId = defineImport(node.source.value);
  51022. s.remove(node.start, node.end);
  51023. for (const spec of node.specifiers) {
  51024. if (spec.type === 'ImportSpecifier') {
  51025. idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
  51026. }
  51027. else if (spec.type === 'ImportDefaultSpecifier') {
  51028. idToImportMap.set(spec.local.name, `${importId}.default`);
  51029. }
  51030. else {
  51031. // namespace specifier
  51032. idToImportMap.set(spec.local.name, importId);
  51033. }
  51034. }
  51035. }
  51036. }
  51037. // 2. check all export statements and define exports
  51038. for (const node of ast.body) {
  51039. // named exports
  51040. if (node.type === 'ExportNamedDeclaration') {
  51041. if (node.declaration) {
  51042. if (node.declaration.type === 'FunctionDeclaration' ||
  51043. node.declaration.type === 'ClassDeclaration') {
  51044. // export function foo() {}
  51045. defineExport(node.end, node.declaration.id.name);
  51046. }
  51047. else {
  51048. // export const foo = 1, bar = 2
  51049. for (const declaration of node.declaration.declarations) {
  51050. const names = extract_names(declaration.id);
  51051. for (const name of names) {
  51052. defineExport(node.end, name);
  51053. }
  51054. }
  51055. }
  51056. s.remove(node.start, node.declaration.start);
  51057. }
  51058. else {
  51059. s.remove(node.start, node.end);
  51060. if (node.source) {
  51061. // export { foo, bar } from './foo'
  51062. const importId = defineImport(node.source.value);
  51063. // hoist re-exports near the defined import so they are immediately exported
  51064. for (const spec of node.specifiers) {
  51065. defineExport(hoistIndex, spec.exported.name, `${importId}.${spec.local.name}`);
  51066. }
  51067. }
  51068. else {
  51069. // export { foo, bar }
  51070. for (const spec of node.specifiers) {
  51071. const local = spec.local.name;
  51072. const binding = idToImportMap.get(local);
  51073. defineExport(node.end, spec.exported.name, binding || local);
  51074. }
  51075. }
  51076. }
  51077. }
  51078. // default export
  51079. if (node.type === 'ExportDefaultDeclaration') {
  51080. const expressionTypes = ['FunctionExpression', 'ClassExpression'];
  51081. if ('id' in node.declaration &&
  51082. node.declaration.id &&
  51083. !expressionTypes.includes(node.declaration.type)) {
  51084. // named hoistable/class exports
  51085. // export default function foo() {}
  51086. // export default class A {}
  51087. const { name } = node.declaration.id;
  51088. s.remove(node.start, node.start + 15 /* 'export default '.length */);
  51089. s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` +
  51090. `{ enumerable: true, configurable: true, value: ${name} });`);
  51091. }
  51092. else {
  51093. // anonymous default exports
  51094. s.update(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`);
  51095. }
  51096. }
  51097. // export * from './foo'
  51098. if (node.type === 'ExportAllDeclaration') {
  51099. s.remove(node.start, node.end);
  51100. const importId = defineImport(node.source.value);
  51101. // hoist re-exports near the defined import so they are immediately exported
  51102. if (node.exported) {
  51103. defineExport(hoistIndex, node.exported.name, `${importId}`);
  51104. }
  51105. else {
  51106. s.appendLeft(hoistIndex, `${ssrExportAllKey}(${importId});\n`);
  51107. }
  51108. }
  51109. }
  51110. // 3. convert references to import bindings & import.meta references
  51111. walk(ast, {
  51112. onIdentifier(id, parent, parentStack) {
  51113. const grandparent = parentStack[1];
  51114. const binding = idToImportMap.get(id.name);
  51115. if (!binding) {
  51116. return;
  51117. }
  51118. if (isStaticProperty(parent) && parent.shorthand) {
  51119. // let binding used in a property shorthand
  51120. // { foo } -> { foo: __import_x__.foo }
  51121. // skip for destructuring patterns
  51122. if (!isNodeInPattern(parent) ||
  51123. isInDestructuringAssignment(parent, parentStack)) {
  51124. s.appendLeft(id.end, `: ${binding}`);
  51125. }
  51126. }
  51127. else if ((parent.type === 'PropertyDefinition' &&
  51128. grandparent?.type === 'ClassBody') ||
  51129. (parent.type === 'ClassDeclaration' && id === parent.superClass)) {
  51130. if (!declaredConst.has(id.name)) {
  51131. declaredConst.add(id.name);
  51132. // locate the top-most node containing the class declaration
  51133. const topNode = parentStack[parentStack.length - 2];
  51134. s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
  51135. }
  51136. }
  51137. else if (
  51138. // don't transform class name identifier
  51139. !(parent.type === 'ClassExpression' && id === parent.id)) {
  51140. s.update(id.start, id.end, binding);
  51141. }
  51142. },
  51143. onImportMeta(node) {
  51144. s.update(node.start, node.end, ssrImportMetaKey);
  51145. },
  51146. onDynamicImport(node) {
  51147. s.update(node.start, node.start + 6, ssrDynamicImportKey);
  51148. if (node.type === 'ImportExpression' && node.source.type === 'Literal') {
  51149. dynamicDeps.add(node.source.value);
  51150. }
  51151. },
  51152. });
  51153. let map = s.generateMap({ hires: 'boundary' });
  51154. if (inMap && inMap.mappings && inMap.sources.length > 0) {
  51155. map = combineSourcemaps(url, [
  51156. {
  51157. ...map,
  51158. sources: inMap.sources,
  51159. sourcesContent: inMap.sourcesContent,
  51160. },
  51161. inMap,
  51162. ]);
  51163. }
  51164. else {
  51165. map.sources = [path$o.basename(url)];
  51166. // needs to use originalCode instead of code
  51167. // because code might be already transformed even if map is null
  51168. map.sourcesContent = [originalCode];
  51169. }
  51170. return {
  51171. code: s.toString(),
  51172. map,
  51173. deps: [...deps],
  51174. dynamicDeps: [...dynamicDeps],
  51175. };
  51176. }
  51177. const isNodeInPatternWeakSet = new WeakSet();
  51178. const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
  51179. const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
  51180. /**
  51181. * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
  51182. * Except this is using acorn AST
  51183. */
  51184. function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
  51185. const parentStack = [];
  51186. const varKindStack = [];
  51187. const scopeMap = new WeakMap();
  51188. const identifiers = [];
  51189. const setScope = (node, name) => {
  51190. let scopeIds = scopeMap.get(node);
  51191. if (scopeIds && scopeIds.has(name)) {
  51192. return;
  51193. }
  51194. if (!scopeIds) {
  51195. scopeIds = new Set();
  51196. scopeMap.set(node, scopeIds);
  51197. }
  51198. scopeIds.add(name);
  51199. };
  51200. function isInScope(name, parents) {
  51201. return parents.some((node) => node && scopeMap.get(node)?.has(name));
  51202. }
  51203. function handlePattern(p, parentScope) {
  51204. if (p.type === 'Identifier') {
  51205. setScope(parentScope, p.name);
  51206. }
  51207. else if (p.type === 'RestElement') {
  51208. handlePattern(p.argument, parentScope);
  51209. }
  51210. else if (p.type === 'ObjectPattern') {
  51211. p.properties.forEach((property) => {
  51212. if (property.type === 'RestElement') {
  51213. setScope(parentScope, property.argument.name);
  51214. }
  51215. else {
  51216. handlePattern(property.value, parentScope);
  51217. }
  51218. });
  51219. }
  51220. else if (p.type === 'ArrayPattern') {
  51221. p.elements.forEach((element) => {
  51222. if (element) {
  51223. handlePattern(element, parentScope);
  51224. }
  51225. });
  51226. }
  51227. else if (p.type === 'AssignmentPattern') {
  51228. handlePattern(p.left, parentScope);
  51229. }
  51230. else {
  51231. setScope(parentScope, p.name);
  51232. }
  51233. }
  51234. walk$1(root, {
  51235. enter(node, parent) {
  51236. if (node.type === 'ImportDeclaration') {
  51237. return this.skip();
  51238. }
  51239. // track parent stack, skip for "else-if"/"else" branches as acorn nests
  51240. // the ast within "if" nodes instead of flattening them
  51241. if (parent &&
  51242. !(parent.type === 'IfStatement' && node === parent.alternate)) {
  51243. parentStack.unshift(parent);
  51244. }
  51245. // track variable declaration kind stack used by VariableDeclarator
  51246. if (node.type === 'VariableDeclaration') {
  51247. varKindStack.unshift(node.kind);
  51248. }
  51249. if (node.type === 'MetaProperty' && node.meta.name === 'import') {
  51250. onImportMeta(node);
  51251. }
  51252. else if (node.type === 'ImportExpression') {
  51253. onDynamicImport(node);
  51254. }
  51255. if (node.type === 'Identifier') {
  51256. if (!isInScope(node.name, parentStack) &&
  51257. isRefIdentifier(node, parent, parentStack)) {
  51258. // record the identifier, for DFS -> BFS
  51259. identifiers.push([node, parentStack.slice(0)]);
  51260. }
  51261. }
  51262. else if (isFunction(node)) {
  51263. // If it is a function declaration, it could be shadowing an import
  51264. // Add its name to the scope so it won't get replaced
  51265. if (node.type === 'FunctionDeclaration') {
  51266. const parentScope = findParentScope(parentStack);
  51267. if (parentScope) {
  51268. setScope(parentScope, node.id.name);
  51269. }
  51270. }
  51271. // walk function expressions and add its arguments to known identifiers
  51272. // so that we don't prefix them
  51273. node.params.forEach((p) => {
  51274. if (p.type === 'ObjectPattern' || p.type === 'ArrayPattern') {
  51275. handlePattern(p, node);
  51276. return;
  51277. }
  51278. walk$1(p.type === 'AssignmentPattern' ? p.left : p, {
  51279. enter(child, parent) {
  51280. // skip params default value of destructure
  51281. if (parent?.type === 'AssignmentPattern' &&
  51282. parent?.right === child) {
  51283. return this.skip();
  51284. }
  51285. if (child.type !== 'Identifier')
  51286. return;
  51287. // do not record as scope variable if is a destructuring keyword
  51288. if (isStaticPropertyKey(child, parent))
  51289. return;
  51290. // do not record if this is a default value
  51291. // assignment of a destructuring variable
  51292. if ((parent?.type === 'TemplateLiteral' &&
  51293. parent?.expressions.includes(child)) ||
  51294. (parent?.type === 'CallExpression' && parent?.callee === child)) {
  51295. return;
  51296. }
  51297. setScope(node, child.name);
  51298. },
  51299. });
  51300. });
  51301. }
  51302. else if (node.type === 'Property' && parent.type === 'ObjectPattern') {
  51303. // mark property in destructuring pattern
  51304. setIsNodeInPattern(node);
  51305. }
  51306. else if (node.type === 'VariableDeclarator') {
  51307. const parentFunction = findParentScope(parentStack, varKindStack[0] === 'var');
  51308. if (parentFunction) {
  51309. handlePattern(node.id, parentFunction);
  51310. }
  51311. }
  51312. else if (node.type === 'CatchClause' && node.param) {
  51313. handlePattern(node.param, node);
  51314. }
  51315. },
  51316. leave(node, parent) {
  51317. // untrack parent stack from above
  51318. if (parent &&
  51319. !(parent.type === 'IfStatement' && node === parent.alternate)) {
  51320. parentStack.shift();
  51321. }
  51322. if (node.type === 'VariableDeclaration') {
  51323. varKindStack.shift();
  51324. }
  51325. },
  51326. });
  51327. // emit the identifier events in BFS so the hoisted declarations
  51328. // can be captured correctly
  51329. identifiers.forEach(([node, stack]) => {
  51330. if (!isInScope(node.name, stack))
  51331. onIdentifier(node, stack[0], stack);
  51332. });
  51333. }
  51334. function isRefIdentifier(id, parent, parentStack) {
  51335. // declaration id
  51336. if (parent.type === 'CatchClause' ||
  51337. ((parent.type === 'VariableDeclarator' ||
  51338. parent.type === 'ClassDeclaration') &&
  51339. parent.id === id)) {
  51340. return false;
  51341. }
  51342. if (isFunction(parent)) {
  51343. // function declaration/expression id
  51344. if (parent.id === id) {
  51345. return false;
  51346. }
  51347. // params list
  51348. if (parent.params.includes(id)) {
  51349. return false;
  51350. }
  51351. }
  51352. // class method name
  51353. if (parent.type === 'MethodDefinition' && !parent.computed) {
  51354. return false;
  51355. }
  51356. // property key
  51357. if (isStaticPropertyKey(id, parent)) {
  51358. return false;
  51359. }
  51360. // object destructuring pattern
  51361. if (isNodeInPattern(parent) && parent.value === id) {
  51362. return false;
  51363. }
  51364. // non-assignment array destructuring pattern
  51365. if (parent.type === 'ArrayPattern' &&
  51366. !isInDestructuringAssignment(parent, parentStack)) {
  51367. return false;
  51368. }
  51369. // member expression property
  51370. if (parent.type === 'MemberExpression' &&
  51371. parent.property === id &&
  51372. !parent.computed) {
  51373. return false;
  51374. }
  51375. if (parent.type === 'ExportSpecifier') {
  51376. return false;
  51377. }
  51378. // is a special keyword but parsed as identifier
  51379. if (id.name === 'arguments') {
  51380. return false;
  51381. }
  51382. return true;
  51383. }
  51384. const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
  51385. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  51386. const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
  51387. function isFunction(node) {
  51388. return functionNodeTypeRE.test(node.type);
  51389. }
  51390. const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
  51391. function isBlock(node) {
  51392. return blockNodeTypeRE.test(node.type);
  51393. }
  51394. function findParentScope(parentStack, isVar = false) {
  51395. return parentStack.find(isVar ? isFunction : isBlock);
  51396. }
  51397. function isInDestructuringAssignment(parent, parentStack) {
  51398. if (parent &&
  51399. (parent.type === 'Property' || parent.type === 'ArrayPattern')) {
  51400. return parentStack.some((i) => i.type === 'AssignmentExpression');
  51401. }
  51402. return false;
  51403. }
  51404. let offset;
  51405. function calculateOffsetOnce() {
  51406. if (offset !== undefined) {
  51407. return;
  51408. }
  51409. try {
  51410. new Function('throw new Error(1)')();
  51411. }
  51412. catch (e) {
  51413. // in Node 12, stack traces account for the function wrapper.
  51414. // in Node 13 and later, the function wrapper adds two lines,
  51415. // which must be subtracted to generate a valid mapping
  51416. const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]);
  51417. offset = match ? +match[1] - 1 : 0;
  51418. }
  51419. }
  51420. function ssrRewriteStacktrace(stack, moduleGraph) {
  51421. calculateOffsetOnce();
  51422. return stack
  51423. .split('\n')
  51424. .map((line) => {
  51425. return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, line, column) => {
  51426. if (!id)
  51427. return input;
  51428. const mod = moduleGraph.idToModuleMap.get(id);
  51429. const rawSourceMap = mod?.ssrTransformResult?.map;
  51430. if (!rawSourceMap) {
  51431. return input;
  51432. }
  51433. const traced = new TraceMap(rawSourceMap);
  51434. const pos = originalPositionFor$1(traced, {
  51435. line: Number(line) - offset,
  51436. // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
  51437. column: Number(column) - 1,
  51438. });
  51439. if (!pos.source || pos.line == null || pos.column == null) {
  51440. return input;
  51441. }
  51442. const trimmedVarName = varName.trim();
  51443. const sourceFile = path$o.resolve(path$o.dirname(id), pos.source);
  51444. // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
  51445. const source = `${sourceFile}:${pos.line}:${pos.column + 1}`;
  51446. if (!trimmedVarName || trimmedVarName === 'eval') {
  51447. return ` at ${source}`;
  51448. }
  51449. else {
  51450. return ` at ${trimmedVarName} (${source})`;
  51451. }
  51452. });
  51453. })
  51454. .join('\n');
  51455. }
  51456. function rebindErrorStacktrace(e, stacktrace) {
  51457. const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack');
  51458. if (configurable) {
  51459. Object.defineProperty(e, 'stack', {
  51460. value: stacktrace,
  51461. enumerable: true,
  51462. configurable: true,
  51463. writable: true,
  51464. });
  51465. }
  51466. else if (writable) {
  51467. e.stack = stacktrace;
  51468. }
  51469. }
  51470. const rewroteStacktraces = new WeakSet();
  51471. function ssrFixStacktrace(e, moduleGraph) {
  51472. if (!e.stack)
  51473. return;
  51474. // stacktrace shouldn't be rewritten more than once
  51475. if (rewroteStacktraces.has(e))
  51476. return;
  51477. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  51478. rebindErrorStacktrace(e, stacktrace);
  51479. rewroteStacktraces.add(e);
  51480. }
  51481. // eslint-disable-next-line @typescript-eslint/no-empty-function
  51482. const AsyncFunction = async function () { }.constructor;
  51483. let fnDeclarationLineCount = 0;
  51484. {
  51485. const body = '/*code*/';
  51486. const source = new AsyncFunction('a', 'b', body).toString();
  51487. fnDeclarationLineCount =
  51488. source.slice(0, source.indexOf(body)).split('\n').length - 1;
  51489. }
  51490. const pendingModules = new Map();
  51491. const pendingImports = new Map();
  51492. const importErrors = new WeakMap();
  51493. async function ssrLoadModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
  51494. url = unwrapId(url);
  51495. // when we instantiate multiple dependency modules in parallel, they may
  51496. // point to shared modules. We need to avoid duplicate instantiation attempts
  51497. // by register every module as pending synchronously so that all subsequent
  51498. // request to that module are simply waiting on the same promise.
  51499. const pending = pendingModules.get(url);
  51500. if (pending) {
  51501. return pending;
  51502. }
  51503. const modulePromise = instantiateModule(url, server, context, urlStack, fixStacktrace);
  51504. pendingModules.set(url, modulePromise);
  51505. modulePromise
  51506. .catch(() => {
  51507. pendingImports.delete(url);
  51508. })
  51509. .finally(() => {
  51510. pendingModules.delete(url);
  51511. });
  51512. return modulePromise;
  51513. }
  51514. async function instantiateModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
  51515. const { moduleGraph } = server;
  51516. const mod = await moduleGraph.ensureEntryFromUrl(url, true);
  51517. if (mod.ssrError) {
  51518. throw mod.ssrError;
  51519. }
  51520. if (mod.ssrModule) {
  51521. return mod.ssrModule;
  51522. }
  51523. const result = mod.ssrTransformResult ||
  51524. (await transformRequest(url, server, { ssr: true }));
  51525. if (!result) {
  51526. // TODO more info? is this even necessary?
  51527. throw new Error(`failed to load module for ssr: ${url}`);
  51528. }
  51529. const ssrModule = {
  51530. [Symbol.toStringTag]: 'Module',
  51531. };
  51532. Object.defineProperty(ssrModule, '__esModule', { value: true });
  51533. // Tolerate circular imports by ensuring the module can be
  51534. // referenced before it's been instantiated.
  51535. mod.ssrModule = ssrModule;
  51536. const ssrImportMeta = {
  51537. // The filesystem URL, matching native Node.js modules
  51538. url: pathToFileURL(mod.file).toString(),
  51539. };
  51540. urlStack = urlStack.concat(url);
  51541. const isCircular = (url) => urlStack.includes(url);
  51542. const { isProduction, resolve: { dedupe, preserveSymlinks }, root, ssr, } = server.config;
  51543. const overrideConditions = ssr.resolve?.externalConditions || [];
  51544. const resolveOptions = {
  51545. mainFields: ['main'],
  51546. browserField: true,
  51547. conditions: [],
  51548. overrideConditions: [...overrideConditions, 'production', 'development'],
  51549. extensions: ['.js', '.cjs', '.json'],
  51550. dedupe,
  51551. preserveSymlinks,
  51552. isBuild: false,
  51553. isProduction,
  51554. root,
  51555. ssrConfig: ssr,
  51556. };
  51557. // Since dynamic imports can happen in parallel, we need to
  51558. // account for multiple pending deps and duplicate imports.
  51559. const pendingDeps = [];
  51560. const ssrImport = async (dep) => {
  51561. try {
  51562. if (dep[0] !== '.' && dep[0] !== '/') {
  51563. return await nodeImport(dep, mod.file, resolveOptions);
  51564. }
  51565. // convert to rollup URL because `pendingImports`, `moduleGraph.urlToModuleMap` requires that
  51566. dep = unwrapId(dep);
  51567. if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) {
  51568. pendingDeps.push(dep);
  51569. if (pendingDeps.length === 1) {
  51570. pendingImports.set(url, pendingDeps);
  51571. }
  51572. const mod = await ssrLoadModule(dep, server, context, urlStack, fixStacktrace);
  51573. if (pendingDeps.length === 1) {
  51574. pendingImports.delete(url);
  51575. }
  51576. else {
  51577. pendingDeps.splice(pendingDeps.indexOf(dep), 1);
  51578. }
  51579. // return local module to avoid race condition #5470
  51580. return mod;
  51581. }
  51582. return moduleGraph.urlToModuleMap.get(dep)?.ssrModule;
  51583. }
  51584. catch (err) {
  51585. // tell external error handler which mod was imported with error
  51586. importErrors.set(err, { importee: dep });
  51587. throw err;
  51588. }
  51589. };
  51590. const ssrDynamicImport = (dep) => {
  51591. // #3087 dynamic import vars is ignored at rewrite import path,
  51592. // so here need process relative path
  51593. if (dep[0] === '.') {
  51594. dep = path$o.posix.resolve(path$o.dirname(url), dep);
  51595. }
  51596. return ssrImport(dep);
  51597. };
  51598. function ssrExportAll(sourceModule) {
  51599. for (const key in sourceModule) {
  51600. if (key !== 'default' && key !== '__esModule') {
  51601. Object.defineProperty(ssrModule, key, {
  51602. enumerable: true,
  51603. configurable: true,
  51604. get() {
  51605. return sourceModule[key];
  51606. },
  51607. });
  51608. }
  51609. }
  51610. }
  51611. let sourceMapSuffix = '';
  51612. if (result.map) {
  51613. const moduleSourceMap = Object.assign({}, result.map, {
  51614. // currently we need to offset the line
  51615. // https://github.com/nodejs/node/issues/43047#issuecomment-1180632750
  51616. mappings: ';'.repeat(fnDeclarationLineCount) + result.map.mappings,
  51617. });
  51618. sourceMapSuffix =
  51619. '\n//# sourceMappingURL=' + genSourceMapUrl(moduleSourceMap);
  51620. }
  51621. try {
  51622. const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, '"use strict";' +
  51623. result.code +
  51624. `\n//# sourceURL=${mod.id}${sourceMapSuffix}`);
  51625. await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
  51626. }
  51627. catch (e) {
  51628. mod.ssrError = e;
  51629. const errorData = importErrors.get(e);
  51630. if (e.stack && fixStacktrace) {
  51631. ssrFixStacktrace(e, moduleGraph);
  51632. }
  51633. server.config.logger.error(colors$1.red(`Error when evaluating SSR module ${url}:` +
  51634. (errorData?.importee
  51635. ? ` failed to import "${errorData.importee}"`
  51636. : '') +
  51637. `\n|- ${e.stack}\n`), {
  51638. timestamp: true,
  51639. clear: server.config.clearScreen,
  51640. error: e,
  51641. });
  51642. throw e;
  51643. }
  51644. return Object.freeze(ssrModule);
  51645. }
  51646. // In node@12+ we can use dynamic import to load CJS and ESM
  51647. async function nodeImport(id, importer, resolveOptions) {
  51648. let url;
  51649. if (id.startsWith('data:') || isBuiltin(id)) {
  51650. url = id;
  51651. }
  51652. else {
  51653. const resolved = tryNodeResolve(id, importer,
  51654. // Non-external modules can import ESM-only modules, but only outside
  51655. // of test runs, because we use Node `require` in Jest to avoid segfault.
  51656. // @ts-expect-error jest only exists when running Jest
  51657. typeof jest === 'undefined'
  51658. ? { ...resolveOptions, tryEsmOnly: true }
  51659. : resolveOptions, false, undefined, true);
  51660. if (!resolved) {
  51661. const err = new Error(`Cannot find module '${id}' imported from '${importer}'`);
  51662. err.code = 'ERR_MODULE_NOT_FOUND';
  51663. throw err;
  51664. }
  51665. url = resolved.id;
  51666. if (usingDynamicImport) {
  51667. url = pathToFileURL(url).toString();
  51668. }
  51669. }
  51670. const mod = await dynamicImport(url);
  51671. return proxyESM(mod);
  51672. }
  51673. // rollup-style default import interop for cjs
  51674. function proxyESM(mod) {
  51675. // This is the only sensible option when the exports object is a primitive
  51676. if (isPrimitive(mod))
  51677. return { default: mod };
  51678. let defaultExport = 'default' in mod ? mod.default : mod;
  51679. if (!isPrimitive(defaultExport) && '__esModule' in defaultExport) {
  51680. mod = defaultExport;
  51681. if ('default' in defaultExport) {
  51682. defaultExport = defaultExport.default;
  51683. }
  51684. }
  51685. return new Proxy(mod, {
  51686. get(mod, prop) {
  51687. if (prop === 'default')
  51688. return defaultExport;
  51689. return mod[prop] ?? defaultExport?.[prop];
  51690. },
  51691. });
  51692. }
  51693. function isPrimitive(value) {
  51694. return !value || (typeof value !== 'object' && typeof value !== 'function');
  51695. }
  51696. var isWsl$2 = {exports: {}};
  51697. const fs$3 = require$$0__default;
  51698. let isDocker$2;
  51699. function hasDockerEnv() {
  51700. try {
  51701. fs$3.statSync('/.dockerenv');
  51702. return true;
  51703. } catch (_) {
  51704. return false;
  51705. }
  51706. }
  51707. function hasDockerCGroup() {
  51708. try {
  51709. return fs$3.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
  51710. } catch (_) {
  51711. return false;
  51712. }
  51713. }
  51714. var isDocker_1 = () => {
  51715. if (isDocker$2 === undefined) {
  51716. isDocker$2 = hasDockerEnv() || hasDockerCGroup();
  51717. }
  51718. return isDocker$2;
  51719. };
  51720. const os = require$$2;
  51721. const fs$2 = require$$0__default;
  51722. const isDocker$1 = isDocker_1;
  51723. const isWsl$1 = () => {
  51724. if (process.platform !== 'linux') {
  51725. return false;
  51726. }
  51727. if (os.release().toLowerCase().includes('microsoft')) {
  51728. if (isDocker$1()) {
  51729. return false;
  51730. }
  51731. return true;
  51732. }
  51733. try {
  51734. return fs$2.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
  51735. !isDocker$1() : false;
  51736. } catch (_) {
  51737. return false;
  51738. }
  51739. };
  51740. if (process.env.__IS_WSL_TEST__) {
  51741. isWsl$2.exports = isWsl$1;
  51742. } else {
  51743. isWsl$2.exports = isWsl$1();
  51744. }
  51745. var isWslExports = isWsl$2.exports;
  51746. var defineLazyProp = (object, propertyName, fn) => {
  51747. const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
  51748. Object.defineProperty(object, propertyName, {
  51749. configurable: true,
  51750. enumerable: true,
  51751. get() {
  51752. const result = fn();
  51753. define(result);
  51754. return result;
  51755. },
  51756. set(value) {
  51757. define(value);
  51758. }
  51759. });
  51760. return object;
  51761. };
  51762. const path$3 = require$$0$4;
  51763. const childProcess = require$$2$1;
  51764. const {promises: fs$1, constants: fsConstants} = require$$0__default;
  51765. const isWsl = isWslExports;
  51766. const isDocker = isDocker_1;
  51767. const defineLazyProperty = defineLazyProp;
  51768. // Path to included `xdg-open`.
  51769. const localXdgOpenPath = path$3.join(__dirname, 'xdg-open');
  51770. const {platform, arch} = process;
  51771. // Podman detection
  51772. const hasContainerEnv = () => {
  51773. try {
  51774. fs$1.statSync('/run/.containerenv');
  51775. return true;
  51776. } catch {
  51777. return false;
  51778. }
  51779. };
  51780. let cachedResult;
  51781. function isInsideContainer() {
  51782. if (cachedResult === undefined) {
  51783. cachedResult = hasContainerEnv() || isDocker();
  51784. }
  51785. return cachedResult;
  51786. }
  51787. /**
  51788. Get the mount point for fixed drives in WSL.
  51789. @inner
  51790. @returns {string} The mount point.
  51791. */
  51792. const getWslDrivesMountPoint = (() => {
  51793. // Default value for "root" param
  51794. // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
  51795. const defaultMountPoint = '/mnt/';
  51796. let mountPoint;
  51797. return async function () {
  51798. if (mountPoint) {
  51799. // Return memoized mount point value
  51800. return mountPoint;
  51801. }
  51802. const configFilePath = '/etc/wsl.conf';
  51803. let isConfigFileExists = false;
  51804. try {
  51805. await fs$1.access(configFilePath, fsConstants.F_OK);
  51806. isConfigFileExists = true;
  51807. } catch {}
  51808. if (!isConfigFileExists) {
  51809. return defaultMountPoint;
  51810. }
  51811. const configContent = await fs$1.readFile(configFilePath, {encoding: 'utf8'});
  51812. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  51813. if (!configMountPoint) {
  51814. return defaultMountPoint;
  51815. }
  51816. mountPoint = configMountPoint.groups.mountPoint.trim();
  51817. mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
  51818. return mountPoint;
  51819. };
  51820. })();
  51821. const pTryEach = async (array, mapper) => {
  51822. let latestError;
  51823. for (const item of array) {
  51824. try {
  51825. return await mapper(item); // eslint-disable-line no-await-in-loop
  51826. } catch (error) {
  51827. latestError = error;
  51828. }
  51829. }
  51830. throw latestError;
  51831. };
  51832. const baseOpen = async options => {
  51833. options = {
  51834. wait: false,
  51835. background: false,
  51836. newInstance: false,
  51837. allowNonzeroExitCode: false,
  51838. ...options
  51839. };
  51840. if (Array.isArray(options.app)) {
  51841. return pTryEach(options.app, singleApp => baseOpen({
  51842. ...options,
  51843. app: singleApp
  51844. }));
  51845. }
  51846. let {name: app, arguments: appArguments = []} = options.app || {};
  51847. appArguments = [...appArguments];
  51848. if (Array.isArray(app)) {
  51849. return pTryEach(app, appName => baseOpen({
  51850. ...options,
  51851. app: {
  51852. name: appName,
  51853. arguments: appArguments
  51854. }
  51855. }));
  51856. }
  51857. let command;
  51858. const cliArguments = [];
  51859. const childProcessOptions = {};
  51860. if (platform === 'darwin') {
  51861. command = 'open';
  51862. if (options.wait) {
  51863. cliArguments.push('--wait-apps');
  51864. }
  51865. if (options.background) {
  51866. cliArguments.push('--background');
  51867. }
  51868. if (options.newInstance) {
  51869. cliArguments.push('--new');
  51870. }
  51871. if (app) {
  51872. cliArguments.push('-a', app);
  51873. }
  51874. } else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) {
  51875. const mountPoint = await getWslDrivesMountPoint();
  51876. command = isWsl ?
  51877. `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
  51878. `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
  51879. cliArguments.push(
  51880. '-NoProfile',
  51881. '-NonInteractive',
  51882. '–ExecutionPolicy',
  51883. 'Bypass',
  51884. '-EncodedCommand'
  51885. );
  51886. if (!isWsl) {
  51887. childProcessOptions.windowsVerbatimArguments = true;
  51888. }
  51889. const encodedArguments = ['Start'];
  51890. if (options.wait) {
  51891. encodedArguments.push('-Wait');
  51892. }
  51893. if (app) {
  51894. // Double quote with double quotes to ensure the inner quotes are passed through.
  51895. // Inner quotes are delimited for PowerShell interpretation with backticks.
  51896. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
  51897. if (options.target) {
  51898. appArguments.unshift(options.target);
  51899. }
  51900. } else if (options.target) {
  51901. encodedArguments.push(`"${options.target}"`);
  51902. }
  51903. if (appArguments.length > 0) {
  51904. appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
  51905. encodedArguments.push(appArguments.join(','));
  51906. }
  51907. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  51908. options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  51909. } else {
  51910. if (app) {
  51911. command = app;
  51912. } else {
  51913. // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
  51914. const isBundled = !__dirname || __dirname === '/';
  51915. // Check if local `xdg-open` exists and is executable.
  51916. let exeLocalXdgOpen = false;
  51917. try {
  51918. await fs$1.access(localXdgOpenPath, fsConstants.X_OK);
  51919. exeLocalXdgOpen = true;
  51920. } catch {}
  51921. const useSystemXdgOpen = process.versions.electron ||
  51922. platform === 'android' || isBundled || !exeLocalXdgOpen;
  51923. command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
  51924. }
  51925. if (appArguments.length > 0) {
  51926. cliArguments.push(...appArguments);
  51927. }
  51928. if (!options.wait) {
  51929. // `xdg-open` will block the process unless stdio is ignored
  51930. // and it's detached from the parent even if it's unref'd.
  51931. childProcessOptions.stdio = 'ignore';
  51932. childProcessOptions.detached = true;
  51933. }
  51934. }
  51935. if (options.target) {
  51936. cliArguments.push(options.target);
  51937. }
  51938. if (platform === 'darwin' && appArguments.length > 0) {
  51939. cliArguments.push('--args', ...appArguments);
  51940. }
  51941. const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
  51942. if (options.wait) {
  51943. return new Promise((resolve, reject) => {
  51944. subprocess.once('error', reject);
  51945. subprocess.once('close', exitCode => {
  51946. if (!options.allowNonzeroExitCode && exitCode > 0) {
  51947. reject(new Error(`Exited with code ${exitCode}`));
  51948. return;
  51949. }
  51950. resolve(subprocess);
  51951. });
  51952. });
  51953. }
  51954. subprocess.unref();
  51955. return subprocess;
  51956. };
  51957. const open = (target, options) => {
  51958. if (typeof target !== 'string') {
  51959. throw new TypeError('Expected a `target`');
  51960. }
  51961. return baseOpen({
  51962. ...options,
  51963. target
  51964. });
  51965. };
  51966. const openApp = (name, options) => {
  51967. if (typeof name !== 'string') {
  51968. throw new TypeError('Expected a `name`');
  51969. }
  51970. const {arguments: appArguments = []} = options || {};
  51971. if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
  51972. throw new TypeError('Expected `appArguments` as Array type');
  51973. }
  51974. return baseOpen({
  51975. ...options,
  51976. app: {
  51977. name,
  51978. arguments: appArguments
  51979. }
  51980. });
  51981. };
  51982. function detectArchBinary(binary) {
  51983. if (typeof binary === 'string' || Array.isArray(binary)) {
  51984. return binary;
  51985. }
  51986. const {[arch]: archBinary} = binary;
  51987. if (!archBinary) {
  51988. throw new Error(`${arch} is not supported`);
  51989. }
  51990. return archBinary;
  51991. }
  51992. function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
  51993. if (wsl && isWsl) {
  51994. return detectArchBinary(wsl);
  51995. }
  51996. if (!platformBinary) {
  51997. throw new Error(`${platform} is not supported`);
  51998. }
  51999. return detectArchBinary(platformBinary);
  52000. }
  52001. const apps = {};
  52002. defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
  52003. darwin: 'google chrome',
  52004. win32: 'chrome',
  52005. linux: ['google-chrome', 'google-chrome-stable', 'chromium']
  52006. }, {
  52007. wsl: {
  52008. ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  52009. x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
  52010. }
  52011. }));
  52012. defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
  52013. darwin: 'firefox',
  52014. win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
  52015. linux: 'firefox'
  52016. }, {
  52017. wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
  52018. }));
  52019. defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
  52020. darwin: 'microsoft edge',
  52021. win32: 'msedge',
  52022. linux: ['microsoft-edge', 'microsoft-edge-dev']
  52023. }, {
  52024. wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
  52025. }));
  52026. open.apps = apps;
  52027. open.openApp = openApp;
  52028. var open_1 = open;
  52029. var open$1 = /*@__PURE__*/getDefaultExportFromCjs(open_1);
  52030. var crossSpawn = {exports: {}};
  52031. var windows;
  52032. var hasRequiredWindows;
  52033. function requireWindows () {
  52034. if (hasRequiredWindows) return windows;
  52035. hasRequiredWindows = 1;
  52036. windows = isexe;
  52037. isexe.sync = sync;
  52038. var fs = require$$0__default;
  52039. function checkPathExt (path, options) {
  52040. var pathext = options.pathExt !== undefined ?
  52041. options.pathExt : process.env.PATHEXT;
  52042. if (!pathext) {
  52043. return true
  52044. }
  52045. pathext = pathext.split(';');
  52046. if (pathext.indexOf('') !== -1) {
  52047. return true
  52048. }
  52049. for (var i = 0; i < pathext.length; i++) {
  52050. var p = pathext[i].toLowerCase();
  52051. if (p && path.substr(-p.length).toLowerCase() === p) {
  52052. return true
  52053. }
  52054. }
  52055. return false
  52056. }
  52057. function checkStat (stat, path, options) {
  52058. if (!stat.isSymbolicLink() && !stat.isFile()) {
  52059. return false
  52060. }
  52061. return checkPathExt(path, options)
  52062. }
  52063. function isexe (path, options, cb) {
  52064. fs.stat(path, function (er, stat) {
  52065. cb(er, er ? false : checkStat(stat, path, options));
  52066. });
  52067. }
  52068. function sync (path, options) {
  52069. return checkStat(fs.statSync(path), path, options)
  52070. }
  52071. return windows;
  52072. }
  52073. var mode;
  52074. var hasRequiredMode;
  52075. function requireMode () {
  52076. if (hasRequiredMode) return mode;
  52077. hasRequiredMode = 1;
  52078. mode = isexe;
  52079. isexe.sync = sync;
  52080. var fs = require$$0__default;
  52081. function isexe (path, options, cb) {
  52082. fs.stat(path, function (er, stat) {
  52083. cb(er, er ? false : checkStat(stat, options));
  52084. });
  52085. }
  52086. function sync (path, options) {
  52087. return checkStat(fs.statSync(path), options)
  52088. }
  52089. function checkStat (stat, options) {
  52090. return stat.isFile() && checkMode(stat, options)
  52091. }
  52092. function checkMode (stat, options) {
  52093. var mod = stat.mode;
  52094. var uid = stat.uid;
  52095. var gid = stat.gid;
  52096. var myUid = options.uid !== undefined ?
  52097. options.uid : process.getuid && process.getuid();
  52098. var myGid = options.gid !== undefined ?
  52099. options.gid : process.getgid && process.getgid();
  52100. var u = parseInt('100', 8);
  52101. var g = parseInt('010', 8);
  52102. var o = parseInt('001', 8);
  52103. var ug = u | g;
  52104. var ret = (mod & o) ||
  52105. (mod & g) && gid === myGid ||
  52106. (mod & u) && uid === myUid ||
  52107. (mod & ug) && myUid === 0;
  52108. return ret
  52109. }
  52110. return mode;
  52111. }
  52112. var core;
  52113. if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
  52114. core = requireWindows();
  52115. } else {
  52116. core = requireMode();
  52117. }
  52118. var isexe_1 = isexe$1;
  52119. isexe$1.sync = sync;
  52120. function isexe$1 (path, options, cb) {
  52121. if (typeof options === 'function') {
  52122. cb = options;
  52123. options = {};
  52124. }
  52125. if (!cb) {
  52126. if (typeof Promise !== 'function') {
  52127. throw new TypeError('callback not provided')
  52128. }
  52129. return new Promise(function (resolve, reject) {
  52130. isexe$1(path, options || {}, function (er, is) {
  52131. if (er) {
  52132. reject(er);
  52133. } else {
  52134. resolve(is);
  52135. }
  52136. });
  52137. })
  52138. }
  52139. core(path, options || {}, function (er, is) {
  52140. // ignore EACCES because that just means we aren't allowed to run it
  52141. if (er) {
  52142. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  52143. er = null;
  52144. is = false;
  52145. }
  52146. }
  52147. cb(er, is);
  52148. });
  52149. }
  52150. function sync (path, options) {
  52151. // my kingdom for a filtered catch
  52152. try {
  52153. return core.sync(path, options || {})
  52154. } catch (er) {
  52155. if (options && options.ignoreErrors || er.code === 'EACCES') {
  52156. return false
  52157. } else {
  52158. throw er
  52159. }
  52160. }
  52161. }
  52162. const isWindows = process.platform === 'win32' ||
  52163. process.env.OSTYPE === 'cygwin' ||
  52164. process.env.OSTYPE === 'msys';
  52165. const path$2 = require$$0$4;
  52166. const COLON = isWindows ? ';' : ':';
  52167. const isexe = isexe_1;
  52168. const getNotFoundError = (cmd) =>
  52169. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
  52170. const getPathInfo = (cmd, opt) => {
  52171. const colon = opt.colon || COLON;
  52172. // If it has a slash, then we don't bother searching the pathenv.
  52173. // just check the file itself, and that's it.
  52174. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  52175. : (
  52176. [
  52177. // windows always checks the cwd first
  52178. ...(isWindows ? [process.cwd()] : []),
  52179. ...(opt.path || process.env.PATH ||
  52180. /* istanbul ignore next: very unusual */ '').split(colon),
  52181. ]
  52182. );
  52183. const pathExtExe = isWindows
  52184. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  52185. : '';
  52186. const pathExt = isWindows ? pathExtExe.split(colon) : [''];
  52187. if (isWindows) {
  52188. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  52189. pathExt.unshift('');
  52190. }
  52191. return {
  52192. pathEnv,
  52193. pathExt,
  52194. pathExtExe,
  52195. }
  52196. };
  52197. const which$1 = (cmd, opt, cb) => {
  52198. if (typeof opt === 'function') {
  52199. cb = opt;
  52200. opt = {};
  52201. }
  52202. if (!opt)
  52203. opt = {};
  52204. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  52205. const found = [];
  52206. const step = i => new Promise((resolve, reject) => {
  52207. if (i === pathEnv.length)
  52208. return opt.all && found.length ? resolve(found)
  52209. : reject(getNotFoundError(cmd))
  52210. const ppRaw = pathEnv[i];
  52211. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  52212. const pCmd = path$2.join(pathPart, cmd);
  52213. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  52214. : pCmd;
  52215. resolve(subStep(p, i, 0));
  52216. });
  52217. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  52218. if (ii === pathExt.length)
  52219. return resolve(step(i + 1))
  52220. const ext = pathExt[ii];
  52221. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  52222. if (!er && is) {
  52223. if (opt.all)
  52224. found.push(p + ext);
  52225. else
  52226. return resolve(p + ext)
  52227. }
  52228. return resolve(subStep(p, i, ii + 1))
  52229. });
  52230. });
  52231. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  52232. };
  52233. const whichSync = (cmd, opt) => {
  52234. opt = opt || {};
  52235. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  52236. const found = [];
  52237. for (let i = 0; i < pathEnv.length; i ++) {
  52238. const ppRaw = pathEnv[i];
  52239. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  52240. const pCmd = path$2.join(pathPart, cmd);
  52241. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  52242. : pCmd;
  52243. for (let j = 0; j < pathExt.length; j ++) {
  52244. const cur = p + pathExt[j];
  52245. try {
  52246. const is = isexe.sync(cur, { pathExt: pathExtExe });
  52247. if (is) {
  52248. if (opt.all)
  52249. found.push(cur);
  52250. else
  52251. return cur
  52252. }
  52253. } catch (ex) {}
  52254. }
  52255. }
  52256. if (opt.all && found.length)
  52257. return found
  52258. if (opt.nothrow)
  52259. return null
  52260. throw getNotFoundError(cmd)
  52261. };
  52262. var which_1 = which$1;
  52263. which$1.sync = whichSync;
  52264. var pathKey$1 = {exports: {}};
  52265. const pathKey = (options = {}) => {
  52266. const environment = options.env || process.env;
  52267. const platform = options.platform || process.platform;
  52268. if (platform !== 'win32') {
  52269. return 'PATH';
  52270. }
  52271. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  52272. };
  52273. pathKey$1.exports = pathKey;
  52274. // TODO: Remove this for the next major release
  52275. pathKey$1.exports.default = pathKey;
  52276. var pathKeyExports = pathKey$1.exports;
  52277. const path$1 = require$$0$4;
  52278. const which = which_1;
  52279. const getPathKey = pathKeyExports;
  52280. function resolveCommandAttempt(parsed, withoutPathExt) {
  52281. const env = parsed.options.env || process.env;
  52282. const cwd = process.cwd();
  52283. const hasCustomCwd = parsed.options.cwd != null;
  52284. // Worker threads do not have process.chdir()
  52285. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
  52286. // If a custom `cwd` was specified, we need to change the process cwd
  52287. // because `which` will do stat calls but does not support a custom cwd
  52288. if (shouldSwitchCwd) {
  52289. try {
  52290. process.chdir(parsed.options.cwd);
  52291. } catch (err) {
  52292. /* Empty */
  52293. }
  52294. }
  52295. let resolved;
  52296. try {
  52297. resolved = which.sync(parsed.command, {
  52298. path: env[getPathKey({ env })],
  52299. pathExt: withoutPathExt ? path$1.delimiter : undefined,
  52300. });
  52301. } catch (e) {
  52302. /* Empty */
  52303. } finally {
  52304. if (shouldSwitchCwd) {
  52305. process.chdir(cwd);
  52306. }
  52307. }
  52308. // If we successfully resolved, ensure that an absolute path is returned
  52309. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  52310. if (resolved) {
  52311. resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  52312. }
  52313. return resolved;
  52314. }
  52315. function resolveCommand$1(parsed) {
  52316. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  52317. }
  52318. var resolveCommand_1 = resolveCommand$1;
  52319. var _escape = {};
  52320. // See http://www.robvanderwoude.com/escapechars.php
  52321. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  52322. function escapeCommand(arg) {
  52323. // Escape meta chars
  52324. arg = arg.replace(metaCharsRegExp, '^$1');
  52325. return arg;
  52326. }
  52327. function escapeArgument(arg, doubleEscapeMetaChars) {
  52328. // Convert to string
  52329. arg = `${arg}`;
  52330. // Algorithm below is based on https://qntm.org/cmd
  52331. // Sequence of backslashes followed by a double quote:
  52332. // double up all the backslashes and escape the double quote
  52333. arg = arg.replace(/(\\*)"/g, '$1$1\\"');
  52334. // Sequence of backslashes followed by the end of the string
  52335. // (which will become a double quote later):
  52336. // double up all the backslashes
  52337. arg = arg.replace(/(\\*)$/, '$1$1');
  52338. // All other backslashes occur literally
  52339. // Quote the whole thing:
  52340. arg = `"${arg}"`;
  52341. // Escape meta chars
  52342. arg = arg.replace(metaCharsRegExp, '^$1');
  52343. // Double escape meta chars if necessary
  52344. if (doubleEscapeMetaChars) {
  52345. arg = arg.replace(metaCharsRegExp, '^$1');
  52346. }
  52347. return arg;
  52348. }
  52349. _escape.command = escapeCommand;
  52350. _escape.argument = escapeArgument;
  52351. var shebangRegex$1 = /^#!(.*)/;
  52352. const shebangRegex = shebangRegex$1;
  52353. var shebangCommand$1 = (string = '') => {
  52354. const match = string.match(shebangRegex);
  52355. if (!match) {
  52356. return null;
  52357. }
  52358. const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
  52359. const binary = path.split('/').pop();
  52360. if (binary === 'env') {
  52361. return argument;
  52362. }
  52363. return argument ? `${binary} ${argument}` : binary;
  52364. };
  52365. const fs = require$$0__default;
  52366. const shebangCommand = shebangCommand$1;
  52367. function readShebang$1(command) {
  52368. // Read the first 150 bytes from the file
  52369. const size = 150;
  52370. const buffer = Buffer.alloc(size);
  52371. let fd;
  52372. try {
  52373. fd = fs.openSync(command, 'r');
  52374. fs.readSync(fd, buffer, 0, size, 0);
  52375. fs.closeSync(fd);
  52376. } catch (e) { /* Empty */ }
  52377. // Attempt to extract shebang (null is returned if not a shebang)
  52378. return shebangCommand(buffer.toString());
  52379. }
  52380. var readShebang_1 = readShebang$1;
  52381. const path = require$$0$4;
  52382. const resolveCommand = resolveCommand_1;
  52383. const escape$1 = _escape;
  52384. const readShebang = readShebang_1;
  52385. const isWin$1 = process.platform === 'win32';
  52386. const isExecutableRegExp = /\.(?:com|exe)$/i;
  52387. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  52388. function detectShebang(parsed) {
  52389. parsed.file = resolveCommand(parsed);
  52390. const shebang = parsed.file && readShebang(parsed.file);
  52391. if (shebang) {
  52392. parsed.args.unshift(parsed.file);
  52393. parsed.command = shebang;
  52394. return resolveCommand(parsed);
  52395. }
  52396. return parsed.file;
  52397. }
  52398. function parseNonShell(parsed) {
  52399. if (!isWin$1) {
  52400. return parsed;
  52401. }
  52402. // Detect & add support for shebangs
  52403. const commandFile = detectShebang(parsed);
  52404. // We don't need a shell if the command filename is an executable
  52405. const needsShell = !isExecutableRegExp.test(commandFile);
  52406. // If a shell is required, use cmd.exe and take care of escaping everything correctly
  52407. // Note that `forceShell` is an hidden option used only in tests
  52408. if (parsed.options.forceShell || needsShell) {
  52409. // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
  52410. // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
  52411. // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
  52412. // we need to double escape them
  52413. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  52414. // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
  52415. // This is necessary otherwise it will always fail with ENOENT in those cases
  52416. parsed.command = path.normalize(parsed.command);
  52417. // Escape command & arguments
  52418. parsed.command = escape$1.command(parsed.command);
  52419. parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars));
  52420. const shellCommand = [parsed.command].concat(parsed.args).join(' ');
  52421. parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
  52422. parsed.command = process.env.comspec || 'cmd.exe';
  52423. parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
  52424. }
  52425. return parsed;
  52426. }
  52427. function parse$4(command, args, options) {
  52428. // Normalize arguments, similar to nodejs
  52429. if (args && !Array.isArray(args)) {
  52430. options = args;
  52431. args = null;
  52432. }
  52433. args = args ? args.slice(0) : []; // Clone array to avoid changing the original
  52434. options = Object.assign({}, options); // Clone object to avoid changing the original
  52435. // Build our parsed object
  52436. const parsed = {
  52437. command,
  52438. args,
  52439. options,
  52440. file: undefined,
  52441. original: {
  52442. command,
  52443. args,
  52444. },
  52445. };
  52446. // Delegate further parsing to shell or non-shell
  52447. return options.shell ? parsed : parseNonShell(parsed);
  52448. }
  52449. var parse_1 = parse$4;
  52450. const isWin = process.platform === 'win32';
  52451. function notFoundError(original, syscall) {
  52452. return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
  52453. code: 'ENOENT',
  52454. errno: 'ENOENT',
  52455. syscall: `${syscall} ${original.command}`,
  52456. path: original.command,
  52457. spawnargs: original.args,
  52458. });
  52459. }
  52460. function hookChildProcess(cp, parsed) {
  52461. if (!isWin) {
  52462. return;
  52463. }
  52464. const originalEmit = cp.emit;
  52465. cp.emit = function (name, arg1) {
  52466. // If emitting "exit" event and exit code is 1, we need to check if
  52467. // the command exists and emit an "error" instead
  52468. // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
  52469. if (name === 'exit') {
  52470. const err = verifyENOENT(arg1, parsed);
  52471. if (err) {
  52472. return originalEmit.call(cp, 'error', err);
  52473. }
  52474. }
  52475. return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
  52476. };
  52477. }
  52478. function verifyENOENT(status, parsed) {
  52479. if (isWin && status === 1 && !parsed.file) {
  52480. return notFoundError(parsed.original, 'spawn');
  52481. }
  52482. return null;
  52483. }
  52484. function verifyENOENTSync(status, parsed) {
  52485. if (isWin && status === 1 && !parsed.file) {
  52486. return notFoundError(parsed.original, 'spawnSync');
  52487. }
  52488. return null;
  52489. }
  52490. var enoent$1 = {
  52491. hookChildProcess,
  52492. verifyENOENT,
  52493. verifyENOENTSync,
  52494. notFoundError,
  52495. };
  52496. const cp = require$$2$1;
  52497. const parse$3 = parse_1;
  52498. const enoent = enoent$1;
  52499. function spawn(command, args, options) {
  52500. // Parse the arguments
  52501. const parsed = parse$3(command, args, options);
  52502. // Spawn the child process
  52503. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  52504. // Hook into child process "exit" event to emit an error if the command
  52505. // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  52506. enoent.hookChildProcess(spawned, parsed);
  52507. return spawned;
  52508. }
  52509. function spawnSync(command, args, options) {
  52510. // Parse the arguments
  52511. const parsed = parse$3(command, args, options);
  52512. // Spawn the child process
  52513. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  52514. // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  52515. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  52516. return result;
  52517. }
  52518. crossSpawn.exports = spawn;
  52519. crossSpawn.exports.spawn = spawn;
  52520. crossSpawn.exports.sync = spawnSync;
  52521. crossSpawn.exports._parse = parse$3;
  52522. crossSpawn.exports._enoent = enoent;
  52523. var crossSpawnExports = crossSpawn.exports;
  52524. var spawn$1 = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports);
  52525. /**
  52526. * The following is modified based on source found in
  52527. * https://github.com/facebook/create-react-app
  52528. *
  52529. * MIT Licensed
  52530. * Copyright (c) 2015-present, Facebook, Inc.
  52531. * https://github.com/facebook/create-react-app/blob/master/LICENSE
  52532. *
  52533. */
  52534. /**
  52535. * Reads the BROWSER environment variable and decides what to do with it.
  52536. */
  52537. function openBrowser(url, opt, logger) {
  52538. // The browser executable to open.
  52539. // See https://github.com/sindresorhus/open#app for documentation.
  52540. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '';
  52541. if (browser.toLowerCase().endsWith('.js')) {
  52542. executeNodeScript(browser, url, logger);
  52543. }
  52544. else if (browser.toLowerCase() !== 'none') {
  52545. const browserArgs = process.env.BROWSER_ARGS
  52546. ? process.env.BROWSER_ARGS.split(' ')
  52547. : [];
  52548. startBrowserProcess(browser, browserArgs, url);
  52549. }
  52550. }
  52551. function executeNodeScript(scriptPath, url, logger) {
  52552. const extraArgs = process.argv.slice(2);
  52553. const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url], {
  52554. stdio: 'inherit',
  52555. });
  52556. child.on('close', (code) => {
  52557. if (code !== 0) {
  52558. logger.error(colors$1.red(`\nThe script specified as BROWSER environment variable failed.\n\n${colors$1.cyan(scriptPath)} exited with code ${code}.`), { error: null });
  52559. }
  52560. });
  52561. }
  52562. const supportedChromiumBrowsers = [
  52563. 'Google Chrome Canary',
  52564. 'Google Chrome Dev',
  52565. 'Google Chrome Beta',
  52566. 'Google Chrome',
  52567. 'Microsoft Edge',
  52568. 'Brave Browser',
  52569. 'Vivaldi',
  52570. 'Chromium',
  52571. ];
  52572. async function startBrowserProcess(browser, browserArgs, url) {
  52573. // If we're on OS X, the user hasn't specifically
  52574. // requested a different browser, we can try opening
  52575. // a Chromium browser with AppleScript. This lets us reuse an
  52576. // existing tab when possible instead of creating a new one.
  52577. const preferredOSXBrowser = browser === 'google chrome' ? 'Google Chrome' : browser;
  52578. const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' &&
  52579. (!preferredOSXBrowser ||
  52580. supportedChromiumBrowsers.includes(preferredOSXBrowser));
  52581. if (shouldTryOpenChromeWithAppleScript) {
  52582. try {
  52583. const ps = await execAsync('ps cax');
  52584. const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser)
  52585. ? preferredOSXBrowser
  52586. : supportedChromiumBrowsers.find((b) => ps.includes(b));
  52587. if (openedBrowser) {
  52588. // Try our best to reuse existing tab with AppleScript
  52589. await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, {
  52590. cwd: join$2(VITE_PACKAGE_DIR, 'bin'),
  52591. });
  52592. return true;
  52593. }
  52594. }
  52595. catch (err) {
  52596. // Ignore errors
  52597. }
  52598. }
  52599. // Another special case: on OS X, check if BROWSER has been set to "open".
  52600. // In this case, instead of passing the string `open` to `open` function (which won't work),
  52601. // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  52602. // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
  52603. if (process.platform === 'darwin' && browser === 'open') {
  52604. browser = undefined;
  52605. }
  52606. // Fallback to open
  52607. // (It will always open new tab)
  52608. try {
  52609. const options = browser
  52610. ? { app: { name: browser, arguments: browserArgs } }
  52611. : {};
  52612. open$1(url, options).catch(() => { }); // Prevent `unhandledRejection` error.
  52613. return true;
  52614. }
  52615. catch (err) {
  52616. return false;
  52617. }
  52618. }
  52619. function execAsync(command, options) {
  52620. return new Promise((resolve, reject) => {
  52621. exec(command, options, (error, stdout) => {
  52622. if (error) {
  52623. reject(error);
  52624. }
  52625. else {
  52626. resolve(stdout.toString());
  52627. }
  52628. });
  52629. });
  52630. }
  52631. function bindShortcuts(server, opts) {
  52632. if (!server.httpServer || !process.stdin.isTTY || process.env.CI) {
  52633. return;
  52634. }
  52635. const isDev = isDevServer(server);
  52636. if (isDev) {
  52637. server._shortcutsOptions = opts;
  52638. }
  52639. if (opts?.print) {
  52640. server.config.logger.info(colors$1.dim(colors$1.green(' ➜')) +
  52641. colors$1.dim(' press ') +
  52642. colors$1.bold('h') +
  52643. colors$1.dim(' to show help'));
  52644. }
  52645. const shortcuts = (opts?.customShortcuts ?? [])
  52646. .filter(isDefined)
  52647. // @ts-expect-error passing the right types, but typescript can't detect it
  52648. .concat(isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS);
  52649. let actionRunning = false;
  52650. const onInput = async (input) => {
  52651. // ctrl+c or ctrl+d
  52652. if (input === '\x03' || input === '\x04') {
  52653. try {
  52654. if (isDev) {
  52655. await server.close();
  52656. }
  52657. else {
  52658. server.httpServer.close();
  52659. }
  52660. }
  52661. finally {
  52662. process.exit(1);
  52663. }
  52664. return;
  52665. }
  52666. if (actionRunning)
  52667. return;
  52668. if (input === 'h') {
  52669. server.config.logger.info([
  52670. '',
  52671. colors$1.bold(' Shortcuts'),
  52672. ...shortcuts.map((shortcut) => colors$1.dim(' press ') +
  52673. colors$1.bold(shortcut.key) +
  52674. colors$1.dim(` to ${shortcut.description}`)),
  52675. ].join('\n'));
  52676. }
  52677. const shortcut = shortcuts.find((shortcut) => shortcut.key === input);
  52678. if (!shortcut)
  52679. return;
  52680. actionRunning = true;
  52681. await shortcut.action(server);
  52682. actionRunning = false;
  52683. };
  52684. process.stdin.setRawMode(true);
  52685. process.stdin.on('data', onInput).setEncoding('utf8').resume();
  52686. server.httpServer.on('close', () => {
  52687. process.stdin.off('data', onInput).pause();
  52688. });
  52689. }
  52690. function isDevServer(server) {
  52691. return 'pluginContainer' in server;
  52692. }
  52693. const BASE_DEV_SHORTCUTS = [
  52694. {
  52695. key: 'r',
  52696. description: 'restart the server',
  52697. async action(server) {
  52698. await server.restart();
  52699. },
  52700. },
  52701. {
  52702. key: 'u',
  52703. description: 'show server url',
  52704. action(server) {
  52705. server.config.logger.info('');
  52706. server.printUrls();
  52707. },
  52708. },
  52709. {
  52710. key: 'o',
  52711. description: 'open in browser',
  52712. action(server) {
  52713. server.openBrowser();
  52714. },
  52715. },
  52716. {
  52717. key: 'c',
  52718. description: 'clear console',
  52719. action(server) {
  52720. server.config.logger.clearScreen('error');
  52721. },
  52722. },
  52723. {
  52724. key: 'q',
  52725. description: 'quit',
  52726. async action(server) {
  52727. await server.close().finally(() => process.exit());
  52728. },
  52729. },
  52730. ];
  52731. const BASE_PREVIEW_SHORTCUTS = [
  52732. {
  52733. key: 'o',
  52734. description: 'open in browser',
  52735. action(server) {
  52736. const url = server.resolvedUrls.local[0] ?? server.resolvedUrls.network[0];
  52737. openBrowser(url, true, server.config.logger);
  52738. },
  52739. },
  52740. {
  52741. key: 'q',
  52742. description: 'quit',
  52743. action(server) {
  52744. try {
  52745. server.httpServer.close();
  52746. }
  52747. finally {
  52748. process.exit();
  52749. }
  52750. },
  52751. },
  52752. ];
  52753. var bufferUtil$1 = {exports: {}};
  52754. var constants = {
  52755. BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
  52756. EMPTY_BUFFER: Buffer.alloc(0),
  52757. GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
  52758. kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
  52759. kListener: Symbol('kListener'),
  52760. kStatusCode: Symbol('status-code'),
  52761. kWebSocket: Symbol('websocket'),
  52762. NOOP: () => {}
  52763. };
  52764. const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
  52765. const FastBuffer$2 = Buffer[Symbol.species];
  52766. /**
  52767. * Merges an array of buffers into a new buffer.
  52768. *
  52769. * @param {Buffer[]} list The array of buffers to concat
  52770. * @param {Number} totalLength The total length of buffers in the list
  52771. * @return {Buffer} The resulting buffer
  52772. * @public
  52773. */
  52774. function concat$1(list, totalLength) {
  52775. if (list.length === 0) return EMPTY_BUFFER$3;
  52776. if (list.length === 1) return list[0];
  52777. const target = Buffer.allocUnsafe(totalLength);
  52778. let offset = 0;
  52779. for (let i = 0; i < list.length; i++) {
  52780. const buf = list[i];
  52781. target.set(buf, offset);
  52782. offset += buf.length;
  52783. }
  52784. if (offset < totalLength) {
  52785. return new FastBuffer$2(target.buffer, target.byteOffset, offset);
  52786. }
  52787. return target;
  52788. }
  52789. /**
  52790. * Masks a buffer using the given mask.
  52791. *
  52792. * @param {Buffer} source The buffer to mask
  52793. * @param {Buffer} mask The mask to use
  52794. * @param {Buffer} output The buffer where to store the result
  52795. * @param {Number} offset The offset at which to start writing
  52796. * @param {Number} length The number of bytes to mask.
  52797. * @public
  52798. */
  52799. function _mask(source, mask, output, offset, length) {
  52800. for (let i = 0; i < length; i++) {
  52801. output[offset + i] = source[i] ^ mask[i & 3];
  52802. }
  52803. }
  52804. /**
  52805. * Unmasks a buffer using the given mask.
  52806. *
  52807. * @param {Buffer} buffer The buffer to unmask
  52808. * @param {Buffer} mask The mask to use
  52809. * @public
  52810. */
  52811. function _unmask(buffer, mask) {
  52812. for (let i = 0; i < buffer.length; i++) {
  52813. buffer[i] ^= mask[i & 3];
  52814. }
  52815. }
  52816. /**
  52817. * Converts a buffer to an `ArrayBuffer`.
  52818. *
  52819. * @param {Buffer} buf The buffer to convert
  52820. * @return {ArrayBuffer} Converted buffer
  52821. * @public
  52822. */
  52823. function toArrayBuffer$1(buf) {
  52824. if (buf.length === buf.buffer.byteLength) {
  52825. return buf.buffer;
  52826. }
  52827. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  52828. }
  52829. /**
  52830. * Converts `data` to a `Buffer`.
  52831. *
  52832. * @param {*} data The data to convert
  52833. * @return {Buffer} The buffer
  52834. * @throws {TypeError}
  52835. * @public
  52836. */
  52837. function toBuffer$2(data) {
  52838. toBuffer$2.readOnly = true;
  52839. if (Buffer.isBuffer(data)) return data;
  52840. let buf;
  52841. if (data instanceof ArrayBuffer) {
  52842. buf = new FastBuffer$2(data);
  52843. } else if (ArrayBuffer.isView(data)) {
  52844. buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
  52845. } else {
  52846. buf = Buffer.from(data);
  52847. toBuffer$2.readOnly = false;
  52848. }
  52849. return buf;
  52850. }
  52851. bufferUtil$1.exports = {
  52852. concat: concat$1,
  52853. mask: _mask,
  52854. toArrayBuffer: toArrayBuffer$1,
  52855. toBuffer: toBuffer$2,
  52856. unmask: _unmask
  52857. };
  52858. /* istanbul ignore else */
  52859. if (!process.env.WS_NO_BUFFER_UTIL) {
  52860. try {
  52861. const bufferUtil = require('bufferutil');
  52862. bufferUtil$1.exports.mask = function (source, mask, output, offset, length) {
  52863. if (length < 48) _mask(source, mask, output, offset, length);
  52864. else bufferUtil.mask(source, mask, output, offset, length);
  52865. };
  52866. bufferUtil$1.exports.unmask = function (buffer, mask) {
  52867. if (buffer.length < 32) _unmask(buffer, mask);
  52868. else bufferUtil.unmask(buffer, mask);
  52869. };
  52870. } catch (e) {
  52871. // Continue regardless of the error.
  52872. }
  52873. }
  52874. var bufferUtilExports = bufferUtil$1.exports;
  52875. const kDone = Symbol('kDone');
  52876. const kRun = Symbol('kRun');
  52877. /**
  52878. * A very simple job queue with adjustable concurrency. Adapted from
  52879. * https://github.com/STRML/async-limiter
  52880. */
  52881. let Limiter$1 = class Limiter {
  52882. /**
  52883. * Creates a new `Limiter`.
  52884. *
  52885. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  52886. * to run concurrently
  52887. */
  52888. constructor(concurrency) {
  52889. this[kDone] = () => {
  52890. this.pending--;
  52891. this[kRun]();
  52892. };
  52893. this.concurrency = concurrency || Infinity;
  52894. this.jobs = [];
  52895. this.pending = 0;
  52896. }
  52897. /**
  52898. * Adds a job to the queue.
  52899. *
  52900. * @param {Function} job The job to run
  52901. * @public
  52902. */
  52903. add(job) {
  52904. this.jobs.push(job);
  52905. this[kRun]();
  52906. }
  52907. /**
  52908. * Removes a job from the queue and runs it if possible.
  52909. *
  52910. * @private
  52911. */
  52912. [kRun]() {
  52913. if (this.pending === this.concurrency) return;
  52914. if (this.jobs.length) {
  52915. const job = this.jobs.shift();
  52916. this.pending++;
  52917. job(this[kDone]);
  52918. }
  52919. }
  52920. };
  52921. var limiter = Limiter$1;
  52922. const zlib = require$$0$a;
  52923. const bufferUtil = bufferUtilExports;
  52924. const Limiter = limiter;
  52925. const { kStatusCode: kStatusCode$2 } = constants;
  52926. const FastBuffer$1 = Buffer[Symbol.species];
  52927. const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
  52928. const kPerMessageDeflate = Symbol('permessage-deflate');
  52929. const kTotalLength = Symbol('total-length');
  52930. const kCallback = Symbol('callback');
  52931. const kBuffers = Symbol('buffers');
  52932. const kError$1 = Symbol('error');
  52933. //
  52934. // We limit zlib concurrency, which prevents severe memory fragmentation
  52935. // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
  52936. // and https://github.com/websockets/ws/issues/1202
  52937. //
  52938. // Intentionally global; it's the global thread pool that's an issue.
  52939. //
  52940. let zlibLimiter;
  52941. /**
  52942. * permessage-deflate implementation.
  52943. */
  52944. let PerMessageDeflate$4 = class PerMessageDeflate {
  52945. /**
  52946. * Creates a PerMessageDeflate instance.
  52947. *
  52948. * @param {Object} [options] Configuration options
  52949. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  52950. * for, or request, a custom client window size
  52951. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  52952. * acknowledge disabling of client context takeover
  52953. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  52954. * calls to zlib
  52955. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  52956. * use of a custom server window size
  52957. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  52958. * disabling of server context takeover
  52959. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  52960. * messages should not be compressed if context takeover is disabled
  52961. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  52962. * deflate
  52963. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  52964. * inflate
  52965. * @param {Boolean} [isServer=false] Create the instance in either server or
  52966. * client mode
  52967. * @param {Number} [maxPayload=0] The maximum allowed message length
  52968. */
  52969. constructor(options, isServer, maxPayload) {
  52970. this._maxPayload = maxPayload | 0;
  52971. this._options = options || {};
  52972. this._threshold =
  52973. this._options.threshold !== undefined ? this._options.threshold : 1024;
  52974. this._isServer = !!isServer;
  52975. this._deflate = null;
  52976. this._inflate = null;
  52977. this.params = null;
  52978. if (!zlibLimiter) {
  52979. const concurrency =
  52980. this._options.concurrencyLimit !== undefined
  52981. ? this._options.concurrencyLimit
  52982. : 10;
  52983. zlibLimiter = new Limiter(concurrency);
  52984. }
  52985. }
  52986. /**
  52987. * @type {String}
  52988. */
  52989. static get extensionName() {
  52990. return 'permessage-deflate';
  52991. }
  52992. /**
  52993. * Create an extension negotiation offer.
  52994. *
  52995. * @return {Object} Extension parameters
  52996. * @public
  52997. */
  52998. offer() {
  52999. const params = {};
  53000. if (this._options.serverNoContextTakeover) {
  53001. params.server_no_context_takeover = true;
  53002. }
  53003. if (this._options.clientNoContextTakeover) {
  53004. params.client_no_context_takeover = true;
  53005. }
  53006. if (this._options.serverMaxWindowBits) {
  53007. params.server_max_window_bits = this._options.serverMaxWindowBits;
  53008. }
  53009. if (this._options.clientMaxWindowBits) {
  53010. params.client_max_window_bits = this._options.clientMaxWindowBits;
  53011. } else if (this._options.clientMaxWindowBits == null) {
  53012. params.client_max_window_bits = true;
  53013. }
  53014. return params;
  53015. }
  53016. /**
  53017. * Accept an extension negotiation offer/response.
  53018. *
  53019. * @param {Array} configurations The extension negotiation offers/reponse
  53020. * @return {Object} Accepted configuration
  53021. * @public
  53022. */
  53023. accept(configurations) {
  53024. configurations = this.normalizeParams(configurations);
  53025. this.params = this._isServer
  53026. ? this.acceptAsServer(configurations)
  53027. : this.acceptAsClient(configurations);
  53028. return this.params;
  53029. }
  53030. /**
  53031. * Releases all resources used by the extension.
  53032. *
  53033. * @public
  53034. */
  53035. cleanup() {
  53036. if (this._inflate) {
  53037. this._inflate.close();
  53038. this._inflate = null;
  53039. }
  53040. if (this._deflate) {
  53041. const callback = this._deflate[kCallback];
  53042. this._deflate.close();
  53043. this._deflate = null;
  53044. if (callback) {
  53045. callback(
  53046. new Error(
  53047. 'The deflate stream was closed while data was being processed'
  53048. )
  53049. );
  53050. }
  53051. }
  53052. }
  53053. /**
  53054. * Accept an extension negotiation offer.
  53055. *
  53056. * @param {Array} offers The extension negotiation offers
  53057. * @return {Object} Accepted configuration
  53058. * @private
  53059. */
  53060. acceptAsServer(offers) {
  53061. const opts = this._options;
  53062. const accepted = offers.find((params) => {
  53063. if (
  53064. (opts.serverNoContextTakeover === false &&
  53065. params.server_no_context_takeover) ||
  53066. (params.server_max_window_bits &&
  53067. (opts.serverMaxWindowBits === false ||
  53068. (typeof opts.serverMaxWindowBits === 'number' &&
  53069. opts.serverMaxWindowBits > params.server_max_window_bits))) ||
  53070. (typeof opts.clientMaxWindowBits === 'number' &&
  53071. !params.client_max_window_bits)
  53072. ) {
  53073. return false;
  53074. }
  53075. return true;
  53076. });
  53077. if (!accepted) {
  53078. throw new Error('None of the extension offers can be accepted');
  53079. }
  53080. if (opts.serverNoContextTakeover) {
  53081. accepted.server_no_context_takeover = true;
  53082. }
  53083. if (opts.clientNoContextTakeover) {
  53084. accepted.client_no_context_takeover = true;
  53085. }
  53086. if (typeof opts.serverMaxWindowBits === 'number') {
  53087. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  53088. }
  53089. if (typeof opts.clientMaxWindowBits === 'number') {
  53090. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  53091. } else if (
  53092. accepted.client_max_window_bits === true ||
  53093. opts.clientMaxWindowBits === false
  53094. ) {
  53095. delete accepted.client_max_window_bits;
  53096. }
  53097. return accepted;
  53098. }
  53099. /**
  53100. * Accept the extension negotiation response.
  53101. *
  53102. * @param {Array} response The extension negotiation response
  53103. * @return {Object} Accepted configuration
  53104. * @private
  53105. */
  53106. acceptAsClient(response) {
  53107. const params = response[0];
  53108. if (
  53109. this._options.clientNoContextTakeover === false &&
  53110. params.client_no_context_takeover
  53111. ) {
  53112. throw new Error('Unexpected parameter "client_no_context_takeover"');
  53113. }
  53114. if (!params.client_max_window_bits) {
  53115. if (typeof this._options.clientMaxWindowBits === 'number') {
  53116. params.client_max_window_bits = this._options.clientMaxWindowBits;
  53117. }
  53118. } else if (
  53119. this._options.clientMaxWindowBits === false ||
  53120. (typeof this._options.clientMaxWindowBits === 'number' &&
  53121. params.client_max_window_bits > this._options.clientMaxWindowBits)
  53122. ) {
  53123. throw new Error(
  53124. 'Unexpected or invalid parameter "client_max_window_bits"'
  53125. );
  53126. }
  53127. return params;
  53128. }
  53129. /**
  53130. * Normalize parameters.
  53131. *
  53132. * @param {Array} configurations The extension negotiation offers/reponse
  53133. * @return {Array} The offers/response with normalized parameters
  53134. * @private
  53135. */
  53136. normalizeParams(configurations) {
  53137. configurations.forEach((params) => {
  53138. Object.keys(params).forEach((key) => {
  53139. let value = params[key];
  53140. if (value.length > 1) {
  53141. throw new Error(`Parameter "${key}" must have only a single value`);
  53142. }
  53143. value = value[0];
  53144. if (key === 'client_max_window_bits') {
  53145. if (value !== true) {
  53146. const num = +value;
  53147. if (!Number.isInteger(num) || num < 8 || num > 15) {
  53148. throw new TypeError(
  53149. `Invalid value for parameter "${key}": ${value}`
  53150. );
  53151. }
  53152. value = num;
  53153. } else if (!this._isServer) {
  53154. throw new TypeError(
  53155. `Invalid value for parameter "${key}": ${value}`
  53156. );
  53157. }
  53158. } else if (key === 'server_max_window_bits') {
  53159. const num = +value;
  53160. if (!Number.isInteger(num) || num < 8 || num > 15) {
  53161. throw new TypeError(
  53162. `Invalid value for parameter "${key}": ${value}`
  53163. );
  53164. }
  53165. value = num;
  53166. } else if (
  53167. key === 'client_no_context_takeover' ||
  53168. key === 'server_no_context_takeover'
  53169. ) {
  53170. if (value !== true) {
  53171. throw new TypeError(
  53172. `Invalid value for parameter "${key}": ${value}`
  53173. );
  53174. }
  53175. } else {
  53176. throw new Error(`Unknown parameter "${key}"`);
  53177. }
  53178. params[key] = value;
  53179. });
  53180. });
  53181. return configurations;
  53182. }
  53183. /**
  53184. * Decompress data. Concurrency limited.
  53185. *
  53186. * @param {Buffer} data Compressed data
  53187. * @param {Boolean} fin Specifies whether or not this is the last fragment
  53188. * @param {Function} callback Callback
  53189. * @public
  53190. */
  53191. decompress(data, fin, callback) {
  53192. zlibLimiter.add((done) => {
  53193. this._decompress(data, fin, (err, result) => {
  53194. done();
  53195. callback(err, result);
  53196. });
  53197. });
  53198. }
  53199. /**
  53200. * Compress data. Concurrency limited.
  53201. *
  53202. * @param {(Buffer|String)} data Data to compress
  53203. * @param {Boolean} fin Specifies whether or not this is the last fragment
  53204. * @param {Function} callback Callback
  53205. * @public
  53206. */
  53207. compress(data, fin, callback) {
  53208. zlibLimiter.add((done) => {
  53209. this._compress(data, fin, (err, result) => {
  53210. done();
  53211. callback(err, result);
  53212. });
  53213. });
  53214. }
  53215. /**
  53216. * Decompress data.
  53217. *
  53218. * @param {Buffer} data Compressed data
  53219. * @param {Boolean} fin Specifies whether or not this is the last fragment
  53220. * @param {Function} callback Callback
  53221. * @private
  53222. */
  53223. _decompress(data, fin, callback) {
  53224. const endpoint = this._isServer ? 'client' : 'server';
  53225. if (!this._inflate) {
  53226. const key = `${endpoint}_max_window_bits`;
  53227. const windowBits =
  53228. typeof this.params[key] !== 'number'
  53229. ? zlib.Z_DEFAULT_WINDOWBITS
  53230. : this.params[key];
  53231. this._inflate = zlib.createInflateRaw({
  53232. ...this._options.zlibInflateOptions,
  53233. windowBits
  53234. });
  53235. this._inflate[kPerMessageDeflate] = this;
  53236. this._inflate[kTotalLength] = 0;
  53237. this._inflate[kBuffers] = [];
  53238. this._inflate.on('error', inflateOnError);
  53239. this._inflate.on('data', inflateOnData);
  53240. }
  53241. this._inflate[kCallback] = callback;
  53242. this._inflate.write(data);
  53243. if (fin) this._inflate.write(TRAILER);
  53244. this._inflate.flush(() => {
  53245. const err = this._inflate[kError$1];
  53246. if (err) {
  53247. this._inflate.close();
  53248. this._inflate = null;
  53249. callback(err);
  53250. return;
  53251. }
  53252. const data = bufferUtil.concat(
  53253. this._inflate[kBuffers],
  53254. this._inflate[kTotalLength]
  53255. );
  53256. if (this._inflate._readableState.endEmitted) {
  53257. this._inflate.close();
  53258. this._inflate = null;
  53259. } else {
  53260. this._inflate[kTotalLength] = 0;
  53261. this._inflate[kBuffers] = [];
  53262. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  53263. this._inflate.reset();
  53264. }
  53265. }
  53266. callback(null, data);
  53267. });
  53268. }
  53269. /**
  53270. * Compress data.
  53271. *
  53272. * @param {(Buffer|String)} data Data to compress
  53273. * @param {Boolean} fin Specifies whether or not this is the last fragment
  53274. * @param {Function} callback Callback
  53275. * @private
  53276. */
  53277. _compress(data, fin, callback) {
  53278. const endpoint = this._isServer ? 'server' : 'client';
  53279. if (!this._deflate) {
  53280. const key = `${endpoint}_max_window_bits`;
  53281. const windowBits =
  53282. typeof this.params[key] !== 'number'
  53283. ? zlib.Z_DEFAULT_WINDOWBITS
  53284. : this.params[key];
  53285. this._deflate = zlib.createDeflateRaw({
  53286. ...this._options.zlibDeflateOptions,
  53287. windowBits
  53288. });
  53289. this._deflate[kTotalLength] = 0;
  53290. this._deflate[kBuffers] = [];
  53291. this._deflate.on('data', deflateOnData);
  53292. }
  53293. this._deflate[kCallback] = callback;
  53294. this._deflate.write(data);
  53295. this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
  53296. if (!this._deflate) {
  53297. //
  53298. // The deflate stream was closed while data was being processed.
  53299. //
  53300. return;
  53301. }
  53302. let data = bufferUtil.concat(
  53303. this._deflate[kBuffers],
  53304. this._deflate[kTotalLength]
  53305. );
  53306. if (fin) {
  53307. data = new FastBuffer$1(data.buffer, data.byteOffset, data.length - 4);
  53308. }
  53309. //
  53310. // Ensure that the callback will not be called again in
  53311. // `PerMessageDeflate#cleanup()`.
  53312. //
  53313. this._deflate[kCallback] = null;
  53314. this._deflate[kTotalLength] = 0;
  53315. this._deflate[kBuffers] = [];
  53316. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  53317. this._deflate.reset();
  53318. }
  53319. callback(null, data);
  53320. });
  53321. }
  53322. };
  53323. var permessageDeflate = PerMessageDeflate$4;
  53324. /**
  53325. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  53326. *
  53327. * @param {Buffer} chunk A chunk of data
  53328. * @private
  53329. */
  53330. function deflateOnData(chunk) {
  53331. this[kBuffers].push(chunk);
  53332. this[kTotalLength] += chunk.length;
  53333. }
  53334. /**
  53335. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  53336. *
  53337. * @param {Buffer} chunk A chunk of data
  53338. * @private
  53339. */
  53340. function inflateOnData(chunk) {
  53341. this[kTotalLength] += chunk.length;
  53342. if (
  53343. this[kPerMessageDeflate]._maxPayload < 1 ||
  53344. this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
  53345. ) {
  53346. this[kBuffers].push(chunk);
  53347. return;
  53348. }
  53349. this[kError$1] = new RangeError('Max payload size exceeded');
  53350. this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
  53351. this[kError$1][kStatusCode$2] = 1009;
  53352. this.removeListener('data', inflateOnData);
  53353. this.reset();
  53354. }
  53355. /**
  53356. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  53357. *
  53358. * @param {Error} err The emitted error
  53359. * @private
  53360. */
  53361. function inflateOnError(err) {
  53362. //
  53363. // There is no need to call `Zlib#close()` as the handle is automatically
  53364. // closed when an error is emitted.
  53365. //
  53366. this[kPerMessageDeflate]._inflate = null;
  53367. err[kStatusCode$2] = 1007;
  53368. this[kCallback](err);
  53369. }
  53370. var validation = {exports: {}};
  53371. const { isUtf8 } = require$$0$b;
  53372. //
  53373. // Allowed token characters:
  53374. //
  53375. // '!', '#', '$', '%', '&', ''', '*', '+', '-',
  53376. // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
  53377. //
  53378. // tokenChars[32] === 0 // ' '
  53379. // tokenChars[33] === 1 // '!'
  53380. // tokenChars[34] === 0 // '"'
  53381. // ...
  53382. //
  53383. // prettier-ignore
  53384. const tokenChars$2 = [
  53385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
  53386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
  53387. 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
  53388. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
  53389. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
  53390. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
  53391. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
  53392. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
  53393. ];
  53394. /**
  53395. * Checks if a status code is allowed in a close frame.
  53396. *
  53397. * @param {Number} code The status code
  53398. * @return {Boolean} `true` if the status code is valid, else `false`
  53399. * @public
  53400. */
  53401. function isValidStatusCode$2(code) {
  53402. return (
  53403. (code >= 1000 &&
  53404. code <= 1014 &&
  53405. code !== 1004 &&
  53406. code !== 1005 &&
  53407. code !== 1006) ||
  53408. (code >= 3000 && code <= 4999)
  53409. );
  53410. }
  53411. /**
  53412. * Checks if a given buffer contains only correct UTF-8.
  53413. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  53414. * Markus Kuhn.
  53415. *
  53416. * @param {Buffer} buf The buffer to check
  53417. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  53418. * @public
  53419. */
  53420. function _isValidUTF8(buf) {
  53421. const len = buf.length;
  53422. let i = 0;
  53423. while (i < len) {
  53424. if ((buf[i] & 0x80) === 0) {
  53425. // 0xxxxxxx
  53426. i++;
  53427. } else if ((buf[i] & 0xe0) === 0xc0) {
  53428. // 110xxxxx 10xxxxxx
  53429. if (
  53430. i + 1 === len ||
  53431. (buf[i + 1] & 0xc0) !== 0x80 ||
  53432. (buf[i] & 0xfe) === 0xc0 // Overlong
  53433. ) {
  53434. return false;
  53435. }
  53436. i += 2;
  53437. } else if ((buf[i] & 0xf0) === 0xe0) {
  53438. // 1110xxxx 10xxxxxx 10xxxxxx
  53439. if (
  53440. i + 2 >= len ||
  53441. (buf[i + 1] & 0xc0) !== 0x80 ||
  53442. (buf[i + 2] & 0xc0) !== 0x80 ||
  53443. (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
  53444. (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
  53445. ) {
  53446. return false;
  53447. }
  53448. i += 3;
  53449. } else if ((buf[i] & 0xf8) === 0xf0) {
  53450. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  53451. if (
  53452. i + 3 >= len ||
  53453. (buf[i + 1] & 0xc0) !== 0x80 ||
  53454. (buf[i + 2] & 0xc0) !== 0x80 ||
  53455. (buf[i + 3] & 0xc0) !== 0x80 ||
  53456. (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
  53457. (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
  53458. buf[i] > 0xf4 // > U+10FFFF
  53459. ) {
  53460. return false;
  53461. }
  53462. i += 4;
  53463. } else {
  53464. return false;
  53465. }
  53466. }
  53467. return true;
  53468. }
  53469. validation.exports = {
  53470. isValidStatusCode: isValidStatusCode$2,
  53471. isValidUTF8: _isValidUTF8,
  53472. tokenChars: tokenChars$2
  53473. };
  53474. if (isUtf8) {
  53475. validation.exports.isValidUTF8 = function (buf) {
  53476. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  53477. };
  53478. } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
  53479. try {
  53480. const isValidUTF8 = require('utf-8-validate');
  53481. validation.exports.isValidUTF8 = function (buf) {
  53482. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  53483. };
  53484. } catch (e) {
  53485. // Continue regardless of the error.
  53486. }
  53487. }
  53488. var validationExports = validation.exports;
  53489. const { Writable: Writable$1 } = require$$0$7;
  53490. const PerMessageDeflate$3 = permessageDeflate;
  53491. const {
  53492. BINARY_TYPES: BINARY_TYPES$1,
  53493. EMPTY_BUFFER: EMPTY_BUFFER$2,
  53494. kStatusCode: kStatusCode$1,
  53495. kWebSocket: kWebSocket$2
  53496. } = constants;
  53497. const { concat, toArrayBuffer, unmask } = bufferUtilExports;
  53498. const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
  53499. const FastBuffer = Buffer[Symbol.species];
  53500. const GET_INFO = 0;
  53501. const GET_PAYLOAD_LENGTH_16 = 1;
  53502. const GET_PAYLOAD_LENGTH_64 = 2;
  53503. const GET_MASK = 3;
  53504. const GET_DATA = 4;
  53505. const INFLATING = 5;
  53506. /**
  53507. * HyBi Receiver implementation.
  53508. *
  53509. * @extends Writable
  53510. */
  53511. let Receiver$1 = class Receiver extends Writable$1 {
  53512. /**
  53513. * Creates a Receiver instance.
  53514. *
  53515. * @param {Object} [options] Options object
  53516. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  53517. * @param {Object} [options.extensions] An object containing the negotiated
  53518. * extensions
  53519. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  53520. * client or server mode
  53521. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  53522. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  53523. * not to skip UTF-8 validation for text and close messages
  53524. */
  53525. constructor(options = {}) {
  53526. super();
  53527. this._binaryType = options.binaryType || BINARY_TYPES$1[0];
  53528. this._extensions = options.extensions || {};
  53529. this._isServer = !!options.isServer;
  53530. this._maxPayload = options.maxPayload | 0;
  53531. this._skipUTF8Validation = !!options.skipUTF8Validation;
  53532. this[kWebSocket$2] = undefined;
  53533. this._bufferedBytes = 0;
  53534. this._buffers = [];
  53535. this._compressed = false;
  53536. this._payloadLength = 0;
  53537. this._mask = undefined;
  53538. this._fragmented = 0;
  53539. this._masked = false;
  53540. this._fin = false;
  53541. this._opcode = 0;
  53542. this._totalPayloadLength = 0;
  53543. this._messageLength = 0;
  53544. this._fragments = [];
  53545. this._state = GET_INFO;
  53546. this._loop = false;
  53547. }
  53548. /**
  53549. * Implements `Writable.prototype._write()`.
  53550. *
  53551. * @param {Buffer} chunk The chunk of data to write
  53552. * @param {String} encoding The character encoding of `chunk`
  53553. * @param {Function} cb Callback
  53554. * @private
  53555. */
  53556. _write(chunk, encoding, cb) {
  53557. if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
  53558. this._bufferedBytes += chunk.length;
  53559. this._buffers.push(chunk);
  53560. this.startLoop(cb);
  53561. }
  53562. /**
  53563. * Consumes `n` bytes from the buffered data.
  53564. *
  53565. * @param {Number} n The number of bytes to consume
  53566. * @return {Buffer} The consumed bytes
  53567. * @private
  53568. */
  53569. consume(n) {
  53570. this._bufferedBytes -= n;
  53571. if (n === this._buffers[0].length) return this._buffers.shift();
  53572. if (n < this._buffers[0].length) {
  53573. const buf = this._buffers[0];
  53574. this._buffers[0] = new FastBuffer(
  53575. buf.buffer,
  53576. buf.byteOffset + n,
  53577. buf.length - n
  53578. );
  53579. return new FastBuffer(buf.buffer, buf.byteOffset, n);
  53580. }
  53581. const dst = Buffer.allocUnsafe(n);
  53582. do {
  53583. const buf = this._buffers[0];
  53584. const offset = dst.length - n;
  53585. if (n >= buf.length) {
  53586. dst.set(this._buffers.shift(), offset);
  53587. } else {
  53588. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  53589. this._buffers[0] = new FastBuffer(
  53590. buf.buffer,
  53591. buf.byteOffset + n,
  53592. buf.length - n
  53593. );
  53594. }
  53595. n -= buf.length;
  53596. } while (n > 0);
  53597. return dst;
  53598. }
  53599. /**
  53600. * Starts the parsing loop.
  53601. *
  53602. * @param {Function} cb Callback
  53603. * @private
  53604. */
  53605. startLoop(cb) {
  53606. let err;
  53607. this._loop = true;
  53608. do {
  53609. switch (this._state) {
  53610. case GET_INFO:
  53611. err = this.getInfo();
  53612. break;
  53613. case GET_PAYLOAD_LENGTH_16:
  53614. err = this.getPayloadLength16();
  53615. break;
  53616. case GET_PAYLOAD_LENGTH_64:
  53617. err = this.getPayloadLength64();
  53618. break;
  53619. case GET_MASK:
  53620. this.getMask();
  53621. break;
  53622. case GET_DATA:
  53623. err = this.getData(cb);
  53624. break;
  53625. default:
  53626. // `INFLATING`
  53627. this._loop = false;
  53628. return;
  53629. }
  53630. } while (this._loop);
  53631. cb(err);
  53632. }
  53633. /**
  53634. * Reads the first two bytes of a frame.
  53635. *
  53636. * @return {(RangeError|undefined)} A possible error
  53637. * @private
  53638. */
  53639. getInfo() {
  53640. if (this._bufferedBytes < 2) {
  53641. this._loop = false;
  53642. return;
  53643. }
  53644. const buf = this.consume(2);
  53645. if ((buf[0] & 0x30) !== 0x00) {
  53646. this._loop = false;
  53647. return error(
  53648. RangeError,
  53649. 'RSV2 and RSV3 must be clear',
  53650. true,
  53651. 1002,
  53652. 'WS_ERR_UNEXPECTED_RSV_2_3'
  53653. );
  53654. }
  53655. const compressed = (buf[0] & 0x40) === 0x40;
  53656. if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
  53657. this._loop = false;
  53658. return error(
  53659. RangeError,
  53660. 'RSV1 must be clear',
  53661. true,
  53662. 1002,
  53663. 'WS_ERR_UNEXPECTED_RSV_1'
  53664. );
  53665. }
  53666. this._fin = (buf[0] & 0x80) === 0x80;
  53667. this._opcode = buf[0] & 0x0f;
  53668. this._payloadLength = buf[1] & 0x7f;
  53669. if (this._opcode === 0x00) {
  53670. if (compressed) {
  53671. this._loop = false;
  53672. return error(
  53673. RangeError,
  53674. 'RSV1 must be clear',
  53675. true,
  53676. 1002,
  53677. 'WS_ERR_UNEXPECTED_RSV_1'
  53678. );
  53679. }
  53680. if (!this._fragmented) {
  53681. this._loop = false;
  53682. return error(
  53683. RangeError,
  53684. 'invalid opcode 0',
  53685. true,
  53686. 1002,
  53687. 'WS_ERR_INVALID_OPCODE'
  53688. );
  53689. }
  53690. this._opcode = this._fragmented;
  53691. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  53692. if (this._fragmented) {
  53693. this._loop = false;
  53694. return error(
  53695. RangeError,
  53696. `invalid opcode ${this._opcode}`,
  53697. true,
  53698. 1002,
  53699. 'WS_ERR_INVALID_OPCODE'
  53700. );
  53701. }
  53702. this._compressed = compressed;
  53703. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  53704. if (!this._fin) {
  53705. this._loop = false;
  53706. return error(
  53707. RangeError,
  53708. 'FIN must be set',
  53709. true,
  53710. 1002,
  53711. 'WS_ERR_EXPECTED_FIN'
  53712. );
  53713. }
  53714. if (compressed) {
  53715. this._loop = false;
  53716. return error(
  53717. RangeError,
  53718. 'RSV1 must be clear',
  53719. true,
  53720. 1002,
  53721. 'WS_ERR_UNEXPECTED_RSV_1'
  53722. );
  53723. }
  53724. if (
  53725. this._payloadLength > 0x7d ||
  53726. (this._opcode === 0x08 && this._payloadLength === 1)
  53727. ) {
  53728. this._loop = false;
  53729. return error(
  53730. RangeError,
  53731. `invalid payload length ${this._payloadLength}`,
  53732. true,
  53733. 1002,
  53734. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  53735. );
  53736. }
  53737. } else {
  53738. this._loop = false;
  53739. return error(
  53740. RangeError,
  53741. `invalid opcode ${this._opcode}`,
  53742. true,
  53743. 1002,
  53744. 'WS_ERR_INVALID_OPCODE'
  53745. );
  53746. }
  53747. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  53748. this._masked = (buf[1] & 0x80) === 0x80;
  53749. if (this._isServer) {
  53750. if (!this._masked) {
  53751. this._loop = false;
  53752. return error(
  53753. RangeError,
  53754. 'MASK must be set',
  53755. true,
  53756. 1002,
  53757. 'WS_ERR_EXPECTED_MASK'
  53758. );
  53759. }
  53760. } else if (this._masked) {
  53761. this._loop = false;
  53762. return error(
  53763. RangeError,
  53764. 'MASK must be clear',
  53765. true,
  53766. 1002,
  53767. 'WS_ERR_UNEXPECTED_MASK'
  53768. );
  53769. }
  53770. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  53771. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  53772. else return this.haveLength();
  53773. }
  53774. /**
  53775. * Gets extended payload length (7+16).
  53776. *
  53777. * @return {(RangeError|undefined)} A possible error
  53778. * @private
  53779. */
  53780. getPayloadLength16() {
  53781. if (this._bufferedBytes < 2) {
  53782. this._loop = false;
  53783. return;
  53784. }
  53785. this._payloadLength = this.consume(2).readUInt16BE(0);
  53786. return this.haveLength();
  53787. }
  53788. /**
  53789. * Gets extended payload length (7+64).
  53790. *
  53791. * @return {(RangeError|undefined)} A possible error
  53792. * @private
  53793. */
  53794. getPayloadLength64() {
  53795. if (this._bufferedBytes < 8) {
  53796. this._loop = false;
  53797. return;
  53798. }
  53799. const buf = this.consume(8);
  53800. const num = buf.readUInt32BE(0);
  53801. //
  53802. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  53803. // if payload length is greater than this number.
  53804. //
  53805. if (num > Math.pow(2, 53 - 32) - 1) {
  53806. this._loop = false;
  53807. return error(
  53808. RangeError,
  53809. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  53810. false,
  53811. 1009,
  53812. 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
  53813. );
  53814. }
  53815. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  53816. return this.haveLength();
  53817. }
  53818. /**
  53819. * Payload length has been read.
  53820. *
  53821. * @return {(RangeError|undefined)} A possible error
  53822. * @private
  53823. */
  53824. haveLength() {
  53825. if (this._payloadLength && this._opcode < 0x08) {
  53826. this._totalPayloadLength += this._payloadLength;
  53827. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  53828. this._loop = false;
  53829. return error(
  53830. RangeError,
  53831. 'Max payload size exceeded',
  53832. false,
  53833. 1009,
  53834. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  53835. );
  53836. }
  53837. }
  53838. if (this._masked) this._state = GET_MASK;
  53839. else this._state = GET_DATA;
  53840. }
  53841. /**
  53842. * Reads mask bytes.
  53843. *
  53844. * @private
  53845. */
  53846. getMask() {
  53847. if (this._bufferedBytes < 4) {
  53848. this._loop = false;
  53849. return;
  53850. }
  53851. this._mask = this.consume(4);
  53852. this._state = GET_DATA;
  53853. }
  53854. /**
  53855. * Reads data bytes.
  53856. *
  53857. * @param {Function} cb Callback
  53858. * @return {(Error|RangeError|undefined)} A possible error
  53859. * @private
  53860. */
  53861. getData(cb) {
  53862. let data = EMPTY_BUFFER$2;
  53863. if (this._payloadLength) {
  53864. if (this._bufferedBytes < this._payloadLength) {
  53865. this._loop = false;
  53866. return;
  53867. }
  53868. data = this.consume(this._payloadLength);
  53869. if (
  53870. this._masked &&
  53871. (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
  53872. ) {
  53873. unmask(data, this._mask);
  53874. }
  53875. }
  53876. if (this._opcode > 0x07) return this.controlMessage(data);
  53877. if (this._compressed) {
  53878. this._state = INFLATING;
  53879. this.decompress(data, cb);
  53880. return;
  53881. }
  53882. if (data.length) {
  53883. //
  53884. // This message is not compressed so its length is the sum of the payload
  53885. // length of all fragments.
  53886. //
  53887. this._messageLength = this._totalPayloadLength;
  53888. this._fragments.push(data);
  53889. }
  53890. return this.dataMessage();
  53891. }
  53892. /**
  53893. * Decompresses data.
  53894. *
  53895. * @param {Buffer} data Compressed data
  53896. * @param {Function} cb Callback
  53897. * @private
  53898. */
  53899. decompress(data, cb) {
  53900. const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
  53901. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  53902. if (err) return cb(err);
  53903. if (buf.length) {
  53904. this._messageLength += buf.length;
  53905. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  53906. return cb(
  53907. error(
  53908. RangeError,
  53909. 'Max payload size exceeded',
  53910. false,
  53911. 1009,
  53912. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  53913. )
  53914. );
  53915. }
  53916. this._fragments.push(buf);
  53917. }
  53918. const er = this.dataMessage();
  53919. if (er) return cb(er);
  53920. this.startLoop(cb);
  53921. });
  53922. }
  53923. /**
  53924. * Handles a data message.
  53925. *
  53926. * @return {(Error|undefined)} A possible error
  53927. * @private
  53928. */
  53929. dataMessage() {
  53930. if (this._fin) {
  53931. const messageLength = this._messageLength;
  53932. const fragments = this._fragments;
  53933. this._totalPayloadLength = 0;
  53934. this._messageLength = 0;
  53935. this._fragmented = 0;
  53936. this._fragments = [];
  53937. if (this._opcode === 2) {
  53938. let data;
  53939. if (this._binaryType === 'nodebuffer') {
  53940. data = concat(fragments, messageLength);
  53941. } else if (this._binaryType === 'arraybuffer') {
  53942. data = toArrayBuffer(concat(fragments, messageLength));
  53943. } else {
  53944. data = fragments;
  53945. }
  53946. this.emit('message', data, true);
  53947. } else {
  53948. const buf = concat(fragments, messageLength);
  53949. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  53950. this._loop = false;
  53951. return error(
  53952. Error,
  53953. 'invalid UTF-8 sequence',
  53954. true,
  53955. 1007,
  53956. 'WS_ERR_INVALID_UTF8'
  53957. );
  53958. }
  53959. this.emit('message', buf, false);
  53960. }
  53961. }
  53962. this._state = GET_INFO;
  53963. }
  53964. /**
  53965. * Handles a control message.
  53966. *
  53967. * @param {Buffer} data Data to handle
  53968. * @return {(Error|RangeError|undefined)} A possible error
  53969. * @private
  53970. */
  53971. controlMessage(data) {
  53972. if (this._opcode === 0x08) {
  53973. this._loop = false;
  53974. if (data.length === 0) {
  53975. this.emit('conclude', 1005, EMPTY_BUFFER$2);
  53976. this.end();
  53977. } else {
  53978. const code = data.readUInt16BE(0);
  53979. if (!isValidStatusCode$1(code)) {
  53980. return error(
  53981. RangeError,
  53982. `invalid status code ${code}`,
  53983. true,
  53984. 1002,
  53985. 'WS_ERR_INVALID_CLOSE_CODE'
  53986. );
  53987. }
  53988. const buf = new FastBuffer(
  53989. data.buffer,
  53990. data.byteOffset + 2,
  53991. data.length - 2
  53992. );
  53993. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  53994. return error(
  53995. Error,
  53996. 'invalid UTF-8 sequence',
  53997. true,
  53998. 1007,
  53999. 'WS_ERR_INVALID_UTF8'
  54000. );
  54001. }
  54002. this.emit('conclude', code, buf);
  54003. this.end();
  54004. }
  54005. } else if (this._opcode === 0x09) {
  54006. this.emit('ping', data);
  54007. } else {
  54008. this.emit('pong', data);
  54009. }
  54010. this._state = GET_INFO;
  54011. }
  54012. };
  54013. var receiver = Receiver$1;
  54014. /**
  54015. * Builds an error object.
  54016. *
  54017. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  54018. * @param {String} message The error message
  54019. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  54020. * `message`
  54021. * @param {Number} statusCode The status code
  54022. * @param {String} errorCode The exposed error code
  54023. * @return {(Error|RangeError)} The error
  54024. * @private
  54025. */
  54026. function error(ErrorCtor, message, prefix, statusCode, errorCode) {
  54027. const err = new ErrorCtor(
  54028. prefix ? `Invalid WebSocket frame: ${message}` : message
  54029. );
  54030. Error.captureStackTrace(err, error);
  54031. err.code = errorCode;
  54032. err[kStatusCode$1] = statusCode;
  54033. return err;
  54034. }
  54035. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */
  54036. const { randomFillSync } = require$$3$1;
  54037. const PerMessageDeflate$2 = permessageDeflate;
  54038. const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
  54039. const { isValidStatusCode } = validationExports;
  54040. const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports;
  54041. const kByteLength = Symbol('kByteLength');
  54042. const maskBuffer = Buffer.alloc(4);
  54043. /**
  54044. * HyBi Sender implementation.
  54045. */
  54046. let Sender$1 = class Sender {
  54047. /**
  54048. * Creates a Sender instance.
  54049. *
  54050. * @param {(net.Socket|tls.Socket)} socket The connection socket
  54051. * @param {Object} [extensions] An object containing the negotiated extensions
  54052. * @param {Function} [generateMask] The function used to generate the masking
  54053. * key
  54054. */
  54055. constructor(socket, extensions, generateMask) {
  54056. this._extensions = extensions || {};
  54057. if (generateMask) {
  54058. this._generateMask = generateMask;
  54059. this._maskBuffer = Buffer.alloc(4);
  54060. }
  54061. this._socket = socket;
  54062. this._firstFragment = true;
  54063. this._compress = false;
  54064. this._bufferedBytes = 0;
  54065. this._deflating = false;
  54066. this._queue = [];
  54067. }
  54068. /**
  54069. * Frames a piece of data according to the HyBi WebSocket protocol.
  54070. *
  54071. * @param {(Buffer|String)} data The data to frame
  54072. * @param {Object} options Options object
  54073. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  54074. * FIN bit
  54075. * @param {Function} [options.generateMask] The function used to generate the
  54076. * masking key
  54077. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  54078. * `data`
  54079. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  54080. * key
  54081. * @param {Number} options.opcode The opcode
  54082. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  54083. * modified
  54084. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  54085. * RSV1 bit
  54086. * @return {(Buffer|String)[]} The framed data
  54087. * @public
  54088. */
  54089. static frame(data, options) {
  54090. let mask;
  54091. let merge = false;
  54092. let offset = 2;
  54093. let skipMasking = false;
  54094. if (options.mask) {
  54095. mask = options.maskBuffer || maskBuffer;
  54096. if (options.generateMask) {
  54097. options.generateMask(mask);
  54098. } else {
  54099. randomFillSync(mask, 0, 4);
  54100. }
  54101. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  54102. offset = 6;
  54103. }
  54104. let dataLength;
  54105. if (typeof data === 'string') {
  54106. if (
  54107. (!options.mask || skipMasking) &&
  54108. options[kByteLength] !== undefined
  54109. ) {
  54110. dataLength = options[kByteLength];
  54111. } else {
  54112. data = Buffer.from(data);
  54113. dataLength = data.length;
  54114. }
  54115. } else {
  54116. dataLength = data.length;
  54117. merge = options.mask && options.readOnly && !skipMasking;
  54118. }
  54119. let payloadLength = dataLength;
  54120. if (dataLength >= 65536) {
  54121. offset += 8;
  54122. payloadLength = 127;
  54123. } else if (dataLength > 125) {
  54124. offset += 2;
  54125. payloadLength = 126;
  54126. }
  54127. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  54128. target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
  54129. if (options.rsv1) target[0] |= 0x40;
  54130. target[1] = payloadLength;
  54131. if (payloadLength === 126) {
  54132. target.writeUInt16BE(dataLength, 2);
  54133. } else if (payloadLength === 127) {
  54134. target[2] = target[3] = 0;
  54135. target.writeUIntBE(dataLength, 4, 6);
  54136. }
  54137. if (!options.mask) return [target, data];
  54138. target[1] |= 0x80;
  54139. target[offset - 4] = mask[0];
  54140. target[offset - 3] = mask[1];
  54141. target[offset - 2] = mask[2];
  54142. target[offset - 1] = mask[3];
  54143. if (skipMasking) return [target, data];
  54144. if (merge) {
  54145. applyMask(data, mask, target, offset, dataLength);
  54146. return [target];
  54147. }
  54148. applyMask(data, mask, data, 0, dataLength);
  54149. return [target, data];
  54150. }
  54151. /**
  54152. * Sends a close message to the other peer.
  54153. *
  54154. * @param {Number} [code] The status code component of the body
  54155. * @param {(String|Buffer)} [data] The message component of the body
  54156. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  54157. * @param {Function} [cb] Callback
  54158. * @public
  54159. */
  54160. close(code, data, mask, cb) {
  54161. let buf;
  54162. if (code === undefined) {
  54163. buf = EMPTY_BUFFER$1;
  54164. } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
  54165. throw new TypeError('First argument must be a valid error code number');
  54166. } else if (data === undefined || !data.length) {
  54167. buf = Buffer.allocUnsafe(2);
  54168. buf.writeUInt16BE(code, 0);
  54169. } else {
  54170. const length = Buffer.byteLength(data);
  54171. if (length > 123) {
  54172. throw new RangeError('The message must not be greater than 123 bytes');
  54173. }
  54174. buf = Buffer.allocUnsafe(2 + length);
  54175. buf.writeUInt16BE(code, 0);
  54176. if (typeof data === 'string') {
  54177. buf.write(data, 2);
  54178. } else {
  54179. buf.set(data, 2);
  54180. }
  54181. }
  54182. const options = {
  54183. [kByteLength]: buf.length,
  54184. fin: true,
  54185. generateMask: this._generateMask,
  54186. mask,
  54187. maskBuffer: this._maskBuffer,
  54188. opcode: 0x08,
  54189. readOnly: false,
  54190. rsv1: false
  54191. };
  54192. if (this._deflating) {
  54193. this.enqueue([this.dispatch, buf, false, options, cb]);
  54194. } else {
  54195. this.sendFrame(Sender.frame(buf, options), cb);
  54196. }
  54197. }
  54198. /**
  54199. * Sends a ping message to the other peer.
  54200. *
  54201. * @param {*} data The message to send
  54202. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  54203. * @param {Function} [cb] Callback
  54204. * @public
  54205. */
  54206. ping(data, mask, cb) {
  54207. let byteLength;
  54208. let readOnly;
  54209. if (typeof data === 'string') {
  54210. byteLength = Buffer.byteLength(data);
  54211. readOnly = false;
  54212. } else {
  54213. data = toBuffer$1(data);
  54214. byteLength = data.length;
  54215. readOnly = toBuffer$1.readOnly;
  54216. }
  54217. if (byteLength > 125) {
  54218. throw new RangeError('The data size must not be greater than 125 bytes');
  54219. }
  54220. const options = {
  54221. [kByteLength]: byteLength,
  54222. fin: true,
  54223. generateMask: this._generateMask,
  54224. mask,
  54225. maskBuffer: this._maskBuffer,
  54226. opcode: 0x09,
  54227. readOnly,
  54228. rsv1: false
  54229. };
  54230. if (this._deflating) {
  54231. this.enqueue([this.dispatch, data, false, options, cb]);
  54232. } else {
  54233. this.sendFrame(Sender.frame(data, options), cb);
  54234. }
  54235. }
  54236. /**
  54237. * Sends a pong message to the other peer.
  54238. *
  54239. * @param {*} data The message to send
  54240. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  54241. * @param {Function} [cb] Callback
  54242. * @public
  54243. */
  54244. pong(data, mask, cb) {
  54245. let byteLength;
  54246. let readOnly;
  54247. if (typeof data === 'string') {
  54248. byteLength = Buffer.byteLength(data);
  54249. readOnly = false;
  54250. } else {
  54251. data = toBuffer$1(data);
  54252. byteLength = data.length;
  54253. readOnly = toBuffer$1.readOnly;
  54254. }
  54255. if (byteLength > 125) {
  54256. throw new RangeError('The data size must not be greater than 125 bytes');
  54257. }
  54258. const options = {
  54259. [kByteLength]: byteLength,
  54260. fin: true,
  54261. generateMask: this._generateMask,
  54262. mask,
  54263. maskBuffer: this._maskBuffer,
  54264. opcode: 0x0a,
  54265. readOnly,
  54266. rsv1: false
  54267. };
  54268. if (this._deflating) {
  54269. this.enqueue([this.dispatch, data, false, options, cb]);
  54270. } else {
  54271. this.sendFrame(Sender.frame(data, options), cb);
  54272. }
  54273. }
  54274. /**
  54275. * Sends a data message to the other peer.
  54276. *
  54277. * @param {*} data The message to send
  54278. * @param {Object} options Options object
  54279. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  54280. * or text
  54281. * @param {Boolean} [options.compress=false] Specifies whether or not to
  54282. * compress `data`
  54283. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  54284. * last one
  54285. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  54286. * `data`
  54287. * @param {Function} [cb] Callback
  54288. * @public
  54289. */
  54290. send(data, options, cb) {
  54291. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  54292. let opcode = options.binary ? 2 : 1;
  54293. let rsv1 = options.compress;
  54294. let byteLength;
  54295. let readOnly;
  54296. if (typeof data === 'string') {
  54297. byteLength = Buffer.byteLength(data);
  54298. readOnly = false;
  54299. } else {
  54300. data = toBuffer$1(data);
  54301. byteLength = data.length;
  54302. readOnly = toBuffer$1.readOnly;
  54303. }
  54304. if (this._firstFragment) {
  54305. this._firstFragment = false;
  54306. if (
  54307. rsv1 &&
  54308. perMessageDeflate &&
  54309. perMessageDeflate.params[
  54310. perMessageDeflate._isServer
  54311. ? 'server_no_context_takeover'
  54312. : 'client_no_context_takeover'
  54313. ]
  54314. ) {
  54315. rsv1 = byteLength >= perMessageDeflate._threshold;
  54316. }
  54317. this._compress = rsv1;
  54318. } else {
  54319. rsv1 = false;
  54320. opcode = 0;
  54321. }
  54322. if (options.fin) this._firstFragment = true;
  54323. if (perMessageDeflate) {
  54324. const opts = {
  54325. [kByteLength]: byteLength,
  54326. fin: options.fin,
  54327. generateMask: this._generateMask,
  54328. mask: options.mask,
  54329. maskBuffer: this._maskBuffer,
  54330. opcode,
  54331. readOnly,
  54332. rsv1
  54333. };
  54334. if (this._deflating) {
  54335. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  54336. } else {
  54337. this.dispatch(data, this._compress, opts, cb);
  54338. }
  54339. } else {
  54340. this.sendFrame(
  54341. Sender.frame(data, {
  54342. [kByteLength]: byteLength,
  54343. fin: options.fin,
  54344. generateMask: this._generateMask,
  54345. mask: options.mask,
  54346. maskBuffer: this._maskBuffer,
  54347. opcode,
  54348. readOnly,
  54349. rsv1: false
  54350. }),
  54351. cb
  54352. );
  54353. }
  54354. }
  54355. /**
  54356. * Dispatches a message.
  54357. *
  54358. * @param {(Buffer|String)} data The message to send
  54359. * @param {Boolean} [compress=false] Specifies whether or not to compress
  54360. * `data`
  54361. * @param {Object} options Options object
  54362. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  54363. * FIN bit
  54364. * @param {Function} [options.generateMask] The function used to generate the
  54365. * masking key
  54366. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  54367. * `data`
  54368. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  54369. * key
  54370. * @param {Number} options.opcode The opcode
  54371. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  54372. * modified
  54373. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  54374. * RSV1 bit
  54375. * @param {Function} [cb] Callback
  54376. * @private
  54377. */
  54378. dispatch(data, compress, options, cb) {
  54379. if (!compress) {
  54380. this.sendFrame(Sender.frame(data, options), cb);
  54381. return;
  54382. }
  54383. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  54384. this._bufferedBytes += options[kByteLength];
  54385. this._deflating = true;
  54386. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  54387. if (this._socket.destroyed) {
  54388. const err = new Error(
  54389. 'The socket was closed while data was being compressed'
  54390. );
  54391. if (typeof cb === 'function') cb(err);
  54392. for (let i = 0; i < this._queue.length; i++) {
  54393. const params = this._queue[i];
  54394. const callback = params[params.length - 1];
  54395. if (typeof callback === 'function') callback(err);
  54396. }
  54397. return;
  54398. }
  54399. this._bufferedBytes -= options[kByteLength];
  54400. this._deflating = false;
  54401. options.readOnly = false;
  54402. this.sendFrame(Sender.frame(buf, options), cb);
  54403. this.dequeue();
  54404. });
  54405. }
  54406. /**
  54407. * Executes queued send operations.
  54408. *
  54409. * @private
  54410. */
  54411. dequeue() {
  54412. while (!this._deflating && this._queue.length) {
  54413. const params = this._queue.shift();
  54414. this._bufferedBytes -= params[3][kByteLength];
  54415. Reflect.apply(params[0], this, params.slice(1));
  54416. }
  54417. }
  54418. /**
  54419. * Enqueues a send operation.
  54420. *
  54421. * @param {Array} params Send operation parameters.
  54422. * @private
  54423. */
  54424. enqueue(params) {
  54425. this._bufferedBytes += params[3][kByteLength];
  54426. this._queue.push(params);
  54427. }
  54428. /**
  54429. * Sends a frame.
  54430. *
  54431. * @param {Buffer[]} list The frame to send
  54432. * @param {Function} [cb] Callback
  54433. * @private
  54434. */
  54435. sendFrame(list, cb) {
  54436. if (list.length === 2) {
  54437. this._socket.cork();
  54438. this._socket.write(list[0]);
  54439. this._socket.write(list[1], cb);
  54440. this._socket.uncork();
  54441. } else {
  54442. this._socket.write(list[0], cb);
  54443. }
  54444. }
  54445. };
  54446. var sender = Sender$1;
  54447. const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
  54448. const kCode = Symbol('kCode');
  54449. const kData = Symbol('kData');
  54450. const kError = Symbol('kError');
  54451. const kMessage = Symbol('kMessage');
  54452. const kReason = Symbol('kReason');
  54453. const kTarget = Symbol('kTarget');
  54454. const kType = Symbol('kType');
  54455. const kWasClean = Symbol('kWasClean');
  54456. /**
  54457. * Class representing an event.
  54458. */
  54459. let Event$1 = class Event {
  54460. /**
  54461. * Create a new `Event`.
  54462. *
  54463. * @param {String} type The name of the event
  54464. * @throws {TypeError} If the `type` argument is not specified
  54465. */
  54466. constructor(type) {
  54467. this[kTarget] = null;
  54468. this[kType] = type;
  54469. }
  54470. /**
  54471. * @type {*}
  54472. */
  54473. get target() {
  54474. return this[kTarget];
  54475. }
  54476. /**
  54477. * @type {String}
  54478. */
  54479. get type() {
  54480. return this[kType];
  54481. }
  54482. };
  54483. Object.defineProperty(Event$1.prototype, 'target', { enumerable: true });
  54484. Object.defineProperty(Event$1.prototype, 'type', { enumerable: true });
  54485. /**
  54486. * Class representing a close event.
  54487. *
  54488. * @extends Event
  54489. */
  54490. class CloseEvent extends Event$1 {
  54491. /**
  54492. * Create a new `CloseEvent`.
  54493. *
  54494. * @param {String} type The name of the event
  54495. * @param {Object} [options] A dictionary object that allows for setting
  54496. * attributes via object members of the same name
  54497. * @param {Number} [options.code=0] The status code explaining why the
  54498. * connection was closed
  54499. * @param {String} [options.reason=''] A human-readable string explaining why
  54500. * the connection was closed
  54501. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  54502. * connection was cleanly closed
  54503. */
  54504. constructor(type, options = {}) {
  54505. super(type);
  54506. this[kCode] = options.code === undefined ? 0 : options.code;
  54507. this[kReason] = options.reason === undefined ? '' : options.reason;
  54508. this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
  54509. }
  54510. /**
  54511. * @type {Number}
  54512. */
  54513. get code() {
  54514. return this[kCode];
  54515. }
  54516. /**
  54517. * @type {String}
  54518. */
  54519. get reason() {
  54520. return this[kReason];
  54521. }
  54522. /**
  54523. * @type {Boolean}
  54524. */
  54525. get wasClean() {
  54526. return this[kWasClean];
  54527. }
  54528. }
  54529. Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
  54530. Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
  54531. Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
  54532. /**
  54533. * Class representing an error event.
  54534. *
  54535. * @extends Event
  54536. */
  54537. class ErrorEvent extends Event$1 {
  54538. /**
  54539. * Create a new `ErrorEvent`.
  54540. *
  54541. * @param {String} type The name of the event
  54542. * @param {Object} [options] A dictionary object that allows for setting
  54543. * attributes via object members of the same name
  54544. * @param {*} [options.error=null] The error that generated this event
  54545. * @param {String} [options.message=''] The error message
  54546. */
  54547. constructor(type, options = {}) {
  54548. super(type);
  54549. this[kError] = options.error === undefined ? null : options.error;
  54550. this[kMessage] = options.message === undefined ? '' : options.message;
  54551. }
  54552. /**
  54553. * @type {*}
  54554. */
  54555. get error() {
  54556. return this[kError];
  54557. }
  54558. /**
  54559. * @type {String}
  54560. */
  54561. get message() {
  54562. return this[kMessage];
  54563. }
  54564. }
  54565. Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
  54566. Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
  54567. /**
  54568. * Class representing a message event.
  54569. *
  54570. * @extends Event
  54571. */
  54572. class MessageEvent extends Event$1 {
  54573. /**
  54574. * Create a new `MessageEvent`.
  54575. *
  54576. * @param {String} type The name of the event
  54577. * @param {Object} [options] A dictionary object that allows for setting
  54578. * attributes via object members of the same name
  54579. * @param {*} [options.data=null] The message content
  54580. */
  54581. constructor(type, options = {}) {
  54582. super(type);
  54583. this[kData] = options.data === undefined ? null : options.data;
  54584. }
  54585. /**
  54586. * @type {*}
  54587. */
  54588. get data() {
  54589. return this[kData];
  54590. }
  54591. }
  54592. Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
  54593. /**
  54594. * This provides methods for emulating the `EventTarget` interface. It's not
  54595. * meant to be used directly.
  54596. *
  54597. * @mixin
  54598. */
  54599. const EventTarget = {
  54600. /**
  54601. * Register an event listener.
  54602. *
  54603. * @param {String} type A string representing the event type to listen for
  54604. * @param {(Function|Object)} handler The listener to add
  54605. * @param {Object} [options] An options object specifies characteristics about
  54606. * the event listener
  54607. * @param {Boolean} [options.once=false] A `Boolean` indicating that the
  54608. * listener should be invoked at most once after being added. If `true`,
  54609. * the listener would be automatically removed when invoked.
  54610. * @public
  54611. */
  54612. addEventListener(type, handler, options = {}) {
  54613. for (const listener of this.listeners(type)) {
  54614. if (
  54615. !options[kForOnEventAttribute$1] &&
  54616. listener[kListener$1] === handler &&
  54617. !listener[kForOnEventAttribute$1]
  54618. ) {
  54619. return;
  54620. }
  54621. }
  54622. let wrapper;
  54623. if (type === 'message') {
  54624. wrapper = function onMessage(data, isBinary) {
  54625. const event = new MessageEvent('message', {
  54626. data: isBinary ? data : data.toString()
  54627. });
  54628. event[kTarget] = this;
  54629. callListener(handler, this, event);
  54630. };
  54631. } else if (type === 'close') {
  54632. wrapper = function onClose(code, message) {
  54633. const event = new CloseEvent('close', {
  54634. code,
  54635. reason: message.toString(),
  54636. wasClean: this._closeFrameReceived && this._closeFrameSent
  54637. });
  54638. event[kTarget] = this;
  54639. callListener(handler, this, event);
  54640. };
  54641. } else if (type === 'error') {
  54642. wrapper = function onError(error) {
  54643. const event = new ErrorEvent('error', {
  54644. error,
  54645. message: error.message
  54646. });
  54647. event[kTarget] = this;
  54648. callListener(handler, this, event);
  54649. };
  54650. } else if (type === 'open') {
  54651. wrapper = function onOpen() {
  54652. const event = new Event$1('open');
  54653. event[kTarget] = this;
  54654. callListener(handler, this, event);
  54655. };
  54656. } else {
  54657. return;
  54658. }
  54659. wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
  54660. wrapper[kListener$1] = handler;
  54661. if (options.once) {
  54662. this.once(type, wrapper);
  54663. } else {
  54664. this.on(type, wrapper);
  54665. }
  54666. },
  54667. /**
  54668. * Remove an event listener.
  54669. *
  54670. * @param {String} type A string representing the event type to remove
  54671. * @param {(Function|Object)} handler The listener to remove
  54672. * @public
  54673. */
  54674. removeEventListener(type, handler) {
  54675. for (const listener of this.listeners(type)) {
  54676. if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
  54677. this.removeListener(type, listener);
  54678. break;
  54679. }
  54680. }
  54681. }
  54682. };
  54683. var eventTarget = {
  54684. CloseEvent,
  54685. ErrorEvent,
  54686. Event: Event$1,
  54687. EventTarget,
  54688. MessageEvent
  54689. };
  54690. /**
  54691. * Call an event listener
  54692. *
  54693. * @param {(Function|Object)} listener The listener to call
  54694. * @param {*} thisArg The value to use as `this`` when calling the listener
  54695. * @param {Event} event The event to pass to the listener
  54696. * @private
  54697. */
  54698. function callListener(listener, thisArg, event) {
  54699. if (typeof listener === 'object' && listener.handleEvent) {
  54700. listener.handleEvent.call(listener, event);
  54701. } else {
  54702. listener.call(thisArg, event);
  54703. }
  54704. }
  54705. const { tokenChars: tokenChars$1 } = validationExports;
  54706. /**
  54707. * Adds an offer to the map of extension offers or a parameter to the map of
  54708. * parameters.
  54709. *
  54710. * @param {Object} dest The map of extension offers or parameters
  54711. * @param {String} name The extension or parameter name
  54712. * @param {(Object|Boolean|String)} elem The extension parameters or the
  54713. * parameter value
  54714. * @private
  54715. */
  54716. function push(dest, name, elem) {
  54717. if (dest[name] === undefined) dest[name] = [elem];
  54718. else dest[name].push(elem);
  54719. }
  54720. /**
  54721. * Parses the `Sec-WebSocket-Extensions` header into an object.
  54722. *
  54723. * @param {String} header The field value of the header
  54724. * @return {Object} The parsed object
  54725. * @public
  54726. */
  54727. function parse$2(header) {
  54728. const offers = Object.create(null);
  54729. let params = Object.create(null);
  54730. let mustUnescape = false;
  54731. let isEscaping = false;
  54732. let inQuotes = false;
  54733. let extensionName;
  54734. let paramName;
  54735. let start = -1;
  54736. let code = -1;
  54737. let end = -1;
  54738. let i = 0;
  54739. for (; i < header.length; i++) {
  54740. code = header.charCodeAt(i);
  54741. if (extensionName === undefined) {
  54742. if (end === -1 && tokenChars$1[code] === 1) {
  54743. if (start === -1) start = i;
  54744. } else if (
  54745. i !== 0 &&
  54746. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  54747. ) {
  54748. if (end === -1 && start !== -1) end = i;
  54749. } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
  54750. if (start === -1) {
  54751. throw new SyntaxError(`Unexpected character at index ${i}`);
  54752. }
  54753. if (end === -1) end = i;
  54754. const name = header.slice(start, end);
  54755. if (code === 0x2c) {
  54756. push(offers, name, params);
  54757. params = Object.create(null);
  54758. } else {
  54759. extensionName = name;
  54760. }
  54761. start = end = -1;
  54762. } else {
  54763. throw new SyntaxError(`Unexpected character at index ${i}`);
  54764. }
  54765. } else if (paramName === undefined) {
  54766. if (end === -1 && tokenChars$1[code] === 1) {
  54767. if (start === -1) start = i;
  54768. } else if (code === 0x20 || code === 0x09) {
  54769. if (end === -1 && start !== -1) end = i;
  54770. } else if (code === 0x3b || code === 0x2c) {
  54771. if (start === -1) {
  54772. throw new SyntaxError(`Unexpected character at index ${i}`);
  54773. }
  54774. if (end === -1) end = i;
  54775. push(params, header.slice(start, end), true);
  54776. if (code === 0x2c) {
  54777. push(offers, extensionName, params);
  54778. params = Object.create(null);
  54779. extensionName = undefined;
  54780. }
  54781. start = end = -1;
  54782. } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
  54783. paramName = header.slice(start, i);
  54784. start = end = -1;
  54785. } else {
  54786. throw new SyntaxError(`Unexpected character at index ${i}`);
  54787. }
  54788. } else {
  54789. //
  54790. // The value of a quoted-string after unescaping must conform to the
  54791. // token ABNF, so only token characters are valid.
  54792. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
  54793. //
  54794. if (isEscaping) {
  54795. if (tokenChars$1[code] !== 1) {
  54796. throw new SyntaxError(`Unexpected character at index ${i}`);
  54797. }
  54798. if (start === -1) start = i;
  54799. else if (!mustUnescape) mustUnescape = true;
  54800. isEscaping = false;
  54801. } else if (inQuotes) {
  54802. if (tokenChars$1[code] === 1) {
  54803. if (start === -1) start = i;
  54804. } else if (code === 0x22 /* '"' */ && start !== -1) {
  54805. inQuotes = false;
  54806. end = i;
  54807. } else if (code === 0x5c /* '\' */) {
  54808. isEscaping = true;
  54809. } else {
  54810. throw new SyntaxError(`Unexpected character at index ${i}`);
  54811. }
  54812. } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
  54813. inQuotes = true;
  54814. } else if (end === -1 && tokenChars$1[code] === 1) {
  54815. if (start === -1) start = i;
  54816. } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
  54817. if (end === -1) end = i;
  54818. } else if (code === 0x3b || code === 0x2c) {
  54819. if (start === -1) {
  54820. throw new SyntaxError(`Unexpected character at index ${i}`);
  54821. }
  54822. if (end === -1) end = i;
  54823. let value = header.slice(start, end);
  54824. if (mustUnescape) {
  54825. value = value.replace(/\\/g, '');
  54826. mustUnescape = false;
  54827. }
  54828. push(params, paramName, value);
  54829. if (code === 0x2c) {
  54830. push(offers, extensionName, params);
  54831. params = Object.create(null);
  54832. extensionName = undefined;
  54833. }
  54834. paramName = undefined;
  54835. start = end = -1;
  54836. } else {
  54837. throw new SyntaxError(`Unexpected character at index ${i}`);
  54838. }
  54839. }
  54840. }
  54841. if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
  54842. throw new SyntaxError('Unexpected end of input');
  54843. }
  54844. if (end === -1) end = i;
  54845. const token = header.slice(start, end);
  54846. if (extensionName === undefined) {
  54847. push(offers, token, params);
  54848. } else {
  54849. if (paramName === undefined) {
  54850. push(params, token, true);
  54851. } else if (mustUnescape) {
  54852. push(params, paramName, token.replace(/\\/g, ''));
  54853. } else {
  54854. push(params, paramName, token);
  54855. }
  54856. push(offers, extensionName, params);
  54857. }
  54858. return offers;
  54859. }
  54860. /**
  54861. * Builds the `Sec-WebSocket-Extensions` header field value.
  54862. *
  54863. * @param {Object} extensions The map of extensions and parameters to format
  54864. * @return {String} A string representing the given object
  54865. * @public
  54866. */
  54867. function format$1(extensions) {
  54868. return Object.keys(extensions)
  54869. .map((extension) => {
  54870. let configurations = extensions[extension];
  54871. if (!Array.isArray(configurations)) configurations = [configurations];
  54872. return configurations
  54873. .map((params) => {
  54874. return [extension]
  54875. .concat(
  54876. Object.keys(params).map((k) => {
  54877. let values = params[k];
  54878. if (!Array.isArray(values)) values = [values];
  54879. return values
  54880. .map((v) => (v === true ? k : `${k}=${v}`))
  54881. .join('; ');
  54882. })
  54883. )
  54884. .join('; ');
  54885. })
  54886. .join(', ');
  54887. })
  54888. .join(', ');
  54889. }
  54890. var extension$1 = { format: format$1, parse: parse$2 };
  54891. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */
  54892. const EventEmitter$1 = require$$0$5;
  54893. const https$2 = require$$1$2;
  54894. const http$3 = require$$1$1;
  54895. const net = require$$3$2;
  54896. const tls = require$$4$1;
  54897. const { randomBytes, createHash: createHash$1 } = require$$3$1;
  54898. const { URL: URL$2 } = require$$0$9;
  54899. const PerMessageDeflate$1 = permessageDeflate;
  54900. const Receiver = receiver;
  54901. const Sender = sender;
  54902. const {
  54903. BINARY_TYPES,
  54904. EMPTY_BUFFER,
  54905. GUID: GUID$1,
  54906. kForOnEventAttribute,
  54907. kListener,
  54908. kStatusCode,
  54909. kWebSocket: kWebSocket$1,
  54910. NOOP
  54911. } = constants;
  54912. const {
  54913. EventTarget: { addEventListener, removeEventListener }
  54914. } = eventTarget;
  54915. const { format, parse: parse$1 } = extension$1;
  54916. const { toBuffer } = bufferUtilExports;
  54917. const closeTimeout = 30 * 1000;
  54918. const kAborted = Symbol('kAborted');
  54919. const protocolVersions = [8, 13];
  54920. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  54921. const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  54922. /**
  54923. * Class representing a WebSocket.
  54924. *
  54925. * @extends EventEmitter
  54926. */
  54927. let WebSocket$1 = class WebSocket extends EventEmitter$1 {
  54928. /**
  54929. * Create a new `WebSocket`.
  54930. *
  54931. * @param {(String|URL)} address The URL to which to connect
  54932. * @param {(String|String[])} [protocols] The subprotocols
  54933. * @param {Object} [options] Connection options
  54934. */
  54935. constructor(address, protocols, options) {
  54936. super();
  54937. this._binaryType = BINARY_TYPES[0];
  54938. this._closeCode = 1006;
  54939. this._closeFrameReceived = false;
  54940. this._closeFrameSent = false;
  54941. this._closeMessage = EMPTY_BUFFER;
  54942. this._closeTimer = null;
  54943. this._extensions = {};
  54944. this._paused = false;
  54945. this._protocol = '';
  54946. this._readyState = WebSocket.CONNECTING;
  54947. this._receiver = null;
  54948. this._sender = null;
  54949. this._socket = null;
  54950. if (address !== null) {
  54951. this._bufferedAmount = 0;
  54952. this._isServer = false;
  54953. this._redirects = 0;
  54954. if (protocols === undefined) {
  54955. protocols = [];
  54956. } else if (!Array.isArray(protocols)) {
  54957. if (typeof protocols === 'object' && protocols !== null) {
  54958. options = protocols;
  54959. protocols = [];
  54960. } else {
  54961. protocols = [protocols];
  54962. }
  54963. }
  54964. initAsClient(this, address, protocols, options);
  54965. } else {
  54966. this._isServer = true;
  54967. }
  54968. }
  54969. /**
  54970. * This deviates from the WHATWG interface since ws doesn't support the
  54971. * required default "blob" type (instead we define a custom "nodebuffer"
  54972. * type).
  54973. *
  54974. * @type {String}
  54975. */
  54976. get binaryType() {
  54977. return this._binaryType;
  54978. }
  54979. set binaryType(type) {
  54980. if (!BINARY_TYPES.includes(type)) return;
  54981. this._binaryType = type;
  54982. //
  54983. // Allow to change `binaryType` on the fly.
  54984. //
  54985. if (this._receiver) this._receiver._binaryType = type;
  54986. }
  54987. /**
  54988. * @type {Number}
  54989. */
  54990. get bufferedAmount() {
  54991. if (!this._socket) return this._bufferedAmount;
  54992. return this._socket._writableState.length + this._sender._bufferedBytes;
  54993. }
  54994. /**
  54995. * @type {String}
  54996. */
  54997. get extensions() {
  54998. return Object.keys(this._extensions).join();
  54999. }
  55000. /**
  55001. * @type {Boolean}
  55002. */
  55003. get isPaused() {
  55004. return this._paused;
  55005. }
  55006. /**
  55007. * @type {Function}
  55008. */
  55009. /* istanbul ignore next */
  55010. get onclose() {
  55011. return null;
  55012. }
  55013. /**
  55014. * @type {Function}
  55015. */
  55016. /* istanbul ignore next */
  55017. get onerror() {
  55018. return null;
  55019. }
  55020. /**
  55021. * @type {Function}
  55022. */
  55023. /* istanbul ignore next */
  55024. get onopen() {
  55025. return null;
  55026. }
  55027. /**
  55028. * @type {Function}
  55029. */
  55030. /* istanbul ignore next */
  55031. get onmessage() {
  55032. return null;
  55033. }
  55034. /**
  55035. * @type {String}
  55036. */
  55037. get protocol() {
  55038. return this._protocol;
  55039. }
  55040. /**
  55041. * @type {Number}
  55042. */
  55043. get readyState() {
  55044. return this._readyState;
  55045. }
  55046. /**
  55047. * @type {String}
  55048. */
  55049. get url() {
  55050. return this._url;
  55051. }
  55052. /**
  55053. * Set up the socket and the internal resources.
  55054. *
  55055. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  55056. * server and client
  55057. * @param {Buffer} head The first packet of the upgraded stream
  55058. * @param {Object} options Options object
  55059. * @param {Function} [options.generateMask] The function used to generate the
  55060. * masking key
  55061. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  55062. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  55063. * not to skip UTF-8 validation for text and close messages
  55064. * @private
  55065. */
  55066. setSocket(socket, head, options) {
  55067. const receiver = new Receiver({
  55068. binaryType: this.binaryType,
  55069. extensions: this._extensions,
  55070. isServer: this._isServer,
  55071. maxPayload: options.maxPayload,
  55072. skipUTF8Validation: options.skipUTF8Validation
  55073. });
  55074. this._sender = new Sender(socket, this._extensions, options.generateMask);
  55075. this._receiver = receiver;
  55076. this._socket = socket;
  55077. receiver[kWebSocket$1] = this;
  55078. socket[kWebSocket$1] = this;
  55079. receiver.on('conclude', receiverOnConclude);
  55080. receiver.on('drain', receiverOnDrain);
  55081. receiver.on('error', receiverOnError);
  55082. receiver.on('message', receiverOnMessage);
  55083. receiver.on('ping', receiverOnPing);
  55084. receiver.on('pong', receiverOnPong);
  55085. socket.setTimeout(0);
  55086. socket.setNoDelay();
  55087. if (head.length > 0) socket.unshift(head);
  55088. socket.on('close', socketOnClose);
  55089. socket.on('data', socketOnData);
  55090. socket.on('end', socketOnEnd);
  55091. socket.on('error', socketOnError$1);
  55092. this._readyState = WebSocket.OPEN;
  55093. this.emit('open');
  55094. }
  55095. /**
  55096. * Emit the `'close'` event.
  55097. *
  55098. * @private
  55099. */
  55100. emitClose() {
  55101. if (!this._socket) {
  55102. this._readyState = WebSocket.CLOSED;
  55103. this.emit('close', this._closeCode, this._closeMessage);
  55104. return;
  55105. }
  55106. if (this._extensions[PerMessageDeflate$1.extensionName]) {
  55107. this._extensions[PerMessageDeflate$1.extensionName].cleanup();
  55108. }
  55109. this._receiver.removeAllListeners();
  55110. this._readyState = WebSocket.CLOSED;
  55111. this.emit('close', this._closeCode, this._closeMessage);
  55112. }
  55113. /**
  55114. * Start a closing handshake.
  55115. *
  55116. * +----------+ +-----------+ +----------+
  55117. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  55118. * | +----------+ +-----------+ +----------+ |
  55119. * +----------+ +-----------+ |
  55120. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  55121. * +----------+ +-----------+ |
  55122. * | | | +---+ |
  55123. * +------------------------+-->|fin| - - - -
  55124. * | +---+ | +---+
  55125. * - - - - -|fin|<---------------------+
  55126. * +---+
  55127. *
  55128. * @param {Number} [code] Status code explaining why the connection is closing
  55129. * @param {(String|Buffer)} [data] The reason why the connection is
  55130. * closing
  55131. * @public
  55132. */
  55133. close(code, data) {
  55134. if (this.readyState === WebSocket.CLOSED) return;
  55135. if (this.readyState === WebSocket.CONNECTING) {
  55136. const msg = 'WebSocket was closed before the connection was established';
  55137. abortHandshake$1(this, this._req, msg);
  55138. return;
  55139. }
  55140. if (this.readyState === WebSocket.CLOSING) {
  55141. if (
  55142. this._closeFrameSent &&
  55143. (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
  55144. ) {
  55145. this._socket.end();
  55146. }
  55147. return;
  55148. }
  55149. this._readyState = WebSocket.CLOSING;
  55150. this._sender.close(code, data, !this._isServer, (err) => {
  55151. //
  55152. // This error is handled by the `'error'` listener on the socket. We only
  55153. // want to know if the close frame has been sent here.
  55154. //
  55155. if (err) return;
  55156. this._closeFrameSent = true;
  55157. if (
  55158. this._closeFrameReceived ||
  55159. this._receiver._writableState.errorEmitted
  55160. ) {
  55161. this._socket.end();
  55162. }
  55163. });
  55164. //
  55165. // Specify a timeout for the closing handshake to complete.
  55166. //
  55167. this._closeTimer = setTimeout(
  55168. this._socket.destroy.bind(this._socket),
  55169. closeTimeout
  55170. );
  55171. }
  55172. /**
  55173. * Pause the socket.
  55174. *
  55175. * @public
  55176. */
  55177. pause() {
  55178. if (
  55179. this.readyState === WebSocket.CONNECTING ||
  55180. this.readyState === WebSocket.CLOSED
  55181. ) {
  55182. return;
  55183. }
  55184. this._paused = true;
  55185. this._socket.pause();
  55186. }
  55187. /**
  55188. * Send a ping.
  55189. *
  55190. * @param {*} [data] The data to send
  55191. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  55192. * @param {Function} [cb] Callback which is executed when the ping is sent
  55193. * @public
  55194. */
  55195. ping(data, mask, cb) {
  55196. if (this.readyState === WebSocket.CONNECTING) {
  55197. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  55198. }
  55199. if (typeof data === 'function') {
  55200. cb = data;
  55201. data = mask = undefined;
  55202. } else if (typeof mask === 'function') {
  55203. cb = mask;
  55204. mask = undefined;
  55205. }
  55206. if (typeof data === 'number') data = data.toString();
  55207. if (this.readyState !== WebSocket.OPEN) {
  55208. sendAfterClose(this, data, cb);
  55209. return;
  55210. }
  55211. if (mask === undefined) mask = !this._isServer;
  55212. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  55213. }
  55214. /**
  55215. * Send a pong.
  55216. *
  55217. * @param {*} [data] The data to send
  55218. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  55219. * @param {Function} [cb] Callback which is executed when the pong is sent
  55220. * @public
  55221. */
  55222. pong(data, mask, cb) {
  55223. if (this.readyState === WebSocket.CONNECTING) {
  55224. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  55225. }
  55226. if (typeof data === 'function') {
  55227. cb = data;
  55228. data = mask = undefined;
  55229. } else if (typeof mask === 'function') {
  55230. cb = mask;
  55231. mask = undefined;
  55232. }
  55233. if (typeof data === 'number') data = data.toString();
  55234. if (this.readyState !== WebSocket.OPEN) {
  55235. sendAfterClose(this, data, cb);
  55236. return;
  55237. }
  55238. if (mask === undefined) mask = !this._isServer;
  55239. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  55240. }
  55241. /**
  55242. * Resume the socket.
  55243. *
  55244. * @public
  55245. */
  55246. resume() {
  55247. if (
  55248. this.readyState === WebSocket.CONNECTING ||
  55249. this.readyState === WebSocket.CLOSED
  55250. ) {
  55251. return;
  55252. }
  55253. this._paused = false;
  55254. if (!this._receiver._writableState.needDrain) this._socket.resume();
  55255. }
  55256. /**
  55257. * Send a data message.
  55258. *
  55259. * @param {*} data The message to send
  55260. * @param {Object} [options] Options object
  55261. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  55262. * text
  55263. * @param {Boolean} [options.compress] Specifies whether or not to compress
  55264. * `data`
  55265. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  55266. * last one
  55267. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  55268. * @param {Function} [cb] Callback which is executed when data is written out
  55269. * @public
  55270. */
  55271. send(data, options, cb) {
  55272. if (this.readyState === WebSocket.CONNECTING) {
  55273. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  55274. }
  55275. if (typeof options === 'function') {
  55276. cb = options;
  55277. options = {};
  55278. }
  55279. if (typeof data === 'number') data = data.toString();
  55280. if (this.readyState !== WebSocket.OPEN) {
  55281. sendAfterClose(this, data, cb);
  55282. return;
  55283. }
  55284. const opts = {
  55285. binary: typeof data !== 'string',
  55286. mask: !this._isServer,
  55287. compress: true,
  55288. fin: true,
  55289. ...options
  55290. };
  55291. if (!this._extensions[PerMessageDeflate$1.extensionName]) {
  55292. opts.compress = false;
  55293. }
  55294. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  55295. }
  55296. /**
  55297. * Forcibly close the connection.
  55298. *
  55299. * @public
  55300. */
  55301. terminate() {
  55302. if (this.readyState === WebSocket.CLOSED) return;
  55303. if (this.readyState === WebSocket.CONNECTING) {
  55304. const msg = 'WebSocket was closed before the connection was established';
  55305. abortHandshake$1(this, this._req, msg);
  55306. return;
  55307. }
  55308. if (this._socket) {
  55309. this._readyState = WebSocket.CLOSING;
  55310. this._socket.destroy();
  55311. }
  55312. }
  55313. };
  55314. /**
  55315. * @constant {Number} CONNECTING
  55316. * @memberof WebSocket
  55317. */
  55318. Object.defineProperty(WebSocket$1, 'CONNECTING', {
  55319. enumerable: true,
  55320. value: readyStates.indexOf('CONNECTING')
  55321. });
  55322. /**
  55323. * @constant {Number} CONNECTING
  55324. * @memberof WebSocket.prototype
  55325. */
  55326. Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', {
  55327. enumerable: true,
  55328. value: readyStates.indexOf('CONNECTING')
  55329. });
  55330. /**
  55331. * @constant {Number} OPEN
  55332. * @memberof WebSocket
  55333. */
  55334. Object.defineProperty(WebSocket$1, 'OPEN', {
  55335. enumerable: true,
  55336. value: readyStates.indexOf('OPEN')
  55337. });
  55338. /**
  55339. * @constant {Number} OPEN
  55340. * @memberof WebSocket.prototype
  55341. */
  55342. Object.defineProperty(WebSocket$1.prototype, 'OPEN', {
  55343. enumerable: true,
  55344. value: readyStates.indexOf('OPEN')
  55345. });
  55346. /**
  55347. * @constant {Number} CLOSING
  55348. * @memberof WebSocket
  55349. */
  55350. Object.defineProperty(WebSocket$1, 'CLOSING', {
  55351. enumerable: true,
  55352. value: readyStates.indexOf('CLOSING')
  55353. });
  55354. /**
  55355. * @constant {Number} CLOSING
  55356. * @memberof WebSocket.prototype
  55357. */
  55358. Object.defineProperty(WebSocket$1.prototype, 'CLOSING', {
  55359. enumerable: true,
  55360. value: readyStates.indexOf('CLOSING')
  55361. });
  55362. /**
  55363. * @constant {Number} CLOSED
  55364. * @memberof WebSocket
  55365. */
  55366. Object.defineProperty(WebSocket$1, 'CLOSED', {
  55367. enumerable: true,
  55368. value: readyStates.indexOf('CLOSED')
  55369. });
  55370. /**
  55371. * @constant {Number} CLOSED
  55372. * @memberof WebSocket.prototype
  55373. */
  55374. Object.defineProperty(WebSocket$1.prototype, 'CLOSED', {
  55375. enumerable: true,
  55376. value: readyStates.indexOf('CLOSED')
  55377. });
  55378. [
  55379. 'binaryType',
  55380. 'bufferedAmount',
  55381. 'extensions',
  55382. 'isPaused',
  55383. 'protocol',
  55384. 'readyState',
  55385. 'url'
  55386. ].forEach((property) => {
  55387. Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true });
  55388. });
  55389. //
  55390. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  55391. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  55392. //
  55393. ['open', 'error', 'close', 'message'].forEach((method) => {
  55394. Object.defineProperty(WebSocket$1.prototype, `on${method}`, {
  55395. enumerable: true,
  55396. get() {
  55397. for (const listener of this.listeners(method)) {
  55398. if (listener[kForOnEventAttribute]) return listener[kListener];
  55399. }
  55400. return null;
  55401. },
  55402. set(handler) {
  55403. for (const listener of this.listeners(method)) {
  55404. if (listener[kForOnEventAttribute]) {
  55405. this.removeListener(method, listener);
  55406. break;
  55407. }
  55408. }
  55409. if (typeof handler !== 'function') return;
  55410. this.addEventListener(method, handler, {
  55411. [kForOnEventAttribute]: true
  55412. });
  55413. }
  55414. });
  55415. });
  55416. WebSocket$1.prototype.addEventListener = addEventListener;
  55417. WebSocket$1.prototype.removeEventListener = removeEventListener;
  55418. var websocket = WebSocket$1;
  55419. /**
  55420. * Initialize a WebSocket client.
  55421. *
  55422. * @param {WebSocket} websocket The client to initialize
  55423. * @param {(String|URL)} address The URL to which to connect
  55424. * @param {Array} protocols The subprotocols
  55425. * @param {Object} [options] Connection options
  55426. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  55427. * redirects
  55428. * @param {Function} [options.generateMask] The function used to generate the
  55429. * masking key
  55430. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  55431. * handshake request
  55432. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  55433. * size
  55434. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  55435. * allowed
  55436. * @param {String} [options.origin] Value of the `Origin` or
  55437. * `Sec-WebSocket-Origin` header
  55438. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  55439. * permessage-deflate
  55440. * @param {Number} [options.protocolVersion=13] Value of the
  55441. * `Sec-WebSocket-Version` header
  55442. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  55443. * not to skip UTF-8 validation for text and close messages
  55444. * @private
  55445. */
  55446. function initAsClient(websocket, address, protocols, options) {
  55447. const opts = {
  55448. protocolVersion: protocolVersions[1],
  55449. maxPayload: 100 * 1024 * 1024,
  55450. skipUTF8Validation: false,
  55451. perMessageDeflate: true,
  55452. followRedirects: false,
  55453. maxRedirects: 10,
  55454. ...options,
  55455. createConnection: undefined,
  55456. socketPath: undefined,
  55457. hostname: undefined,
  55458. protocol: undefined,
  55459. timeout: undefined,
  55460. method: 'GET',
  55461. host: undefined,
  55462. path: undefined,
  55463. port: undefined
  55464. };
  55465. if (!protocolVersions.includes(opts.protocolVersion)) {
  55466. throw new RangeError(
  55467. `Unsupported protocol version: ${opts.protocolVersion} ` +
  55468. `(supported versions: ${protocolVersions.join(', ')})`
  55469. );
  55470. }
  55471. let parsedUrl;
  55472. if (address instanceof URL$2) {
  55473. parsedUrl = address;
  55474. websocket._url = address.href;
  55475. } else {
  55476. try {
  55477. parsedUrl = new URL$2(address);
  55478. } catch (e) {
  55479. throw new SyntaxError(`Invalid URL: ${address}`);
  55480. }
  55481. websocket._url = address;
  55482. }
  55483. const isSecure = parsedUrl.protocol === 'wss:';
  55484. const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
  55485. let invalidUrlMessage;
  55486. if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
  55487. invalidUrlMessage =
  55488. 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
  55489. } else if (isIpcUrl && !parsedUrl.pathname) {
  55490. invalidUrlMessage = "The URL's pathname is empty";
  55491. } else if (parsedUrl.hash) {
  55492. invalidUrlMessage = 'The URL contains a fragment identifier';
  55493. }
  55494. if (invalidUrlMessage) {
  55495. const err = new SyntaxError(invalidUrlMessage);
  55496. if (websocket._redirects === 0) {
  55497. throw err;
  55498. } else {
  55499. emitErrorAndClose(websocket, err);
  55500. return;
  55501. }
  55502. }
  55503. const defaultPort = isSecure ? 443 : 80;
  55504. const key = randomBytes(16).toString('base64');
  55505. const request = isSecure ? https$2.request : http$3.request;
  55506. const protocolSet = new Set();
  55507. let perMessageDeflate;
  55508. opts.createConnection = isSecure ? tlsConnect : netConnect;
  55509. opts.defaultPort = opts.defaultPort || defaultPort;
  55510. opts.port = parsedUrl.port || defaultPort;
  55511. opts.host = parsedUrl.hostname.startsWith('[')
  55512. ? parsedUrl.hostname.slice(1, -1)
  55513. : parsedUrl.hostname;
  55514. opts.headers = {
  55515. ...opts.headers,
  55516. 'Sec-WebSocket-Version': opts.protocolVersion,
  55517. 'Sec-WebSocket-Key': key,
  55518. Connection: 'Upgrade',
  55519. Upgrade: 'websocket'
  55520. };
  55521. opts.path = parsedUrl.pathname + parsedUrl.search;
  55522. opts.timeout = opts.handshakeTimeout;
  55523. if (opts.perMessageDeflate) {
  55524. perMessageDeflate = new PerMessageDeflate$1(
  55525. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  55526. false,
  55527. opts.maxPayload
  55528. );
  55529. opts.headers['Sec-WebSocket-Extensions'] = format({
  55530. [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
  55531. });
  55532. }
  55533. if (protocols.length) {
  55534. for (const protocol of protocols) {
  55535. if (
  55536. typeof protocol !== 'string' ||
  55537. !subprotocolRegex.test(protocol) ||
  55538. protocolSet.has(protocol)
  55539. ) {
  55540. throw new SyntaxError(
  55541. 'An invalid or duplicated subprotocol was specified'
  55542. );
  55543. }
  55544. protocolSet.add(protocol);
  55545. }
  55546. opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
  55547. }
  55548. if (opts.origin) {
  55549. if (opts.protocolVersion < 13) {
  55550. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  55551. } else {
  55552. opts.headers.Origin = opts.origin;
  55553. }
  55554. }
  55555. if (parsedUrl.username || parsedUrl.password) {
  55556. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  55557. }
  55558. if (isIpcUrl) {
  55559. const parts = opts.path.split(':');
  55560. opts.socketPath = parts[0];
  55561. opts.path = parts[1];
  55562. }
  55563. let req;
  55564. if (opts.followRedirects) {
  55565. if (websocket._redirects === 0) {
  55566. websocket._originalIpc = isIpcUrl;
  55567. websocket._originalSecure = isSecure;
  55568. websocket._originalHostOrSocketPath = isIpcUrl
  55569. ? opts.socketPath
  55570. : parsedUrl.host;
  55571. const headers = options && options.headers;
  55572. //
  55573. // Shallow copy the user provided options so that headers can be changed
  55574. // without mutating the original object.
  55575. //
  55576. options = { ...options, headers: {} };
  55577. if (headers) {
  55578. for (const [key, value] of Object.entries(headers)) {
  55579. options.headers[key.toLowerCase()] = value;
  55580. }
  55581. }
  55582. } else if (websocket.listenerCount('redirect') === 0) {
  55583. const isSameHost = isIpcUrl
  55584. ? websocket._originalIpc
  55585. ? opts.socketPath === websocket._originalHostOrSocketPath
  55586. : false
  55587. : websocket._originalIpc
  55588. ? false
  55589. : parsedUrl.host === websocket._originalHostOrSocketPath;
  55590. if (!isSameHost || (websocket._originalSecure && !isSecure)) {
  55591. //
  55592. // Match curl 7.77.0 behavior and drop the following headers. These
  55593. // headers are also dropped when following a redirect to a subdomain.
  55594. //
  55595. delete opts.headers.authorization;
  55596. delete opts.headers.cookie;
  55597. if (!isSameHost) delete opts.headers.host;
  55598. opts.auth = undefined;
  55599. }
  55600. }
  55601. //
  55602. // Match curl 7.77.0 behavior and make the first `Authorization` header win.
  55603. // If the `Authorization` header is set, then there is nothing to do as it
  55604. // will take precedence.
  55605. //
  55606. if (opts.auth && !options.headers.authorization) {
  55607. options.headers.authorization =
  55608. 'Basic ' + Buffer.from(opts.auth).toString('base64');
  55609. }
  55610. req = websocket._req = request(opts);
  55611. if (websocket._redirects) {
  55612. //
  55613. // Unlike what is done for the `'upgrade'` event, no early exit is
  55614. // triggered here if the user calls `websocket.close()` or
  55615. // `websocket.terminate()` from a listener of the `'redirect'` event. This
  55616. // is because the user can also call `request.destroy()` with an error
  55617. // before calling `websocket.close()` or `websocket.terminate()` and this
  55618. // would result in an error being emitted on the `request` object with no
  55619. // `'error'` event listeners attached.
  55620. //
  55621. websocket.emit('redirect', websocket.url, req);
  55622. }
  55623. } else {
  55624. req = websocket._req = request(opts);
  55625. }
  55626. if (opts.timeout) {
  55627. req.on('timeout', () => {
  55628. abortHandshake$1(websocket, req, 'Opening handshake has timed out');
  55629. });
  55630. }
  55631. req.on('error', (err) => {
  55632. if (req === null || req[kAborted]) return;
  55633. req = websocket._req = null;
  55634. emitErrorAndClose(websocket, err);
  55635. });
  55636. req.on('response', (res) => {
  55637. const location = res.headers.location;
  55638. const statusCode = res.statusCode;
  55639. if (
  55640. location &&
  55641. opts.followRedirects &&
  55642. statusCode >= 300 &&
  55643. statusCode < 400
  55644. ) {
  55645. if (++websocket._redirects > opts.maxRedirects) {
  55646. abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
  55647. return;
  55648. }
  55649. req.abort();
  55650. let addr;
  55651. try {
  55652. addr = new URL$2(location, address);
  55653. } catch (e) {
  55654. const err = new SyntaxError(`Invalid URL: ${location}`);
  55655. emitErrorAndClose(websocket, err);
  55656. return;
  55657. }
  55658. initAsClient(websocket, addr, protocols, options);
  55659. } else if (!websocket.emit('unexpected-response', req, res)) {
  55660. abortHandshake$1(
  55661. websocket,
  55662. req,
  55663. `Unexpected server response: ${res.statusCode}`
  55664. );
  55665. }
  55666. });
  55667. req.on('upgrade', (res, socket, head) => {
  55668. websocket.emit('upgrade', res);
  55669. //
  55670. // The user may have closed the connection from a listener of the
  55671. // `'upgrade'` event.
  55672. //
  55673. if (websocket.readyState !== WebSocket$1.CONNECTING) return;
  55674. req = websocket._req = null;
  55675. if (res.headers.upgrade.toLowerCase() !== 'websocket') {
  55676. abortHandshake$1(websocket, socket, 'Invalid Upgrade header');
  55677. return;
  55678. }
  55679. const digest = createHash$1('sha1')
  55680. .update(key + GUID$1)
  55681. .digest('base64');
  55682. if (res.headers['sec-websocket-accept'] !== digest) {
  55683. abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  55684. return;
  55685. }
  55686. const serverProt = res.headers['sec-websocket-protocol'];
  55687. let protError;
  55688. if (serverProt !== undefined) {
  55689. if (!protocolSet.size) {
  55690. protError = 'Server sent a subprotocol but none was requested';
  55691. } else if (!protocolSet.has(serverProt)) {
  55692. protError = 'Server sent an invalid subprotocol';
  55693. }
  55694. } else if (protocolSet.size) {
  55695. protError = 'Server sent no subprotocol';
  55696. }
  55697. if (protError) {
  55698. abortHandshake$1(websocket, socket, protError);
  55699. return;
  55700. }
  55701. if (serverProt) websocket._protocol = serverProt;
  55702. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  55703. if (secWebSocketExtensions !== undefined) {
  55704. if (!perMessageDeflate) {
  55705. const message =
  55706. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  55707. 'was requested';
  55708. abortHandshake$1(websocket, socket, message);
  55709. return;
  55710. }
  55711. let extensions;
  55712. try {
  55713. extensions = parse$1(secWebSocketExtensions);
  55714. } catch (err) {
  55715. const message = 'Invalid Sec-WebSocket-Extensions header';
  55716. abortHandshake$1(websocket, socket, message);
  55717. return;
  55718. }
  55719. const extensionNames = Object.keys(extensions);
  55720. if (
  55721. extensionNames.length !== 1 ||
  55722. extensionNames[0] !== PerMessageDeflate$1.extensionName
  55723. ) {
  55724. const message = 'Server indicated an extension that was not requested';
  55725. abortHandshake$1(websocket, socket, message);
  55726. return;
  55727. }
  55728. try {
  55729. perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
  55730. } catch (err) {
  55731. const message = 'Invalid Sec-WebSocket-Extensions header';
  55732. abortHandshake$1(websocket, socket, message);
  55733. return;
  55734. }
  55735. websocket._extensions[PerMessageDeflate$1.extensionName] =
  55736. perMessageDeflate;
  55737. }
  55738. websocket.setSocket(socket, head, {
  55739. generateMask: opts.generateMask,
  55740. maxPayload: opts.maxPayload,
  55741. skipUTF8Validation: opts.skipUTF8Validation
  55742. });
  55743. });
  55744. if (opts.finishRequest) {
  55745. opts.finishRequest(req, websocket);
  55746. } else {
  55747. req.end();
  55748. }
  55749. }
  55750. /**
  55751. * Emit the `'error'` and `'close'` events.
  55752. *
  55753. * @param {WebSocket} websocket The WebSocket instance
  55754. * @param {Error} The error to emit
  55755. * @private
  55756. */
  55757. function emitErrorAndClose(websocket, err) {
  55758. websocket._readyState = WebSocket$1.CLOSING;
  55759. websocket.emit('error', err);
  55760. websocket.emitClose();
  55761. }
  55762. /**
  55763. * Create a `net.Socket` and initiate a connection.
  55764. *
  55765. * @param {Object} options Connection options
  55766. * @return {net.Socket} The newly created socket used to start the connection
  55767. * @private
  55768. */
  55769. function netConnect(options) {
  55770. options.path = options.socketPath;
  55771. return net.connect(options);
  55772. }
  55773. /**
  55774. * Create a `tls.TLSSocket` and initiate a connection.
  55775. *
  55776. * @param {Object} options Connection options
  55777. * @return {tls.TLSSocket} The newly created socket used to start the connection
  55778. * @private
  55779. */
  55780. function tlsConnect(options) {
  55781. options.path = undefined;
  55782. if (!options.servername && options.servername !== '') {
  55783. options.servername = net.isIP(options.host) ? '' : options.host;
  55784. }
  55785. return tls.connect(options);
  55786. }
  55787. /**
  55788. * Abort the handshake and emit an error.
  55789. *
  55790. * @param {WebSocket} websocket The WebSocket instance
  55791. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  55792. * abort or the socket to destroy
  55793. * @param {String} message The error message
  55794. * @private
  55795. */
  55796. function abortHandshake$1(websocket, stream, message) {
  55797. websocket._readyState = WebSocket$1.CLOSING;
  55798. const err = new Error(message);
  55799. Error.captureStackTrace(err, abortHandshake$1);
  55800. if (stream.setHeader) {
  55801. stream[kAborted] = true;
  55802. stream.abort();
  55803. if (stream.socket && !stream.socket.destroyed) {
  55804. //
  55805. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  55806. // called after the request completed. See
  55807. // https://github.com/websockets/ws/issues/1869.
  55808. //
  55809. stream.socket.destroy();
  55810. }
  55811. process.nextTick(emitErrorAndClose, websocket, err);
  55812. } else {
  55813. stream.destroy(err);
  55814. stream.once('error', websocket.emit.bind(websocket, 'error'));
  55815. stream.once('close', websocket.emitClose.bind(websocket));
  55816. }
  55817. }
  55818. /**
  55819. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  55820. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  55821. *
  55822. * @param {WebSocket} websocket The WebSocket instance
  55823. * @param {*} [data] The data to send
  55824. * @param {Function} [cb] Callback
  55825. * @private
  55826. */
  55827. function sendAfterClose(websocket, data, cb) {
  55828. if (data) {
  55829. const length = toBuffer(data).length;
  55830. //
  55831. // The `_bufferedAmount` property is used only when the peer is a client and
  55832. // the opening handshake fails. Under these circumstances, in fact, the
  55833. // `setSocket()` method is not called, so the `_socket` and `_sender`
  55834. // properties are set to `null`.
  55835. //
  55836. if (websocket._socket) websocket._sender._bufferedBytes += length;
  55837. else websocket._bufferedAmount += length;
  55838. }
  55839. if (cb) {
  55840. const err = new Error(
  55841. `WebSocket is not open: readyState ${websocket.readyState} ` +
  55842. `(${readyStates[websocket.readyState]})`
  55843. );
  55844. process.nextTick(cb, err);
  55845. }
  55846. }
  55847. /**
  55848. * The listener of the `Receiver` `'conclude'` event.
  55849. *
  55850. * @param {Number} code The status code
  55851. * @param {Buffer} reason The reason for closing
  55852. * @private
  55853. */
  55854. function receiverOnConclude(code, reason) {
  55855. const websocket = this[kWebSocket$1];
  55856. websocket._closeFrameReceived = true;
  55857. websocket._closeMessage = reason;
  55858. websocket._closeCode = code;
  55859. if (websocket._socket[kWebSocket$1] === undefined) return;
  55860. websocket._socket.removeListener('data', socketOnData);
  55861. process.nextTick(resume, websocket._socket);
  55862. if (code === 1005) websocket.close();
  55863. else websocket.close(code, reason);
  55864. }
  55865. /**
  55866. * The listener of the `Receiver` `'drain'` event.
  55867. *
  55868. * @private
  55869. */
  55870. function receiverOnDrain() {
  55871. const websocket = this[kWebSocket$1];
  55872. if (!websocket.isPaused) websocket._socket.resume();
  55873. }
  55874. /**
  55875. * The listener of the `Receiver` `'error'` event.
  55876. *
  55877. * @param {(RangeError|Error)} err The emitted error
  55878. * @private
  55879. */
  55880. function receiverOnError(err) {
  55881. const websocket = this[kWebSocket$1];
  55882. if (websocket._socket[kWebSocket$1] !== undefined) {
  55883. websocket._socket.removeListener('data', socketOnData);
  55884. //
  55885. // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
  55886. // https://github.com/websockets/ws/issues/1940.
  55887. //
  55888. process.nextTick(resume, websocket._socket);
  55889. websocket.close(err[kStatusCode]);
  55890. }
  55891. websocket.emit('error', err);
  55892. }
  55893. /**
  55894. * The listener of the `Receiver` `'finish'` event.
  55895. *
  55896. * @private
  55897. */
  55898. function receiverOnFinish() {
  55899. this[kWebSocket$1].emitClose();
  55900. }
  55901. /**
  55902. * The listener of the `Receiver` `'message'` event.
  55903. *
  55904. * @param {Buffer|ArrayBuffer|Buffer[])} data The message
  55905. * @param {Boolean} isBinary Specifies whether the message is binary or not
  55906. * @private
  55907. */
  55908. function receiverOnMessage(data, isBinary) {
  55909. this[kWebSocket$1].emit('message', data, isBinary);
  55910. }
  55911. /**
  55912. * The listener of the `Receiver` `'ping'` event.
  55913. *
  55914. * @param {Buffer} data The data included in the ping frame
  55915. * @private
  55916. */
  55917. function receiverOnPing(data) {
  55918. const websocket = this[kWebSocket$1];
  55919. websocket.pong(data, !websocket._isServer, NOOP);
  55920. websocket.emit('ping', data);
  55921. }
  55922. /**
  55923. * The listener of the `Receiver` `'pong'` event.
  55924. *
  55925. * @param {Buffer} data The data included in the pong frame
  55926. * @private
  55927. */
  55928. function receiverOnPong(data) {
  55929. this[kWebSocket$1].emit('pong', data);
  55930. }
  55931. /**
  55932. * Resume a readable stream
  55933. *
  55934. * @param {Readable} stream The readable stream
  55935. * @private
  55936. */
  55937. function resume(stream) {
  55938. stream.resume();
  55939. }
  55940. /**
  55941. * The listener of the `net.Socket` `'close'` event.
  55942. *
  55943. * @private
  55944. */
  55945. function socketOnClose() {
  55946. const websocket = this[kWebSocket$1];
  55947. this.removeListener('close', socketOnClose);
  55948. this.removeListener('data', socketOnData);
  55949. this.removeListener('end', socketOnEnd);
  55950. websocket._readyState = WebSocket$1.CLOSING;
  55951. let chunk;
  55952. //
  55953. // The close frame might not have been received or the `'end'` event emitted,
  55954. // for example, if the socket was destroyed due to an error. Ensure that the
  55955. // `receiver` stream is closed after writing any remaining buffered data to
  55956. // it. If the readable side of the socket is in flowing mode then there is no
  55957. // buffered data as everything has been already written and `readable.read()`
  55958. // will return `null`. If instead, the socket is paused, any possible buffered
  55959. // data will be read as a single chunk.
  55960. //
  55961. if (
  55962. !this._readableState.endEmitted &&
  55963. !websocket._closeFrameReceived &&
  55964. !websocket._receiver._writableState.errorEmitted &&
  55965. (chunk = websocket._socket.read()) !== null
  55966. ) {
  55967. websocket._receiver.write(chunk);
  55968. }
  55969. websocket._receiver.end();
  55970. this[kWebSocket$1] = undefined;
  55971. clearTimeout(websocket._closeTimer);
  55972. if (
  55973. websocket._receiver._writableState.finished ||
  55974. websocket._receiver._writableState.errorEmitted
  55975. ) {
  55976. websocket.emitClose();
  55977. } else {
  55978. websocket._receiver.on('error', receiverOnFinish);
  55979. websocket._receiver.on('finish', receiverOnFinish);
  55980. }
  55981. }
  55982. /**
  55983. * The listener of the `net.Socket` `'data'` event.
  55984. *
  55985. * @param {Buffer} chunk A chunk of data
  55986. * @private
  55987. */
  55988. function socketOnData(chunk) {
  55989. if (!this[kWebSocket$1]._receiver.write(chunk)) {
  55990. this.pause();
  55991. }
  55992. }
  55993. /**
  55994. * The listener of the `net.Socket` `'end'` event.
  55995. *
  55996. * @private
  55997. */
  55998. function socketOnEnd() {
  55999. const websocket = this[kWebSocket$1];
  56000. websocket._readyState = WebSocket$1.CLOSING;
  56001. websocket._receiver.end();
  56002. this.end();
  56003. }
  56004. /**
  56005. * The listener of the `net.Socket` `'error'` event.
  56006. *
  56007. * @private
  56008. */
  56009. function socketOnError$1() {
  56010. const websocket = this[kWebSocket$1];
  56011. this.removeListener('error', socketOnError$1);
  56012. this.on('error', NOOP);
  56013. if (websocket) {
  56014. websocket._readyState = WebSocket$1.CLOSING;
  56015. this.destroy();
  56016. }
  56017. }
  56018. const { tokenChars } = validationExports;
  56019. /**
  56020. * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
  56021. *
  56022. * @param {String} header The field value of the header
  56023. * @return {Set} The subprotocol names
  56024. * @public
  56025. */
  56026. function parse(header) {
  56027. const protocols = new Set();
  56028. let start = -1;
  56029. let end = -1;
  56030. let i = 0;
  56031. for (i; i < header.length; i++) {
  56032. const code = header.charCodeAt(i);
  56033. if (end === -1 && tokenChars[code] === 1) {
  56034. if (start === -1) start = i;
  56035. } else if (
  56036. i !== 0 &&
  56037. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  56038. ) {
  56039. if (end === -1 && start !== -1) end = i;
  56040. } else if (code === 0x2c /* ',' */) {
  56041. if (start === -1) {
  56042. throw new SyntaxError(`Unexpected character at index ${i}`);
  56043. }
  56044. if (end === -1) end = i;
  56045. const protocol = header.slice(start, end);
  56046. if (protocols.has(protocol)) {
  56047. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  56048. }
  56049. protocols.add(protocol);
  56050. start = end = -1;
  56051. } else {
  56052. throw new SyntaxError(`Unexpected character at index ${i}`);
  56053. }
  56054. }
  56055. if (start === -1 || end !== -1) {
  56056. throw new SyntaxError('Unexpected end of input');
  56057. }
  56058. const protocol = header.slice(start, i);
  56059. if (protocols.has(protocol)) {
  56060. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  56061. }
  56062. protocols.add(protocol);
  56063. return protocols;
  56064. }
  56065. var subprotocol$1 = { parse };
  56066. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */
  56067. const EventEmitter = require$$0$5;
  56068. const http$2 = require$$1$1;
  56069. const { createHash } = require$$3$1;
  56070. const extension = extension$1;
  56071. const PerMessageDeflate = permessageDeflate;
  56072. const subprotocol = subprotocol$1;
  56073. const WebSocket = websocket;
  56074. const { GUID, kWebSocket } = constants;
  56075. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  56076. const RUNNING = 0;
  56077. const CLOSING = 1;
  56078. const CLOSED = 2;
  56079. /**
  56080. * Class representing a WebSocket server.
  56081. *
  56082. * @extends EventEmitter
  56083. */
  56084. class WebSocketServer extends EventEmitter {
  56085. /**
  56086. * Create a `WebSocketServer` instance.
  56087. *
  56088. * @param {Object} options Configuration options
  56089. * @param {Number} [options.backlog=511] The maximum length of the queue of
  56090. * pending connections
  56091. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  56092. * track clients
  56093. * @param {Function} [options.handleProtocols] A hook to handle protocols
  56094. * @param {String} [options.host] The hostname where to bind the server
  56095. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  56096. * size
  56097. * @param {Boolean} [options.noServer=false] Enable no server mode
  56098. * @param {String} [options.path] Accept only connections matching this path
  56099. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  56100. * permessage-deflate
  56101. * @param {Number} [options.port] The port where to bind the server
  56102. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  56103. * server to use
  56104. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  56105. * not to skip UTF-8 validation for text and close messages
  56106. * @param {Function} [options.verifyClient] A hook to reject connections
  56107. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  56108. * class to use. It must be the `WebSocket` class or class that extends it
  56109. * @param {Function} [callback] A listener for the `listening` event
  56110. */
  56111. constructor(options, callback) {
  56112. super();
  56113. options = {
  56114. maxPayload: 100 * 1024 * 1024,
  56115. skipUTF8Validation: false,
  56116. perMessageDeflate: false,
  56117. handleProtocols: null,
  56118. clientTracking: true,
  56119. verifyClient: null,
  56120. noServer: false,
  56121. backlog: null, // use default (511 as implemented in net.js)
  56122. server: null,
  56123. host: null,
  56124. path: null,
  56125. port: null,
  56126. WebSocket,
  56127. ...options
  56128. };
  56129. if (
  56130. (options.port == null && !options.server && !options.noServer) ||
  56131. (options.port != null && (options.server || options.noServer)) ||
  56132. (options.server && options.noServer)
  56133. ) {
  56134. throw new TypeError(
  56135. 'One and only one of the "port", "server", or "noServer" options ' +
  56136. 'must be specified'
  56137. );
  56138. }
  56139. if (options.port != null) {
  56140. this._server = http$2.createServer((req, res) => {
  56141. const body = http$2.STATUS_CODES[426];
  56142. res.writeHead(426, {
  56143. 'Content-Length': body.length,
  56144. 'Content-Type': 'text/plain'
  56145. });
  56146. res.end(body);
  56147. });
  56148. this._server.listen(
  56149. options.port,
  56150. options.host,
  56151. options.backlog,
  56152. callback
  56153. );
  56154. } else if (options.server) {
  56155. this._server = options.server;
  56156. }
  56157. if (this._server) {
  56158. const emitConnection = this.emit.bind(this, 'connection');
  56159. this._removeListeners = addListeners(this._server, {
  56160. listening: this.emit.bind(this, 'listening'),
  56161. error: this.emit.bind(this, 'error'),
  56162. upgrade: (req, socket, head) => {
  56163. this.handleUpgrade(req, socket, head, emitConnection);
  56164. }
  56165. });
  56166. }
  56167. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  56168. if (options.clientTracking) {
  56169. this.clients = new Set();
  56170. this._shouldEmitClose = false;
  56171. }
  56172. this.options = options;
  56173. this._state = RUNNING;
  56174. }
  56175. /**
  56176. * Returns the bound address, the address family name, and port of the server
  56177. * as reported by the operating system if listening on an IP socket.
  56178. * If the server is listening on a pipe or UNIX domain socket, the name is
  56179. * returned as a string.
  56180. *
  56181. * @return {(Object|String|null)} The address of the server
  56182. * @public
  56183. */
  56184. address() {
  56185. if (this.options.noServer) {
  56186. throw new Error('The server is operating in "noServer" mode');
  56187. }
  56188. if (!this._server) return null;
  56189. return this._server.address();
  56190. }
  56191. /**
  56192. * Stop the server from accepting new connections and emit the `'close'` event
  56193. * when all existing connections are closed.
  56194. *
  56195. * @param {Function} [cb] A one-time listener for the `'close'` event
  56196. * @public
  56197. */
  56198. close(cb) {
  56199. if (this._state === CLOSED) {
  56200. if (cb) {
  56201. this.once('close', () => {
  56202. cb(new Error('The server is not running'));
  56203. });
  56204. }
  56205. process.nextTick(emitClose, this);
  56206. return;
  56207. }
  56208. if (cb) this.once('close', cb);
  56209. if (this._state === CLOSING) return;
  56210. this._state = CLOSING;
  56211. if (this.options.noServer || this.options.server) {
  56212. if (this._server) {
  56213. this._removeListeners();
  56214. this._removeListeners = this._server = null;
  56215. }
  56216. if (this.clients) {
  56217. if (!this.clients.size) {
  56218. process.nextTick(emitClose, this);
  56219. } else {
  56220. this._shouldEmitClose = true;
  56221. }
  56222. } else {
  56223. process.nextTick(emitClose, this);
  56224. }
  56225. } else {
  56226. const server = this._server;
  56227. this._removeListeners();
  56228. this._removeListeners = this._server = null;
  56229. //
  56230. // The HTTP/S server was created internally. Close it, and rely on its
  56231. // `'close'` event.
  56232. //
  56233. server.close(() => {
  56234. emitClose(this);
  56235. });
  56236. }
  56237. }
  56238. /**
  56239. * See if a given request should be handled by this server instance.
  56240. *
  56241. * @param {http.IncomingMessage} req Request object to inspect
  56242. * @return {Boolean} `true` if the request is valid, else `false`
  56243. * @public
  56244. */
  56245. shouldHandle(req) {
  56246. if (this.options.path) {
  56247. const index = req.url.indexOf('?');
  56248. const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
  56249. if (pathname !== this.options.path) return false;
  56250. }
  56251. return true;
  56252. }
  56253. /**
  56254. * Handle a HTTP Upgrade request.
  56255. *
  56256. * @param {http.IncomingMessage} req The request object
  56257. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  56258. * server and client
  56259. * @param {Buffer} head The first packet of the upgraded stream
  56260. * @param {Function} cb Callback
  56261. * @public
  56262. */
  56263. handleUpgrade(req, socket, head, cb) {
  56264. socket.on('error', socketOnError);
  56265. const key = req.headers['sec-websocket-key'];
  56266. const version = +req.headers['sec-websocket-version'];
  56267. if (req.method !== 'GET') {
  56268. const message = 'Invalid HTTP method';
  56269. abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
  56270. return;
  56271. }
  56272. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  56273. const message = 'Invalid Upgrade header';
  56274. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  56275. return;
  56276. }
  56277. if (!key || !keyRegex.test(key)) {
  56278. const message = 'Missing or invalid Sec-WebSocket-Key header';
  56279. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  56280. return;
  56281. }
  56282. if (version !== 8 && version !== 13) {
  56283. const message = 'Missing or invalid Sec-WebSocket-Version header';
  56284. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  56285. return;
  56286. }
  56287. if (!this.shouldHandle(req)) {
  56288. abortHandshake(socket, 400);
  56289. return;
  56290. }
  56291. const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
  56292. let protocols = new Set();
  56293. if (secWebSocketProtocol !== undefined) {
  56294. try {
  56295. protocols = subprotocol.parse(secWebSocketProtocol);
  56296. } catch (err) {
  56297. const message = 'Invalid Sec-WebSocket-Protocol header';
  56298. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  56299. return;
  56300. }
  56301. }
  56302. const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
  56303. const extensions = {};
  56304. if (
  56305. this.options.perMessageDeflate &&
  56306. secWebSocketExtensions !== undefined
  56307. ) {
  56308. const perMessageDeflate = new PerMessageDeflate(
  56309. this.options.perMessageDeflate,
  56310. true,
  56311. this.options.maxPayload
  56312. );
  56313. try {
  56314. const offers = extension.parse(secWebSocketExtensions);
  56315. if (offers[PerMessageDeflate.extensionName]) {
  56316. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  56317. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  56318. }
  56319. } catch (err) {
  56320. const message =
  56321. 'Invalid or unacceptable Sec-WebSocket-Extensions header';
  56322. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  56323. return;
  56324. }
  56325. }
  56326. //
  56327. // Optionally call external client verification handler.
  56328. //
  56329. if (this.options.verifyClient) {
  56330. const info = {
  56331. origin:
  56332. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  56333. secure: !!(req.socket.authorized || req.socket.encrypted),
  56334. req
  56335. };
  56336. if (this.options.verifyClient.length === 2) {
  56337. this.options.verifyClient(info, (verified, code, message, headers) => {
  56338. if (!verified) {
  56339. return abortHandshake(socket, code || 401, message, headers);
  56340. }
  56341. this.completeUpgrade(
  56342. extensions,
  56343. key,
  56344. protocols,
  56345. req,
  56346. socket,
  56347. head,
  56348. cb
  56349. );
  56350. });
  56351. return;
  56352. }
  56353. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  56354. }
  56355. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  56356. }
  56357. /**
  56358. * Upgrade the connection to WebSocket.
  56359. *
  56360. * @param {Object} extensions The accepted extensions
  56361. * @param {String} key The value of the `Sec-WebSocket-Key` header
  56362. * @param {Set} protocols The subprotocols
  56363. * @param {http.IncomingMessage} req The request object
  56364. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  56365. * server and client
  56366. * @param {Buffer} head The first packet of the upgraded stream
  56367. * @param {Function} cb Callback
  56368. * @throws {Error} If called more than once with the same socket
  56369. * @private
  56370. */
  56371. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  56372. //
  56373. // Destroy the socket if the client has already sent a FIN packet.
  56374. //
  56375. if (!socket.readable || !socket.writable) return socket.destroy();
  56376. if (socket[kWebSocket]) {
  56377. throw new Error(
  56378. 'server.handleUpgrade() was called more than once with the same ' +
  56379. 'socket, possibly due to a misconfiguration'
  56380. );
  56381. }
  56382. if (this._state > RUNNING) return abortHandshake(socket, 503);
  56383. const digest = createHash('sha1')
  56384. .update(key + GUID)
  56385. .digest('base64');
  56386. const headers = [
  56387. 'HTTP/1.1 101 Switching Protocols',
  56388. 'Upgrade: websocket',
  56389. 'Connection: Upgrade',
  56390. `Sec-WebSocket-Accept: ${digest}`
  56391. ];
  56392. const ws = new this.options.WebSocket(null);
  56393. if (protocols.size) {
  56394. //
  56395. // Optionally call external protocol selection handler.
  56396. //
  56397. const protocol = this.options.handleProtocols
  56398. ? this.options.handleProtocols(protocols, req)
  56399. : protocols.values().next().value;
  56400. if (protocol) {
  56401. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  56402. ws._protocol = protocol;
  56403. }
  56404. }
  56405. if (extensions[PerMessageDeflate.extensionName]) {
  56406. const params = extensions[PerMessageDeflate.extensionName].params;
  56407. const value = extension.format({
  56408. [PerMessageDeflate.extensionName]: [params]
  56409. });
  56410. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  56411. ws._extensions = extensions;
  56412. }
  56413. //
  56414. // Allow external modification/inspection of handshake headers.
  56415. //
  56416. this.emit('headers', headers, req);
  56417. socket.write(headers.concat('\r\n').join('\r\n'));
  56418. socket.removeListener('error', socketOnError);
  56419. ws.setSocket(socket, head, {
  56420. maxPayload: this.options.maxPayload,
  56421. skipUTF8Validation: this.options.skipUTF8Validation
  56422. });
  56423. if (this.clients) {
  56424. this.clients.add(ws);
  56425. ws.on('close', () => {
  56426. this.clients.delete(ws);
  56427. if (this._shouldEmitClose && !this.clients.size) {
  56428. process.nextTick(emitClose, this);
  56429. }
  56430. });
  56431. }
  56432. cb(ws, req);
  56433. }
  56434. }
  56435. var websocketServer = WebSocketServer;
  56436. /**
  56437. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  56438. * pairs.
  56439. *
  56440. * @param {EventEmitter} server The event emitter
  56441. * @param {Object.<String, Function>} map The listeners to add
  56442. * @return {Function} A function that will remove the added listeners when
  56443. * called
  56444. * @private
  56445. */
  56446. function addListeners(server, map) {
  56447. for (const event of Object.keys(map)) server.on(event, map[event]);
  56448. return function removeListeners() {
  56449. for (const event of Object.keys(map)) {
  56450. server.removeListener(event, map[event]);
  56451. }
  56452. };
  56453. }
  56454. /**
  56455. * Emit a `'close'` event on an `EventEmitter`.
  56456. *
  56457. * @param {EventEmitter} server The event emitter
  56458. * @private
  56459. */
  56460. function emitClose(server) {
  56461. server._state = CLOSED;
  56462. server.emit('close');
  56463. }
  56464. /**
  56465. * Handle socket errors.
  56466. *
  56467. * @private
  56468. */
  56469. function socketOnError() {
  56470. this.destroy();
  56471. }
  56472. /**
  56473. * Close the connection when preconditions are not fulfilled.
  56474. *
  56475. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  56476. * @param {Number} code The HTTP response status code
  56477. * @param {String} [message] The HTTP response body
  56478. * @param {Object} [headers] Additional HTTP response headers
  56479. * @private
  56480. */
  56481. function abortHandshake(socket, code, message, headers) {
  56482. //
  56483. // The socket is writable unless the user destroyed or ended it before calling
  56484. // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
  56485. // error. Handling this does not make much sense as the worst that can happen
  56486. // is that some of the data written by the user might be discarded due to the
  56487. // call to `socket.end()` below, which triggers an `'error'` event that in
  56488. // turn causes the socket to be destroyed.
  56489. //
  56490. message = message || http$2.STATUS_CODES[code];
  56491. headers = {
  56492. Connection: 'close',
  56493. 'Content-Type': 'text/html',
  56494. 'Content-Length': Buffer.byteLength(message),
  56495. ...headers
  56496. };
  56497. socket.once('finish', socket.destroy);
  56498. socket.end(
  56499. `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
  56500. Object.keys(headers)
  56501. .map((h) => `${h}: ${headers[h]}`)
  56502. .join('\r\n') +
  56503. '\r\n\r\n' +
  56504. message
  56505. );
  56506. }
  56507. /**
  56508. * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
  56509. * one listener for it, otherwise call `abortHandshake()`.
  56510. *
  56511. * @param {WebSocketServer} server The WebSocket server
  56512. * @param {http.IncomingMessage} req The request object
  56513. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  56514. * @param {Number} code The HTTP response status code
  56515. * @param {String} message The HTTP response body
  56516. * @private
  56517. */
  56518. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
  56519. if (server.listenerCount('wsClientError')) {
  56520. const err = new Error(message);
  56521. Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
  56522. server.emit('wsClientError', err, socket, req);
  56523. } else {
  56524. abortHandshake(socket, code, message);
  56525. }
  56526. }
  56527. var WebSocketServerRaw_ = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
  56528. const allowedHostsServerCache = new WeakMap();
  56529. const allowedHostsPreviewCache = new WeakMap();
  56530. const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
  56531. function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
  56532. const list = [];
  56533. // allow host option by default as that indicates that the user is
  56534. // expecting Vite to respond on that host
  56535. if (typeof resolvedServerOptions.host === 'string' &&
  56536. resolvedServerOptions.host) {
  56537. list.push(resolvedServerOptions.host);
  56538. }
  56539. if (typeof resolvedServerOptions.hmr === 'object' &&
  56540. resolvedServerOptions.hmr.host) {
  56541. list.push(resolvedServerOptions.hmr.host);
  56542. }
  56543. if (typeof resolvedPreviewOptions.host === 'string' &&
  56544. resolvedPreviewOptions.host) {
  56545. list.push(resolvedPreviewOptions.host);
  56546. }
  56547. // allow server origin by default as that indicates that the user is
  56548. // expecting Vite to respond on that host
  56549. if (resolvedServerOptions.origin) {
  56550. // some frameworks may pass the origin as a placeholder, so it's not
  56551. // possible to parse as URL, so use a try-catch here as a best effort
  56552. try {
  56553. const serverOriginUrl = new URL(resolvedServerOptions.origin);
  56554. list.push(serverOriginUrl.hostname);
  56555. }
  56556. catch { }
  56557. }
  56558. return list;
  56559. }
  56560. // Based on webpack-dev-server's `checkHeader` function: https://github.com/webpack/webpack-dev-server/blob/v5.2.0/lib/Server.js#L3086
  56561. // https://github.com/webpack/webpack-dev-server/blob/v5.2.0/LICENSE
  56562. function isHostAllowedWithoutCache(allowedHosts, additionalAllowedHosts, host) {
  56563. if (isFileOrExtensionProtocolRE.test(host)) {
  56564. return true;
  56565. }
  56566. // We don't care about malformed Host headers,
  56567. // because we only need to consider browser requests.
  56568. // Non-browser clients can send any value they want anyway.
  56569. //
  56570. // `Host = uri-host [ ":" port ]`
  56571. const trimmedHost = host.trim();
  56572. // IPv6
  56573. if (trimmedHost[0] === '[') {
  56574. const endIpv6 = trimmedHost.indexOf(']');
  56575. if (endIpv6 < 0) {
  56576. return false;
  56577. }
  56578. // DNS rebinding attacks does not happen with IP addresses
  56579. return net$1.isIP(trimmedHost.slice(1, endIpv6)) === 6;
  56580. }
  56581. // uri-host does not include ":" unless IPv6 address
  56582. const colonPos = trimmedHost.indexOf(':');
  56583. const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos);
  56584. // DNS rebinding attacks does not happen with IP addresses
  56585. if (net$1.isIP(hostname) === 4) {
  56586. return true;
  56587. }
  56588. // allow localhost and .localhost by default as they always resolve to the loopback address
  56589. // https://datatracker.ietf.org/doc/html/rfc6761#section-6.3
  56590. if (hostname === 'localhost' || hostname.endsWith('.localhost')) {
  56591. return true;
  56592. }
  56593. for (const additionalAllowedHost of additionalAllowedHosts) {
  56594. if (additionalAllowedHost === hostname) {
  56595. return true;
  56596. }
  56597. }
  56598. for (const allowedHost of allowedHosts) {
  56599. if (allowedHost === hostname) {
  56600. return true;
  56601. }
  56602. // allow all subdomains of it
  56603. // e.g. `.foo.example` will allow `foo.example`, `*.foo.example`, `*.*.foo.example`, etc
  56604. if (allowedHost[0] === '.' &&
  56605. (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) {
  56606. return true;
  56607. }
  56608. }
  56609. return false;
  56610. }
  56611. /**
  56612. * @param config resolved config
  56613. * @param isPreview whether it's for the preview server or not
  56614. * @param host the value of host header. See [RFC 9110 7.2](https://datatracker.ietf.org/doc/html/rfc9110#name-host-and-authority).
  56615. */
  56616. function isHostAllowed(config, isPreview, host) {
  56617. const allowedHosts = isPreview
  56618. ? config.preview.allowedHosts
  56619. : config.server.allowedHosts;
  56620. if (allowedHosts === true) {
  56621. return true;
  56622. }
  56623. const cache = isPreview ? allowedHostsPreviewCache : allowedHostsServerCache;
  56624. if (!cache.has(config)) {
  56625. cache.set(config, new Set());
  56626. }
  56627. const cachedAllowedHosts = cache.get(config);
  56628. if (cachedAllowedHosts.has(host)) {
  56629. return true;
  56630. }
  56631. const result = isHostAllowedWithoutCache(allowedHosts ?? [], config.additionalAllowedHosts, host);
  56632. if (result) {
  56633. cachedAllowedHosts.add(host);
  56634. }
  56635. return result;
  56636. }
  56637. function hostCheckMiddleware(config, isPreview) {
  56638. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56639. return function viteHostCheckMiddleware(req, res, next) {
  56640. const hostHeader = req.headers.host;
  56641. if (!hostHeader || !isHostAllowed(config, isPreview, hostHeader)) {
  56642. const hostname = hostHeader?.replace(/:\d+$/, '');
  56643. const hostnameWithQuotes = JSON.stringify(hostname);
  56644. const optionName = `${isPreview ? 'preview' : 'server'}.allowedHosts`;
  56645. res.writeHead(403, {
  56646. 'Content-Type': 'text/plain',
  56647. });
  56648. res.end(`Blocked request. This host (${hostnameWithQuotes}) is not allowed.\n` +
  56649. `To allow this host, add ${hostnameWithQuotes} to \`${optionName}\` in vite.config.js.`);
  56650. return;
  56651. }
  56652. return next();
  56653. };
  56654. }
  56655. /* In Bun, the `ws` module is overridden to hook into the native code. Using the bundled `js` version
  56656. * of `ws` will not work as Bun's req.socket does not allow reading/writing to the underlying socket.
  56657. */
  56658. const WebSocketServerRaw = process.versions.bun
  56659. ? // @ts-expect-error: Bun defines `import.meta.require`
  56660. import.meta.require('ws').WebSocketServer
  56661. : WebSocketServerRaw_;
  56662. const HMR_HEADER = 'vite-hmr';
  56663. const wsServerEvents = [
  56664. 'connection',
  56665. 'error',
  56666. 'headers',
  56667. 'listening',
  56668. 'message',
  56669. ];
  56670. // we only allow websockets to be connected if it has a valid token
  56671. // this is to prevent untrusted origins to connect to the server
  56672. // for example, Cross-site WebSocket hijacking
  56673. //
  56674. // we should check the token before calling wss.handleUpgrade
  56675. // otherwise untrusted ws clients will be included in wss.clients
  56676. //
  56677. // using the query params means the token might be logged out in server or middleware logs
  56678. // but we assume that is not an issue since the token is regenerated for each process
  56679. function hasValidToken(config, url) {
  56680. const token = url.searchParams.get('token');
  56681. if (!token)
  56682. return false;
  56683. try {
  56684. const isValidToken = crypto$2.timingSafeEqual(Buffer.from(token), Buffer.from(config.webSocketToken));
  56685. return isValidToken;
  56686. }
  56687. catch { } // an error is thrown when the length is incorrect
  56688. return false;
  56689. }
  56690. function createWebSocketServer(server, config, httpsOptions) {
  56691. let wsHttpServer = undefined;
  56692. const hmr = isObject$2(config.server.hmr) && config.server.hmr;
  56693. const hmrServer = hmr && hmr.server;
  56694. const hmrPort = hmr && hmr.port;
  56695. // TODO: the main server port may not have been chosen yet as it may use the next available
  56696. const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
  56697. const wsServer = hmrServer || (portsAreCompatible && server);
  56698. let hmrServerWsListener;
  56699. const customListeners = new Map();
  56700. const clientsMap = new WeakMap();
  56701. const port = hmrPort || 24678;
  56702. const host = (hmr && hmr.host) || undefined;
  56703. const shouldHandle = (req) => {
  56704. const hostHeader = req.headers.host;
  56705. if (!hostHeader || !isHostAllowed(config, false, hostHeader)) {
  56706. return false;
  56707. }
  56708. if (config.legacy?.skipWebSocketTokenCheck) {
  56709. return true;
  56710. }
  56711. // If the Origin header is set, this request might be coming from a browser.
  56712. // Browsers always sets the Origin header for WebSocket connections.
  56713. if (req.headers.origin) {
  56714. const parsedUrl = new URL(`http://example.com${req.url}`);
  56715. return hasValidToken(config, parsedUrl);
  56716. }
  56717. // We allow non-browser requests to connect without a token
  56718. // for backward compat and convenience
  56719. // This is fine because if you can sent a request without the SOP limitation,
  56720. // you can also send a normal HTTP request to the server.
  56721. return true;
  56722. };
  56723. const handleUpgrade = (req, socket, head, _isPing) => {
  56724. wss.handleUpgrade(req, socket, head, (ws) => {
  56725. wss.emit('connection', ws, req);
  56726. });
  56727. };
  56728. const wss = new WebSocketServerRaw({ noServer: true });
  56729. wss.shouldHandle = shouldHandle;
  56730. if (wsServer) {
  56731. let hmrBase = config.base;
  56732. const hmrPath = hmr ? hmr.path : undefined;
  56733. if (hmrPath) {
  56734. hmrBase = path$o.posix.join(hmrBase, hmrPath);
  56735. }
  56736. hmrServerWsListener = (req, socket, head) => {
  56737. const parsedUrl = new URL(`http://example.com${req.url}`);
  56738. if (req.headers['sec-websocket-protocol'] === HMR_HEADER &&
  56739. parsedUrl.pathname === hmrBase) {
  56740. handleUpgrade(req, socket, head);
  56741. }
  56742. };
  56743. wsServer.on('upgrade', hmrServerWsListener);
  56744. }
  56745. else {
  56746. // http server request handler keeps the same with
  56747. // https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96
  56748. const route = ((_, res) => {
  56749. const statusCode = 426;
  56750. const body = STATUS_CODES[statusCode];
  56751. if (!body)
  56752. throw new Error(`No body text found for the ${statusCode} status code`);
  56753. res.writeHead(statusCode, {
  56754. 'Content-Length': body.length,
  56755. 'Content-Type': 'text/plain',
  56756. });
  56757. res.end(body);
  56758. });
  56759. if (httpsOptions) {
  56760. wsHttpServer = createServer$2(httpsOptions, route);
  56761. }
  56762. else {
  56763. wsHttpServer = createServer$3(route);
  56764. }
  56765. wsHttpServer.on('upgrade', (req, socket, head) => {
  56766. handleUpgrade(req, socket, head);
  56767. });
  56768. wsHttpServer.on('error', (e) => {
  56769. if (e.code === 'EADDRINUSE') {
  56770. config.logger.error(colors$1.red(`WebSocket server error: Port is already in use`), { error: e });
  56771. }
  56772. else {
  56773. config.logger.error(colors$1.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  56774. }
  56775. });
  56776. }
  56777. wss.on('connection', (socket) => {
  56778. socket.on('message', (raw) => {
  56779. if (!customListeners.size)
  56780. return;
  56781. let parsed;
  56782. try {
  56783. parsed = JSON.parse(String(raw));
  56784. }
  56785. catch { }
  56786. if (!parsed || parsed.type !== 'custom' || !parsed.event)
  56787. return;
  56788. const listeners = customListeners.get(parsed.event);
  56789. if (!listeners?.size)
  56790. return;
  56791. const client = getSocketClient(socket);
  56792. listeners.forEach((listener) => listener(parsed.data, client));
  56793. });
  56794. socket.on('error', (err) => {
  56795. config.logger.error(`${colors$1.red(`ws error:`)}\n${err.stack}`, {
  56796. timestamp: true,
  56797. error: err,
  56798. });
  56799. });
  56800. socket.send(JSON.stringify({ type: 'connected' }));
  56801. if (bufferedError) {
  56802. socket.send(JSON.stringify(bufferedError));
  56803. bufferedError = null;
  56804. }
  56805. });
  56806. wss.on('error', (e) => {
  56807. if (e.code === 'EADDRINUSE') {
  56808. config.logger.error(colors$1.red(`WebSocket server error: Port is already in use`), { error: e });
  56809. }
  56810. else {
  56811. config.logger.error(colors$1.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  56812. }
  56813. });
  56814. // Provide a wrapper to the ws client so we can send messages in JSON format
  56815. // To be consistent with server.ws.send
  56816. function getSocketClient(socket) {
  56817. if (!clientsMap.has(socket)) {
  56818. clientsMap.set(socket, {
  56819. send: (...args) => {
  56820. let payload;
  56821. if (typeof args[0] === 'string') {
  56822. payload = {
  56823. type: 'custom',
  56824. event: args[0],
  56825. data: args[1],
  56826. };
  56827. }
  56828. else {
  56829. payload = args[0];
  56830. }
  56831. socket.send(JSON.stringify(payload));
  56832. },
  56833. socket,
  56834. });
  56835. }
  56836. return clientsMap.get(socket);
  56837. }
  56838. // On page reloads, if a file fails to compile and returns 500, the server
  56839. // sends the error payload before the client connection is established.
  56840. // If we have no open clients, buffer the error and send it to the next
  56841. // connected client.
  56842. let bufferedError = null;
  56843. return {
  56844. listen: () => {
  56845. wsHttpServer?.listen(port, host);
  56846. },
  56847. on: ((event, fn) => {
  56848. if (wsServerEvents.includes(event))
  56849. wss.on(event, fn);
  56850. else {
  56851. if (!customListeners.has(event)) {
  56852. customListeners.set(event, new Set());
  56853. }
  56854. customListeners.get(event).add(fn);
  56855. }
  56856. }),
  56857. off: ((event, fn) => {
  56858. if (wsServerEvents.includes(event)) {
  56859. wss.off(event, fn);
  56860. }
  56861. else {
  56862. customListeners.get(event)?.delete(fn);
  56863. }
  56864. }),
  56865. get clients() {
  56866. return new Set(Array.from(wss.clients).map(getSocketClient));
  56867. },
  56868. send(...args) {
  56869. let payload;
  56870. if (typeof args[0] === 'string') {
  56871. payload = {
  56872. type: 'custom',
  56873. event: args[0],
  56874. data: args[1],
  56875. };
  56876. }
  56877. else {
  56878. payload = args[0];
  56879. }
  56880. if (payload.type === 'error' && !wss.clients.size) {
  56881. bufferedError = payload;
  56882. return;
  56883. }
  56884. const stringified = JSON.stringify(payload);
  56885. wss.clients.forEach((client) => {
  56886. // readyState 1 means the connection is open
  56887. if (client.readyState === 1) {
  56888. client.send(stringified);
  56889. }
  56890. });
  56891. },
  56892. close() {
  56893. // should remove listener if hmr.server is set
  56894. // otherwise the old listener swallows all WebSocket connections
  56895. if (hmrServerWsListener && wsServer) {
  56896. wsServer.off('upgrade', hmrServerWsListener);
  56897. }
  56898. return new Promise((resolve, reject) => {
  56899. wss.clients.forEach((client) => {
  56900. client.terminate();
  56901. });
  56902. wss.close((err) => {
  56903. if (err) {
  56904. reject(err);
  56905. }
  56906. else {
  56907. if (wsHttpServer) {
  56908. wsHttpServer.close((err) => {
  56909. if (err) {
  56910. reject(err);
  56911. }
  56912. else {
  56913. resolve();
  56914. }
  56915. });
  56916. }
  56917. else {
  56918. resolve();
  56919. }
  56920. }
  56921. });
  56922. });
  56923. },
  56924. };
  56925. }
  56926. // this middleware is only active when (base !== '/')
  56927. function baseMiddleware({ config, }) {
  56928. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56929. return function viteBaseMiddleware(req, res, next) {
  56930. const url = req.url;
  56931. const parsed = new URL(url, 'http://vitejs.dev');
  56932. const path = parsed.pathname || '/';
  56933. const base = config.rawBase;
  56934. if (path.startsWith(base)) {
  56935. // rewrite url to remove base. this ensures that other middleware does
  56936. // not need to consider base being prepended or not
  56937. req.url = stripBase(url, base);
  56938. return next();
  56939. }
  56940. // skip redirect and error fallback on middleware mode, #4057
  56941. if (config.server.middlewareMode) {
  56942. return next();
  56943. }
  56944. if (path === '/' || path === '/index.html') {
  56945. // redirect root visit to based url with search and hash
  56946. res.writeHead(302, {
  56947. Location: base + (parsed.search || '') + (parsed.hash || ''),
  56948. });
  56949. res.end();
  56950. return;
  56951. }
  56952. else if (req.headers.accept?.includes('text/html')) {
  56953. // non-based page visit
  56954. const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
  56955. res.writeHead(404, {
  56956. 'Content-Type': 'text/html',
  56957. });
  56958. res.end(`The server is configured with a public base URL of ${base} - ` +
  56959. `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
  56960. return;
  56961. }
  56962. next();
  56963. };
  56964. }
  56965. var httpProxy$3 = {exports: {}};
  56966. var eventemitter3 = {exports: {}};
  56967. (function (module) {
  56968. var has = Object.prototype.hasOwnProperty
  56969. , prefix = '~';
  56970. /**
  56971. * Constructor to create a storage for our `EE` objects.
  56972. * An `Events` instance is a plain object whose properties are event names.
  56973. *
  56974. * @constructor
  56975. * @private
  56976. */
  56977. function Events() {}
  56978. //
  56979. // We try to not inherit from `Object.prototype`. In some engines creating an
  56980. // instance in this way is faster than calling `Object.create(null)` directly.
  56981. // If `Object.create(null)` is not supported we prefix the event names with a
  56982. // character to make sure that the built-in object properties are not
  56983. // overridden or used as an attack vector.
  56984. //
  56985. if (Object.create) {
  56986. Events.prototype = Object.create(null);
  56987. //
  56988. // This hack is needed because the `__proto__` property is still inherited in
  56989. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  56990. //
  56991. if (!new Events().__proto__) prefix = false;
  56992. }
  56993. /**
  56994. * Representation of a single event listener.
  56995. *
  56996. * @param {Function} fn The listener function.
  56997. * @param {*} context The context to invoke the listener with.
  56998. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  56999. * @constructor
  57000. * @private
  57001. */
  57002. function EE(fn, context, once) {
  57003. this.fn = fn;
  57004. this.context = context;
  57005. this.once = once || false;
  57006. }
  57007. /**
  57008. * Add a listener for a given event.
  57009. *
  57010. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  57011. * @param {(String|Symbol)} event The event name.
  57012. * @param {Function} fn The listener function.
  57013. * @param {*} context The context to invoke the listener with.
  57014. * @param {Boolean} once Specify if the listener is a one-time listener.
  57015. * @returns {EventEmitter}
  57016. * @private
  57017. */
  57018. function addListener(emitter, event, fn, context, once) {
  57019. if (typeof fn !== 'function') {
  57020. throw new TypeError('The listener must be a function');
  57021. }
  57022. var listener = new EE(fn, context || emitter, once)
  57023. , evt = prefix ? prefix + event : event;
  57024. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  57025. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  57026. else emitter._events[evt] = [emitter._events[evt], listener];
  57027. return emitter;
  57028. }
  57029. /**
  57030. * Clear event by name.
  57031. *
  57032. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  57033. * @param {(String|Symbol)} evt The Event name.
  57034. * @private
  57035. */
  57036. function clearEvent(emitter, evt) {
  57037. if (--emitter._eventsCount === 0) emitter._events = new Events();
  57038. else delete emitter._events[evt];
  57039. }
  57040. /**
  57041. * Minimal `EventEmitter` interface that is molded against the Node.js
  57042. * `EventEmitter` interface.
  57043. *
  57044. * @constructor
  57045. * @public
  57046. */
  57047. function EventEmitter() {
  57048. this._events = new Events();
  57049. this._eventsCount = 0;
  57050. }
  57051. /**
  57052. * Return an array listing the events for which the emitter has registered
  57053. * listeners.
  57054. *
  57055. * @returns {Array}
  57056. * @public
  57057. */
  57058. EventEmitter.prototype.eventNames = function eventNames() {
  57059. var names = []
  57060. , events
  57061. , name;
  57062. if (this._eventsCount === 0) return names;
  57063. for (name in (events = this._events)) {
  57064. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  57065. }
  57066. if (Object.getOwnPropertySymbols) {
  57067. return names.concat(Object.getOwnPropertySymbols(events));
  57068. }
  57069. return names;
  57070. };
  57071. /**
  57072. * Return the listeners registered for a given event.
  57073. *
  57074. * @param {(String|Symbol)} event The event name.
  57075. * @returns {Array} The registered listeners.
  57076. * @public
  57077. */
  57078. EventEmitter.prototype.listeners = function listeners(event) {
  57079. var evt = prefix ? prefix + event : event
  57080. , handlers = this._events[evt];
  57081. if (!handlers) return [];
  57082. if (handlers.fn) return [handlers.fn];
  57083. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  57084. ee[i] = handlers[i].fn;
  57085. }
  57086. return ee;
  57087. };
  57088. /**
  57089. * Return the number of listeners listening to a given event.
  57090. *
  57091. * @param {(String|Symbol)} event The event name.
  57092. * @returns {Number} The number of listeners.
  57093. * @public
  57094. */
  57095. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  57096. var evt = prefix ? prefix + event : event
  57097. , listeners = this._events[evt];
  57098. if (!listeners) return 0;
  57099. if (listeners.fn) return 1;
  57100. return listeners.length;
  57101. };
  57102. /**
  57103. * Calls each of the listeners registered for a given event.
  57104. *
  57105. * @param {(String|Symbol)} event The event name.
  57106. * @returns {Boolean} `true` if the event had listeners, else `false`.
  57107. * @public
  57108. */
  57109. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  57110. var evt = prefix ? prefix + event : event;
  57111. if (!this._events[evt]) return false;
  57112. var listeners = this._events[evt]
  57113. , len = arguments.length
  57114. , args
  57115. , i;
  57116. if (listeners.fn) {
  57117. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  57118. switch (len) {
  57119. case 1: return listeners.fn.call(listeners.context), true;
  57120. case 2: return listeners.fn.call(listeners.context, a1), true;
  57121. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  57122. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  57123. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  57124. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  57125. }
  57126. for (i = 1, args = new Array(len -1); i < len; i++) {
  57127. args[i - 1] = arguments[i];
  57128. }
  57129. listeners.fn.apply(listeners.context, args);
  57130. } else {
  57131. var length = listeners.length
  57132. , j;
  57133. for (i = 0; i < length; i++) {
  57134. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  57135. switch (len) {
  57136. case 1: listeners[i].fn.call(listeners[i].context); break;
  57137. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  57138. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  57139. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  57140. default:
  57141. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  57142. args[j - 1] = arguments[j];
  57143. }
  57144. listeners[i].fn.apply(listeners[i].context, args);
  57145. }
  57146. }
  57147. }
  57148. return true;
  57149. };
  57150. /**
  57151. * Add a listener for a given event.
  57152. *
  57153. * @param {(String|Symbol)} event The event name.
  57154. * @param {Function} fn The listener function.
  57155. * @param {*} [context=this] The context to invoke the listener with.
  57156. * @returns {EventEmitter} `this`.
  57157. * @public
  57158. */
  57159. EventEmitter.prototype.on = function on(event, fn, context) {
  57160. return addListener(this, event, fn, context, false);
  57161. };
  57162. /**
  57163. * Add a one-time listener for a given event.
  57164. *
  57165. * @param {(String|Symbol)} event The event name.
  57166. * @param {Function} fn The listener function.
  57167. * @param {*} [context=this] The context to invoke the listener with.
  57168. * @returns {EventEmitter} `this`.
  57169. * @public
  57170. */
  57171. EventEmitter.prototype.once = function once(event, fn, context) {
  57172. return addListener(this, event, fn, context, true);
  57173. };
  57174. /**
  57175. * Remove the listeners of a given event.
  57176. *
  57177. * @param {(String|Symbol)} event The event name.
  57178. * @param {Function} fn Only remove the listeners that match this function.
  57179. * @param {*} context Only remove the listeners that have this context.
  57180. * @param {Boolean} once Only remove one-time listeners.
  57181. * @returns {EventEmitter} `this`.
  57182. * @public
  57183. */
  57184. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  57185. var evt = prefix ? prefix + event : event;
  57186. if (!this._events[evt]) return this;
  57187. if (!fn) {
  57188. clearEvent(this, evt);
  57189. return this;
  57190. }
  57191. var listeners = this._events[evt];
  57192. if (listeners.fn) {
  57193. if (
  57194. listeners.fn === fn &&
  57195. (!once || listeners.once) &&
  57196. (!context || listeners.context === context)
  57197. ) {
  57198. clearEvent(this, evt);
  57199. }
  57200. } else {
  57201. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  57202. if (
  57203. listeners[i].fn !== fn ||
  57204. (once && !listeners[i].once) ||
  57205. (context && listeners[i].context !== context)
  57206. ) {
  57207. events.push(listeners[i]);
  57208. }
  57209. }
  57210. //
  57211. // Reset the array, or remove it completely if we have no more listeners.
  57212. //
  57213. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  57214. else clearEvent(this, evt);
  57215. }
  57216. return this;
  57217. };
  57218. /**
  57219. * Remove all listeners, or those of the specified event.
  57220. *
  57221. * @param {(String|Symbol)} [event] The event name.
  57222. * @returns {EventEmitter} `this`.
  57223. * @public
  57224. */
  57225. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  57226. var evt;
  57227. if (event) {
  57228. evt = prefix ? prefix + event : event;
  57229. if (this._events[evt]) clearEvent(this, evt);
  57230. } else {
  57231. this._events = new Events();
  57232. this._eventsCount = 0;
  57233. }
  57234. return this;
  57235. };
  57236. //
  57237. // Alias methods names because people roll like that.
  57238. //
  57239. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  57240. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  57241. //
  57242. // Expose the prefix.
  57243. //
  57244. EventEmitter.prefixed = prefix;
  57245. //
  57246. // Allow `EventEmitter` to be imported as module namespace.
  57247. //
  57248. EventEmitter.EventEmitter = EventEmitter;
  57249. //
  57250. // Expose the module.
  57251. //
  57252. {
  57253. module.exports = EventEmitter;
  57254. }
  57255. } (eventemitter3));
  57256. var eventemitter3Exports = eventemitter3.exports;
  57257. var common$3 = {};
  57258. /**
  57259. * Check if we're required to add a port number.
  57260. *
  57261. * @see https://url.spec.whatwg.org/#default-port
  57262. * @param {Number|String} port Port number we need to check
  57263. * @param {String} protocol Protocol we need to check against.
  57264. * @returns {Boolean} Is it a default port for the given protocol
  57265. * @api private
  57266. */
  57267. var requiresPort = function required(port, protocol) {
  57268. protocol = protocol.split(':')[0];
  57269. port = +port;
  57270. if (!port) return false;
  57271. switch (protocol) {
  57272. case 'http':
  57273. case 'ws':
  57274. return port !== 80;
  57275. case 'https':
  57276. case 'wss':
  57277. return port !== 443;
  57278. case 'ftp':
  57279. return port !== 21;
  57280. case 'gopher':
  57281. return port !== 70;
  57282. case 'file':
  57283. return false;
  57284. }
  57285. return port !== 0;
  57286. };
  57287. (function (exports) {
  57288. var common = exports,
  57289. url = require$$0$9,
  57290. extend = require$$0$6._extend,
  57291. required = requiresPort;
  57292. var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
  57293. isSSL = /^https|wss/;
  57294. /**
  57295. * Simple Regex for testing if protocol is https
  57296. */
  57297. common.isSSL = isSSL;
  57298. /**
  57299. * Copies the right headers from `options` and `req` to
  57300. * `outgoing` which is then used to fire the proxied
  57301. * request.
  57302. *
  57303. * Examples:
  57304. *
  57305. * common.setupOutgoing(outgoing, options, req)
  57306. * // => { host: ..., hostname: ...}
  57307. *
  57308. * @param {Object} Outgoing Base object to be filled with required properties
  57309. * @param {Object} Options Config object passed to the proxy
  57310. * @param {ClientRequest} Req Request Object
  57311. * @param {String} Forward String to select forward or target
  57312. * @return {Object} Outgoing Object with all required properties set
  57313. *
  57314. * @api private
  57315. */
  57316. common.setupOutgoing = function(outgoing, options, req, forward) {
  57317. outgoing.port = options[forward || 'target'].port ||
  57318. (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
  57319. ['host', 'hostname', 'socketPath', 'pfx', 'key',
  57320. 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
  57321. function(e) { outgoing[e] = options[forward || 'target'][e]; }
  57322. );
  57323. outgoing.method = options.method || req.method;
  57324. outgoing.headers = extend({}, req.headers);
  57325. if (options.headers){
  57326. extend(outgoing.headers, options.headers);
  57327. }
  57328. if (options.auth) {
  57329. outgoing.auth = options.auth;
  57330. }
  57331. if (options.ca) {
  57332. outgoing.ca = options.ca;
  57333. }
  57334. if (isSSL.test(options[forward || 'target'].protocol)) {
  57335. outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
  57336. }
  57337. outgoing.agent = options.agent || false;
  57338. outgoing.localAddress = options.localAddress;
  57339. //
  57340. // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
  57341. // as node core doesn't handle this COMPLETELY properly yet.
  57342. //
  57343. if (!outgoing.agent) {
  57344. outgoing.headers = outgoing.headers || {};
  57345. if (typeof outgoing.headers.connection !== 'string'
  57346. || !upgradeHeader.test(outgoing.headers.connection)
  57347. ) { outgoing.headers.connection = 'close'; }
  57348. }
  57349. // the final path is target path + relative path requested by user:
  57350. var target = options[forward || 'target'];
  57351. var targetPath = target && options.prependPath !== false
  57352. ? (target.path || '')
  57353. : '';
  57354. //
  57355. // Remark: Can we somehow not use url.parse as a perf optimization?
  57356. //
  57357. var outgoingPath = !options.toProxy
  57358. ? (url.parse(req.url).path || '')
  57359. : req.url;
  57360. //
  57361. // Remark: ignorePath will just straight up ignore whatever the request's
  57362. // path is. This can be labeled as FOOT-GUN material if you do not know what
  57363. // you are doing and are using conflicting options.
  57364. //
  57365. outgoingPath = !options.ignorePath ? outgoingPath : '';
  57366. outgoing.path = common.urlJoin(targetPath, outgoingPath);
  57367. if (options.changeOrigin) {
  57368. outgoing.headers.host =
  57369. required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
  57370. ? outgoing.host + ':' + outgoing.port
  57371. : outgoing.host;
  57372. }
  57373. return outgoing;
  57374. };
  57375. /**
  57376. * Set the proper configuration for sockets,
  57377. * set no delay and set keep alive, also set
  57378. * the timeout to 0.
  57379. *
  57380. * Examples:
  57381. *
  57382. * common.setupSocket(socket)
  57383. * // => Socket
  57384. *
  57385. * @param {Socket} Socket instance to setup
  57386. * @return {Socket} Return the configured socket.
  57387. *
  57388. * @api private
  57389. */
  57390. common.setupSocket = function(socket) {
  57391. socket.setTimeout(0);
  57392. socket.setNoDelay(true);
  57393. socket.setKeepAlive(true, 0);
  57394. return socket;
  57395. };
  57396. /**
  57397. * Get the port number from the host. Or guess it based on the connection type.
  57398. *
  57399. * @param {Request} req Incoming HTTP request.
  57400. *
  57401. * @return {String} The port number.
  57402. *
  57403. * @api private
  57404. */
  57405. common.getPort = function(req) {
  57406. var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
  57407. return res ?
  57408. res[1] :
  57409. common.hasEncryptedConnection(req) ? '443' : '80';
  57410. };
  57411. /**
  57412. * Check if the request has an encrypted connection.
  57413. *
  57414. * @param {Request} req Incoming HTTP request.
  57415. *
  57416. * @return {Boolean} Whether the connection is encrypted or not.
  57417. *
  57418. * @api private
  57419. */
  57420. common.hasEncryptedConnection = function(req) {
  57421. return Boolean(req.connection.encrypted || req.connection.pair);
  57422. };
  57423. /**
  57424. * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
  57425. *
  57426. * @return {String} The generated path.
  57427. *
  57428. * @api private
  57429. */
  57430. common.urlJoin = function() {
  57431. //
  57432. // We do not want to mess with the query string. All we want to touch is the path.
  57433. //
  57434. var args = Array.prototype.slice.call(arguments),
  57435. lastIndex = args.length - 1,
  57436. last = args[lastIndex],
  57437. lastSegs = last.split('?'),
  57438. retSegs;
  57439. args[lastIndex] = lastSegs.shift();
  57440. //
  57441. // Join all strings, but remove empty strings so we don't get extra slashes from
  57442. // joining e.g. ['', 'am']
  57443. //
  57444. retSegs = [
  57445. args.filter(Boolean).join('/')
  57446. .replace(/\/+/g, '/')
  57447. .replace('http:/', 'http://')
  57448. .replace('https:/', 'https://')
  57449. ];
  57450. // Only join the query string if it exists so we don't have trailing a '?'
  57451. // on every request
  57452. // Handle case where there could be multiple ? in the URL.
  57453. retSegs.push.apply(retSegs, lastSegs);
  57454. return retSegs.join('?')
  57455. };
  57456. /**
  57457. * Rewrites or removes the domain of a cookie header
  57458. *
  57459. * @param {String|Array} Header
  57460. * @param {Object} Config, mapping of domain to rewritten domain.
  57461. * '*' key to match any domain, null value to remove the domain.
  57462. *
  57463. * @api private
  57464. */
  57465. common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
  57466. if (Array.isArray(header)) {
  57467. return header.map(function (headerElement) {
  57468. return rewriteCookieProperty(headerElement, config, property);
  57469. });
  57470. }
  57471. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
  57472. var newValue;
  57473. if (previousValue in config) {
  57474. newValue = config[previousValue];
  57475. } else if ('*' in config) {
  57476. newValue = config['*'];
  57477. } else {
  57478. //no match, return previous value
  57479. return match;
  57480. }
  57481. if (newValue) {
  57482. //replace value
  57483. return prefix + newValue;
  57484. } else {
  57485. //remove value
  57486. return '';
  57487. }
  57488. });
  57489. };
  57490. /**
  57491. * Check the host and see if it potentially has a port in it (keep it simple)
  57492. *
  57493. * @returns {Boolean} Whether we have one or not
  57494. *
  57495. * @api private
  57496. */
  57497. function hasPort(host) {
  57498. return !!~host.indexOf(':');
  57499. }} (common$3));
  57500. var url$1 = require$$0$9,
  57501. common$2 = common$3;
  57502. var redirectRegex = /^201|30(1|2|7|8)$/;
  57503. /*!
  57504. * Array of passes.
  57505. *
  57506. * A `pass` is just a function that is executed on `req, res, options`
  57507. * so that you can easily add new checks while still keeping the base
  57508. * flexible.
  57509. */
  57510. var webOutgoing = { // <--
  57511. /**
  57512. * If is a HTTP 1.0 request, remove chunk headers
  57513. *
  57514. * @param {ClientRequest} Req Request object
  57515. * @param {IncomingMessage} Res Response object
  57516. * @param {proxyResponse} Res Response object from the proxy request
  57517. *
  57518. * @api private
  57519. */
  57520. removeChunked: function removeChunked(req, res, proxyRes) {
  57521. if (req.httpVersion === '1.0') {
  57522. delete proxyRes.headers['transfer-encoding'];
  57523. }
  57524. },
  57525. /**
  57526. * If is a HTTP 1.0 request, set the correct connection header
  57527. * or if connection header not present, then use `keep-alive`
  57528. *
  57529. * @param {ClientRequest} Req Request object
  57530. * @param {IncomingMessage} Res Response object
  57531. * @param {proxyResponse} Res Response object from the proxy request
  57532. *
  57533. * @api private
  57534. */
  57535. setConnection: function setConnection(req, res, proxyRes) {
  57536. if (req.httpVersion === '1.0') {
  57537. proxyRes.headers.connection = req.headers.connection || 'close';
  57538. } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
  57539. proxyRes.headers.connection = req.headers.connection || 'keep-alive';
  57540. }
  57541. },
  57542. setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
  57543. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
  57544. && proxyRes.headers['location']
  57545. && redirectRegex.test(proxyRes.statusCode)) {
  57546. var target = url$1.parse(options.target);
  57547. var u = url$1.parse(proxyRes.headers['location']);
  57548. // make sure the redirected host matches the target host before rewriting
  57549. if (target.host != u.host) {
  57550. return;
  57551. }
  57552. if (options.hostRewrite) {
  57553. u.host = options.hostRewrite;
  57554. } else if (options.autoRewrite) {
  57555. u.host = req.headers['host'];
  57556. }
  57557. if (options.protocolRewrite) {
  57558. u.protocol = options.protocolRewrite;
  57559. }
  57560. proxyRes.headers['location'] = u.format();
  57561. }
  57562. },
  57563. /**
  57564. * Copy headers from proxyResponse to response
  57565. * set each header in response object.
  57566. *
  57567. * @param {ClientRequest} Req Request object
  57568. * @param {IncomingMessage} Res Response object
  57569. * @param {proxyResponse} Res Response object from the proxy request
  57570. * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
  57571. *
  57572. * @api private
  57573. */
  57574. writeHeaders: function writeHeaders(req, res, proxyRes, options) {
  57575. var rewriteCookieDomainConfig = options.cookieDomainRewrite,
  57576. rewriteCookiePathConfig = options.cookiePathRewrite,
  57577. preserveHeaderKeyCase = options.preserveHeaderKeyCase,
  57578. rawHeaderKeyMap,
  57579. setHeader = function(key, header) {
  57580. if (header == undefined) return;
  57581. if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
  57582. header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
  57583. }
  57584. if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
  57585. header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
  57586. }
  57587. res.setHeader(String(key).trim(), header);
  57588. };
  57589. if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
  57590. rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
  57591. }
  57592. if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
  57593. rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
  57594. }
  57595. // message.rawHeaders is added in: v0.11.6
  57596. // https://nodejs.org/api/http.html#http_message_rawheaders
  57597. if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
  57598. rawHeaderKeyMap = {};
  57599. for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  57600. var key = proxyRes.rawHeaders[i];
  57601. rawHeaderKeyMap[key.toLowerCase()] = key;
  57602. }
  57603. }
  57604. Object.keys(proxyRes.headers).forEach(function(key) {
  57605. var header = proxyRes.headers[key];
  57606. if (preserveHeaderKeyCase && rawHeaderKeyMap) {
  57607. key = rawHeaderKeyMap[key] || key;
  57608. }
  57609. setHeader(key, header);
  57610. });
  57611. },
  57612. /**
  57613. * Set the statusCode from the proxyResponse
  57614. *
  57615. * @param {ClientRequest} Req Request object
  57616. * @param {IncomingMessage} Res Response object
  57617. * @param {proxyResponse} Res Response object from the proxy request
  57618. *
  57619. * @api private
  57620. */
  57621. writeStatusCode: function writeStatusCode(req, res, proxyRes) {
  57622. // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
  57623. if(proxyRes.statusMessage) {
  57624. res.statusCode = proxyRes.statusCode;
  57625. res.statusMessage = proxyRes.statusMessage;
  57626. } else {
  57627. res.statusCode = proxyRes.statusCode;
  57628. }
  57629. }
  57630. };
  57631. var followRedirects$1 = {exports: {}};
  57632. var debug$3;
  57633. var debug_1 = function () {
  57634. if (!debug$3) {
  57635. try {
  57636. /* eslint global-require: off */
  57637. debug$3 = srcExports$1("follow-redirects");
  57638. }
  57639. catch (error) { /* */ }
  57640. if (typeof debug$3 !== "function") {
  57641. debug$3 = function () { /* */ };
  57642. }
  57643. }
  57644. debug$3.apply(null, arguments);
  57645. };
  57646. var url = require$$0$9;
  57647. var URL$1 = url.URL;
  57648. var http$1 = require$$1$1;
  57649. var https$1 = require$$1$2;
  57650. var Writable = require$$0$7.Writable;
  57651. var assert = require$$5;
  57652. var debug$2 = debug_1;
  57653. // Create handlers that pass events from native requests
  57654. var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  57655. var eventHandlers = Object.create(null);
  57656. events.forEach(function (event) {
  57657. eventHandlers[event] = function (arg1, arg2, arg3) {
  57658. this._redirectable.emit(event, arg1, arg2, arg3);
  57659. };
  57660. });
  57661. // Error types with codes
  57662. var RedirectionError = createErrorType(
  57663. "ERR_FR_REDIRECTION_FAILURE",
  57664. "Redirected request failed"
  57665. );
  57666. var TooManyRedirectsError = createErrorType(
  57667. "ERR_FR_TOO_MANY_REDIRECTS",
  57668. "Maximum number of redirects exceeded"
  57669. );
  57670. var MaxBodyLengthExceededError = createErrorType(
  57671. "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
  57672. "Request body larger than maxBodyLength limit"
  57673. );
  57674. var WriteAfterEndError = createErrorType(
  57675. "ERR_STREAM_WRITE_AFTER_END",
  57676. "write after end"
  57677. );
  57678. // An HTTP(S) request that can be redirected
  57679. function RedirectableRequest(options, responseCallback) {
  57680. // Initialize the request
  57681. Writable.call(this);
  57682. this._sanitizeOptions(options);
  57683. this._options = options;
  57684. this._ended = false;
  57685. this._ending = false;
  57686. this._redirectCount = 0;
  57687. this._redirects = [];
  57688. this._requestBodyLength = 0;
  57689. this._requestBodyBuffers = [];
  57690. // Attach a callback if passed
  57691. if (responseCallback) {
  57692. this.on("response", responseCallback);
  57693. }
  57694. // React to responses of native requests
  57695. var self = this;
  57696. this._onNativeResponse = function (response) {
  57697. self._processResponse(response);
  57698. };
  57699. // Perform the first request
  57700. this._performRequest();
  57701. }
  57702. RedirectableRequest.prototype = Object.create(Writable.prototype);
  57703. RedirectableRequest.prototype.abort = function () {
  57704. abortRequest(this._currentRequest);
  57705. this.emit("abort");
  57706. };
  57707. // Writes buffered data to the current native request
  57708. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  57709. // Writing is not allowed if end has been called
  57710. if (this._ending) {
  57711. throw new WriteAfterEndError();
  57712. }
  57713. // Validate input and shift parameters if necessary
  57714. if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
  57715. throw new TypeError("data should be a string, Buffer or Uint8Array");
  57716. }
  57717. if (typeof encoding === "function") {
  57718. callback = encoding;
  57719. encoding = null;
  57720. }
  57721. // Ignore empty buffers, since writing them doesn't invoke the callback
  57722. // https://github.com/nodejs/node/issues/22066
  57723. if (data.length === 0) {
  57724. if (callback) {
  57725. callback();
  57726. }
  57727. return;
  57728. }
  57729. // Only write when we don't exceed the maximum body length
  57730. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  57731. this._requestBodyLength += data.length;
  57732. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  57733. this._currentRequest.write(data, encoding, callback);
  57734. }
  57735. // Error when we exceed the maximum body length
  57736. else {
  57737. this.emit("error", new MaxBodyLengthExceededError());
  57738. this.abort();
  57739. }
  57740. };
  57741. // Ends the current native request
  57742. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  57743. // Shift parameters if necessary
  57744. if (typeof data === "function") {
  57745. callback = data;
  57746. data = encoding = null;
  57747. }
  57748. else if (typeof encoding === "function") {
  57749. callback = encoding;
  57750. encoding = null;
  57751. }
  57752. // Write data if needed and end
  57753. if (!data) {
  57754. this._ended = this._ending = true;
  57755. this._currentRequest.end(null, null, callback);
  57756. }
  57757. else {
  57758. var self = this;
  57759. var currentRequest = this._currentRequest;
  57760. this.write(data, encoding, function () {
  57761. self._ended = true;
  57762. currentRequest.end(null, null, callback);
  57763. });
  57764. this._ending = true;
  57765. }
  57766. };
  57767. // Sets a header value on the current native request
  57768. RedirectableRequest.prototype.setHeader = function (name, value) {
  57769. this._options.headers[name] = value;
  57770. this._currentRequest.setHeader(name, value);
  57771. };
  57772. // Clears a header value on the current native request
  57773. RedirectableRequest.prototype.removeHeader = function (name) {
  57774. delete this._options.headers[name];
  57775. this._currentRequest.removeHeader(name);
  57776. };
  57777. // Global timeout for all underlying requests
  57778. RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
  57779. var self = this;
  57780. // Destroys the socket on timeout
  57781. function destroyOnTimeout(socket) {
  57782. socket.setTimeout(msecs);
  57783. socket.removeListener("timeout", socket.destroy);
  57784. socket.addListener("timeout", socket.destroy);
  57785. }
  57786. // Sets up a timer to trigger a timeout event
  57787. function startTimer(socket) {
  57788. if (self._timeout) {
  57789. clearTimeout(self._timeout);
  57790. }
  57791. self._timeout = setTimeout(function () {
  57792. self.emit("timeout");
  57793. clearTimer();
  57794. }, msecs);
  57795. destroyOnTimeout(socket);
  57796. }
  57797. // Stops a timeout from triggering
  57798. function clearTimer() {
  57799. // Clear the timeout
  57800. if (self._timeout) {
  57801. clearTimeout(self._timeout);
  57802. self._timeout = null;
  57803. }
  57804. // Clean up all attached listeners
  57805. self.removeListener("abort", clearTimer);
  57806. self.removeListener("error", clearTimer);
  57807. self.removeListener("response", clearTimer);
  57808. if (callback) {
  57809. self.removeListener("timeout", callback);
  57810. }
  57811. if (!self.socket) {
  57812. self._currentRequest.removeListener("socket", startTimer);
  57813. }
  57814. }
  57815. // Attach callback if passed
  57816. if (callback) {
  57817. this.on("timeout", callback);
  57818. }
  57819. // Start the timer if or when the socket is opened
  57820. if (this.socket) {
  57821. startTimer(this.socket);
  57822. }
  57823. else {
  57824. this._currentRequest.once("socket", startTimer);
  57825. }
  57826. // Clean up on events
  57827. this.on("socket", destroyOnTimeout);
  57828. this.on("abort", clearTimer);
  57829. this.on("error", clearTimer);
  57830. this.on("response", clearTimer);
  57831. return this;
  57832. };
  57833. // Proxy all other public ClientRequest methods
  57834. [
  57835. "flushHeaders", "getHeader",
  57836. "setNoDelay", "setSocketKeepAlive",
  57837. ].forEach(function (method) {
  57838. RedirectableRequest.prototype[method] = function (a, b) {
  57839. return this._currentRequest[method](a, b);
  57840. };
  57841. });
  57842. // Proxy all public ClientRequest properties
  57843. ["aborted", "connection", "socket"].forEach(function (property) {
  57844. Object.defineProperty(RedirectableRequest.prototype, property, {
  57845. get: function () { return this._currentRequest[property]; },
  57846. });
  57847. });
  57848. RedirectableRequest.prototype._sanitizeOptions = function (options) {
  57849. // Ensure headers are always present
  57850. if (!options.headers) {
  57851. options.headers = {};
  57852. }
  57853. // Since http.request treats host as an alias of hostname,
  57854. // but the url module interprets host as hostname plus port,
  57855. // eliminate the host property to avoid confusion.
  57856. if (options.host) {
  57857. // Use hostname if set, because it has precedence
  57858. if (!options.hostname) {
  57859. options.hostname = options.host;
  57860. }
  57861. delete options.host;
  57862. }
  57863. // Complete the URL object when necessary
  57864. if (!options.pathname && options.path) {
  57865. var searchPos = options.path.indexOf("?");
  57866. if (searchPos < 0) {
  57867. options.pathname = options.path;
  57868. }
  57869. else {
  57870. options.pathname = options.path.substring(0, searchPos);
  57871. options.search = options.path.substring(searchPos);
  57872. }
  57873. }
  57874. };
  57875. // Executes the next native request (initial or redirect)
  57876. RedirectableRequest.prototype._performRequest = function () {
  57877. // Load the native protocol
  57878. var protocol = this._options.protocol;
  57879. var nativeProtocol = this._options.nativeProtocols[protocol];
  57880. if (!nativeProtocol) {
  57881. this.emit("error", new TypeError("Unsupported protocol " + protocol));
  57882. return;
  57883. }
  57884. // If specified, use the agent corresponding to the protocol
  57885. // (HTTP and HTTPS use different types of agents)
  57886. if (this._options.agents) {
  57887. var scheme = protocol.slice(0, -1);
  57888. this._options.agent = this._options.agents[scheme];
  57889. }
  57890. // Create the native request
  57891. var request = this._currentRequest =
  57892. nativeProtocol.request(this._options, this._onNativeResponse);
  57893. this._currentUrl = url.format(this._options);
  57894. // Set up event handlers
  57895. request._redirectable = this;
  57896. for (var e = 0; e < events.length; e++) {
  57897. request.on(events[e], eventHandlers[events[e]]);
  57898. }
  57899. // End a redirected request
  57900. // (The first request must be ended explicitly with RedirectableRequest#end)
  57901. if (this._isRedirect) {
  57902. // Write the request entity and end.
  57903. var i = 0;
  57904. var self = this;
  57905. var buffers = this._requestBodyBuffers;
  57906. (function writeNext(error) {
  57907. // Only write if this request has not been redirected yet
  57908. /* istanbul ignore else */
  57909. if (request === self._currentRequest) {
  57910. // Report any write errors
  57911. /* istanbul ignore if */
  57912. if (error) {
  57913. self.emit("error", error);
  57914. }
  57915. // Write the next buffer if there are still left
  57916. else if (i < buffers.length) {
  57917. var buffer = buffers[i++];
  57918. /* istanbul ignore else */
  57919. if (!request.finished) {
  57920. request.write(buffer.data, buffer.encoding, writeNext);
  57921. }
  57922. }
  57923. // End the request if `end` has been called on us
  57924. else if (self._ended) {
  57925. request.end();
  57926. }
  57927. }
  57928. }());
  57929. }
  57930. };
  57931. // Processes a response from the current native request
  57932. RedirectableRequest.prototype._processResponse = function (response) {
  57933. // Store the redirected response
  57934. var statusCode = response.statusCode;
  57935. if (this._options.trackRedirects) {
  57936. this._redirects.push({
  57937. url: this._currentUrl,
  57938. headers: response.headers,
  57939. statusCode: statusCode,
  57940. });
  57941. }
  57942. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  57943. // that further action needs to be taken by the user agent in order to
  57944. // fulfill the request. If a Location header field is provided,
  57945. // the user agent MAY automatically redirect its request to the URI
  57946. // referenced by the Location field value,
  57947. // even if the specific status code is not understood.
  57948. // If the response is not a redirect; return it as-is
  57949. var location = response.headers.location;
  57950. if (!location || this._options.followRedirects === false ||
  57951. statusCode < 300 || statusCode >= 400) {
  57952. response.responseUrl = this._currentUrl;
  57953. response.redirects = this._redirects;
  57954. this.emit("response", response);
  57955. // Clean up
  57956. this._requestBodyBuffers = [];
  57957. return;
  57958. }
  57959. // The response is a redirect, so abort the current request
  57960. abortRequest(this._currentRequest);
  57961. // Discard the remainder of the response to avoid waiting for data
  57962. response.destroy();
  57963. // RFC7231§6.4: A client SHOULD detect and intervene
  57964. // in cyclical redirections (i.e., "infinite" redirection loops).
  57965. if (++this._redirectCount > this._options.maxRedirects) {
  57966. this.emit("error", new TooManyRedirectsError());
  57967. return;
  57968. }
  57969. // Store the request headers if applicable
  57970. var requestHeaders;
  57971. var beforeRedirect = this._options.beforeRedirect;
  57972. if (beforeRedirect) {
  57973. requestHeaders = Object.assign({
  57974. // The Host header was set by nativeProtocol.request
  57975. Host: response.req.getHeader("host"),
  57976. }, this._options.headers);
  57977. }
  57978. // RFC7231§6.4: Automatic redirection needs to done with
  57979. // care for methods not known to be safe, […]
  57980. // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
  57981. // the request method from POST to GET for the subsequent request.
  57982. var method = this._options.method;
  57983. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
  57984. // RFC7231§6.4.4: The 303 (See Other) status code indicates that
  57985. // the server is redirecting the user agent to a different resource […]
  57986. // A user agent can perform a retrieval request targeting that URI
  57987. // (a GET or HEAD request if using HTTP) […]
  57988. (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  57989. this._options.method = "GET";
  57990. // Drop a possible entity and headers related to it
  57991. this._requestBodyBuffers = [];
  57992. removeMatchingHeaders(/^content-/i, this._options.headers);
  57993. }
  57994. // Drop the Host header, as the redirect might lead to a different host
  57995. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  57996. // If the redirect is relative, carry over the host of the last request
  57997. var currentUrlParts = url.parse(this._currentUrl);
  57998. var currentHost = currentHostHeader || currentUrlParts.host;
  57999. var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
  58000. url.format(Object.assign(currentUrlParts, { host: currentHost }));
  58001. // Determine the URL of the redirection
  58002. var redirectUrl;
  58003. try {
  58004. redirectUrl = url.resolve(currentUrl, location);
  58005. }
  58006. catch (cause) {
  58007. this.emit("error", new RedirectionError(cause));
  58008. return;
  58009. }
  58010. // Create the redirected request
  58011. debug$2("redirecting to", redirectUrl);
  58012. this._isRedirect = true;
  58013. var redirectUrlParts = url.parse(redirectUrl);
  58014. Object.assign(this._options, redirectUrlParts);
  58015. // Drop confidential headers when redirecting to a less secure protocol
  58016. // or to a different domain that is not a superdomain
  58017. if (redirectUrlParts.protocol !== currentUrlParts.protocol &&
  58018. redirectUrlParts.protocol !== "https:" ||
  58019. redirectUrlParts.host !== currentHost &&
  58020. !isSubdomain(redirectUrlParts.host, currentHost)) {
  58021. removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
  58022. }
  58023. // Evaluate the beforeRedirect callback
  58024. if (typeof beforeRedirect === "function") {
  58025. var responseDetails = {
  58026. headers: response.headers,
  58027. statusCode: statusCode,
  58028. };
  58029. var requestDetails = {
  58030. url: currentUrl,
  58031. method: method,
  58032. headers: requestHeaders,
  58033. };
  58034. try {
  58035. beforeRedirect(this._options, responseDetails, requestDetails);
  58036. }
  58037. catch (err) {
  58038. this.emit("error", err);
  58039. return;
  58040. }
  58041. this._sanitizeOptions(this._options);
  58042. }
  58043. // Perform the redirected request
  58044. try {
  58045. this._performRequest();
  58046. }
  58047. catch (cause) {
  58048. this.emit("error", new RedirectionError(cause));
  58049. }
  58050. };
  58051. // Wraps the key/value object of protocols with redirect functionality
  58052. function wrap(protocols) {
  58053. // Default settings
  58054. var exports = {
  58055. maxRedirects: 21,
  58056. maxBodyLength: 10 * 1024 * 1024,
  58057. };
  58058. // Wrap each protocol
  58059. var nativeProtocols = {};
  58060. Object.keys(protocols).forEach(function (scheme) {
  58061. var protocol = scheme + ":";
  58062. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  58063. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  58064. // Executes a request, following redirects
  58065. function request(input, options, callback) {
  58066. // Parse parameters
  58067. if (typeof input === "string") {
  58068. var urlStr = input;
  58069. try {
  58070. input = urlToOptions(new URL$1(urlStr));
  58071. }
  58072. catch (err) {
  58073. /* istanbul ignore next */
  58074. input = url.parse(urlStr);
  58075. }
  58076. }
  58077. else if (URL$1 && (input instanceof URL$1)) {
  58078. input = urlToOptions(input);
  58079. }
  58080. else {
  58081. callback = options;
  58082. options = input;
  58083. input = { protocol: protocol };
  58084. }
  58085. if (typeof options === "function") {
  58086. callback = options;
  58087. options = null;
  58088. }
  58089. // Set defaults
  58090. options = Object.assign({
  58091. maxRedirects: exports.maxRedirects,
  58092. maxBodyLength: exports.maxBodyLength,
  58093. }, input, options);
  58094. options.nativeProtocols = nativeProtocols;
  58095. assert.equal(options.protocol, protocol, "protocol mismatch");
  58096. debug$2("options", options);
  58097. return new RedirectableRequest(options, callback);
  58098. }
  58099. // Executes a GET request, following redirects
  58100. function get(input, options, callback) {
  58101. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  58102. wrappedRequest.end();
  58103. return wrappedRequest;
  58104. }
  58105. // Expose the properties on the wrapped protocol
  58106. Object.defineProperties(wrappedProtocol, {
  58107. request: { value: request, configurable: true, enumerable: true, writable: true },
  58108. get: { value: get, configurable: true, enumerable: true, writable: true },
  58109. });
  58110. });
  58111. return exports;
  58112. }
  58113. /* istanbul ignore next */
  58114. function noop$1() { /* empty */ }
  58115. // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
  58116. function urlToOptions(urlObject) {
  58117. var options = {
  58118. protocol: urlObject.protocol,
  58119. hostname: urlObject.hostname.startsWith("[") ?
  58120. /* istanbul ignore next */
  58121. urlObject.hostname.slice(1, -1) :
  58122. urlObject.hostname,
  58123. hash: urlObject.hash,
  58124. search: urlObject.search,
  58125. pathname: urlObject.pathname,
  58126. path: urlObject.pathname + urlObject.search,
  58127. href: urlObject.href,
  58128. };
  58129. if (urlObject.port !== "") {
  58130. options.port = Number(urlObject.port);
  58131. }
  58132. return options;
  58133. }
  58134. function removeMatchingHeaders(regex, headers) {
  58135. var lastValue;
  58136. for (var header in headers) {
  58137. if (regex.test(header)) {
  58138. lastValue = headers[header];
  58139. delete headers[header];
  58140. }
  58141. }
  58142. return (lastValue === null || typeof lastValue === "undefined") ?
  58143. undefined : String(lastValue).trim();
  58144. }
  58145. function createErrorType(code, defaultMessage) {
  58146. function CustomError(cause) {
  58147. Error.captureStackTrace(this, this.constructor);
  58148. if (!cause) {
  58149. this.message = defaultMessage;
  58150. }
  58151. else {
  58152. this.message = defaultMessage + ": " + cause.message;
  58153. this.cause = cause;
  58154. }
  58155. }
  58156. CustomError.prototype = new Error();
  58157. CustomError.prototype.constructor = CustomError;
  58158. CustomError.prototype.name = "Error [" + code + "]";
  58159. CustomError.prototype.code = code;
  58160. return CustomError;
  58161. }
  58162. function abortRequest(request) {
  58163. for (var e = 0; e < events.length; e++) {
  58164. request.removeListener(events[e], eventHandlers[events[e]]);
  58165. }
  58166. request.on("error", noop$1);
  58167. request.abort();
  58168. }
  58169. function isSubdomain(subdomain, domain) {
  58170. const dot = subdomain.length - domain.length - 1;
  58171. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  58172. }
  58173. // Exports
  58174. followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
  58175. followRedirects$1.exports.wrap = wrap;
  58176. var followRedirectsExports = followRedirects$1.exports;
  58177. var httpNative = require$$1$1,
  58178. httpsNative = require$$1$2,
  58179. web_o = webOutgoing,
  58180. common$1 = common$3,
  58181. followRedirects = followRedirectsExports;
  58182. web_o = Object.keys(web_o).map(function(pass) {
  58183. return web_o[pass];
  58184. });
  58185. var nativeAgents = { http: httpNative, https: httpsNative };
  58186. /*!
  58187. * Array of passes.
  58188. *
  58189. * A `pass` is just a function that is executed on `req, res, options`
  58190. * so that you can easily add new checks while still keeping the base
  58191. * flexible.
  58192. */
  58193. var webIncoming = {
  58194. /**
  58195. * Sets `content-length` to '0' if request is of DELETE type.
  58196. *
  58197. * @param {ClientRequest} Req Request object
  58198. * @param {IncomingMessage} Res Response object
  58199. * @param {Object} Options Config object passed to the proxy
  58200. *
  58201. * @api private
  58202. */
  58203. deleteLength: function deleteLength(req, res, options) {
  58204. if((req.method === 'DELETE' || req.method === 'OPTIONS')
  58205. && !req.headers['content-length']) {
  58206. req.headers['content-length'] = '0';
  58207. delete req.headers['transfer-encoding'];
  58208. }
  58209. },
  58210. /**
  58211. * Sets timeout in request socket if it was specified in options.
  58212. *
  58213. * @param {ClientRequest} Req Request object
  58214. * @param {IncomingMessage} Res Response object
  58215. * @param {Object} Options Config object passed to the proxy
  58216. *
  58217. * @api private
  58218. */
  58219. timeout: function timeout(req, res, options) {
  58220. if(options.timeout) {
  58221. req.socket.setTimeout(options.timeout);
  58222. }
  58223. },
  58224. /**
  58225. * Sets `x-forwarded-*` headers if specified in config.
  58226. *
  58227. * @param {ClientRequest} Req Request object
  58228. * @param {IncomingMessage} Res Response object
  58229. * @param {Object} Options Config object passed to the proxy
  58230. *
  58231. * @api private
  58232. */
  58233. XHeaders: function XHeaders(req, res, options) {
  58234. if(!options.xfwd) return;
  58235. var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req);
  58236. var values = {
  58237. for : req.connection.remoteAddress || req.socket.remoteAddress,
  58238. port : common$1.getPort(req),
  58239. proto: encrypted ? 'https' : 'http'
  58240. };
  58241. ['for', 'port', 'proto'].forEach(function(header) {
  58242. req.headers['x-forwarded-' + header] =
  58243. (req.headers['x-forwarded-' + header] || '') +
  58244. (req.headers['x-forwarded-' + header] ? ',' : '') +
  58245. values[header];
  58246. });
  58247. req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
  58248. },
  58249. /**
  58250. * Does the actual proxying. If `forward` is enabled fires up
  58251. * a ForwardStream, same happens for ProxyStream. The request
  58252. * just dies otherwise.
  58253. *
  58254. * @param {ClientRequest} Req Request object
  58255. * @param {IncomingMessage} Res Response object
  58256. * @param {Object} Options Config object passed to the proxy
  58257. *
  58258. * @api private
  58259. */
  58260. stream: function stream(req, res, options, _, server, clb) {
  58261. // And we begin!
  58262. server.emit('start', req, res, options.target || options.forward);
  58263. var agents = options.followRedirects ? followRedirects : nativeAgents;
  58264. var http = agents.http;
  58265. var https = agents.https;
  58266. if(options.forward) {
  58267. // If forward enable, so just pipe the request
  58268. var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
  58269. common$1.setupOutgoing(options.ssl || {}, options, req, 'forward')
  58270. );
  58271. // error handler (e.g. ECONNRESET, ECONNREFUSED)
  58272. // Handle errors on incoming request as well as it makes sense to
  58273. var forwardError = createErrorHandler(forwardReq, options.forward);
  58274. req.on('error', forwardError);
  58275. forwardReq.on('error', forwardError);
  58276. (options.buffer || req).pipe(forwardReq);
  58277. if(!options.target) { return res.end(); }
  58278. }
  58279. // Request initalization
  58280. var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
  58281. common$1.setupOutgoing(options.ssl || {}, options, req)
  58282. );
  58283. // Enable developers to modify the proxyReq before headers are sent
  58284. proxyReq.on('socket', function(socket) {
  58285. if(server && !proxyReq.getHeader('expect')) {
  58286. server.emit('proxyReq', proxyReq, req, res, options);
  58287. }
  58288. });
  58289. // allow outgoing socket to timeout so that we could
  58290. // show an error page at the initial request
  58291. if(options.proxyTimeout) {
  58292. proxyReq.setTimeout(options.proxyTimeout, function() {
  58293. proxyReq.abort();
  58294. });
  58295. }
  58296. // Ensure we abort proxy if request is aborted
  58297. req.on('aborted', function () {
  58298. proxyReq.abort();
  58299. });
  58300. // handle errors in proxy and incoming request, just like for forward proxy
  58301. var proxyError = createErrorHandler(proxyReq, options.target);
  58302. req.on('error', proxyError);
  58303. proxyReq.on('error', proxyError);
  58304. function createErrorHandler(proxyReq, url) {
  58305. return function proxyError(err) {
  58306. if (req.socket.destroyed && err.code === 'ECONNRESET') {
  58307. server.emit('econnreset', err, req, res, url);
  58308. return proxyReq.abort();
  58309. }
  58310. if (clb) {
  58311. clb(err, req, res, url);
  58312. } else {
  58313. server.emit('error', err, req, res, url);
  58314. }
  58315. }
  58316. }
  58317. (options.buffer || req).pipe(proxyReq);
  58318. proxyReq.on('response', function(proxyRes) {
  58319. if(server) { server.emit('proxyRes', proxyRes, req, res); }
  58320. if(!res.headersSent && !options.selfHandleResponse) {
  58321. for(var i=0; i < web_o.length; i++) {
  58322. if(web_o[i](req, res, proxyRes, options)) { break; }
  58323. }
  58324. }
  58325. if (!res.finished) {
  58326. // Allow us to listen when the proxy has completed
  58327. proxyRes.on('end', function () {
  58328. if (server) server.emit('end', req, res, proxyRes);
  58329. });
  58330. // We pipe to the response unless its expected to be handled by the user
  58331. if (!options.selfHandleResponse) proxyRes.pipe(res);
  58332. } else {
  58333. if (server) server.emit('end', req, res, proxyRes);
  58334. }
  58335. });
  58336. }
  58337. };
  58338. var http = require$$1$1,
  58339. https = require$$1$2,
  58340. common = common$3;
  58341. /*!
  58342. * Array of passes.
  58343. *
  58344. * A `pass` is just a function that is executed on `req, socket, options`
  58345. * so that you can easily add new checks while still keeping the base
  58346. * flexible.
  58347. */
  58348. /*
  58349. * Websockets Passes
  58350. *
  58351. */
  58352. var wsIncoming = {
  58353. /**
  58354. * WebSocket requests must have the `GET` method and
  58355. * the `upgrade:websocket` header
  58356. *
  58357. * @param {ClientRequest} Req Request object
  58358. * @param {Socket} Websocket
  58359. *
  58360. * @api private
  58361. */
  58362. checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
  58363. if (req.method !== 'GET' || !req.headers.upgrade) {
  58364. socket.destroy();
  58365. return true;
  58366. }
  58367. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  58368. socket.destroy();
  58369. return true;
  58370. }
  58371. },
  58372. /**
  58373. * Sets `x-forwarded-*` headers if specified in config.
  58374. *
  58375. * @param {ClientRequest} Req Request object
  58376. * @param {Socket} Websocket
  58377. * @param {Object} Options Config object passed to the proxy
  58378. *
  58379. * @api private
  58380. */
  58381. XHeaders : function XHeaders(req, socket, options) {
  58382. if(!options.xfwd) return;
  58383. var values = {
  58384. for : req.connection.remoteAddress || req.socket.remoteAddress,
  58385. port : common.getPort(req),
  58386. proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
  58387. };
  58388. ['for', 'port', 'proto'].forEach(function(header) {
  58389. req.headers['x-forwarded-' + header] =
  58390. (req.headers['x-forwarded-' + header] || '') +
  58391. (req.headers['x-forwarded-' + header] ? ',' : '') +
  58392. values[header];
  58393. });
  58394. },
  58395. /**
  58396. * Does the actual proxying. Make the request and upgrade it
  58397. * send the Switching Protocols request and pipe the sockets.
  58398. *
  58399. * @param {ClientRequest} Req Request object
  58400. * @param {Socket} Websocket
  58401. * @param {Object} Options Config object passed to the proxy
  58402. *
  58403. * @api private
  58404. */
  58405. stream : function stream(req, socket, options, head, server, clb) {
  58406. var createHttpHeader = function(line, headers) {
  58407. return Object.keys(headers).reduce(function (head, key) {
  58408. var value = headers[key];
  58409. if (!Array.isArray(value)) {
  58410. head.push(key + ': ' + value);
  58411. return head;
  58412. }
  58413. for (var i = 0; i < value.length; i++) {
  58414. head.push(key + ': ' + value[i]);
  58415. }
  58416. return head;
  58417. }, [line])
  58418. .join('\r\n') + '\r\n\r\n';
  58419. };
  58420. common.setupSocket(socket);
  58421. if (head && head.length) socket.unshift(head);
  58422. var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
  58423. common.setupOutgoing(options.ssl || {}, options, req)
  58424. );
  58425. // Enable developers to modify the proxyReq before headers are sent
  58426. if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
  58427. // Error Handler
  58428. proxyReq.on('error', onOutgoingError);
  58429. proxyReq.on('response', function (res) {
  58430. // if upgrade event isn't going to happen, close the socket
  58431. if (!res.upgrade) {
  58432. socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
  58433. res.pipe(socket);
  58434. }
  58435. });
  58436. proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
  58437. proxySocket.on('error', onOutgoingError);
  58438. // Allow us to listen when the websocket has completed
  58439. proxySocket.on('end', function () {
  58440. server.emit('close', proxyRes, proxySocket, proxyHead);
  58441. });
  58442. // The pipe below will end proxySocket if socket closes cleanly, but not
  58443. // if it errors (eg, vanishes from the net and starts returning
  58444. // EHOSTUNREACH). We need to do that explicitly.
  58445. socket.on('error', function () {
  58446. proxySocket.end();
  58447. });
  58448. common.setupSocket(proxySocket);
  58449. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  58450. //
  58451. // Remark: Handle writing the headers to the socket when switching protocols
  58452. // Also handles when a header is an array
  58453. //
  58454. socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
  58455. proxySocket.pipe(socket).pipe(proxySocket);
  58456. server.emit('open', proxySocket);
  58457. server.emit('proxySocket', proxySocket); //DEPRECATED.
  58458. });
  58459. return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
  58460. function onOutgoingError(err) {
  58461. if (clb) {
  58462. clb(err, req, socket);
  58463. } else {
  58464. server.emit('error', err, req, socket);
  58465. }
  58466. socket.end();
  58467. }
  58468. }
  58469. };
  58470. (function (module) {
  58471. var httpProxy = module.exports,
  58472. extend = require$$0$6._extend,
  58473. parse_url = require$$0$9.parse,
  58474. EE3 = eventemitter3Exports,
  58475. http = require$$1$1,
  58476. https = require$$1$2,
  58477. web = webIncoming,
  58478. ws = wsIncoming;
  58479. httpProxy.Server = ProxyServer;
  58480. /**
  58481. * Returns a function that creates the loader for
  58482. * either `ws` or `web`'s passes.
  58483. *
  58484. * Examples:
  58485. *
  58486. * httpProxy.createRightProxy('ws')
  58487. * // => [Function]
  58488. *
  58489. * @param {String} Type Either 'ws' or 'web'
  58490. * @return {Function} Loader Function that when called returns an iterator for the right passes
  58491. *
  58492. * @api private
  58493. */
  58494. function createRightProxy(type) {
  58495. return function(options) {
  58496. return function(req, res /*, [head], [opts] */) {
  58497. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  58498. args = [].slice.call(arguments),
  58499. cntr = args.length - 1,
  58500. head, cbl;
  58501. /* optional args parse begin */
  58502. if(typeof args[cntr] === 'function') {
  58503. cbl = args[cntr];
  58504. cntr--;
  58505. }
  58506. var requestOptions = options;
  58507. if(
  58508. !(args[cntr] instanceof Buffer) &&
  58509. args[cntr] !== res
  58510. ) {
  58511. //Copy global options
  58512. requestOptions = extend({}, options);
  58513. //Overwrite with request options
  58514. extend(requestOptions, args[cntr]);
  58515. cntr--;
  58516. }
  58517. if(args[cntr] instanceof Buffer) {
  58518. head = args[cntr];
  58519. }
  58520. /* optional args parse end */
  58521. ['target', 'forward'].forEach(function(e) {
  58522. if (typeof requestOptions[e] === 'string')
  58523. requestOptions[e] = parse_url(requestOptions[e]);
  58524. });
  58525. if (!requestOptions.target && !requestOptions.forward) {
  58526. return this.emit('error', new Error('Must provide a proper URL as target'));
  58527. }
  58528. for(var i=0; i < passes.length; i++) {
  58529. /**
  58530. * Call of passes functions
  58531. * pass(req, res, options, head)
  58532. *
  58533. * In WebSockets case the `res` variable
  58534. * refer to the connection socket
  58535. * pass(req, socket, options, head)
  58536. */
  58537. if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
  58538. break;
  58539. }
  58540. }
  58541. };
  58542. };
  58543. }
  58544. httpProxy.createRightProxy = createRightProxy;
  58545. function ProxyServer(options) {
  58546. EE3.call(this);
  58547. options = options || {};
  58548. options.prependPath = options.prependPath === false ? false : true;
  58549. this.web = this.proxyRequest = createRightProxy('web')(options);
  58550. this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
  58551. this.options = options;
  58552. this.webPasses = Object.keys(web).map(function(pass) {
  58553. return web[pass];
  58554. });
  58555. this.wsPasses = Object.keys(ws).map(function(pass) {
  58556. return ws[pass];
  58557. });
  58558. this.on('error', this.onError, this);
  58559. }
  58560. require$$0$6.inherits(ProxyServer, EE3);
  58561. ProxyServer.prototype.onError = function (err) {
  58562. //
  58563. // Remark: Replicate node core behavior using EE3
  58564. // so we force people to handle their own errors
  58565. //
  58566. if(this.listeners('error').length === 1) {
  58567. throw err;
  58568. }
  58569. };
  58570. ProxyServer.prototype.listen = function(port, hostname) {
  58571. var self = this,
  58572. closure = function(req, res) { self.web(req, res); };
  58573. this._server = this.options.ssl ?
  58574. https.createServer(this.options.ssl, closure) :
  58575. http.createServer(closure);
  58576. if(this.options.ws) {
  58577. this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
  58578. }
  58579. this._server.listen(port, hostname);
  58580. return this;
  58581. };
  58582. ProxyServer.prototype.close = function(callback) {
  58583. var self = this;
  58584. if (this._server) {
  58585. this._server.close(done);
  58586. }
  58587. // Wrap callback to nullify server after all open connections are closed.
  58588. function done() {
  58589. self._server = null;
  58590. if (callback) {
  58591. callback.apply(null, arguments);
  58592. }
  58593. } };
  58594. ProxyServer.prototype.before = function(type, passName, callback) {
  58595. if (type !== 'ws' && type !== 'web') {
  58596. throw new Error('type must be `web` or `ws`');
  58597. }
  58598. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  58599. i = false;
  58600. passes.forEach(function(v, idx) {
  58601. if(v.name === passName) i = idx;
  58602. });
  58603. if(i === false) throw new Error('No such pass');
  58604. passes.splice(i, 0, callback);
  58605. };
  58606. ProxyServer.prototype.after = function(type, passName, callback) {
  58607. if (type !== 'ws' && type !== 'web') {
  58608. throw new Error('type must be `web` or `ws`');
  58609. }
  58610. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  58611. i = false;
  58612. passes.forEach(function(v, idx) {
  58613. if(v.name === passName) i = idx;
  58614. });
  58615. if(i === false) throw new Error('No such pass');
  58616. passes.splice(i++, 0, callback);
  58617. };
  58618. } (httpProxy$3));
  58619. var httpProxyExports = httpProxy$3.exports;
  58620. // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
  58621. var ProxyServer = httpProxyExports.Server;
  58622. /**
  58623. * Creates the proxy server.
  58624. *
  58625. * Examples:
  58626. *
  58627. * httpProxy.createProxyServer({ .. }, 8000)
  58628. * // => '{ web: [Function], ws: [Function] ... }'
  58629. *
  58630. * @param {Object} Options Config object passed to the proxy
  58631. *
  58632. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  58633. *
  58634. * @api public
  58635. */
  58636. function createProxyServer(options) {
  58637. /*
  58638. * `options` is needed and it must have the following layout:
  58639. *
  58640. * {
  58641. * target : <url string to be parsed with the url module>
  58642. * forward: <url string to be parsed with the url module>
  58643. * agent : <object to be passed to http(s).request>
  58644. * ssl : <object to be passed to https.createServer()>
  58645. * ws : <true/false, if you want to proxy websockets>
  58646. * xfwd : <true/false, adds x-forward headers>
  58647. * secure : <true/false, verify SSL certificate>
  58648. * toProxy: <true/false, explicitly specify if we are proxying to another proxy>
  58649. * prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
  58650. * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
  58651. * localAddress : <Local interface string to bind for outgoing connections>
  58652. * changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
  58653. * preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
  58654. * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
  58655. * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
  58656. * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
  58657. * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
  58658. * }
  58659. *
  58660. * NOTE: `options.ws` and `options.ssl` are optional.
  58661. * `options.target and `options.forward` cannot be
  58662. * both missing
  58663. * }
  58664. */
  58665. return new ProxyServer(options);
  58666. }
  58667. ProxyServer.createProxyServer = createProxyServer;
  58668. ProxyServer.createServer = createProxyServer;
  58669. ProxyServer.createProxy = createProxyServer;
  58670. /**
  58671. * Export the proxy "Server" as the main export.
  58672. */
  58673. var httpProxy$2 = ProxyServer;
  58674. /*!
  58675. * Caron dimonio, con occhi di bragia
  58676. * loro accennando, tutte le raccoglie;
  58677. * batte col remo qualunque s’adagia
  58678. *
  58679. * Charon the demon, with the eyes of glede,
  58680. * Beckoning to them, collects them all together,
  58681. * Beats with his oar whoever lags behind
  58682. *
  58683. * Dante - The Divine Comedy (Canto III)
  58684. */
  58685. var httpProxy = httpProxy$2;
  58686. var httpProxy$1 = /*@__PURE__*/getDefaultExportFromCjs(httpProxy);
  58687. const debug$1 = createDebugger('vite:proxy');
  58688. function proxyMiddleware(httpServer, options, config) {
  58689. // lazy require only when proxy is used
  58690. const proxies = {};
  58691. Object.keys(options).forEach((context) => {
  58692. let opts = options[context];
  58693. if (!opts) {
  58694. return;
  58695. }
  58696. if (typeof opts === 'string') {
  58697. opts = { target: opts, changeOrigin: true };
  58698. }
  58699. const proxy = httpProxy$1.createProxyServer(opts);
  58700. if (opts.configure) {
  58701. opts.configure(proxy, opts);
  58702. }
  58703. proxy.on('error', (err, req, originalRes) => {
  58704. // When it is ws proxy, res is net.Socket
  58705. // originalRes can be falsy if the proxy itself errored
  58706. const res = originalRes;
  58707. if (!res) {
  58708. config.logger.error(`${colors$1.red(`http proxy error: ${err.message}`)}\n${err.stack}`, {
  58709. timestamp: true,
  58710. error: err,
  58711. });
  58712. }
  58713. else if ('req' in res) {
  58714. config.logger.error(`${colors$1.red(`http proxy error at ${originalRes.req.url}:`)}\n${err.stack}`, {
  58715. timestamp: true,
  58716. error: err,
  58717. });
  58718. if (!res.headersSent && !res.writableEnded) {
  58719. res
  58720. .writeHead(500, {
  58721. 'Content-Type': 'text/plain',
  58722. })
  58723. .end();
  58724. }
  58725. }
  58726. else {
  58727. config.logger.error(`${colors$1.red(`ws proxy error:`)}\n${err.stack}`, {
  58728. timestamp: true,
  58729. error: err,
  58730. });
  58731. res.end();
  58732. }
  58733. });
  58734. proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => {
  58735. socket.on('error', (err) => {
  58736. config.logger.error(`${colors$1.red(`ws proxy socket error:`)}\n${err.stack}`, {
  58737. timestamp: true,
  58738. error: err,
  58739. });
  58740. });
  58741. });
  58742. // https://github.com/http-party/node-http-proxy/issues/1520#issue-877626125
  58743. // https://github.com/chimurai/http-proxy-middleware/blob/cd58f962aec22c925b7df5140502978da8f87d5f/src/plugins/default/debug-proxy-errors-plugin.ts#L25-L37
  58744. proxy.on('proxyRes', (proxyRes, req, res) => {
  58745. res.on('close', () => {
  58746. if (!res.writableEnded) {
  58747. debug$1?.('destroying proxyRes in proxyRes close event');
  58748. proxyRes.destroy();
  58749. }
  58750. });
  58751. });
  58752. // clone before saving because http-proxy mutates the options
  58753. proxies[context] = [proxy, { ...opts }];
  58754. });
  58755. if (httpServer) {
  58756. httpServer.on('upgrade', (req, socket, head) => {
  58757. const url = req.url;
  58758. for (const context in proxies) {
  58759. if (doesProxyContextMatchUrl(context, url)) {
  58760. const [proxy, opts] = proxies[context];
  58761. if (opts.ws ||
  58762. opts.target?.toString().startsWith('ws:') ||
  58763. opts.target?.toString().startsWith('wss:')) {
  58764. if (opts.rewrite) {
  58765. req.url = opts.rewrite(url);
  58766. }
  58767. debug$1?.(`${req.url} -> ws ${opts.target}`);
  58768. proxy.ws(req, socket, head);
  58769. return;
  58770. }
  58771. }
  58772. }
  58773. });
  58774. }
  58775. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  58776. return function viteProxyMiddleware(req, res, next) {
  58777. const url = req.url;
  58778. for (const context in proxies) {
  58779. if (doesProxyContextMatchUrl(context, url)) {
  58780. const [proxy, opts] = proxies[context];
  58781. const options = {};
  58782. if (opts.bypass) {
  58783. const bypassResult = opts.bypass(req, res, opts);
  58784. if (typeof bypassResult === 'string') {
  58785. req.url = bypassResult;
  58786. debug$1?.(`bypass: ${req.url} -> ${bypassResult}`);
  58787. return next();
  58788. }
  58789. else if (bypassResult === false) {
  58790. debug$1?.(`bypass: ${req.url} -> 404`);
  58791. return res.end(404);
  58792. }
  58793. }
  58794. debug$1?.(`${req.url} -> ${opts.target || opts.forward}`);
  58795. if (opts.rewrite) {
  58796. req.url = opts.rewrite(req.url);
  58797. }
  58798. proxy.web(req, res, options);
  58799. return;
  58800. }
  58801. }
  58802. next();
  58803. };
  58804. }
  58805. function doesProxyContextMatchUrl(context, url) {
  58806. return ((context[0] === '^' && new RegExp(context).test(url)) ||
  58807. url.startsWith(context));
  58808. }
  58809. var lib = {exports: {}};
  58810. (function (module, exports) {
  58811. var url = require$$0$9;
  58812. module.exports = function historyApiFallback(options) {
  58813. options = options || {};
  58814. var logger = getLogger(options);
  58815. return function(req, res, next) {
  58816. var headers = req.headers;
  58817. if (req.method !== 'GET' && req.method !== 'HEAD') {
  58818. logger(
  58819. 'Not rewriting',
  58820. req.method,
  58821. req.url,
  58822. 'because the method is not GET or HEAD.'
  58823. );
  58824. return next();
  58825. } else if (!headers || typeof headers.accept !== 'string') {
  58826. logger(
  58827. 'Not rewriting',
  58828. req.method,
  58829. req.url,
  58830. 'because the client did not send an HTTP accept header.'
  58831. );
  58832. return next();
  58833. } else if (headers.accept.indexOf('application/json') === 0) {
  58834. logger(
  58835. 'Not rewriting',
  58836. req.method,
  58837. req.url,
  58838. 'because the client prefers JSON.'
  58839. );
  58840. return next();
  58841. } else if (!acceptsHtml(headers.accept, options)) {
  58842. logger(
  58843. 'Not rewriting',
  58844. req.method,
  58845. req.url,
  58846. 'because the client does not accept HTML.'
  58847. );
  58848. return next();
  58849. }
  58850. var parsedUrl = url.parse(req.url);
  58851. var rewriteTarget;
  58852. options.rewrites = options.rewrites || [];
  58853. for (var i = 0; i < options.rewrites.length; i++) {
  58854. var rewrite = options.rewrites[i];
  58855. var match = parsedUrl.pathname.match(rewrite.from);
  58856. if (match !== null) {
  58857. rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req);
  58858. if(rewriteTarget.charAt(0) !== '/') {
  58859. logger(
  58860. 'We recommend using an absolute path for the rewrite target.',
  58861. 'Received a non-absolute rewrite target',
  58862. rewriteTarget,
  58863. 'for URL',
  58864. req.url
  58865. );
  58866. }
  58867. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  58868. req.url = rewriteTarget;
  58869. return next();
  58870. }
  58871. }
  58872. var pathname = parsedUrl.pathname;
  58873. if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') &&
  58874. options.disableDotRule !== true) {
  58875. logger(
  58876. 'Not rewriting',
  58877. req.method,
  58878. req.url,
  58879. 'because the path includes a dot (.) character.'
  58880. );
  58881. return next();
  58882. }
  58883. rewriteTarget = options.index || '/index.html';
  58884. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  58885. req.url = rewriteTarget;
  58886. next();
  58887. };
  58888. };
  58889. function evaluateRewriteRule(parsedUrl, match, rule, req) {
  58890. if (typeof rule === 'string') {
  58891. return rule;
  58892. } else if (typeof rule !== 'function') {
  58893. throw new Error('Rewrite rule can only be of type string or function.');
  58894. }
  58895. return rule({
  58896. parsedUrl: parsedUrl,
  58897. match: match,
  58898. request: req
  58899. });
  58900. }
  58901. function acceptsHtml(header, options) {
  58902. options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*'];
  58903. for (var i = 0; i < options.htmlAcceptHeaders.length; i++) {
  58904. if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) {
  58905. return true;
  58906. }
  58907. }
  58908. return false;
  58909. }
  58910. function getLogger(options) {
  58911. if (options && options.logger) {
  58912. return options.logger;
  58913. } else if (options && options.verbose) {
  58914. // eslint-disable-next-line no-console
  58915. return console.log.bind(console);
  58916. }
  58917. return function(){};
  58918. }
  58919. } (lib));
  58920. var libExports = lib.exports;
  58921. var history = /*@__PURE__*/getDefaultExportFromCjs(libExports);
  58922. function htmlFallbackMiddleware(root, spaFallback) {
  58923. const historyHtmlFallbackMiddleware = history({
  58924. logger: createDebugger('vite:html-fallback'),
  58925. // support /dir/ without explicit index.html
  58926. rewrites: [
  58927. {
  58928. from: /\/$/,
  58929. to({ parsedUrl, request }) {
  58930. const rewritten = decodeURIComponent(parsedUrl.pathname) + 'index.html';
  58931. if (fs$l.existsSync(path$o.join(root, rewritten))) {
  58932. return rewritten;
  58933. }
  58934. return spaFallback ? `/index.html` : request.url;
  58935. },
  58936. },
  58937. ],
  58938. });
  58939. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  58940. return function viteHtmlFallbackMiddleware(req, res, next) {
  58941. return historyHtmlFallbackMiddleware(req, res, next);
  58942. };
  58943. }
  58944. const debugCache = createDebugger('vite:cache');
  58945. const knownIgnoreList = new Set(['/', '/favicon.ico']);
  58946. const trailingQuerySeparatorsRE = /[?&]+$/;
  58947. // TODO: consolidate this regex pattern with the url, raw, and inline checks in plugins
  58948. const urlRE = /[?&]url\b/;
  58949. const rawRE = /[?&]raw\b/;
  58950. const inlineRE = /[?&]inline\b/;
  58951. const svgRE = /\.svg\b/;
  58952. function deniedServingAccessForTransform(url, server, res, next) {
  58953. if (rawRE.test(url) ||
  58954. urlRE.test(url) ||
  58955. inlineRE.test(url) ||
  58956. svgRE.test(url)) {
  58957. const servingAccessResult = checkServingAccess(url, server);
  58958. if (servingAccessResult === 'denied') {
  58959. respondWithAccessDenied(url, server, res);
  58960. return true;
  58961. }
  58962. if (servingAccessResult === 'fallback') {
  58963. next();
  58964. return true;
  58965. }
  58966. }
  58967. return false;
  58968. }
  58969. function transformMiddleware(server) {
  58970. const { config: { root, logger }, moduleGraph, } = server;
  58971. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  58972. return async function viteTransformMiddleware(req, res, next) {
  58973. if (req.method !== 'GET' || knownIgnoreList.has(req.url)) {
  58974. return next();
  58975. }
  58976. let url;
  58977. try {
  58978. url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, '\0');
  58979. }
  58980. catch (e) {
  58981. return next(e);
  58982. }
  58983. const withoutQuery = cleanUrl(url);
  58984. try {
  58985. const isSourceMap = withoutQuery.endsWith('.map');
  58986. // since we generate source map references, handle those requests here
  58987. if (isSourceMap) {
  58988. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr
  58989. if (depsOptimizer?.isOptimizedDepUrl(url)) {
  58990. // If the browser is requesting a source map for an optimized dep, it
  58991. // means that the dependency has already been pre-bundled and loaded
  58992. const sourcemapPath = url.startsWith(FS_PREFIX)
  58993. ? fsPathFromId(url)
  58994. : normalizePath$3(path$o.resolve(root, url.slice(1)));
  58995. try {
  58996. const map = JSON.parse(await fsp.readFile(sourcemapPath, 'utf-8'));
  58997. applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, logger);
  58998. return send$2(req, res, JSON.stringify(map), 'json', {
  58999. headers: server.config.server.headers,
  59000. });
  59001. }
  59002. catch (e) {
  59003. // Outdated source map request for optimized deps, this isn't an error
  59004. // but part of the normal flow when re-optimizing after missing deps
  59005. // Send back an empty source map so the browser doesn't issue warnings
  59006. const dummySourceMap = {
  59007. version: 3,
  59008. file: sourcemapPath.replace(/\.map$/, ''),
  59009. sources: [],
  59010. sourcesContent: [],
  59011. names: [],
  59012. mappings: ';;;;;;;;;',
  59013. };
  59014. return send$2(req, res, JSON.stringify(dummySourceMap), 'json', {
  59015. cacheControl: 'no-cache',
  59016. headers: server.config.server.headers,
  59017. });
  59018. }
  59019. }
  59020. else {
  59021. const originalUrl = url.replace(/\.map($|\?)/, '$1');
  59022. const map = (await moduleGraph.getModuleByUrl(originalUrl, false))
  59023. ?.transformResult?.map;
  59024. if (map) {
  59025. return send$2(req, res, JSON.stringify(map), 'json', {
  59026. headers: server.config.server.headers,
  59027. });
  59028. }
  59029. else {
  59030. return next();
  59031. }
  59032. }
  59033. }
  59034. // check if public dir is inside root dir
  59035. const publicDir = normalizePath$3(server.config.publicDir);
  59036. const rootDir = normalizePath$3(server.config.root);
  59037. if (publicDir.startsWith(withTrailingSlash(rootDir))) {
  59038. const publicPath = `${publicDir.slice(rootDir.length)}/`;
  59039. // warn explicit public paths
  59040. if (url.startsWith(withTrailingSlash(publicPath))) {
  59041. let warning;
  59042. if (isImportRequest(url)) {
  59043. const rawUrl = removeImportQuery(url);
  59044. if (urlRE.test(url)) {
  59045. warning =
  59046. `Assets in the public directory are served at the root path.\n` +
  59047. `Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan(rawUrl.replace(publicPath, '/'))}.`;
  59048. }
  59049. else {
  59050. warning =
  59051. 'Assets in public directory cannot be imported from JavaScript.\n' +
  59052. `If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan(rawUrl.replace(publicPath, '/src/'))} instead of ${colors$1.cyan(rawUrl)}.\n` +
  59053. `If you intend to use the URL of that asset, use ${colors$1.cyan(injectQuery(rawUrl.replace(publicPath, '/'), 'url'))}.`;
  59054. }
  59055. }
  59056. else {
  59057. warning =
  59058. `files in the public directory are served at the root path.\n` +
  59059. `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`;
  59060. }
  59061. logger.warn(colors$1.yellow(warning));
  59062. }
  59063. }
  59064. const urlWithoutTrailingQuerySeparators = url.replace(trailingQuerySeparatorsRE, '');
  59065. if (deniedServingAccessForTransform(urlWithoutTrailingQuerySeparators, server, res, next)) {
  59066. return;
  59067. }
  59068. if (isJSRequest(url) ||
  59069. isImportRequest(url) ||
  59070. isCSSRequest(url) ||
  59071. isHTMLProxy(url)) {
  59072. // strip ?import
  59073. url = removeImportQuery(url);
  59074. // Strip valid id prefix. This is prepended to resolved Ids that are
  59075. // not valid browser import specifiers by the importAnalysis plugin.
  59076. url = unwrapId(url);
  59077. // for CSS, we need to differentiate between normal CSS requests and
  59078. // imports
  59079. if (isCSSRequest(url) &&
  59080. !isDirectRequest(url) &&
  59081. req.headers.accept?.includes('text/css')) {
  59082. url = injectQuery(url, 'direct');
  59083. }
  59084. // check if we can return 304 early
  59085. const ifNoneMatch = req.headers['if-none-match'];
  59086. if (ifNoneMatch &&
  59087. (await moduleGraph.getModuleByUrl(url, false))?.transformResult
  59088. ?.etag === ifNoneMatch) {
  59089. debugCache?.(`[304] ${prettifyUrl(url, root)}`);
  59090. res.statusCode = 304;
  59091. return res.end();
  59092. }
  59093. // resolve, load and transform using the plugin container
  59094. const result = await transformRequest(url, server, {
  59095. html: req.headers.accept?.includes('text/html'),
  59096. allowId(id) {
  59097. return !deniedServingAccessForTransform(id, server, res, next);
  59098. },
  59099. });
  59100. if (result) {
  59101. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr
  59102. const type = isDirectCSSRequest(url) ? 'css' : 'js';
  59103. const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
  59104. return send$2(req, res, result.code, type, {
  59105. etag: result.etag,
  59106. // allow browser to cache npm deps!
  59107. cacheControl: isDep ? 'max-age=31536000,immutable' : 'no-cache',
  59108. headers: server.config.server.headers,
  59109. map: result.map,
  59110. });
  59111. }
  59112. }
  59113. }
  59114. catch (e) {
  59115. if (e?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
  59116. // Skip if response has already been sent
  59117. if (!res.writableEnded) {
  59118. res.statusCode = 504; // status code request timeout
  59119. res.statusMessage = 'Optimize Deps Processing Error';
  59120. res.end();
  59121. }
  59122. // This timeout is unexpected
  59123. logger.error(e.message);
  59124. return;
  59125. }
  59126. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) {
  59127. // Skip if response has already been sent
  59128. if (!res.writableEnded) {
  59129. res.statusCode = 504; // status code request timeout
  59130. res.statusMessage = 'Outdated Optimize Dep';
  59131. res.end();
  59132. }
  59133. // We don't need to log an error in this case, the request
  59134. // is outdated because new dependencies were discovered and
  59135. // the new pre-bundle dependencies have changed.
  59136. // A full-page reload has been issued, and these old requests
  59137. // can't be properly fulfilled. This isn't an unexpected
  59138. // error but a normal part of the missing deps discovery flow
  59139. return;
  59140. }
  59141. if (e?.code === ERR_CLOSED_SERVER) {
  59142. // Skip if response has already been sent
  59143. if (!res.writableEnded) {
  59144. res.statusCode = 504; // status code request timeout
  59145. res.statusMessage = 'Outdated Request';
  59146. res.end();
  59147. }
  59148. // We don't need to log an error in this case, the request
  59149. // is outdated because new dependencies were discovered and
  59150. // the new pre-bundle dependencies have changed.
  59151. // A full-page reload has been issued, and these old requests
  59152. // can't be properly fulfilled. This isn't an unexpected
  59153. // error but a normal part of the missing deps discovery flow
  59154. return;
  59155. }
  59156. if (e?.code === ERR_LOAD_URL) {
  59157. // Let other middleware handle if we can't load the url via transformRequest
  59158. return next();
  59159. }
  59160. if (e?.code === ERR_DENIED_ID) {
  59161. // next() is called in ensureServingAccess
  59162. return;
  59163. }
  59164. return next(e);
  59165. }
  59166. next();
  59167. };
  59168. }
  59169. function createDevHtmlTransformFn(server) {
  59170. const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(server.config.plugins);
  59171. return (url, html, originalUrl) => {
  59172. return applyHtmlTransforms(html, [
  59173. preImportMapHook(server.config),
  59174. ...preHooks,
  59175. htmlEnvHook(server.config),
  59176. devHtmlHook,
  59177. ...normalHooks,
  59178. ...postHooks,
  59179. postImportMapHook(),
  59180. ], {
  59181. path: url,
  59182. filename: getHtmlFilename(url, server),
  59183. server,
  59184. originalUrl,
  59185. });
  59186. };
  59187. }
  59188. function getHtmlFilename(url, server) {
  59189. if (url.startsWith(FS_PREFIX)) {
  59190. return decodeURIComponent(fsPathFromId(url));
  59191. }
  59192. else {
  59193. return decodeURIComponent(normalizePath$3(path$o.join(server.config.root, url.slice(1))));
  59194. }
  59195. }
  59196. function shouldPreTransform(url, config) {
  59197. return (!checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url)));
  59198. }
  59199. const processNodeUrl = (attr, sourceCodeLocation, s, config, htmlPath, originalUrl, server) => {
  59200. let url = attr.value || '';
  59201. if (server?.moduleGraph) {
  59202. const mod = server.moduleGraph.urlToModuleMap.get(url);
  59203. if (mod && mod.lastHMRTimestamp > 0) {
  59204. url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  59205. }
  59206. }
  59207. const devBase = config.base;
  59208. if (url[0] === '/' && url[1] !== '/') {
  59209. // prefix with base (dev only, base is never relative)
  59210. const fullUrl = path$o.posix.join(devBase, url);
  59211. overwriteAttrValue(s, sourceCodeLocation, fullUrl);
  59212. if (server && shouldPreTransform(url, config)) {
  59213. preTransformRequest(server, fullUrl, devBase);
  59214. }
  59215. }
  59216. else if (url[0] === '.' &&
  59217. originalUrl &&
  59218. originalUrl !== '/' &&
  59219. htmlPath === '/index.html') {
  59220. // prefix with base (dev only, base is never relative)
  59221. const replacer = (url) => {
  59222. const fullUrl = path$o.posix.join(devBase, url);
  59223. if (server && shouldPreTransform(url, config)) {
  59224. preTransformRequest(server, fullUrl, devBase);
  59225. }
  59226. return fullUrl;
  59227. };
  59228. // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
  59229. // path will add `/a/` prefix, it will caused 404.
  59230. // rewrite before `./index.js` -> `localhost:5173/a/index.js`.
  59231. // rewrite after `../index.js` -> `localhost:5173/index.js`.
  59232. const processedUrl = attr.name === 'srcset' && attr.prefix === undefined
  59233. ? processSrcSetSync(url, ({ url }) => replacer(url))
  59234. : replacer(url);
  59235. overwriteAttrValue(s, sourceCodeLocation, processedUrl);
  59236. }
  59237. };
  59238. const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
  59239. const { config, moduleGraph, watcher } = server;
  59240. const base = config.base || '/';
  59241. let proxyModulePath;
  59242. let proxyModuleUrl;
  59243. const trailingSlash = htmlPath.endsWith('/');
  59244. if (!trailingSlash && fs$l.existsSync(filename)) {
  59245. proxyModulePath = htmlPath;
  59246. proxyModuleUrl = joinUrlSegments(base, htmlPath);
  59247. }
  59248. else {
  59249. // There are users of vite.transformIndexHtml calling it with url '/'
  59250. // for SSR integrations #7993, filename is root for this case
  59251. // A user may also use a valid name for a virtual html file
  59252. // Mark the path as virtual in both cases so sourcemaps aren't processed
  59253. // and ids are properly handled
  59254. const validPath = `${htmlPath}${trailingSlash ? 'index.html' : ''}`;
  59255. proxyModulePath = `\0${validPath}`;
  59256. proxyModuleUrl = wrapId(proxyModulePath);
  59257. }
  59258. const s = new MagicString(html);
  59259. let inlineModuleIndex = -1;
  59260. // The key to the proxyHtml cache is decoded, as it will be compared
  59261. // against decoded URLs by the HTML plugins.
  59262. const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), ''));
  59263. const styleUrl = [];
  59264. const addInlineModule = (node, ext) => {
  59265. inlineModuleIndex++;
  59266. const contentNode = node.childNodes[0];
  59267. const code = contentNode.value;
  59268. let map;
  59269. if (proxyModulePath[0] !== '\0') {
  59270. map = new MagicString(html)
  59271. .snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset)
  59272. .generateMap({ hires: 'boundary' });
  59273. map.sources = [filename];
  59274. map.file = filename;
  59275. }
  59276. // add HTML Proxy to Map
  59277. addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map });
  59278. // inline js module. convert to src="proxy" (dev only, base is never relative)
  59279. const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
  59280. // invalidate the module so the newly cached contents will be served
  59281. const module = server?.moduleGraph.getModuleById(modulePath);
  59282. if (module) {
  59283. server?.moduleGraph.invalidateModule(module);
  59284. }
  59285. s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"></script>`);
  59286. preTransformRequest(server, modulePath, base);
  59287. };
  59288. await traverseHtml(html, filename, (node) => {
  59289. if (!nodeIsElement(node)) {
  59290. return;
  59291. }
  59292. // script tags
  59293. if (node.nodeName === 'script') {
  59294. const { src, sourceCodeLocation, isModule } = getScriptInfo(node);
  59295. if (src) {
  59296. processNodeUrl(src, sourceCodeLocation, s, config, htmlPath, originalUrl, server);
  59297. }
  59298. else if (isModule && node.childNodes.length) {
  59299. addInlineModule(node, 'js');
  59300. }
  59301. }
  59302. if (node.nodeName === 'style' && node.childNodes.length) {
  59303. const children = node.childNodes[0];
  59304. styleUrl.push({
  59305. start: children.sourceCodeLocation.startOffset,
  59306. end: children.sourceCodeLocation.endOffset,
  59307. code: children.value,
  59308. });
  59309. }
  59310. // elements with [href/src] attrs
  59311. const assetAttrs = assetAttrsConfig[node.nodeName];
  59312. if (assetAttrs) {
  59313. for (const p of node.attrs) {
  59314. const attrKey = getAttrKey(p);
  59315. if (p.value && assetAttrs.includes(attrKey)) {
  59316. processNodeUrl(p, node.sourceCodeLocation.attrs[attrKey], s, config, htmlPath, originalUrl);
  59317. }
  59318. }
  59319. }
  59320. });
  59321. await Promise.all(styleUrl.map(async ({ start, end, code }, index) => {
  59322. const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
  59323. // ensure module in graph after successful load
  59324. const mod = await moduleGraph.ensureEntryFromUrl(url, false);
  59325. ensureWatchedFile(watcher, mod.file, config.root);
  59326. const result = await server.pluginContainer.transform(code, mod.id);
  59327. let content = '';
  59328. if (result) {
  59329. if (result.map) {
  59330. if (result.map.mappings) {
  59331. await injectSourcesContent(result.map, proxyModulePath, config.logger);
  59332. }
  59333. content = getCodeWithSourcemap('css', result.code, result.map);
  59334. }
  59335. else {
  59336. content = result.code;
  59337. }
  59338. }
  59339. s.overwrite(start, end, content);
  59340. }));
  59341. html = s.toString();
  59342. return {
  59343. html,
  59344. tags: [
  59345. {
  59346. tag: 'script',
  59347. attrs: {
  59348. type: 'module',
  59349. src: path$o.posix.join(base, CLIENT_PUBLIC_PATH),
  59350. },
  59351. injectTo: 'head-prepend',
  59352. },
  59353. ],
  59354. };
  59355. };
  59356. function indexHtmlMiddleware(server) {
  59357. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  59358. return async function viteIndexHtmlMiddleware(req, res, next) {
  59359. if (res.writableEnded) {
  59360. return next();
  59361. }
  59362. const url = req.url && cleanUrl(req.url);
  59363. // htmlFallbackMiddleware appends '.html' to URLs
  59364. if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') {
  59365. const filename = getHtmlFilename(url, server);
  59366. if (fs$l.existsSync(filename)) {
  59367. try {
  59368. let html = await fsp.readFile(filename, 'utf-8');
  59369. html = await server.transformIndexHtml(url, html, req.originalUrl);
  59370. return send$2(req, res, html, 'html', {
  59371. headers: server.config.server.headers,
  59372. });
  59373. }
  59374. catch (e) {
  59375. return next(e);
  59376. }
  59377. }
  59378. }
  59379. next();
  59380. };
  59381. }
  59382. function preTransformRequest(server, url, base) {
  59383. if (!server.config.server.preTransformRequests)
  59384. return;
  59385. try {
  59386. url = unwrapId(stripBase(decodeURI(url), base));
  59387. }
  59388. catch {
  59389. // ignore
  59390. return;
  59391. }
  59392. // transform all url as non-ssr as html includes client-side assets only
  59393. server.transformRequest(url).catch((e) => {
  59394. if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP ||
  59395. e?.code === ERR_CLOSED_SERVER) {
  59396. // these are expected errors
  59397. return;
  59398. }
  59399. // Unexpected error, log the issue but avoid an unhandled exception
  59400. server.config.logger.error(e.message);
  59401. });
  59402. }
  59403. const logTime = createDebugger('vite:time');
  59404. function timeMiddleware(root) {
  59405. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  59406. return function viteTimeMiddleware(req, res, next) {
  59407. const start = performance.now();
  59408. const end = res.end;
  59409. res.end = (...args) => {
  59410. logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  59411. return end.call(res, ...args);
  59412. };
  59413. next();
  59414. };
  59415. }
  59416. class ModuleNode {
  59417. /**
  59418. * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
  59419. */
  59420. constructor(url, setIsSelfAccepting = true) {
  59421. /**
  59422. * Resolved file system path + query
  59423. */
  59424. this.id = null;
  59425. this.file = null;
  59426. this.importers = new Set();
  59427. this.clientImportedModules = new Set();
  59428. this.ssrImportedModules = new Set();
  59429. this.acceptedHmrDeps = new Set();
  59430. this.acceptedHmrExports = null;
  59431. this.importedBindings = null;
  59432. this.transformResult = null;
  59433. this.ssrTransformResult = null;
  59434. this.ssrModule = null;
  59435. this.ssrError = null;
  59436. this.lastHMRTimestamp = 0;
  59437. this.lastInvalidationTimestamp = 0;
  59438. this.url = url;
  59439. this.type = isDirectCSSRequest(url) ? 'css' : 'js';
  59440. if (setIsSelfAccepting) {
  59441. this.isSelfAccepting = false;
  59442. }
  59443. }
  59444. get importedModules() {
  59445. const importedModules = new Set(this.clientImportedModules);
  59446. for (const module of this.ssrImportedModules) {
  59447. importedModules.add(module);
  59448. }
  59449. return importedModules;
  59450. }
  59451. }
  59452. class ModuleGraph {
  59453. constructor(resolveId) {
  59454. this.resolveId = resolveId;
  59455. this.urlToModuleMap = new Map();
  59456. this.idToModuleMap = new Map();
  59457. // a single file may corresponds to multiple modules with different queries
  59458. this.fileToModulesMap = new Map();
  59459. this.safeModulesPath = new Set();
  59460. /**
  59461. * @internal
  59462. */
  59463. this._unresolvedUrlToModuleMap = new Map();
  59464. /**
  59465. * @internal
  59466. */
  59467. this._ssrUnresolvedUrlToModuleMap = new Map();
  59468. }
  59469. async getModuleByUrl(rawUrl, ssr) {
  59470. // Quick path, if we already have a module for this rawUrl (even without extension)
  59471. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  59472. const mod = this._getUnresolvedUrlToModule(rawUrl, ssr);
  59473. if (mod) {
  59474. return mod;
  59475. }
  59476. const [url] = await this._resolveUrl(rawUrl, ssr);
  59477. return this.urlToModuleMap.get(url);
  59478. }
  59479. getModuleById(id) {
  59480. return this.idToModuleMap.get(removeTimestampQuery(id));
  59481. }
  59482. getModulesByFile(file) {
  59483. return this.fileToModulesMap.get(file);
  59484. }
  59485. onFileChange(file) {
  59486. const mods = this.getModulesByFile(file);
  59487. if (mods) {
  59488. const seen = new Set();
  59489. mods.forEach((mod) => {
  59490. this.invalidateModule(mod, seen);
  59491. });
  59492. }
  59493. }
  59494. invalidateModule(mod, seen = new Set(), timestamp = Date.now(), isHmr = false, hmrBoundaries = []) {
  59495. if (seen.has(mod)) {
  59496. return;
  59497. }
  59498. seen.add(mod);
  59499. if (isHmr) {
  59500. mod.lastHMRTimestamp = timestamp;
  59501. }
  59502. else {
  59503. // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started
  59504. // processing being done for this module
  59505. mod.lastInvalidationTimestamp = timestamp;
  59506. }
  59507. // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline
  59508. // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested
  59509. mod.transformResult = null;
  59510. mod.ssrTransformResult = null;
  59511. mod.ssrModule = null;
  59512. mod.ssrError = null;
  59513. // Fix #3033
  59514. if (hmrBoundaries.includes(mod)) {
  59515. return;
  59516. }
  59517. mod.importers.forEach((importer) => {
  59518. if (!importer.acceptedHmrDeps.has(mod)) {
  59519. this.invalidateModule(importer, seen, timestamp, isHmr);
  59520. }
  59521. });
  59522. }
  59523. invalidateAll() {
  59524. const timestamp = Date.now();
  59525. const seen = new Set();
  59526. this.idToModuleMap.forEach((mod) => {
  59527. this.invalidateModule(mod, seen, timestamp);
  59528. });
  59529. }
  59530. /**
  59531. * Update the module graph based on a module's updated imports information
  59532. * If there are dependencies that no longer have any importers, they are
  59533. * returned as a Set.
  59534. */
  59535. async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr) {
  59536. mod.isSelfAccepting = isSelfAccepting;
  59537. const prevImports = ssr ? mod.ssrImportedModules : mod.clientImportedModules;
  59538. let noLongerImported;
  59539. let resolvePromises = [];
  59540. let resolveResults = new Array(importedModules.size);
  59541. let index = 0;
  59542. // update import graph
  59543. for (const imported of importedModules) {
  59544. const nextIndex = index++;
  59545. if (typeof imported === 'string') {
  59546. resolvePromises.push(this.ensureEntryFromUrl(imported, ssr).then((dep) => {
  59547. dep.importers.add(mod);
  59548. resolveResults[nextIndex] = dep;
  59549. }));
  59550. }
  59551. else {
  59552. imported.importers.add(mod);
  59553. resolveResults[nextIndex] = imported;
  59554. }
  59555. }
  59556. if (resolvePromises.length) {
  59557. await Promise.all(resolvePromises);
  59558. }
  59559. const nextImports = new Set(resolveResults);
  59560. if (ssr) {
  59561. mod.ssrImportedModules = nextImports;
  59562. }
  59563. else {
  59564. mod.clientImportedModules = nextImports;
  59565. }
  59566. // remove the importer from deps that were imported but no longer are.
  59567. prevImports.forEach((dep) => {
  59568. if (!mod.clientImportedModules.has(dep) &&
  59569. !mod.ssrImportedModules.has(dep)) {
  59570. dep.importers.delete(mod);
  59571. if (!dep.importers.size) {
  59572. (noLongerImported || (noLongerImported = new Set())).add(dep);
  59573. }
  59574. }
  59575. });
  59576. // update accepted hmr deps
  59577. resolvePromises = [];
  59578. resolveResults = new Array(acceptedModules.size);
  59579. index = 0;
  59580. for (const accepted of acceptedModules) {
  59581. const nextIndex = index++;
  59582. if (typeof accepted === 'string') {
  59583. resolvePromises.push(this.ensureEntryFromUrl(accepted, ssr).then((dep) => {
  59584. resolveResults[nextIndex] = dep;
  59585. }));
  59586. }
  59587. else {
  59588. resolveResults[nextIndex] = accepted;
  59589. }
  59590. }
  59591. if (resolvePromises.length) {
  59592. await Promise.all(resolvePromises);
  59593. }
  59594. mod.acceptedHmrDeps = new Set(resolveResults);
  59595. // update accepted hmr exports
  59596. mod.acceptedHmrExports = acceptedExports;
  59597. mod.importedBindings = importedBindings;
  59598. return noLongerImported;
  59599. }
  59600. async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
  59601. return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting);
  59602. }
  59603. /**
  59604. * @internal
  59605. */
  59606. async _ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true,
  59607. // Optimization, avoid resolving the same url twice if the caller already did it
  59608. resolved) {
  59609. // Quick path, if we already have a module for this rawUrl (even without extension)
  59610. rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
  59611. let mod = this._getUnresolvedUrlToModule(rawUrl, ssr);
  59612. if (mod) {
  59613. return mod;
  59614. }
  59615. const modPromise = (async () => {
  59616. const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, ssr, resolved);
  59617. mod = this.idToModuleMap.get(resolvedId);
  59618. if (!mod) {
  59619. mod = new ModuleNode(url, setIsSelfAccepting);
  59620. if (meta)
  59621. mod.meta = meta;
  59622. this.urlToModuleMap.set(url, mod);
  59623. mod.id = resolvedId;
  59624. this.idToModuleMap.set(resolvedId, mod);
  59625. const file = (mod.file = cleanUrl(resolvedId));
  59626. let fileMappedModules = this.fileToModulesMap.get(file);
  59627. if (!fileMappedModules) {
  59628. fileMappedModules = new Set();
  59629. this.fileToModulesMap.set(file, fileMappedModules);
  59630. }
  59631. fileMappedModules.add(mod);
  59632. }
  59633. // multiple urls can map to the same module and id, make sure we register
  59634. // the url to the existing module in that case
  59635. else if (!this.urlToModuleMap.has(url)) {
  59636. this.urlToModuleMap.set(url, mod);
  59637. }
  59638. this._setUnresolvedUrlToModule(rawUrl, mod, ssr);
  59639. return mod;
  59640. })();
  59641. // Also register the clean url to the module, so that we can short-circuit
  59642. // resolving the same url twice
  59643. this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr);
  59644. return modPromise;
  59645. }
  59646. // some deps, like a css file referenced via @import, don't have its own
  59647. // url because they are inlined into the main css import. But they still
  59648. // need to be represented in the module graph so that they can trigger
  59649. // hmr in the importing css file.
  59650. createFileOnlyEntry(file) {
  59651. file = normalizePath$3(file);
  59652. let fileMappedModules = this.fileToModulesMap.get(file);
  59653. if (!fileMappedModules) {
  59654. fileMappedModules = new Set();
  59655. this.fileToModulesMap.set(file, fileMappedModules);
  59656. }
  59657. const url = `${FS_PREFIX}${file}`;
  59658. for (const m of fileMappedModules) {
  59659. if (m.url === url || m.id === file) {
  59660. return m;
  59661. }
  59662. }
  59663. const mod = new ModuleNode(url);
  59664. mod.file = file;
  59665. fileMappedModules.add(mod);
  59666. return mod;
  59667. }
  59668. // for incoming urls, it is important to:
  59669. // 1. remove the HMR timestamp query (?t=xxxx) and the ?import query
  59670. // 2. resolve its extension so that urls with or without extension all map to
  59671. // the same module
  59672. async resolveUrl(url, ssr) {
  59673. url = removeImportQuery(removeTimestampQuery(url));
  59674. const mod = await this._getUnresolvedUrlToModule(url, ssr);
  59675. if (mod?.id) {
  59676. return [mod.url, mod.id, mod.meta];
  59677. }
  59678. return this._resolveUrl(url, ssr);
  59679. }
  59680. /**
  59681. * @internal
  59682. */
  59683. _getUnresolvedUrlToModule(url, ssr) {
  59684. return (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).get(url);
  59685. }
  59686. /**
  59687. * @internal
  59688. */
  59689. _setUnresolvedUrlToModule(url, mod, ssr) {
  59690. (ssr
  59691. ? this._ssrUnresolvedUrlToModuleMap
  59692. : this._unresolvedUrlToModuleMap).set(url, mod);
  59693. }
  59694. /**
  59695. * @internal
  59696. */
  59697. async _resolveUrl(url, ssr, alreadyResolved) {
  59698. const resolved = alreadyResolved ?? (await this.resolveId(url, !!ssr));
  59699. const resolvedId = resolved?.id || url;
  59700. if (url !== resolvedId &&
  59701. !url.includes('\0') &&
  59702. !url.startsWith(`virtual:`)) {
  59703. const ext = extname$1(cleanUrl(resolvedId));
  59704. if (ext) {
  59705. const pathname = cleanUrl(url);
  59706. if (!pathname.endsWith(ext)) {
  59707. url = pathname + ext + url.slice(pathname.length);
  59708. }
  59709. }
  59710. }
  59711. return [url, resolvedId, resolved?.meta];
  59712. }
  59713. }
  59714. function rejectInvalidRequestMiddleware() {
  59715. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  59716. return function viteRejectInvalidRequestMiddleware(req, res, next) {
  59717. // HTTP spec does not allow `#` in the request-target
  59718. // (HTTP 1.1: https://datatracker.ietf.org/doc/html/rfc9112#section-3.2)
  59719. // (HTTP 2: https://datatracker.ietf.org/doc/html/rfc9113#section-8.3.1-2.4.1)
  59720. // But Node.js allows those requests.
  59721. // Our middlewares don't expect `#` to be included in `req.url`, especially the `server.fs.deny` checks.
  59722. if (req.url?.includes('#')) {
  59723. // HTTP 1.1 spec recommends sending 400 Bad Request
  59724. // (https://datatracker.ietf.org/doc/html/rfc9112#section-3.2-4)
  59725. res.writeHead(400);
  59726. res.end();
  59727. return;
  59728. }
  59729. return next();
  59730. };
  59731. }
  59732. function createServer(inlineConfig = {}) {
  59733. return _createServer(inlineConfig, { ws: true });
  59734. }
  59735. async function _createServer(inlineConfig = {}, options) {
  59736. const config = await resolveConfig(inlineConfig, 'serve');
  59737. const { root, server: serverConfig } = config;
  59738. const httpsOptions = await resolveHttpsConfig(config.server.https);
  59739. const { middlewareMode } = serverConfig;
  59740. const resolvedWatchOptions = resolveChokidarOptions(config, {
  59741. disableGlobbing: true,
  59742. ...serverConfig.watch,
  59743. });
  59744. const middlewares = connect$1();
  59745. const httpServer = middlewareMode
  59746. ? null
  59747. : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
  59748. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  59749. if (httpServer) {
  59750. setClientErrorHandler(httpServer, config.logger);
  59751. }
  59752. const watcher = chokidar.watch(
  59753. // config file dependencies and env file might be outside of root
  59754. [root, ...config.configFileDependencies, config.envDir], resolvedWatchOptions);
  59755. const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr }));
  59756. const container = await createPluginContainer(config, moduleGraph, watcher);
  59757. const closeHttpServer = createServerCloseFn(httpServer);
  59758. let exitProcess;
  59759. const server = {
  59760. config,
  59761. middlewares,
  59762. httpServer,
  59763. watcher,
  59764. pluginContainer: container,
  59765. ws,
  59766. moduleGraph,
  59767. resolvedUrls: null,
  59768. ssrTransform(code, inMap, url, originalCode = code) {
  59769. return ssrTransform(code, inMap, url, originalCode, server.config);
  59770. },
  59771. transformRequest(url, options) {
  59772. return transformRequest(url, server, options);
  59773. },
  59774. transformIndexHtml: null,
  59775. async ssrLoadModule(url, opts) {
  59776. if (isDepsOptimizerEnabled(config, true)) {
  59777. await initDevSsrDepsOptimizer(config, server);
  59778. }
  59779. if (config.legacy?.buildSsrCjsExternalHeuristics) {
  59780. await updateCjsSsrExternals(server);
  59781. }
  59782. return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace);
  59783. },
  59784. ssrFixStacktrace(e) {
  59785. ssrFixStacktrace(e, moduleGraph);
  59786. },
  59787. ssrRewriteStacktrace(stack) {
  59788. return ssrRewriteStacktrace(stack, moduleGraph);
  59789. },
  59790. async reloadModule(module) {
  59791. if (serverConfig.hmr !== false && module.file) {
  59792. updateModules(module.file, [module], Date.now(), server);
  59793. }
  59794. },
  59795. async listen(port, isRestart) {
  59796. await startServer(server, port);
  59797. if (httpServer) {
  59798. server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config);
  59799. if (!isRestart && config.server.open)
  59800. server.openBrowser();
  59801. }
  59802. return server;
  59803. },
  59804. openBrowser() {
  59805. const options = server.config.server;
  59806. const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
  59807. if (url) {
  59808. const path = typeof options.open === 'string'
  59809. ? new URL(options.open, url).href
  59810. : url;
  59811. openBrowser(path, true, server.config.logger);
  59812. }
  59813. else {
  59814. server.config.logger.warn('No URL available to open in browser');
  59815. }
  59816. },
  59817. async close() {
  59818. if (!middlewareMode) {
  59819. process.off('SIGTERM', exitProcess);
  59820. if (process.env.CI !== 'true') {
  59821. process.stdin.off('end', exitProcess);
  59822. }
  59823. }
  59824. await Promise.allSettled([
  59825. watcher.close(),
  59826. ws.close(),
  59827. container.close(),
  59828. getDepsOptimizer(server.config)?.close(),
  59829. getDepsOptimizer(server.config, true)?.close(),
  59830. closeHttpServer(),
  59831. ]);
  59832. // Await pending requests. We throw early in transformRequest
  59833. // and in hooks if the server is closing for non-ssr requests,
  59834. // so the import analysis plugin stops pre-transforming static
  59835. // imports and this block is resolved sooner.
  59836. // During SSR, we let pending requests finish to avoid exposing
  59837. // the server closed error to the users.
  59838. while (server._pendingRequests.size > 0) {
  59839. await Promise.allSettled([...server._pendingRequests.values()].map((pending) => pending.request));
  59840. }
  59841. server.resolvedUrls = null;
  59842. },
  59843. printUrls() {
  59844. if (server.resolvedUrls) {
  59845. printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info);
  59846. }
  59847. else if (middlewareMode) {
  59848. throw new Error('cannot print server URLs in middleware mode.');
  59849. }
  59850. else {
  59851. throw new Error('cannot print server URLs before server.listen is called.');
  59852. }
  59853. },
  59854. async restart(forceOptimize) {
  59855. if (!server._restartPromise) {
  59856. server._forceOptimizeOnRestart = !!forceOptimize;
  59857. server._restartPromise = restartServer(server).finally(() => {
  59858. server._restartPromise = null;
  59859. server._forceOptimizeOnRestart = false;
  59860. });
  59861. }
  59862. return server._restartPromise;
  59863. },
  59864. _ssrExternals: null,
  59865. _restartPromise: null,
  59866. _importGlobMap: new Map(),
  59867. _forceOptimizeOnRestart: false,
  59868. _pendingRequests: new Map(),
  59869. _fsDenyGlob: picomatch$4(
  59870. // matchBase: true does not work as it's documented
  59871. // https://github.com/micromatch/picomatch/issues/89
  59872. // convert patterns without `/` on our side for now
  59873. config.server.fs.deny.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`), {
  59874. matchBase: false,
  59875. nocase: true,
  59876. dot: true,
  59877. }),
  59878. _shortcutsOptions: undefined,
  59879. };
  59880. server.transformIndexHtml = createDevHtmlTransformFn(server);
  59881. if (!middlewareMode) {
  59882. exitProcess = async () => {
  59883. try {
  59884. await server.close();
  59885. }
  59886. finally {
  59887. process.exit();
  59888. }
  59889. };
  59890. process.once('SIGTERM', exitProcess);
  59891. if (process.env.CI !== 'true') {
  59892. process.stdin.on('end', exitProcess);
  59893. }
  59894. }
  59895. const onHMRUpdate = async (file, configOnly) => {
  59896. if (serverConfig.hmr !== false) {
  59897. try {
  59898. await handleHMRUpdate(file, server, configOnly);
  59899. }
  59900. catch (err) {
  59901. ws.send({
  59902. type: 'error',
  59903. err: prepareError(err),
  59904. });
  59905. }
  59906. }
  59907. };
  59908. const onFileAddUnlink = async (file) => {
  59909. file = normalizePath$3(file);
  59910. await handleFileAddUnlink(file, server);
  59911. await onHMRUpdate(file, true);
  59912. };
  59913. watcher.on('change', async (file) => {
  59914. file = normalizePath$3(file);
  59915. // invalidate module graph cache on file change
  59916. moduleGraph.onFileChange(file);
  59917. await onHMRUpdate(file, false);
  59918. });
  59919. watcher.on('add', onFileAddUnlink);
  59920. watcher.on('unlink', onFileAddUnlink);
  59921. ws.on('vite:invalidate', async ({ path, message }) => {
  59922. const mod = moduleGraph.urlToModuleMap.get(path);
  59923. if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) {
  59924. config.logger.info(colors$1.yellow(`hmr invalidate `) +
  59925. colors$1.dim(path) +
  59926. (message ? ` ${message}` : ''), { timestamp: true });
  59927. const file = getShortName(mod.file, config.root);
  59928. updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server, true);
  59929. }
  59930. });
  59931. if (!middlewareMode && httpServer) {
  59932. httpServer.once('listening', () => {
  59933. // update actual port since this may be different from initial value
  59934. serverConfig.port = httpServer.address().port;
  59935. });
  59936. }
  59937. // apply server configuration hooks from plugins
  59938. const postHooks = [];
  59939. for (const hook of config.getSortedPluginHooks('configureServer')) {
  59940. postHooks.push(await hook(server));
  59941. }
  59942. // Internal middlewares ------------------------------------------------------
  59943. // request timer
  59944. if (process.env.DEBUG) {
  59945. middlewares.use(timeMiddleware(root));
  59946. }
  59947. // disallows request that contains `#` in the URL
  59948. middlewares.use(rejectInvalidRequestMiddleware());
  59949. // cors
  59950. const { cors } = serverConfig;
  59951. if (cors !== false) {
  59952. middlewares.use(corsMiddleware(typeof cors === 'boolean'
  59953. ? {}
  59954. : cors ?? { origin: defaultAllowedOrigins }));
  59955. }
  59956. // host check (to prevent DNS rebinding attacks)
  59957. const { allowedHosts } = serverConfig;
  59958. // no need to check for HTTPS as HTTPS is not vulnerable to DNS rebinding attacks
  59959. if (allowedHosts !== true && !serverConfig.https) {
  59960. middlewares.use(hostCheckMiddleware(config, false));
  59961. }
  59962. // proxy
  59963. const { proxy } = serverConfig;
  59964. if (proxy) {
  59965. middlewares.use(proxyMiddleware(httpServer, proxy, config));
  59966. }
  59967. // base
  59968. if (config.base !== '/') {
  59969. middlewares.use(baseMiddleware(server));
  59970. }
  59971. // open in editor support
  59972. middlewares.use('/__open-in-editor', launchEditorMiddleware$1());
  59973. // ping request handler
  59974. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  59975. middlewares.use(function viteHMRPingMiddleware(req, res, next) {
  59976. if (req.headers['accept'] === 'text/x-vite-ping') {
  59977. res.writeHead(204).end();
  59978. }
  59979. else {
  59980. next();
  59981. }
  59982. });
  59983. // serve static files under /public
  59984. // this applies before the transform middleware so that these files are served
  59985. // as-is without transforms.
  59986. if (config.publicDir) {
  59987. middlewares.use(servePublicMiddleware(config.publicDir, server, config.server.headers));
  59988. }
  59989. // main transform middleware
  59990. middlewares.use(transformMiddleware(server));
  59991. // serve static files
  59992. middlewares.use(serveRawFsMiddleware(server));
  59993. middlewares.use(serveStaticMiddleware(root, server));
  59994. // html fallback
  59995. if (config.appType === 'spa' || config.appType === 'mpa') {
  59996. middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa'));
  59997. }
  59998. // run post config hooks
  59999. // This is applied before the html middleware so that user middleware can
  60000. // serve custom content instead of index.html.
  60001. postHooks.forEach((fn) => fn && fn());
  60002. if (config.appType === 'spa' || config.appType === 'mpa') {
  60003. // transform index.html
  60004. middlewares.use(indexHtmlMiddleware(server));
  60005. // handle 404s
  60006. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  60007. middlewares.use(function vite404Middleware(_, res) {
  60008. res.statusCode = 404;
  60009. res.end();
  60010. });
  60011. }
  60012. // error handler
  60013. middlewares.use(errorMiddleware(server, middlewareMode));
  60014. // httpServer.listen can be called multiple times
  60015. // when port when using next port number
  60016. // this code is to avoid calling buildStart multiple times
  60017. let initingServer;
  60018. let serverInited = false;
  60019. const initServer = async () => {
  60020. if (serverInited)
  60021. return;
  60022. if (initingServer)
  60023. return initingServer;
  60024. initingServer = (async function () {
  60025. await container.buildStart({});
  60026. // start deps optimizer after all container plugins are ready
  60027. if (isDepsOptimizerEnabled(config, false)) {
  60028. await initDepsOptimizer(config, server);
  60029. }
  60030. initingServer = undefined;
  60031. serverInited = true;
  60032. })();
  60033. return initingServer;
  60034. };
  60035. if (!middlewareMode && httpServer) {
  60036. // overwrite listen to init optimizer before server start
  60037. const listen = httpServer.listen.bind(httpServer);
  60038. httpServer.listen = (async (port, ...args) => {
  60039. try {
  60040. // ensure ws server started
  60041. ws.listen();
  60042. await initServer();
  60043. }
  60044. catch (e) {
  60045. httpServer.emit('error', e);
  60046. return;
  60047. }
  60048. return listen(port, ...args);
  60049. });
  60050. }
  60051. else {
  60052. if (options.ws) {
  60053. ws.listen();
  60054. }
  60055. await initServer();
  60056. }
  60057. return server;
  60058. }
  60059. async function startServer(server, inlinePort) {
  60060. const httpServer = server.httpServer;
  60061. if (!httpServer) {
  60062. throw new Error('Cannot call server.listen in middleware mode.');
  60063. }
  60064. const options = server.config.server;
  60065. const port = inlinePort ?? options.port ?? DEFAULT_DEV_PORT;
  60066. const hostname = await resolveHostname(options.host);
  60067. await httpServerStart(httpServer, {
  60068. port,
  60069. strictPort: options.strictPort,
  60070. host: hostname.host,
  60071. logger: server.config.logger,
  60072. });
  60073. }
  60074. function createServerCloseFn(server) {
  60075. if (!server) {
  60076. return () => { };
  60077. }
  60078. let hasListened = false;
  60079. const openSockets = new Set();
  60080. server.on('connection', (socket) => {
  60081. openSockets.add(socket);
  60082. socket.on('close', () => {
  60083. openSockets.delete(socket);
  60084. });
  60085. });
  60086. server.once('listening', () => {
  60087. hasListened = true;
  60088. });
  60089. return () => new Promise((resolve, reject) => {
  60090. openSockets.forEach((s) => s.destroy());
  60091. if (hasListened) {
  60092. server.close((err) => {
  60093. if (err) {
  60094. reject(err);
  60095. }
  60096. else {
  60097. resolve();
  60098. }
  60099. });
  60100. }
  60101. else {
  60102. resolve();
  60103. }
  60104. });
  60105. }
  60106. function resolvedAllowDir(root, dir) {
  60107. return normalizePath$3(path$o.resolve(root, dir));
  60108. }
  60109. function resolveServerOptions(root, raw, logger) {
  60110. const server = {
  60111. preTransformRequests: true,
  60112. ...raw,
  60113. sourcemapIgnoreList: raw?.sourcemapIgnoreList === false
  60114. ? () => false
  60115. : raw?.sourcemapIgnoreList || isInNodeModules,
  60116. middlewareMode: !!raw?.middlewareMode,
  60117. };
  60118. let allowDirs = server.fs?.allow;
  60119. const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}'];
  60120. if (!allowDirs) {
  60121. allowDirs = [searchForWorkspaceRoot(root)];
  60122. }
  60123. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  60124. // only push client dir when vite itself is outside-of-root
  60125. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  60126. if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) {
  60127. allowDirs.push(resolvedClientDir);
  60128. }
  60129. server.fs = {
  60130. strict: server.fs?.strict ?? true,
  60131. allow: allowDirs,
  60132. deny,
  60133. };
  60134. if (server.origin?.endsWith('/')) {
  60135. server.origin = server.origin.slice(0, -1);
  60136. logger.warn(colors$1.yellow(`${colors$1.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`));
  60137. }
  60138. return server;
  60139. }
  60140. async function restartServer(server) {
  60141. global.__vite_start_time = performance.now();
  60142. const { port: prevPort, host: prevHost } = server.config.server;
  60143. const shortcutsOptions = server._shortcutsOptions;
  60144. const oldUrls = server.resolvedUrls;
  60145. let inlineConfig = server.config.inlineConfig;
  60146. if (server._forceOptimizeOnRestart) {
  60147. inlineConfig = mergeConfig(inlineConfig, {
  60148. optimizeDeps: {
  60149. force: true,
  60150. },
  60151. });
  60152. }
  60153. let newServer = null;
  60154. try {
  60155. // delay ws server listen
  60156. newServer = await _createServer(inlineConfig, { ws: false });
  60157. }
  60158. catch (err) {
  60159. server.config.logger.error(err.message, {
  60160. timestamp: true,
  60161. });
  60162. server.config.logger.error('server restart failed', { timestamp: true });
  60163. return;
  60164. }
  60165. await server.close();
  60166. // Assign new server props to existing server instance
  60167. Object.assign(server, newServer);
  60168. const { logger, server: { port, host, middlewareMode }, } = server.config;
  60169. if (!middlewareMode) {
  60170. await server.listen(port, true);
  60171. logger.info('server restarted.', { timestamp: true });
  60172. if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) ||
  60173. host !== prevHost ||
  60174. diffDnsOrderChange(oldUrls, newServer.resolvedUrls)) {
  60175. logger.info('');
  60176. server.printUrls();
  60177. }
  60178. }
  60179. else {
  60180. server.ws.listen();
  60181. logger.info('server restarted.', { timestamp: true });
  60182. }
  60183. if (shortcutsOptions) {
  60184. shortcutsOptions.print = false;
  60185. bindShortcuts(newServer, shortcutsOptions);
  60186. }
  60187. }
  60188. async function updateCjsSsrExternals(server) {
  60189. if (!server._ssrExternals) {
  60190. let knownImports = [];
  60191. // Important! We use the non-ssr optimized deps to find known imports
  60192. // Only the explicitly defined deps are optimized during dev SSR, so
  60193. // we use the generated list from the scanned deps in regular dev.
  60194. // This is part of the v2 externalization heuristics and it is kept
  60195. // for backwards compatibility in case user needs to fallback to the
  60196. // legacy scheme. It may be removed in a future v3 minor.
  60197. const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr
  60198. if (depsOptimizer) {
  60199. await depsOptimizer.scanProcessing;
  60200. knownImports = [
  60201. ...Object.keys(depsOptimizer.metadata.optimized),
  60202. ...Object.keys(depsOptimizer.metadata.discovered),
  60203. ];
  60204. }
  60205. server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports);
  60206. }
  60207. }
  60208. var index = {
  60209. __proto__: null,
  60210. _createServer: _createServer,
  60211. createServer: createServer,
  60212. resolveServerOptions: resolveServerOptions
  60213. };
  60214. /* eslint-disable */
  60215. //@ts-nocheck
  60216. //TODO: replace this code with https://github.com/lukeed/polka/pull/148 once it's released
  60217. // This is based on https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/polkompress.js
  60218. // MIT Licensed https://github.com/preactjs/wmr/blob/main/LICENSE
  60219. /* global Buffer */
  60220. const noop = () => { };
  60221. const mimes = /text|javascript|\/json|xml/i;
  60222. const threshold = 1024;
  60223. const level = -1;
  60224. let brotli = false;
  60225. const getChunkSize = (chunk, enc) => (chunk ? Buffer.byteLength(chunk, enc) : 0);
  60226. function compression() {
  60227. const brotliOpts = (typeof brotli === 'object' && brotli) || {};
  60228. const gzipOpts = {};
  60229. // disable Brotli on Node<12.7 where it is unsupported:
  60230. if (!zlib$1.createBrotliCompress)
  60231. brotli = false;
  60232. return function viteCompressionMiddleware(req, res, next = noop) {
  60233. const accept = req.headers['accept-encoding'] + '';
  60234. const encoding = ((brotli && accept.match(/\bbr\b/)) ||
  60235. (accept.match(/\bgzip\b/)) ||
  60236. [])[0];
  60237. // skip if no response body or no supported encoding:
  60238. if (req.method === 'HEAD' || !encoding)
  60239. return next();
  60240. /** @type {zlib.Gzip | zlib.BrotliCompress} */
  60241. let compress;
  60242. let pendingStatus;
  60243. /** @type {[string, function][]?} */
  60244. let pendingListeners = [];
  60245. let started = false;
  60246. let size = 0;
  60247. function start() {
  60248. started = true;
  60249. size = res.getHeader('Content-Length') | 0 || size;
  60250. const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain'));
  60251. const cleartext = !res.getHeader('Content-Encoding');
  60252. const listeners = pendingListeners || [];
  60253. if (compressible && cleartext && size >= threshold) {
  60254. res.setHeader('Content-Encoding', encoding);
  60255. res.removeHeader('Content-Length');
  60256. if (encoding === 'br') {
  60257. const params = {
  60258. [zlib$1.constants.BROTLI_PARAM_QUALITY]: level,
  60259. [zlib$1.constants.BROTLI_PARAM_SIZE_HINT]: size,
  60260. };
  60261. compress = zlib$1.createBrotliCompress({
  60262. params: Object.assign(params, brotliOpts),
  60263. });
  60264. }
  60265. else {
  60266. compress = zlib$1.createGzip(Object.assign({ level }, gzipOpts));
  60267. }
  60268. // backpressure
  60269. compress.on('data', (chunk) => write.call(res, chunk) === false && compress.pause());
  60270. on.call(res, 'drain', () => compress.resume());
  60271. compress.on('end', () => end.call(res));
  60272. listeners.forEach((p) => compress.on.apply(compress, p));
  60273. }
  60274. else {
  60275. pendingListeners = null;
  60276. listeners.forEach((p) => on.apply(res, p));
  60277. }
  60278. writeHead.call(res, pendingStatus || res.statusCode);
  60279. }
  60280. const { end, write, on, writeHead } = res;
  60281. res.writeHead = function (status, reason, headers) {
  60282. if (typeof reason !== 'string')
  60283. [headers, reason] = [reason, headers];
  60284. if (headers)
  60285. for (let i in headers)
  60286. res.setHeader(i, headers[i]);
  60287. pendingStatus = status;
  60288. return this;
  60289. };
  60290. res.write = function (chunk, enc, cb) {
  60291. size += getChunkSize(chunk, enc);
  60292. if (!started)
  60293. start();
  60294. if (!compress)
  60295. return write.apply(this, arguments);
  60296. return compress.write.apply(compress, arguments);
  60297. };
  60298. res.end = function (chunk, enc, cb) {
  60299. if (arguments.length > 0 && typeof chunk !== 'function') {
  60300. size += getChunkSize(chunk, enc);
  60301. }
  60302. if (!started)
  60303. start();
  60304. if (!compress)
  60305. return end.apply(this, arguments);
  60306. return compress.end.apply(compress, arguments);
  60307. };
  60308. res.on = function (type, listener) {
  60309. if (!pendingListeners || type !== 'drain')
  60310. on.call(this, type, listener);
  60311. else if (compress)
  60312. compress.on(type, listener);
  60313. else
  60314. pendingListeners.push([type, listener]);
  60315. return this;
  60316. };
  60317. next();
  60318. };
  60319. }
  60320. function resolvePreviewOptions(preview, server) {
  60321. // The preview server inherits every CommonServerOption from the `server` config
  60322. // except for the port to enable having both the dev and preview servers running
  60323. // at the same time without extra configuration
  60324. return {
  60325. port: preview?.port,
  60326. strictPort: preview?.strictPort ?? server.strictPort,
  60327. host: preview?.host ?? server.host,
  60328. allowedHosts: preview?.allowedHosts ?? server.allowedHosts,
  60329. https: preview?.https ?? server.https,
  60330. open: preview?.open ?? server.open,
  60331. proxy: preview?.proxy ?? server.proxy,
  60332. cors: preview?.cors ?? server.cors,
  60333. headers: preview?.headers ?? server.headers,
  60334. };
  60335. }
  60336. /**
  60337. * Starts the Vite server in preview mode, to simulate a production deployment
  60338. */
  60339. async function preview(inlineConfig = {}) {
  60340. const config = await resolveConfig(inlineConfig, 'serve', 'production', 'production');
  60341. const distDir = path$o.resolve(config.root, config.build.outDir);
  60342. if (!fs$l.existsSync(distDir) &&
  60343. // error if no plugins implement `configurePreviewServer`
  60344. config.plugins.every((plugin) => !plugin.configurePreviewServer) &&
  60345. // error if called in CLI only. programmatic usage could access `httpServer`
  60346. // and affect file serving
  60347. process.argv[1]?.endsWith(path$o.normalize('bin/vite.js')) &&
  60348. process.argv[2] === 'preview') {
  60349. throw new Error(`The directory "${config.build.outDir}" does not exist. Did you build your project?`);
  60350. }
  60351. const app = connect$1();
  60352. const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig(config.preview?.https));
  60353. setClientErrorHandler(httpServer, config.logger);
  60354. const options = config.preview;
  60355. const logger = config.logger;
  60356. const server = {
  60357. config,
  60358. middlewares: app,
  60359. httpServer,
  60360. resolvedUrls: null,
  60361. printUrls() {
  60362. if (server.resolvedUrls) {
  60363. printServerUrls(server.resolvedUrls, options.host, logger.info);
  60364. }
  60365. else {
  60366. throw new Error('cannot print server URLs before server is listening.');
  60367. }
  60368. },
  60369. };
  60370. // apply server hooks from plugins
  60371. const postHooks = [];
  60372. for (const hook of config.getSortedPluginHooks('configurePreviewServer')) {
  60373. postHooks.push(await hook(server));
  60374. }
  60375. // cors
  60376. const { cors } = config.preview;
  60377. if (cors !== false) {
  60378. app.use(corsMiddleware(typeof cors === 'boolean'
  60379. ? {}
  60380. : cors ?? { origin: defaultAllowedOrigins }));
  60381. }
  60382. // host check (to prevent DNS rebinding attacks)
  60383. const { allowedHosts } = config.preview;
  60384. // no need to check for HTTPS as HTTPS is not vulnerable to DNS rebinding attacks
  60385. if (allowedHosts !== true && !config.preview.https) {
  60386. app.use(hostCheckMiddleware(config, true));
  60387. }
  60388. // proxy
  60389. const { proxy } = config.preview;
  60390. if (proxy) {
  60391. app.use(proxyMiddleware(httpServer, proxy, config));
  60392. }
  60393. app.use(compression());
  60394. const previewBase = config.base === './' || config.base === '' ? '/' : config.base;
  60395. // static assets
  60396. const headers = config.preview.headers;
  60397. const viteAssetMiddleware = (...args) => sirv(distDir, {
  60398. etag: true,
  60399. dev: true,
  60400. single: config.appType === 'spa',
  60401. setHeaders(res) {
  60402. if (headers) {
  60403. for (const name in headers) {
  60404. res.setHeader(name, headers[name]);
  60405. }
  60406. }
  60407. },
  60408. shouldServe(filePath) {
  60409. return shouldServeFile(filePath, distDir);
  60410. },
  60411. })(...args);
  60412. app.use(previewBase, viteAssetMiddleware);
  60413. // apply post server hooks from plugins
  60414. postHooks.forEach((fn) => fn && fn());
  60415. const hostname = await resolveHostname(options.host);
  60416. const port = options.port ?? DEFAULT_PREVIEW_PORT;
  60417. const protocol = options.https ? 'https' : 'http';
  60418. const serverPort = await httpServerStart(httpServer, {
  60419. port,
  60420. strictPort: options.strictPort,
  60421. host: hostname.host,
  60422. logger,
  60423. });
  60424. server.resolvedUrls = await resolveServerUrls(httpServer, config.preview, config);
  60425. if (options.open) {
  60426. const path = typeof options.open === 'string' ? options.open : previewBase;
  60427. openBrowser(path.startsWith('http')
  60428. ? path
  60429. : new URL(path, `${protocol}://${hostname.name}:${serverPort}`).href, true, logger);
  60430. }
  60431. return server;
  60432. }
  60433. var preview$1 = {
  60434. __proto__: null,
  60435. preview: preview,
  60436. resolvePreviewOptions: resolvePreviewOptions
  60437. };
  60438. function resolveSSROptions(ssr, preserveSymlinks, buildSsrCjsExternalHeuristics) {
  60439. ssr ?? (ssr = {});
  60440. const optimizeDeps = ssr.optimizeDeps ?? {};
  60441. const format = buildSsrCjsExternalHeuristics ? 'cjs' : 'esm';
  60442. const target = 'node';
  60443. return {
  60444. format,
  60445. target,
  60446. ...ssr,
  60447. optimizeDeps: {
  60448. disabled: true,
  60449. ...optimizeDeps,
  60450. esbuildOptions: {
  60451. preserveSymlinks,
  60452. ...optimizeDeps.esbuildOptions,
  60453. },
  60454. },
  60455. };
  60456. }
  60457. const debug = createDebugger('vite:config');
  60458. const promisifiedRealpath = promisify$4(fs$l.realpath);
  60459. function defineConfig(config) {
  60460. return config;
  60461. }
  60462. async function resolveConfig(inlineConfig, command, defaultMode = 'development', defaultNodeEnv = 'development') {
  60463. let config = inlineConfig;
  60464. let configFileDependencies = [];
  60465. let mode = inlineConfig.mode || defaultMode;
  60466. const isNodeEnvSet = !!process.env.NODE_ENV;
  60467. const packageCache = new Map();
  60468. // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
  60469. // production-specific behavior, so set it early on
  60470. if (!isNodeEnvSet) {
  60471. process.env.NODE_ENV = defaultNodeEnv;
  60472. }
  60473. const configEnv = {
  60474. mode,
  60475. command,
  60476. ssrBuild: !!config.build?.ssr,
  60477. };
  60478. let { configFile } = config;
  60479. if (configFile !== false) {
  60480. const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel);
  60481. if (loadResult) {
  60482. config = mergeConfig(loadResult.config, config);
  60483. configFile = loadResult.path;
  60484. configFileDependencies = loadResult.dependencies;
  60485. }
  60486. }
  60487. // user config may provide an alternative mode. But --mode has a higher priority
  60488. mode = inlineConfig.mode || config.mode || mode;
  60489. configEnv.mode = mode;
  60490. const filterPlugin = (p) => {
  60491. if (!p) {
  60492. return false;
  60493. }
  60494. else if (!p.apply) {
  60495. return true;
  60496. }
  60497. else if (typeof p.apply === 'function') {
  60498. return p.apply({ ...config, mode }, configEnv);
  60499. }
  60500. else {
  60501. return p.apply === command;
  60502. }
  60503. };
  60504. // Some plugins that aren't intended to work in the bundling of workers (doing post-processing at build time for example).
  60505. // And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
  60506. // So we need to separate the worker plugin from the plugin that vite needs to run.
  60507. const rawWorkerUserPlugins = (await asyncFlatten(config.worker?.plugins || [])).filter(filterPlugin);
  60508. // resolve plugins
  60509. const rawUserPlugins = (await asyncFlatten(config.plugins || [])).filter(filterPlugin);
  60510. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
  60511. // run config hooks
  60512. const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
  60513. config = await runConfigHook(config, userPlugins, configEnv);
  60514. // If there are custom commonjsOptions, don't force optimized deps for this test
  60515. // even if the env var is set as it would interfere with the playground specs.
  60516. if (!config.build?.commonjsOptions &&
  60517. process.env.VITE_TEST_WITHOUT_PLUGIN_COMMONJS) {
  60518. config = mergeConfig(config, {
  60519. optimizeDeps: { disabled: false },
  60520. ssr: { optimizeDeps: { disabled: false } },
  60521. });
  60522. config.build ?? (config.build = {});
  60523. config.build.commonjsOptions = { include: [] };
  60524. }
  60525. // Define logger
  60526. const logger = createLogger(config.logLevel, {
  60527. allowClearScreen: config.clearScreen,
  60528. customLogger: config.customLogger,
  60529. });
  60530. // resolve root
  60531. const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd());
  60532. const clientAlias = [
  60533. {
  60534. find: /^\/?@vite\/env/,
  60535. replacement: path$o.posix.join(FS_PREFIX, normalizePath$3(ENV_ENTRY)),
  60536. },
  60537. {
  60538. find: /^\/?@vite\/client/,
  60539. replacement: path$o.posix.join(FS_PREFIX, normalizePath$3(CLIENT_ENTRY)),
  60540. },
  60541. ];
  60542. // resolve alias with internal client alias
  60543. const resolvedAlias = normalizeAlias(mergeAlias(clientAlias, config.resolve?.alias || []));
  60544. const resolveOptions = {
  60545. mainFields: config.resolve?.mainFields ?? DEFAULT_MAIN_FIELDS,
  60546. browserField: config.resolve?.browserField ?? true,
  60547. conditions: config.resolve?.conditions ?? [],
  60548. extensions: config.resolve?.extensions ?? DEFAULT_EXTENSIONS$1,
  60549. dedupe: config.resolve?.dedupe ?? [],
  60550. preserveSymlinks: config.resolve?.preserveSymlinks ?? false,
  60551. alias: resolvedAlias,
  60552. };
  60553. // load .env files
  60554. const envDir = config.envDir
  60555. ? normalizePath$3(path$o.resolve(resolvedRoot, config.envDir))
  60556. : resolvedRoot;
  60557. const userEnv = inlineConfig.envFile !== false &&
  60558. loadEnv(mode, envDir, resolveEnvPrefix(config));
  60559. // Note it is possible for user to have a custom mode, e.g. `staging` where
  60560. // development-like behavior is expected. This is indicated by NODE_ENV=development
  60561. // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV
  60562. const userNodeEnv = process.env.VITE_USER_NODE_ENV;
  60563. if (!isNodeEnvSet && userNodeEnv) {
  60564. if (userNodeEnv === 'development') {
  60565. process.env.NODE_ENV = 'development';
  60566. }
  60567. else {
  60568. // NODE_ENV=production is not supported as it could break HMR in dev for frameworks like Vue
  60569. logger.warn(`NODE_ENV=${userNodeEnv} is not supported in the .env file. ` +
  60570. `Only NODE_ENV=development is supported to create a development build of your project. ` +
  60571. `If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`);
  60572. }
  60573. }
  60574. const isProduction = process.env.NODE_ENV === 'production';
  60575. // resolve public base url
  60576. const isBuild = command === 'build';
  60577. const relativeBaseShortcut = config.base === '' || config.base === './';
  60578. // During dev, we ignore relative base and fallback to '/'
  60579. // For the SSR build, relative base isn't possible by means
  60580. // of import.meta.url.
  60581. const resolvedBase = relativeBaseShortcut
  60582. ? !isBuild || config.build?.ssr
  60583. ? '/'
  60584. : './'
  60585. : resolveBaseUrl(config.base, isBuild, logger) ?? '/';
  60586. const resolvedBuildOptions = resolveBuildOptions(config.build, logger, resolvedRoot);
  60587. // resolve cache directory
  60588. const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
  60589. const cacheDir = normalizePath$3(config.cacheDir
  60590. ? path$o.resolve(resolvedRoot, config.cacheDir)
  60591. : pkgDir
  60592. ? path$o.join(pkgDir, `node_modules/.vite`)
  60593. : path$o.join(resolvedRoot, `.vite`));
  60594. const assetsFilter = config.assetsInclude &&
  60595. (!Array.isArray(config.assetsInclude) || config.assetsInclude.length)
  60596. ? createFilter(config.assetsInclude)
  60597. : () => false;
  60598. // create an internal resolver to be used in special scenarios, e.g.
  60599. // optimizer & handling css @imports
  60600. const createResolver = (options) => {
  60601. let aliasContainer;
  60602. let resolverContainer;
  60603. return async (id, importer, aliasOnly, ssr) => {
  60604. let container;
  60605. if (aliasOnly) {
  60606. container =
  60607. aliasContainer ||
  60608. (aliasContainer = await createPluginContainer({
  60609. ...resolved,
  60610. plugins: [alias$1({ entries: resolved.resolve.alias })],
  60611. }));
  60612. }
  60613. else {
  60614. container =
  60615. resolverContainer ||
  60616. (resolverContainer = await createPluginContainer({
  60617. ...resolved,
  60618. plugins: [
  60619. alias$1({ entries: resolved.resolve.alias }),
  60620. resolvePlugin({
  60621. ...resolved.resolve,
  60622. root: resolvedRoot,
  60623. isProduction,
  60624. isBuild: command === 'build',
  60625. ssrConfig: resolved.ssr,
  60626. asSrc: true,
  60627. preferRelative: false,
  60628. tryIndex: true,
  60629. ...options,
  60630. idOnly: true,
  60631. }),
  60632. ],
  60633. }));
  60634. }
  60635. return (await container.resolveId(id, importer, {
  60636. ssr,
  60637. scan: options?.scan,
  60638. }))?.id;
  60639. };
  60640. };
  60641. const { publicDir } = config;
  60642. const resolvedPublicDir = publicDir !== false && publicDir !== ''
  60643. ? path$o.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
  60644. : '';
  60645. const server = resolveServerOptions(resolvedRoot, config.server, logger);
  60646. const ssr = resolveSSROptions(config.ssr, resolveOptions.preserveSymlinks, config.legacy?.buildSsrCjsExternalHeuristics);
  60647. const preview = resolvePreviewOptions(config.preview, server);
  60648. const middlewareMode = config?.server?.middlewareMode;
  60649. const optimizeDeps = config.optimizeDeps || {};
  60650. const BASE_URL = resolvedBase;
  60651. // resolve worker
  60652. let workerConfig = mergeConfig({}, config);
  60653. const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
  60654. // run config hooks
  60655. const workerUserPlugins = [
  60656. ...workerPrePlugins,
  60657. ...workerNormalPlugins,
  60658. ...workerPostPlugins,
  60659. ];
  60660. workerConfig = await runConfigHook(workerConfig, workerUserPlugins, configEnv);
  60661. const resolvedWorkerOptions = {
  60662. format: workerConfig.worker?.format || 'iife',
  60663. plugins: [],
  60664. rollupOptions: workerConfig.worker?.rollupOptions || {},
  60665. getSortedPlugins: undefined,
  60666. getSortedPluginHooks: undefined,
  60667. };
  60668. const resolvedConfig = {
  60669. configFile: configFile ? normalizePath$3(configFile) : undefined,
  60670. configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
  60671. inlineConfig,
  60672. root: resolvedRoot,
  60673. base: withTrailingSlash(resolvedBase),
  60674. rawBase: resolvedBase,
  60675. resolve: resolveOptions,
  60676. publicDir: resolvedPublicDir,
  60677. cacheDir,
  60678. command,
  60679. mode,
  60680. ssr,
  60681. isWorker: false,
  60682. mainConfig: null,
  60683. isProduction,
  60684. plugins: userPlugins,
  60685. css: resolveCSSOptions(config.css),
  60686. esbuild: config.esbuild === false
  60687. ? false
  60688. : {
  60689. jsxDev: !isProduction,
  60690. ...config.esbuild,
  60691. },
  60692. server,
  60693. build: resolvedBuildOptions,
  60694. preview,
  60695. envDir,
  60696. env: {
  60697. ...userEnv,
  60698. BASE_URL,
  60699. MODE: mode,
  60700. DEV: !isProduction,
  60701. PROD: isProduction,
  60702. },
  60703. assetsInclude(file) {
  60704. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  60705. },
  60706. logger,
  60707. packageCache,
  60708. createResolver,
  60709. optimizeDeps: {
  60710. disabled: 'build',
  60711. ...optimizeDeps,
  60712. esbuildOptions: {
  60713. preserveSymlinks: resolveOptions.preserveSymlinks,
  60714. ...optimizeDeps.esbuildOptions,
  60715. },
  60716. },
  60717. worker: resolvedWorkerOptions,
  60718. appType: config.appType ?? (middlewareMode === 'ssr' ? 'custom' : 'spa'),
  60719. experimental: {
  60720. importGlobRestoreExtension: false,
  60721. hmrPartialAccept: false,
  60722. ...config.experimental,
  60723. },
  60724. // random 72 bits (12 base64 chars)
  60725. // at least 64bits is recommended
  60726. // https://owasp.org/www-community/vulnerabilities/Insufficient_Session-ID_Length
  60727. webSocketToken: Buffer.from(crypto$2.randomFillSync(new Uint8Array(9))).toString('base64url'),
  60728. additionalAllowedHosts: getAdditionalAllowedHosts(server, preview),
  60729. getSortedPlugins: undefined,
  60730. getSortedPluginHooks: undefined,
  60731. };
  60732. const resolved = {
  60733. ...config,
  60734. ...resolvedConfig,
  60735. };
  60736. resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
  60737. Object.assign(resolved, createPluginHookUtils(resolved.plugins));
  60738. const workerResolved = {
  60739. ...workerConfig,
  60740. ...resolvedConfig,
  60741. isWorker: true,
  60742. mainConfig: resolved,
  60743. };
  60744. resolvedConfig.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
  60745. Object.assign(resolvedConfig.worker, createPluginHookUtils(resolvedConfig.worker.plugins));
  60746. // call configResolved hooks
  60747. await Promise.all([
  60748. ...resolved
  60749. .getSortedPluginHooks('configResolved')
  60750. .map((hook) => hook(resolved)),
  60751. ...resolvedConfig.worker
  60752. .getSortedPluginHooks('configResolved')
  60753. .map((hook) => hook(workerResolved)),
  60754. ]);
  60755. // validate config
  60756. if (middlewareMode === 'ssr') {
  60757. logger.warn(colors$1.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`));
  60758. }
  60759. if (middlewareMode === 'html') {
  60760. logger.warn(colors$1.yellow(`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`));
  60761. }
  60762. if (config.server?.force &&
  60763. !isBuild &&
  60764. config.optimizeDeps?.force === undefined) {
  60765. resolved.optimizeDeps.force = true;
  60766. logger.warn(colors$1.yellow(`server.force is deprecated, use optimizeDeps.force instead`));
  60767. }
  60768. debug?.(`using resolved config: %O`, {
  60769. ...resolved,
  60770. plugins: resolved.plugins.map((p) => p.name),
  60771. worker: {
  60772. ...resolved.worker,
  60773. plugins: resolved.worker.plugins.map((p) => p.name),
  60774. },
  60775. });
  60776. if (config.build?.terserOptions && config.build.minify !== 'terser') {
  60777. logger.warn(colors$1.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` +
  60778. `Note Vite now defaults to use esbuild for minification. If you still ` +
  60779. `prefer Terser, set build.minify to "terser".`));
  60780. }
  60781. // Check if all assetFileNames have the same reference.
  60782. // If not, display a warn for user.
  60783. const outputOption = config.build?.rollupOptions?.output ?? [];
  60784. // Use isArray to narrow its type to array
  60785. if (Array.isArray(outputOption)) {
  60786. const assetFileNamesList = outputOption.map((output) => output.assetFileNames);
  60787. if (assetFileNamesList.length > 1) {
  60788. const firstAssetFileNames = assetFileNamesList[0];
  60789. const hasDifferentReference = assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames);
  60790. if (hasDifferentReference) {
  60791. resolved.logger.warn(colors$1.yellow(`
  60792. assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
  60793. `));
  60794. }
  60795. }
  60796. }
  60797. // Warn about removal of experimental features
  60798. if (config.legacy?.buildSsrCjsExternalHeuristics ||
  60799. config.ssr?.format === 'cjs') {
  60800. resolved.logger.warn(colors$1.yellow(`
  60801. (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
  60802. Find more information and give feedback at https://github.com/vitejs/vite/discussions/13816.
  60803. `));
  60804. }
  60805. return resolved;
  60806. }
  60807. /**
  60808. * Resolve base url. Note that some users use Vite to build for non-web targets like
  60809. * electron or expects to deploy
  60810. */
  60811. function resolveBaseUrl(base = '/', isBuild, logger) {
  60812. if (base[0] === '.') {
  60813. logger.warn(colors$1.yellow(colors$1.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
  60814. `URL, ./, or an empty string.`)));
  60815. return '/';
  60816. }
  60817. // external URL flag
  60818. const isExternal = isExternalUrl(base);
  60819. // no leading slash warn
  60820. if (!isExternal && base[0] !== '/') {
  60821. logger.warn(colors$1.yellow(colors$1.bold(`(!) "base" option should start with a slash.`)));
  60822. }
  60823. // parse base when command is serve or base is not External URL
  60824. if (!isBuild || !isExternal) {
  60825. base = new URL(base, 'http://vitejs.dev').pathname;
  60826. // ensure leading slash
  60827. if (base[0] !== '/') {
  60828. base = '/' + base;
  60829. }
  60830. }
  60831. return base;
  60832. }
  60833. function sortUserPlugins(plugins) {
  60834. const prePlugins = [];
  60835. const postPlugins = [];
  60836. const normalPlugins = [];
  60837. if (plugins) {
  60838. plugins.flat().forEach((p) => {
  60839. if (p.enforce === 'pre')
  60840. prePlugins.push(p);
  60841. else if (p.enforce === 'post')
  60842. postPlugins.push(p);
  60843. else
  60844. normalPlugins.push(p);
  60845. });
  60846. }
  60847. return [prePlugins, normalPlugins, postPlugins];
  60848. }
  60849. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) {
  60850. const start = performance.now();
  60851. const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
  60852. let resolvedPath;
  60853. if (configFile) {
  60854. // explicit config path is always resolved from cwd
  60855. resolvedPath = path$o.resolve(configFile);
  60856. }
  60857. else {
  60858. // implicit config file loaded from inline root (if present)
  60859. // otherwise from cwd
  60860. for (const filename of DEFAULT_CONFIG_FILES) {
  60861. const filePath = path$o.resolve(configRoot, filename);
  60862. if (!fs$l.existsSync(filePath))
  60863. continue;
  60864. resolvedPath = filePath;
  60865. break;
  60866. }
  60867. }
  60868. if (!resolvedPath) {
  60869. debug?.('no config file found.');
  60870. return null;
  60871. }
  60872. let isESM = false;
  60873. if (/\.m[jt]s$/.test(resolvedPath)) {
  60874. isESM = true;
  60875. }
  60876. else if (/\.c[jt]s$/.test(resolvedPath)) {
  60877. isESM = false;
  60878. }
  60879. else {
  60880. // check package.json for type: "module" and set `isESM` to true
  60881. try {
  60882. const pkg = lookupFile(configRoot, ['package.json']);
  60883. isESM =
  60884. !!pkg && JSON.parse(fs$l.readFileSync(pkg, 'utf-8')).type === 'module';
  60885. }
  60886. catch (e) { }
  60887. }
  60888. try {
  60889. const bundled = await bundleConfigFile(resolvedPath, isESM);
  60890. const userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM);
  60891. debug?.(`bundled config file loaded in ${getTime()}`);
  60892. const config = await (typeof userConfig === 'function'
  60893. ? userConfig(configEnv)
  60894. : userConfig);
  60895. if (!isObject$2(config)) {
  60896. throw new Error(`config must export or return an object.`);
  60897. }
  60898. return {
  60899. path: normalizePath$3(resolvedPath),
  60900. config,
  60901. dependencies: bundled.dependencies,
  60902. };
  60903. }
  60904. catch (e) {
  60905. createLogger(logLevel).error(colors$1.red(`failed to load config from ${resolvedPath}`), { error: e });
  60906. throw e;
  60907. }
  60908. }
  60909. async function bundleConfigFile(fileName, isESM) {
  60910. const dirnameVarName = '__vite_injected_original_dirname';
  60911. const filenameVarName = '__vite_injected_original_filename';
  60912. const importMetaUrlVarName = '__vite_injected_original_import_meta_url';
  60913. const result = await build$3({
  60914. absWorkingDir: process.cwd(),
  60915. entryPoints: [fileName],
  60916. outfile: 'out.js',
  60917. write: false,
  60918. target: ['node14.18', 'node16'],
  60919. platform: 'node',
  60920. bundle: true,
  60921. format: isESM ? 'esm' : 'cjs',
  60922. mainFields: ['main'],
  60923. sourcemap: 'inline',
  60924. metafile: true,
  60925. define: {
  60926. __dirname: dirnameVarName,
  60927. __filename: filenameVarName,
  60928. 'import.meta.url': importMetaUrlVarName,
  60929. },
  60930. plugins: [
  60931. {
  60932. name: 'externalize-deps',
  60933. setup(build) {
  60934. const packageCache = new Map();
  60935. const resolveByViteResolver = (id, importer, isRequire) => {
  60936. return tryNodeResolve(id, importer, {
  60937. root: path$o.dirname(fileName),
  60938. isBuild: true,
  60939. isProduction: true,
  60940. preferRelative: false,
  60941. tryIndex: true,
  60942. mainFields: [],
  60943. browserField: false,
  60944. conditions: [],
  60945. overrideConditions: ['node'],
  60946. dedupe: [],
  60947. extensions: DEFAULT_EXTENSIONS$1,
  60948. preserveSymlinks: false,
  60949. packageCache,
  60950. isRequire,
  60951. }, false)?.id;
  60952. };
  60953. const isESMFile = (id) => {
  60954. if (id.endsWith('.mjs'))
  60955. return true;
  60956. if (id.endsWith('.cjs'))
  60957. return false;
  60958. const nearestPackageJson = findNearestPackageData(path$o.dirname(id), packageCache);
  60959. return (!!nearestPackageJson && nearestPackageJson.data.type === 'module');
  60960. };
  60961. // externalize bare imports
  60962. build.onResolve({ filter: /^[^.].*/ }, async ({ path: id, importer, kind }) => {
  60963. if (kind === 'entry-point' ||
  60964. path$o.isAbsolute(id) ||
  60965. isNodeBuiltin(id)) {
  60966. return;
  60967. }
  60968. // With the `isNodeBuiltin` check above, this check captures if the builtin is a
  60969. // non-node built-in, which esbuild doesn't know how to handle. In that case, we
  60970. // externalize it so the non-node runtime handles it instead.
  60971. if (isBuiltin(id)) {
  60972. return { external: true };
  60973. }
  60974. const isImport = isESM || kind === 'dynamic-import';
  60975. let idFsPath;
  60976. try {
  60977. idFsPath = resolveByViteResolver(id, importer, !isImport);
  60978. }
  60979. catch (e) {
  60980. if (!isImport) {
  60981. let canResolveWithImport = false;
  60982. try {
  60983. canResolveWithImport = !!resolveByViteResolver(id, importer, false);
  60984. }
  60985. catch { }
  60986. if (canResolveWithImport) {
  60987. throw new Error(`Failed to resolve ${JSON.stringify(id)}. This package is ESM only but it was tried to load by \`require\`. See http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
  60988. }
  60989. }
  60990. throw e;
  60991. }
  60992. if (idFsPath && isImport) {
  60993. idFsPath = pathToFileURL(idFsPath).href;
  60994. }
  60995. if (idFsPath && !isImport && isESMFile(idFsPath)) {
  60996. throw new Error(`${JSON.stringify(id)} resolved to an ESM file. ESM file cannot be loaded by \`require\`. See http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
  60997. }
  60998. return {
  60999. path: idFsPath,
  61000. external: true,
  61001. };
  61002. });
  61003. },
  61004. },
  61005. {
  61006. name: 'inject-file-scope-variables',
  61007. setup(build) {
  61008. build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
  61009. const contents = await fsp.readFile(args.path, 'utf8');
  61010. const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path$o.dirname(args.path))};` +
  61011. `const ${filenameVarName} = ${JSON.stringify(args.path)};` +
  61012. `const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(args.path).href)};`;
  61013. return {
  61014. loader: args.path.endsWith('ts') ? 'ts' : 'js',
  61015. contents: injectValues + contents,
  61016. };
  61017. });
  61018. },
  61019. },
  61020. ],
  61021. });
  61022. const { text } = result.outputFiles[0];
  61023. return {
  61024. code: text,
  61025. dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [],
  61026. };
  61027. }
  61028. const _require = createRequire$1(import.meta.url);
  61029. async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
  61030. // for esm, before we can register loaders without requiring users to run node
  61031. // with --experimental-loader themselves, we have to do a hack here:
  61032. // write it to disk, load it with native Node ESM, then delete the file.
  61033. if (isESM) {
  61034. const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random()
  61035. .toString(16)
  61036. .slice(2)}`;
  61037. const fileNameTmp = `${fileBase}.mjs`;
  61038. const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
  61039. await fsp.writeFile(fileNameTmp, bundledCode);
  61040. try {
  61041. return (await dynamicImport(fileUrl)).default;
  61042. }
  61043. finally {
  61044. fs$l.unlink(fileNameTmp, () => { }); // Ignore errors
  61045. }
  61046. }
  61047. // for cjs, we can register a custom loader via `_require.extensions`
  61048. else {
  61049. const extension = path$o.extname(fileName);
  61050. // We don't use fsp.realpath() here because it has the same behaviour as
  61051. // fs.realpath.native. On some Windows systems, it returns uppercase volume
  61052. // letters (e.g. "C:\") while the Node.js loader uses lowercase volume letters.
  61053. // See https://github.com/vitejs/vite/issues/12923
  61054. const realFileName = await promisifiedRealpath(fileName);
  61055. const loaderExt = extension in _require.extensions ? extension : '.js';
  61056. const defaultLoader = _require.extensions[loaderExt];
  61057. _require.extensions[loaderExt] = (module, filename) => {
  61058. if (filename === realFileName) {
  61059. module._compile(bundledCode, filename);
  61060. }
  61061. else {
  61062. defaultLoader(module, filename);
  61063. }
  61064. };
  61065. // clear cache in case of server restart
  61066. delete _require.cache[_require.resolve(fileName)];
  61067. const raw = _require(fileName);
  61068. _require.extensions[loaderExt] = defaultLoader;
  61069. return raw.__esModule ? raw.default : raw;
  61070. }
  61071. }
  61072. async function runConfigHook(config, plugins, configEnv) {
  61073. let conf = config;
  61074. for (const p of getSortedPluginsByHook('config', plugins)) {
  61075. const hook = p.config;
  61076. const handler = hook && 'handler' in hook ? hook.handler : hook;
  61077. if (handler) {
  61078. const res = await handler(conf, configEnv);
  61079. if (res) {
  61080. conf = mergeConfig(conf, res);
  61081. }
  61082. }
  61083. }
  61084. return conf;
  61085. }
  61086. function getDepOptimizationConfig(config, ssr) {
  61087. return ssr ? config.ssr.optimizeDeps : config.optimizeDeps;
  61088. }
  61089. function isDepsOptimizerEnabled(config, ssr) {
  61090. const { command } = config;
  61091. const { disabled } = getDepOptimizationConfig(config, ssr);
  61092. return !(disabled === true ||
  61093. (command === 'build' && disabled === 'build') ||
  61094. (command === 'serve' && disabled === 'dev'));
  61095. }
  61096. export { isFileLoadingAllowed as A, loadEnv as B, resolveEnvPrefix as C, colors$1 as D, bindShortcuts as E, getDefaultExportFromCjs as F, commonjsGlobal as G, index$1 as H, build$1 as I, index as J, preview$1 as K, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };